A resource repository is similar to a filesystem. It stores {@link PuliResource}
objects, each of which has a path in the repository:
php
$resource = $repo->get('/css/style.css');
Resources may have child resources. These can be accessed with
{@link listChildren()}:
php
$resource = $repo->get('/css');
foreach ($resource->listChildren() as $name => $resource) {
...
}
/** * Handles the "tree" command. * * @param Args $args The console arguments. * @param IO $io The I/O. * * @return int The status code. */ public function handle(Args $args, IO $io) { $path = Path::makeAbsolute($args->getArgument('path'), $this->currentPath); $resource = $this->repo->get($path); $total = 0; $io->writeLine('<c1>' . $resource->getPath() . '</c1>'); $this->printTree($io, $resource, $total); $io->writeLine(''); $io->writeLine($total . ' resources'); return 0; }
private function loadResourceFromRepo() { $path = VarUtils::resolve($this->path, $this->getVars(), $this->getValues()); // Lazily load the resource. If the resource needs to be fetched from // the database, we only want to fetch it when really necessary. $resource = $this->repo->get($path); if (!$resource instanceof BodyResource) { throw new RuntimeException(sprintf('The loaded resource is not a BodyResource. Got: %s', is_object($resource) ? get_class($resource) : gettype($resource))); } $this->resource = $resource; }
/** * Warms up the cache. * * @param string $cacheDir The cache directory * * @throws RuntimeException If setEnvironment() wasn't called */ public function warmUp($cacheDir) { $iterator = new ResourceFilterIterator(new RecursiveResourceIteratorIterator(new ResourceCollectionIterator($this->repo->get('/')->listChildren(), ResourceCollectionIterator::CURRENT_AS_PATH), RecursiveResourceIteratorIterator::SELF_FIRST), $this->suffix, ResourceFilterIterator::FILTER_BY_NAME | ResourceFilterIterator::MATCH_SUFFIX); foreach ($iterator as $path) { try { $this->twig->loadTemplate($path); } catch (Twig_Error $e) { // Problem during compilation, stop } } }
/** * Handles the "url" command. * * @param Args $args The console arguments. * @param IO $io The I/O. * * @return int The status code. */ public function handle(Args $args, IO $io) { foreach ($args->getArgument('path') as $path) { if (!Glob::isDynamic($path)) { $this->printUrl($path, $io); continue; } foreach ($this->repo->find($path) as $resource) { $this->printUrl($resource->getPath(), $io); } } return 0; }
/** * Handles the "ls" command. * * @param Args $args The console arguments. * @param IO $io The I/O. * * @return int The status code. */ public function handle(Args $args, IO $io) { $path = Path::makeAbsolute($args->getArgument('path'), $this->currentPath); $resource = $this->repo->get($path); if (!$resource->hasChildren()) { throw new RuntimeException(sprintf('The resource "%s" does not have children.', $resource->getPath())); } if ($args->isOptionSet('long')) { $this->listLong($io, $resource->listChildren()); } else { $this->listShort($io, $resource->listChildren()); } return 0; }
/** * Handles the "ls" command. * * @param Args $args The console arguments. * @param IO $io The I/O. * * @return int The status code. */ public function handle(Args $args, IO $io) { $path = Path::makeAbsolute($args->getArgument('path'), $this->currentPath); $resources = $this->repo->find($path); if (!count($resources)) { $io->errorLine("No resources found for path {$path}"); return 1; } foreach ($resources as $resource) { if ($resource instanceof BodyResource) { $io->writeLine($resource->getBody()); } } return 0; }
/** * @expectedException \RuntimeException * @expectedExceptionMessage No search criteria specified */ public function testFailIfNoCriteria() { $args = self::$findCommand->parseArgs(new StringArgs('')); $this->repo->expects($this->never())->method('find'); $this->discovery->expects($this->never())->method('findByType'); $this->handler->handle($args, $this->io); }
/** * Returns the bound resources. * * @return ResourceCollection The bound resources. */ public function getResources() { if (null === $this->repo) { throw new NotInitializedException('The repository of the resource binding must be set before accessing resources.'); } return $this->repo->find($this->query, $this->language); }
/** * Loads the complete collection. */ private function load() { foreach ($this->resources as $key => $resource) { if (!$resource instanceof Resource) { $this->resources[$key] = $this->repo->get($resource); } } $this->loaded = true; }
/** * Finds the resources for a given path pattern. * * @param string $query The resource query. * @param string $language The language of the query. * * @return string[] An array of short resource class names indexed by * the resource path. */ private function findByPath($query, $language = 'glob') { $matches = array(); $query = '/' . ltrim($query, '/'); foreach ($this->repo->find($query, $language) as $resource) { $matches[$resource->getPath()] = StringUtil::getShortClassName(get_class($resource)); } return $matches; }
/** * {@inheritdoc} */ public function findByPath($resourcePath, $typeName = null) { if (!$this->repo->contains($resourcePath)) { throw ResourceNotFoundException::forPath($resourcePath); } if (null === $typeName) { return $this->findAllForPath($resourcePath); } return $this->findByPathAndType($resourcePath, $typeName); }
protected function setUp() { $tempnam = tempnam(sys_get_temp_dir(), 'ResourceStreamWrapperTest'); file_put_contents($tempnam, self::FILE_CONTENTS); $this->repo = $this->getMock('Puli\\Repository\\Api\\ResourceRepository'); $this->repo->expects($this->any())->method('get')->will($this->returnCallback(function ($path) use($tempnam) { if ('/webmozart/puli/file' === $path) { return new FileResource($tempnam, '/webmozart/puli/file'); } if ('/webmozart/puli/non-local' === $path) { return new TestFile('/webmozart/puli/non-local'); } if ('/webmozart/puli/dir' === $path) { return new TestDirectory('/webmozart/puli/dir', array(new TestFile('/webmozart/puli/dir/file1'), new TestFile('/webmozart/puli/dir/file2'))); } if ('/webmozart/puli/dir2' === $path) { return new TestDirectory('/webmozart/puli/dir2', array(new TestFile('/webmozart/puli/dir2/.dotfile'), new TestFile('/webmozart/puli/dir2/foo'), new TestFile('/webmozart/puli/dir2/bar'))); } throw new ResourceNotFoundException(); })); }
/** * @param $templatePath * @return null|string * @throws \Exception */ private function getRealTemplatePath($templatePath) { if ($this->repo instanceof ResourceRepository) { if ($this->repo->contains($templatePath)) { return $this->repo->get($templatePath)->getFilesystemPath(); } } if (file_exists($templatePath)) { return $templatePath; } throw new \Exception("Template path not found in repository or on filesystem: {$templatePath}, in PhpTemplate"); }
/** * Returns a full path for a given Puli path. * * @param mixed $path The Puli path to locate * @param string $currentPath The current path * @param bool $first Whether to return the first occurrence or * an array of file names * * @return string|array The full path to the file|An array of file paths * * @throws InvalidArgumentException When the path is not found */ public function locate($path, $currentPath = null, $first = true) { // Accept actual file paths if (file_exists($path)) { return $path; } if (null !== $currentPath && file_exists($currentPath . '/' . $path)) { throw new RuntimeException(sprintf('You tried to load the file "%s" using a relative path. ' . 'This functionality is not supported due to a limitation in ' . 'Symfony, because then this file cannot be overridden anymore. ' . 'Please pass the absolute Puli path instead.', $path)); } try { $resource = $this->repo->get($path); while ($resource instanceof LinkResource) { $resource = $this->repo->get($resource->getTargetPath()); } if (!$resource instanceof FilesystemResource) { throw new InvalidArgumentException(sprintf('The file "%s" is not a local file.', $path)); } return $first ? $resource->getFilesystemPath() : array($resource->getFilesystemPath()); } catch (ResourceNotFoundException $e) { throw new InvalidArgumentException(sprintf('The file "%s" could not be found.', $path), 0, $e); } }
private function loadResourcesFromRepo() { $glob = VarUtils::resolve($this->glob, $this->getVars(), $this->getValues()); // Lazily load the resources. If the resources are stored in a database, // we only want to fetch them if really necessary. foreach ($this->repo->find($glob) as $resource) { // Ignore non-file resources if (!$resource instanceof FileResource) { continue; } $this->add(new PuliResourceAsset($resource)); } $this->loaded = true; }
/** * {@inheritdoc} */ public function prepareInstallation(AssetMapping $mapping) { $glob = $mapping->getGlob(); $serverName = $mapping->getServerName(); $resources = $this->repo->find($glob); if ($resources->isEmpty()) { throw NotInstallableException::noResourceMatches($glob); } if (!$this->servers->contains($serverName)) { throw NotInstallableException::serverNotFound($serverName); } $server = $this->servers->get($serverName); $installerName = $server->getInstallerName(); if (!$this->installerManager->hasInstallerDescriptor($installerName)) { throw NotInstallableException::installerNotFound($installerName); } $installerDescriptor = $this->installerManager->getInstallerDescriptor($installerName); $installer = $this->loadInstaller($installerDescriptor); $rootDir = $this->context->getRootDirectory(); $params = new InstallationParams($installer, $installerDescriptor, $resources, $mapping, $server, $rootDir); $installer->validateParams($params); return $params; }
/** * {@inheritdoc} */ protected function resolvePath($path, $checkPath = false) { // Empty path? WTF I don't want to deal with this. if ('' === $path) { return $path; } // Absolute paths are fine if ('/' === $path[0]) { return $path; } // Resolve relative paths $absolutePath = Path::makeAbsolute($path, $this->currentDir); // With other loaders enabled, it may happen that a path looks like // a relative path, but is none, for example // "AcmeBlogBundle::index.html.twig", which doesn't start with a forward // slash. For this reason, if $checkPath is true, we should only resolve // paths if they actually exist in the repository. if (!$checkPath || $this->repo->contains($absolutePath)) { return $absolutePath; } // Return the path unchanged if $checkPath and the path does not exist return $path; }
/** * @param string $path The path of the DAL to load. * @param string[] $stack The stack of paths that have been loaded since the current call. * * @throws \Exception * * @return AbstractDal */ private function doLoad($path, array $stack) { if (!isset($this->layers[$path])) { if ($this->isDebug || !file_exists($this->getFilename($path))) { $file = $this->repository->get($path); if (!$file instanceof FileResource) { throw new \Exception(sprintf('The path "%s" should reference a file.', $path)); } $ast = $this->syntax->read($file->getBody(), ['path' => $path]); $compiler = new Compiler(); $compiler->compile($ast['definition']); $this->filesystem->dumpFile($this->getMetaFilename($path), serialize($ast['metadata'])); $this->filesystem->dumpFile($this->getFilename($path), $compiler->getSource()); } $this->layers[$path] = $this->loadLayerAndCheck($path, $stack); } return $this->layers[$path]; }
private function parseRelativeInput($input, $currentDir, array $roots, array $vars, array $values) { // If the Puli resource relative to the current directory exists, // prefer to return that $inputWithoutVars = VarUtils::resolve($input, $vars, $values); if (null !== $currentDir && $this->repo->contains(Path::makeAbsolute($inputWithoutVars, $currentDir))) { $asset = $this->createPuliAsset(Path::makeAbsolute($input, $currentDir), $vars); $asset->setValues($values); return $asset; } // Otherwise check whether the relative path can be found in the roots foreach ($roots as $root) { if (is_file(Path::makeAbsolute($inputWithoutVars, $root))) { $absolute = Path::makeAbsolute($input, $root); $asset = $this->createFileAsset($absolute, $root, $input, $vars); $asset->setValues($values); return $asset; } } throw new RuntimeException(sprintf('The asset "%s" could not be found. Searched the Puli directory %s ' . 'and the file system directories %s.', $inputWithoutVars, $currentDir, implode(', ', $roots))); }
private function loadModule(ContainerBuilder $builder, ResourceRepository $resources, $module) { // Load all config files in the config/ directory foreach ($resources->find('/' . $module . '/config/*.php') as $resource) { if ($resource instanceof FilesystemResource) { $builder->addDefinitions($resource->getFilesystemPath()); } } // Load the environment-specific config if it exists $envConfig = '/' . $module . '/config/env/' . $this->environment . '.php'; if ($resources->contains($envConfig)) { $resource = $resources->get($envConfig); if ($resource instanceof FilesystemResource) { $builder->addDefinitions($resource->getFilesystemPath()); } } }
/** * {@inheritdoc} */ public function getResources() { return $this->repo->find($this->getQuery()); }