| Conditions | 2 |
| Paths | 1 |
| Total Lines | 92 |
| 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 |
||
| 84 | function cast($value) |
||
| 85 | { |
||
| 86 | return new class($value) |
||
| 87 | { |
||
| 88 | private $value; |
||
| 89 | |||
| 90 | public function __construct(?string $value) |
||
| 91 | { |
||
| 92 | $this->value = $value; |
||
| 93 | } |
||
| 94 | |||
| 95 | /** |
||
| 96 | * @return int |
||
| 97 | */ |
||
| 98 | public function asInt(): int |
||
| 99 | { |
||
| 100 | return (int) $this->value; |
||
| 101 | } |
||
| 102 | |||
| 103 | /** |
||
| 104 | * @return int|null |
||
| 105 | */ |
||
| 106 | public function asIntOrNull(): ?int |
||
| 107 | { |
||
| 108 | if (0 === strlen((string) $this->value)) { |
||
| 109 | return null; |
||
| 110 | } |
||
| 111 | |||
| 112 | return (int) $this->value; |
||
| 113 | } |
||
| 114 | |||
| 115 | /** |
||
| 116 | * @return float |
||
| 117 | */ |
||
| 118 | public function asFloat(): float |
||
| 119 | { |
||
| 120 | return (float) $this->value; |
||
| 121 | } |
||
| 122 | |||
| 123 | /** |
||
| 124 | * @return float|null |
||
| 125 | */ |
||
| 126 | public function asFloatOrNull(): ?float |
||
| 127 | { |
||
| 128 | if (0 === strlen((string) $this->value)) { |
||
| 129 | return null; |
||
| 130 | } |
||
| 131 | |||
| 132 | return (float) $this->value; |
||
| 133 | } |
||
| 134 | |||
| 135 | /** |
||
| 136 | * @return string |
||
| 137 | */ |
||
| 138 | public function asString(): string |
||
| 139 | { |
||
| 140 | return (string) $this->value; |
||
| 141 | } |
||
| 142 | |||
| 143 | /** |
||
| 144 | * @return string|null |
||
| 145 | */ |
||
| 146 | public function asStringOrNull(): ?string |
||
| 147 | { |
||
| 148 | if (0 === strlen((string) $this->value)) { |
||
| 149 | return null; |
||
| 150 | } |
||
| 151 | |||
| 152 | return (string) $this->value; |
||
| 153 | } |
||
| 154 | |||
| 155 | /** |
||
| 156 | * @return bool |
||
| 157 | */ |
||
| 158 | public function asBool(): bool |
||
| 159 | { |
||
| 160 | return filter_var($this->value, FILTER_VALIDATE_BOOLEAN); |
||
| 161 | } |
||
| 162 | |||
| 163 | /** |
||
| 164 | * @return bool|null |
||
| 165 | */ |
||
| 166 | public function asBoolOrNull(): ?bool |
||
| 167 | { |
||
| 168 | if (0 === strlen((string) $this->value)) { |
||
| 169 | return null; |
||
| 170 | } |
||
| 171 | |||
| 172 | return filter_var($this->value, FILTER_VALIDATE_BOOLEAN); |
||
| 173 | } |
||
| 174 | }; |
||
| 175 | } |
||
| 176 | |||
| 220 |