response = $response; $this->isAllowed = $isAllowed; $this->directory = $filesystem->getDirectoryWrite(DirectoryList::PUB); $mediaDirectory = trim($mediaDirectory); if (!empty($mediaDirectory)) { $this->mediaDirectoryPath = str_replace('\\', '/', realpath($mediaDirectory)); } $this->configCacheFile = $configCacheFile; $this->relativeFileName = $relativeFileName; $this->configFactory = $configFactory; $this->syncFactory = $syncFactory; $this->placeholderFactory = $placeholderFactory; $this->appState = $state; $this->imageResize = $imageResize; } /** * Run application * * @return Response * @throws \LogicException */ public function launch() { $this->appState->setAreaCode(Area::AREA_GLOBAL); if ($this->mediaDirectoryPath !== $this->directory->getAbsolutePath()) { // Path to media directory changed or absent - update the config /** @var Config $config */ $config = $this->configFactory->create(['cacheFile' => $this->configCacheFile]); $config->save(); $this->mediaDirectoryPath = $config->getMediaDirectory(); $allowedResources = $config->getAllowedResources(); $isAllowed = $this->isAllowed; if (!$isAllowed($this->relativeFileName, $allowedResources)) { throw new \LogicException('The specified path is not allowed.'); } } try { /** @var \Magento\MediaStorage\Model\File\Storage\Synchronization $sync */ $sync = $this->syncFactory->create(['directory' => $this->directory]); $sync->synchronize($this->relativeFileName); $this->imageResize->resizeFromImageName($this->getOriginalImage($this->relativeFileName)); if ($this->directory->isReadable($this->relativeFileName)) { $this->response->setFilePath($this->directory->getAbsolutePath($this->relativeFileName)); } else { $this->setPlaceholderImage(); } } catch (\Exception $e) { $this->setPlaceholderImage(); } return $this->response; } private function setPlaceholderImage() { $placeholder = $this->placeholderFactory->create(['type' => 'image']); $this->response->setFilePath($placeholder->getPath()); } /** * Find the path to the original image of the cache path * * @param string $resizedImagePath * @return string */ private function getOriginalImage(string $resizedImagePath): string { return preg_replace('|^.*((?:/[^/]+){3})$|', '$1', $resizedImagePath); } /** * {@inheritdoc} */ public function catchException(App\Bootstrap $bootstrap, \Exception $exception) { $this->response->setHttpResponseCode(404); if ($bootstrap->isDeveloperMode()) { $this->response->setHeader('Content-Type', 'text/plain'); $this->response->setBody($exception->getMessage() . "\n" . $exception->getTraceAsString()); } $this->response->sendResponse(); return true; } }