/** * @param string|AssetInterface $asset * @param NULL|string $path * @param bool $overwrite * * @throws Exceptions\InvalidArgumentException * @throws Exceptions\WriterException * @throws Exceptions\TargetPathNotSetException * * @return string */ private function writeAssetToFilesystem(AssetInterface $asset, $path = NULL, $overwrite = FALSE) { if ($path === NULL) { // If target path is set explicit (by method parameter or asset targetPath). if ($asset->getTargetPath() !== NULL) { $path = $asset->getTargetPath(); } elseif ($asset instanceof AssetCollection && $asset->getNamingConvention() !== NULL) { $path = $asset->getNamingConvention()->getPath($asset, $this->globalEnvironment ? $this->globalEnvironment->getHash() : ""); } else { if ($asset instanceof AssetCollection) { throw new TargetPathNotSetException("AssertWriter::writerAsset() Target path for asset collection \"{$asset->getName()}\" is NULL. You have to set \"namingConvention\" or directly \"targetPath\"."); } else { /** @var AssetInterface $asset */ throw new TargetPathNotSetException("AssertWriter::writerAsset() Target path for asset is NULL. You have to set target path."); } } } $absolutePath = self::normalizePath(self::isPathAbsolute($path) ? $path : $this->targetDir . '/' . $path); // File already exists? if ($overwrite || !file_exists($absolutePath)) { // Dir exits? if (!file_exists($dir = dirname($absolutePath)) && !@mkdir($dir, 0777, TRUE)) { throw new WriterException("Can not create dir: \"{$dir}\""); } // Is file writable? if (!is_writable(dirname($absolutePath))) { throw new WriterException("Can not write to file: \"{$absolutePath}\""); } $content = $asset->dump(); if (file_put_contents('safe://' . $absolutePath, $content) === FALSE) { throw new WriterException("Error writing to file: \"{$absolutePath}\""); } } return $absolutePath; }
/** * Get web path to compiled asset. * If output file not exists, then compile and write down asset. * * @param string $assetName * @return mixed|NULL */ public function getAssetWebPath($assetName) { $key = $assetName; $key .= '-' . md5(serialize($this->getCollectionEnvironment($assetName)) . $this->globalEnvironment->getHash()); $cache = new Cache($this->cacheStorage, $this->namespace); $path = $cache->load($key); if (!$path || !file_exists($path['absolutePath'])) { $self = $this; $httpRequest = $self->httpRequest; $webPath = $self->webPath; $path = $cache->save($key, function () use($self, $assetName, $httpRequest, $webPath) { $asset = $self->getAssetManager()->get($assetName); $absolutePath = $self->getAssetWriter()->writeAsset($asset); $relativeUrl = $self->convertPathToRelativeUrl($absolutePath); $baseUrl = rtrim($httpRequest->getUrl()->getBaseUrl(), '/'); $basePath = preg_replace('#https?://[^/]+#A', '', $baseUrl); $url = $basePath . '/' . $webPath . '/' . $relativeUrl; return array('absolutePath' => $absolutePath, 'url' => $url); }); } return $path['url']; }