| Conditions | 6 |
| Paths | 7 |
| Total Lines | 63 |
| Code Lines | 27 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 6 | ||
| Bugs | 0 | 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 |
||
| 58 | public function downloadPage($page) |
||
| 59 | { |
||
| 60 | // Initialize |
||
| 61 | $pageParts = pathinfo($page); |
||
| 62 | $downloadFolder = $this->downloadFolder; |
||
| 63 | $saveFile = $downloadFolder.date('Ymd-His').'-'.$pageParts['filename'].'.htm'; |
||
| 64 | |||
| 65 | // Download page |
||
| 66 | $res = $this->client->get($page); |
||
| 67 | |||
| 68 | // Check downloaded content |
||
| 69 | if ($res->getStatusCode() !== 200) { |
||
| 70 | return false; |
||
| 71 | } |
||
| 72 | |||
| 73 | // Get page content |
||
| 74 | $pageContent = $res->getBody()->getContents(); |
||
| 75 | |||
| 76 | // Save page in downloadFolder |
||
| 77 | if (!file_put_contents($saveFile, "\xEF\xBB\xBF".$pageContent)) { |
||
| 78 | // Throw error |
||
| 79 | throw new \Exception('Error saving file', 1); |
||
| 80 | } |
||
| 81 | |||
| 82 | // Initialize crawler |
||
| 83 | $crawler = new Crawler($pageContent); |
||
| 84 | |||
| 85 | // Get images list |
||
| 86 | $images = $crawler->filter('img')->each(function(Crawler $image) { |
||
| 87 | return $image->attr('src'); |
||
| 88 | }); |
||
| 89 | |||
| 90 | // Download images |
||
| 91 | foreach ($images as $image) { |
||
| 92 | // Initialize |
||
| 93 | $image = str_replace(' ', '', $image); |
||
| 94 | $imgExt = pathinfo($image, PATHINFO_EXTENSION); |
||
| 95 | $hasHost = filter_var($image, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED); |
||
| 96 | |||
| 97 | // Check host |
||
| 98 | if (!$hasHost) { |
||
| 99 | $image = $pageParts['dirname'].$image; |
||
| 100 | } |
||
| 101 | |||
| 102 | // Check extension |
||
| 103 | if (!in_array($imgExt, ['png', 'jpg', 'jpeg', 'gif'])) { |
||
| 104 | $imgExt = 'png'; |
||
| 105 | } |
||
| 106 | |||
| 107 | // Create image to publish |
||
| 108 | $imgToPublish = [ |
||
| 109 | 'url' => $image, |
||
| 110 | 'savePath' => $this->downloadFolder.pathinfo($image, PATHINFO_FILENAME).'.'.$imgExt, |
||
| 111 | 'savedHtmlFile' => $saveFile, |
||
| 112 | ]; |
||
| 113 | |||
| 114 | // Publish image |
||
| 115 | $sImg = serialize($imgToPublish); |
||
| 116 | $this->downloadImageProducer->publish($sImg); |
||
| 117 | } |
||
| 118 | |||
| 119 | // Return status |
||
| 120 | return true; |
||
| 121 | } |
||
| 123 |