linkExplorer = $linkExplorer; $this->client = $clientService->newClient(); $this->logger = $logger; } /** * @param Bookmark $bookmark * * @return Image|null */ public function getImage($bookmark): ?IImage { if (!isset($bookmark)) { return null; } $site = $this->scrapeUrl($bookmark->getUrl()); $this->logger->debug('getImage for URL: ' . $bookmark->getUrl() . ' ' . var_export($site, true), ['app' => 'bookmarks']); if (isset($site['image']['small'])) { return $this->fetchImage($site['image']['small']); } if (isset($site['image']['large'])) { return $this->fetchImage($site['image']['large']); } return null; } public function scrapeUrl($url): array { return $this->linkExplorer->get($url); } /** * @param $url * @return Image|null */ protected function fetchImage($url): ?Image { try { $response = $this->client->get($url, ['timeout' => self::HTTP_TIMEOUT]); } catch (Exception $e) { $this->logger->debug($e->getMessage(), ['app' => 'bookmarks']); return null; } $body = $response->getBody(); $contentType = $response->getHeader('Content-Type'); // Some HTPP Error occured :/ if ($response->getStatusCode() !== 200) { return null; } // It's not actually an image, doh. if (!isset($contentType) || stripos($contentType, 'image') !== 0) { return null; } return new Image($contentType, $body); } }