| Conditions | 9 |
| Paths | 36 |
| Total Lines | 62 |
| Code Lines | 34 |
| 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 |
||
| 102 | public static function url2cache(string $url) |
||
| 103 | { |
||
| 104 | if (!self::$api) { |
||
| 105 | self::$api = new \Extender\request('https://unsplash.it'); |
||
| 106 | } |
||
| 107 | /** |
||
| 108 | * @var string Anonymize url into md5 |
||
| 109 | * |
||
| 110 | * @todo Fix unecessary characters from url |
||
| 111 | */ |
||
| 112 | $md5 = md5($url); |
||
| 113 | /** |
||
| 114 | * @var string Save cache name generator. |
||
| 115 | * |
||
| 116 | * @return string domain or default |
||
| 117 | */ |
||
| 118 | $savedname = function () { |
||
| 119 | global $url; |
||
| 120 | $savedname = \MVC\helper::url2host($url); |
||
| 121 | if (!$savedname) { |
||
| 122 | $savedname = 'default'; |
||
| 123 | } |
||
| 124 | |||
| 125 | return $savedname; |
||
| 126 | }; |
||
| 127 | /** |
||
| 128 | * @var string Save location schema image |
||
| 129 | */ |
||
| 130 | $saved = __DIR__ . "/data/$savedname.json"; |
||
| 131 | self::$saved = $saved; |
||
| 132 | $res = read_file($saved, []); |
||
| 133 | if (is_string($res)) { |
||
| 134 | $res = json_decode($res, true); |
||
| 135 | } |
||
| 136 | if (isset($res[$md5])) { |
||
| 137 | self::$url = $res[$md5]; |
||
| 138 | } elseif (\MVC\helper::is_url($url)) { |
||
| 139 | $res[$md5] = self::$url = $url; |
||
| 140 | $saved = __DIR__ . "/data/$savedname.json"; |
||
| 141 | } |
||
| 142 | |||
| 143 | self::$api->setUrl(self::$url); |
||
| 144 | $url = self::$api->url; |
||
| 145 | $cache = ROOT . '/tmp/img/' . md5($url); |
||
| 146 | self::$cache = $cache; |
||
| 147 | |||
| 148 | if (!file_exists($cache)) { |
||
| 149 | self::$api->set_method('get'); |
||
| 150 | self::$api->exec(); |
||
| 151 | for ($i = 0; $i < 10; ++$i) { |
||
| 152 | if (isset(self::$api->responseHeaders['Location'])) { |
||
| 153 | self::$api->get(self::$api->responseHeaders['Location']); |
||
| 154 | } else { |
||
| 155 | break; |
||
| 156 | } |
||
| 157 | } |
||
| 158 | |||
| 159 | write_file($saved, $res, true); |
||
| 160 | write_file($cache, self::$api->response, true); |
||
| 161 | } |
||
| 162 | |||
| 163 | return '/img/cache?hash=' . md5($url); |
||
| 164 | } |
||
| 227 |
Adding explicit visibility (
private,protected, orpublic) is generally recommend to communicate to other developers how, and from where this method is intended to be used.