| Conditions | 15 |
| Paths | 27 |
| Total Lines | 51 |
| Code Lines | 35 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 1 | Features | 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 |
||
| 41 | public function convertFrontmatter(string $string, string $format = 'yaml'): array |
||
| 42 | { |
||
| 43 | switch ($format) { |
||
| 44 | // https://wikipedia.org/wiki/INI_file |
||
| 45 | case 'ini': |
||
| 46 | $result = parse_ini_string($string, true); |
||
| 47 | if ($result === false) { |
||
| 48 | throw new RuntimeException('Can\'t parse INI front matter.'); |
||
| 49 | } |
||
| 50 | |||
| 51 | return $result; |
||
| 52 | // https://wikipedia.org/wiki/JSON |
||
| 53 | case 'json': |
||
| 54 | try { |
||
| 55 | $result = json_decode($string, true); |
||
| 56 | if ($result === null && json_last_error() !== JSON_ERROR_NONE) { |
||
| 57 | throw new \Exception('JSON error.'); |
||
| 58 | } |
||
| 59 | } catch (\Exception $e) { |
||
| 60 | throw new RuntimeException('Can\'t parse JSON front matter.'); |
||
| 61 | } |
||
| 62 | |||
| 63 | return $result; |
||
| 64 | // https://wikipedia.org/wiki/TOML |
||
| 65 | case 'toml': |
||
| 66 | try { |
||
| 67 | $result = Toml::Parse((string) $string) ?? []; |
||
| 68 | if (!is_array($result)) { |
||
| 69 | throw new RuntimeException('Can\'t parse TOML front matter.'); |
||
| 70 | } |
||
| 71 | |||
| 72 | return $result; |
||
| 73 | } catch (TomlParseException $e) { |
||
| 74 | throw new RuntimeException($e->getMessage(), $e->getParsedFile(), $e->getParsedLine()); |
||
| 75 | } catch (\Exception $e) { |
||
| 76 | throw new RuntimeException($e->getMessage()); |
||
| 77 | } |
||
| 78 | // https://wikipedia.org/wiki/YAML |
||
| 79 | case 'yaml': |
||
| 80 | default: |
||
| 81 | try { |
||
| 82 | $result = Yaml::parse((string) $string) ?? []; |
||
| 83 | if (!is_array($result)) { |
||
| 84 | throw new RuntimeException('Can\'t parse YAML front matter.'); |
||
| 85 | } |
||
| 86 | |||
| 87 | return $result; |
||
| 88 | } catch (ParseException $e) { |
||
| 89 | throw new RuntimeException($e->getMessage(), $e->getParsedFile(), $e->getParsedLine()); |
||
| 90 | } catch (\Exception $e) { |
||
| 91 | throw new RuntimeException($e->getMessage()); |
||
| 92 | } |
||
| 106 |