Total Lines | 76 |
Code Lines | 23 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 1 |
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 | if (!is_array($value)) { |
||
44 | $value = []; |
||
45 | } |
||
46 | return new ArrayObject($value); |
||
47 | } |
||
48 | |||
49 | /** |
||
50 | * @inheritDoc |
||
51 | */ |
||
52 | public function set($model, $key, $value, $attributes) |
||
53 | { |
||
54 | if (is_string($value)) { |
||
55 | return [$key => $value]; |
||
56 | } |
||
57 | if ($value instanceof ArrayObject) { |
||
58 | $value = $this->encode($value); |
||
59 | } |
||
60 | return [$key => $value]; |
||
61 | } |
||
62 | |||
63 | /** |
||
64 | * @inheritDoc |
||
65 | */ |
||
66 | public function serialize($model, string $key, $value, array $attributes) |
||
67 | { |
||
68 | return $value->getArrayCopy(); |
||
69 | } |
||
70 | |||
71 | /** |
||
72 | * @param $value |
||
73 | * @return false|string |
||
74 | */ |
||
75 | protected function encode($value) |
||
76 | { |
||
77 | if ($this->encoder == 'serialize') { |
||
78 | return $value instanceof ArrayObject ? $value->serialize() : serialize($value); |
||
79 | } |
||
80 | return json_encode($value); |
||
81 | } |
||
82 | |||
83 | /** |
||
84 | * @param $value |
||
85 | * @return mixed |
||
86 | */ |
||
87 | protected function decode($value) |
||
88 | { |
||
89 | if ($this->encoder == 'serialize') { |
||
90 | return unserialize($value); |
||
91 | } |
||
92 | return json_decode($value, true); |
||
93 | } |
||
97 |
In the issue above, the returned value is violating the contract defined by the mentioned interface.
Let's take a look at an example: