| Conditions | 2 |
| Total Lines | 73 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 17 | public static function castUsing(array $arguments) |
||
| 18 | { |
||
| 19 | $encoder = isset($arguments[0]) ? $arguments[0] : null; |
||
| 20 | return new class($encoder) implements CastsAttributes { |
||
|
|
|||
| 21 | |||
| 22 | protected $encoder = 'json'; |
||
| 23 | |||
| 24 | /** |
||
| 25 | * constructor. |
||
| 26 | * @param $encoder |
||
| 27 | */ |
||
| 28 | public function __construct($encoder) |
||
| 29 | { |
||
| 30 | $this->encoder = $encoder; |
||
| 31 | } |
||
| 32 | |||
| 33 | /** |
||
| 34 | * @inheritDoc |
||
| 35 | */ |
||
| 36 | public function get($model, $key, $value, $attributes): ArrayObject |
||
| 37 | { |
||
| 38 | if (empty($value)) { |
||
| 39 | $value = []; |
||
| 40 | } else { |
||
| 41 | $value = $this->decode($value); |
||
| 42 | } |
||
| 43 | return new ArrayObject($value); |
||
| 44 | } |
||
| 45 | |||
| 46 | /** |
||
| 47 | * @inheritDoc |
||
| 48 | */ |
||
| 49 | public function set($model, $key, $value, $attributes) |
||
| 50 | { |
||
| 51 | if (is_string($value)) { |
||
| 52 | return [$key => $value]; |
||
| 53 | } |
||
| 54 | if ($value instanceof ArrayObject) { |
||
| 55 | $value = $this->encode($value); |
||
| 56 | } |
||
| 57 | return [$key => $value]; |
||
| 58 | } |
||
| 59 | |||
| 60 | /** |
||
| 61 | * @inheritDoc |
||
| 62 | */ |
||
| 63 | public function serialize($model, string $key, $value, array $attributes) |
||
| 64 | { |
||
| 65 | return $value->getArrayCopy(); |
||
| 66 | } |
||
| 67 | |||
| 68 | /** |
||
| 69 | * @param $value |
||
| 70 | * @return false|string |
||
| 71 | */ |
||
| 72 | protected function encode($value) |
||
| 73 | { |
||
| 74 | if ($this->encoder == 'serialize') { |
||
| 75 | return $value instanceof ArrayObject ? $value->serialize() : serialize($value); |
||
| 76 | } |
||
| 77 | return json_encode($value); |
||
| 78 | } |
||
| 79 | |||
| 80 | /** |
||
| 81 | * @param $value |
||
| 82 | * @return mixed |
||
| 83 | */ |
||
| 84 | protected function decode($value) |
||
| 85 | { |
||
| 86 | if ($this->encoder == 'serialize') { |
||
| 87 | return unserialize($value); |
||
| 88 | } |
||
| 89 | return json_decode($value, true); |
||
| 90 | } |
||
| 94 |
In the issue above, the returned value is violating the contract defined by the mentioned interface.
Let's take a look at an example: