Yii2 getters & setters to format string to float - php

Ok so currently have this function in controller, which is called multiple times.
public function formatFloat($value)
{
return (float)sprintf('%0.6f', $value);
}
So I am trying to use getters and setters so I can just use
$model->$whatever;
and the formatting will be done.
In my model I have
public function getChargePeak()
{
return $this->charge_peak;
}
public function setChargePeak($value)
{
return $this->charge_peak = (float)sprintf('%0.6f', $value);
}
but when doing
$peak = $model->chargepeak;
var_dump($peak);die;
it is still returning as a string

If the charge_peak property is stored as string and you need a float in you app you should use
public function getChargePeak()
{
return floatval($this->charge_peak);
}
Anyway you should store the values in a coherent way as you use the values in your app ..
http://php.net/manual/en/function.floatval.php

So I suggest u another pattern: decorator and helpers. You should use a controller only to get data from request, prepare it for model and send it to view.
Formatting values is a helper logic. So create a new class
\common\helpers\Number.php
namespace common\helpers;
class Number
{
public static function formatFloat($value)
{
return (float)sprintf('%0.6f', $value);
}
}
Then create decorator for your model:
namespace common\models\decorators;
class YourModelDecorator
{
/**
* YourModel
*/
private $model;
public function __construct(YourModel $model)
{
$this->model = $model;
}
public function __get($name)
{
$methodName = 'get' . $name;
if (method_exists(self::class, $methodName)) {
return $this->$methodName();
} else {
return $this->model->{$name};
}
}
public function __call($name, $arguments)
{
return $this->model->$name($arguments);
}
public function getChargePeak()
{
return \common\helpers\Number::formatFloat($this->model->charge_peak);
}
}
and send it to view for example:
public function actionView($id)
{
$model = $this->loadModel($id);
$this->render('view', [
'model' => new \common\models\decorators\YourModelDecorator($model)
]);
}

Related

Create DB record return wrong data types Laravel 5.8

In my model I have functions for create and find records.
Model
use Illuminate\Database\Eloquent\Model;
class Charge extends Model
{
use ChargeMutator;
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->request = $attributes;
}
public function add() {
$result = self::create($this->request);
return $result;
}
public function find($id) {
$record = self::find($id);
return $record;
}
}
And I have a mutator to mutate the values.
<?php
trait ChargeMutator
{
public function getCostAttribute($value)
{
return $this->attributes['cost'] = // call function A;
}
public function getTotalCostAttribute($value)
{
dd(gettype($value));
return $this->attributes['total_cost'] = // call function A;
}
public function setCostAttribute($value)
{
return $this->attributes['cost'] = // call function B;
}
public function setTotalCostAttribute($value)
{
return $this->attributes['total_cost'] = // call function B;
}
}
Controller
class ChargesController extends Controller
{
use ValidateCreditNoteCharges, Messages, ApiResponser;
public function addCharge(Request $request)
{
// $this->validateAddCharge($request);
$credit_note_charge = new Charge($request->all());
$get_result = $credit_note_charge->add();
return $this->createdResponse($get_result);
}
}
the $request is like this
{
"name":"TEST",
"quantity":1,
"cost":56.00,
"total_cost":56.00
}
The Problem is:
when I dd(gettype($value)); in getTotalCostAttribute
from the add() function the type of total_cost value is string
from the find() function the type of total_cost value is integer
in the database the data type for total_cost is int(10)
I am not sure why is the type of the return values casted into strings when use create()
I have searched for this for 3 hours now and couldn't find a solution. i need the data type correctly because accoriding to the data type i do different calculations in my calling functions A and B

How to make Laravel Nova like Fields

I wanna create class for making fields, but in Laravel Nova this classes called like Text::make()->placeholder() and etc. This means that methods inside that class is static.
This is my field class:
class Field
{
private $field = [];
public function set($key, $value)
{
$this->field[$key] = $value;
}
public function get()
{
return $this->field;
}
}
class Text
{
private static $field;
public static function make($name)
{
self::$field = new Field;
self::$field->set('#saturn_type', 'string');
self::$field->set('#saturn_key', $name);
self::$field->set('#saturn_field', 'text');
return new Text;
}
public function placeholder($value)
{
self::$field->set('placeholder', $value);
return $this;
}
public function required()
{
self::$field->set('required', true);
return $this;
}
public function translate()
{
self::$field->set('translate', true);
return $this;
}
public function wysiwyg()
{
self::$field->set('wysiwyg', true);
return $this;
}
public function get()
{
return (array) self::$field->get();
}
}
and this is how i call it:
$fields = [
Text::make('name')->placeholder('Full Name'),
Text::make('email')->placeholder('Email'),
Text::make('password')->placeholder('Password'),
]
$lastArray = $fields->map(function ($field) {
return $field->get();
}
);
But when i call get() method for each item in this array to get array, each item returns the last item's name and placeholder because it is static. How can i solve this.
I found the solution. Actually my friend Nijat found ))
class Field
{
private $field = [];
public function set($key, $value)
{
$this->field[$key] = $value;
}
public function get()
{
return $this->field;
}
}
class Text
{
private $field;
public function __construct($name)
{
$this->field = new Field;
$this->field->set('#saturn_type', 'string');
$this->field->set('#saturn_key', $name);
$this->field->set('#saturn_field', 'text');
}
public static function make($name)
{
return new Text($name);
}
public function placeholder($value)
{
$this->field->set('placeholder', $value);
return $this;
}
public function required()
{
$this->field->set('required', true);
return $this;
}
public function translate()
{
$this->field->set('translate', true);
return $this;
}
public function wysiwyg()
{
$this->field->set('wysiwyg', true);
return $this;
}
public function get()
{
return (array) $this->field->get();
}
}
You just have to create constructor then call it in static method.
You can make Text inherit from Field and have a much simpler make method:
class Field
{
public static function make(...$arguments)
{
return new static(...$arguments);
}
// ...
}
This will instantiate the parent class (e.g. Text) and return it, allowing you to keep the chaining. In the methods you can then use $this-> as usual (instead of self::). And move the content of Text::make to the constructor:
class Text extends Field
{
public function __construct($name)
{
$this->set('#saturn_type', 'string');
$this->set('#saturn_key', $name);
$this->set('#saturn_field', 'text');
}
// ...
}

Implement a State Pattern with Doctrine ORM

I have a class that is using the State pattern. Here's a simple example
/**
* #Enitity
**/
class Door
{
protected $id;
protected $state;
public function __construct($id, DoorState $state)
public function setState(DoorState $state)
{
$this->state = $state;
}
public function close()
{
$this->setState($this->state->close())
}
...
}
interface DoorState
{
public function close;
public function open;
public function lock;
public function unlock;
}
class DoorAction implements DoorState
{
public function close()
{
throw new DoorError();
}
...
}
then several classes that define the appropriate actions in the states
class OpenedDoor extends DoorAction
{
public function close()
{
return new ClosedDoor();
}
}
So I would have some thing like
$door = new Door('1', new OpenedDoor());
DoctrineDoorRepository::save($door);
$door->close();
DoctrineDoorRepository::save($door);
How would I implement the mapping in Doctrine so I can persist it?
I'm hung up on the $state property. I would like to save the whole DoorAction based object but do I have to the map the DoorAction super class or each individual sub class?
I've looked at implementing it using Embeddable or SuperMapping but run into problems with each.
Doctrine2 DBAL has a feature in the documentation that allows ENUM's
https://www.doctrine-project.org/projects/doctrine-orm/en/current/cookbook/mysql-enums.html#mysql-enums
When we take the Solution 2: Defining a Type as a base, one could create an own type, for instance called doorstatetype or similar to represent the open/closed state. For instance like this:
<?php
namespace Acme\Model\Door;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
class DoorStateType extends Type
{
const ENUM_DOORSTATE = 'enumdoorstate';
const STATE_OPEN = 'open';
const STATE_CLOSED = 'closed';
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return "ENUM('" . self::STATE_OPEN . "', '" . self::STATE_CLOSED . "') COMMENT '(DC2Type:" . ENUM_DOORSTATE . ")'";
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
return $value;
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if (!in_array($value, array(self::STATE_OPEN, self::STATE_CLOSED))) {
throw new \InvalidArgumentException("Invalid state");
}
return $value;
}
public function getName()
{
return self::ENUM_DOORSTATE;
}
}
And then use it like this:
<?php
namespace Acme\Model\Door;
/** #Entity */
class Door
{
/** #Column(type="enumdoorstate") */
private $state;
public function open()
{
if (!DoorStateType::STATE_OPEN === $this->state) {
throw new \LogicException('Cannot open an already open door');
}
$this->state = DoorStateType::STATE_OPEN;
}
public function close()
{
if (!DoorStateType::STATE_CLOSED === $this->state) {
throw new \LogicException('Cannot close an already closed door');
}
$this->state = DoorStateType::STATE_CLOSED;
}
}
This allows searching for states:
$openDoors = $repository->findBy(array('state' => DoorStateType::STATE_OPEN));
You could basically then have the convertToPHPValue method create objects of the desired states that allow for some logic, like checking if an open door can be locked or similar.
In the case where the state has to be a class that contains logic, you could implement it like this:
First we define a normal state from which we can inherit:
<?php
namespace Acme\Model\Door;
abstract class DoorState
{
// Those methods define default behaviour for when something isn't possible
public function open()
{
throw new \LogicException('Cannot open door');
}
public function close()
{
throw new \LogicException('Cannot close door');
}
abstract public function getStateName();
}
Then the OpenState:
<?php
namespace Acme\Model\Door;
class OpenState extends DoorState
{
const STATE = 'open';
public function close()
{
return new ClosedState();
}
public function getStateName()
{
return self::STATE;
}
// More logic
}
And finally the ClosedState:
<?php
namespace Acme\Model\Door;
class ClosedState extends DoorState
{
const STATE = 'closed';
public function open()
{
return new OpenState();
}
public function getStateName()
{
return self::STATE;
}
// More logic
}
We can then, for persistence, simply use different convert methods:
<?php
namespace Acme\Model\Door;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
class DoorStateType extends Type
{
// SQL declarations etc.
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if ($value === OpenState::STATE) {
return new OpenState();
}
if ($value === ClosedState::STATE) {
return new ClosedState();
}
throw new \Exception(sprintf('Unknown state "%s", expected one of "%s"', $value, implode('", "', [OpenState::STATE, ClosedState::STATE])));
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
return $value->getStateName();
}
}
What if you map state as a string and then:
public function setState(DoorState $state)
{
$this->state = serialize($state);
}
and:
private function state()
{
return unserialize($this->state);
}
public function close()
{
$this->setState($this->state()->close())
}

PHP Method Chaining: Calling one method before allowing other methods to be chained

Consider the following class
class myClass {
private $model;
public function update($input) {
return $this->model->update($input);
}
public function find($id) {
$this->model = ORMfind($id);
}
}
How do I prevent
$myClass = new myClass;
$myClass->update($input);
The problem isn't HOW to use the above code but how to make update() a method only callable after find().
EDIT: I changed what my method does so it was more clearly understood that I need to do one method (find()) before another (update())
You could add a flag to your code like so:
class myClass {
private $model;
private $canUpdate = 0;
public function update($input) {
if ($canUpdate === 0) return; // or throw an exception here
return $this->model->update($input);
}
public function find($id) {
$this->model = ORMfind($id);
$canUpdate = 1;
}
}
Setting the flag $canUpdate will caution the update() method to react accordingly. If update() is called, you can throw an exception or exit out of the method if the flag is still 0.
To prevent from returning null value by get :
public function get() {
if (isset($this->value)) return $this->value;
else echo "please give me a value ";
}
You can also create a construct:
function __construct($val){
$this->value=$val;
}
and then give a value to your $value without using set() method:
$myClass=new myClass(10);
Outputting text, returning void, I think all of this is wrong. When you do not expect something to happen, you should throw an exception:
class MyClass {
private $canUpdate = false;
public function find($id) {
// some code...
$this->canUpdate = true;
}
public function canUpdate() {
return $this->canUpdate;
}
private function testCanUpdate() {
if (!$this->canUpdate()) {
throw new Exception('You cannot update');
}
}
public function update($inpjut) {
$this->testCanUpdate();
// ... some code
}
}
Now you can do:
$obj = new MyClass();
try {
$obj->update($input);
} catch (Exception $e) {
$obj->find($id);
$obj->update($input);
}
The proper way to make sure ->update() can only be called when the model has been initialized is to turn it into a dependency:
class myClass
{
private $model;
public function __construct($id)
{
$this->model = ORMfind($id);
}
public function update($input) {
return $this->model->update($input);
}
}
$x = new myClass('123');
Alternatively, if you have multiple find operations, you could introduce them as static constructor methods:
class myClass
{
private $model;
private function __construct($model)
{
$this->model = $model;
}
public function update($input) {
return $this->model->update($input);
}
public static function find($id)
{
return new self(ORMfind($id));
}
}
$x = myClass::find('123');
Update
Tackling your immediate problem can be done by a simple check:
public function update($input) {
return $this->model ? $this->model->update($input) : null;
}

PHP Object+Collections to JSON Using json_encode

In PHP, I have a product object that contains a collection of attributes. json_encode produces this:
{"id":"123","name":"abc","attributes":{"attributes":[{"key":"sku","value":"xyz"}]}}
"attributes" listed twice is redundant. What's the best way of structuring object collections so that the json is clean?
class Product {
public $id;
public $name;
public $attributes;
public function __construct()
{
$this->attributes = new Attributes();
}
public function get($id)
{
$this->id = "123";
$this->name = "abc";
$attribute = new Attribute("sku", "xyz");
$this->attributes->add($attribute);
}
}
class Attributes
{
public $attributes;
public function __construct()
{
$this->attributes = array();
}
public function add($attribute)
{
array_push($this->attributes, $attribute);
}
}
class Attribute
{
public $key;
public $value;
public function __construct($key, $value)
{
$this->set($key, $value);
}
}
I would just use an associative array.
class Product {
...
public $attributes=array();
...
public function get($id)
{
...
$this->attributes["sku"]="xyz";
$this->attributes["foo"]="bar";
}
}
json_encode() should produce something like this:
{"id":"123","name":"abc","attributes":{"sku":"xyz","foo":"bar"}}
OR using variable variables:
class Attributes
{
public function add($key,$value)
{
$this->{$key}=$value;
}
public function drop($key)
{
unset($this->{$key});
}
}
$a=new Attributes();
$a->add('sku','xyz');
$a->add('foo','bar');
echo json_encode($a).'<br>';
$a->drop('sku');
echo json_encode($a).'<br>';
Output:
{"sku":"xyz","foo":"bar"}
{"foo":"bar"}
You can give your classes a custom json encoding format by implementing JsonSerializable.
In your case you'll just need to have Attributes implement that and give it a jsonSerialize method which returns $this->attributes.

Categories