makeAbsolute() public static method

Usually, the relative path is appended to the given base path. Dot segments ("." and "..") are removed/collapsed and all slashes turned into forward slashes. php echo Path::makeAbsolute("../style.css", "/webmozart/puli/css"); => /webmozart/puli/style.css If an absolute path is passed, that path is returned unless its root directory is different than the one of the base path. In that case, an exception is thrown. php Path::makeAbsolute("/style.css", "/webmozart/puli/css"); => /style.css Path::makeAbsolute("C:/style.css", "C:/webmozart/puli/css"); => C:/style.css Path::makeAbsolute("C:/style.css", "/webmozart/puli/css"); InvalidArgumentException If the base path is not an absolute path, an exception is thrown. The result is a canonical path.
Since: 1.0 Added method.
Since: 2.0 Method now fails if $path or $basePath is not a string.
Since: 2.2.2 Method does not fail anymore of $path and $basePath are absolute, but on different partitions.
public static makeAbsolute ( string $path, string $basePath ) : string
$path string A path to make absolute.
$basePath string An absolute base path.
return string An absolute path in canonical form.
 /**
  * {@inheritdoc}
  */
 public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
 {
     Assert::keyExists($options, 'root-dir', 'The "root-dir" option is missing.');
     $options = array_replace_recursive(self::$defaultOptions, $options);
     if (!isset($options['path'])) {
         $options['path'] = $targetMethod->getClass()->getDirectory() . '/path-mappings.json';
     }
     Assert::stringNotEmpty($options['path'], 'The "path" option should be a non-empty string. Got: %s');
     Assert::stringNotEmpty($options['root-dir'], 'The "root-dir" option should be a non-empty string. Got: %s');
     Assert::boolean($options['optimize'], 'The "optimize" option should be a boolean. Got: %s');
     Assert::isArray($options['change-stream'], 'The "change-stream" option should be an array. Got: %s');
     $path = Path::makeAbsolute($options['path'], $options['root-dir']);
     $relPath = Path::makeRelative($path, $targetMethod->getClass()->getDirectory());
     $relBaseDir = Path::makeRelative($options['root-dir'], $targetMethod->getClass()->getDirectory());
     $escPath = '__DIR__.' . var_export('/' . $relPath, true);
     $escBaseDir = $relBaseDir ? '__DIR__.' . var_export('/' . $relBaseDir, true) : '__DIR__';
     if ($options['optimize']) {
         $streamGenerator = $generatorRegistry->getServiceGenerator(GeneratorRegistry::CHANGE_STREAM, $options['change-stream']['type']);
         $streamOptions = $options['change-stream'];
         $streamOptions['root-dir'] = $options['root-dir'];
         $streamGenerator->generateNewInstance('stream', $targetMethod, $generatorRegistry, $streamOptions);
         $targetMethod->getClass()->addImport(new Import('Puli\\Repository\\OptimizedJsonRepository'));
         $targetMethod->addBody(sprintf('$%s = new OptimizedJsonRepository(%s, %s, false, $stream);', $varName, $escPath, $escBaseDir));
     } else {
         $targetMethod->getClass()->addImport(new Import('Puli\\Repository\\JsonRepository'));
         $targetMethod->addBody(sprintf('$%s = new JsonRepository(%s, %s, true);', $varName, $escPath, $escBaseDir));
     }
 }
示例#2
0
 /**
  * {@inheritdoc}
  */
 public function installResource(Resource $resource, InstallationParams $params)
 {
     $targetPath = Path::makeAbsolute($params->getTargetLocation(), $params->getRootDirectory());
     if (!file_exists($targetPath)) {
         mkdir($targetPath, 0777, true);
     }
     $repoPath = $params->getWebPathForResource($resource);
     $parameterValues = $params->getParameterValues();
     $relative = !isset($parameterValues['relative']) || $parameterValues['relative'];
     $filesystemRepo = new FilesystemRepository($targetPath, $this->symlinks, $relative);
     if ('/' === $repoPath) {
         foreach ($resource->listChildren() as $child) {
             $name = $child->getName();
             // If the resource is not attached, the name is empty
             if (!$name && $child instanceof FilesystemResource) {
                 $name = Path::getFilename($child->getFilesystemPath());
             }
             if ($name) {
                 $filesystemRepo->remove($repoPath . '/' . $name);
             }
         }
     } else {
         $filesystemRepo->remove($repoPath);
     }
     $filesystemRepo->add($repoPath, $resource);
 }
    /**
     * {@inheritdoc}
     */
    public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
    {
        Assert::keyExists($options, 'rootDir', 'The "rootDir" option is missing.');
        $options = array_replace(self::$defaultOptions, $options);
        if (!isset($options['path'])) {
            $options['path'] = $targetMethod->getClass()->getDirectory() . '/repository';
        }
        Assert::string($options['path'], 'The "path" option should be a string. Got: %s');
        Assert::string($options['rootDir'], 'The "rootDir" option should be a string. Got: %s');
        Assert::boolean($options['symlink'], 'The "symlink" option should be a boolean. Got: %s');
        $path = Path::makeAbsolute($options['path'], $options['rootDir']);
        $relPath = Path::makeRelative($path, $targetMethod->getClass()->getDirectory());
        $escPath = $relPath ? '__DIR__.' . var_export('/' . $relPath, true) : '__DIR__';
        if ($relPath) {
            $targetMethod->addBody(<<<EOF
if (!file_exists({$escPath})) {
    mkdir({$escPath}, 0777, true);
}

EOF
);
        }
        $targetMethod->getClass()->addImport(new Import('Puli\\Repository\\FilesystemRepository'));
        $targetMethod->addBody(sprintf('$%s = new FilesystemRepository(%s, %s);', $varName, $escPath, var_export($options['symlink'], true)));
    }
示例#4
0
 /**
  * {@inheritdoc}
  */
 public function installResource(PuliResource $resource, InstallationParams $params)
 {
     $documentRoot = Path::makeAbsolute($params->getDocumentRoot(), $params->getRootDirectory());
     if (!file_exists($documentRoot)) {
         mkdir($documentRoot, 0777, true);
     }
     $serverPath = $params->getServerPathForResource($resource);
     $parameterValues = $params->getParameterValues();
     $relative = !isset($parameterValues['relative']) || $parameterValues['relative'];
     $filesystemRepo = new FilesystemRepository($documentRoot, $this->symlinks, $relative);
     if ('/' === $serverPath) {
         foreach ($resource->listChildren() as $child) {
             $name = $child->getName();
             // If the resource is not attached, the name is empty
             if (!$name && $child instanceof FilesystemResource) {
                 $name = Path::getFilename($child->getFilesystemPath());
             }
             if ($name) {
                 $filesystemRepo->remove($serverPath . '/' . $name);
             }
         }
     } else {
         $filesystemRepo->remove($serverPath);
     }
     // Don't attach the original resource to the repository we just created
     $filesystemRepo->add($serverPath, clone $resource);
 }
示例#5
0
 /**
  * {@inheritdoc}
  */
 public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
 {
     Assert::keyExists($options, 'root-dir', 'The "root-dir" option is missing.');
     $options = array_replace(self::$defaultOptions, $options);
     Assert::stringNotEmpty($options['path'], 'The "path" option should be a non-empty string. Got: %s');
     Assert::stringNotEmpty($options['root-dir'], 'The "root-dir" option should be a non-empty string. Got: %s');
     Assert::boolean($options['serialize-strings'], 'The "serialize-strings" option should be a boolean. Got: %s');
     Assert::boolean($options['serialize-arrays'], 'The "serialize-arrays" option should be a boolean. Got: %s');
     Assert::boolean($options['escape-slash'], 'The "escape-slash" option should be a boolean. Got: %s');
     Assert::boolean($options['pretty-print'], 'The "pretty-print" option should be a boolean. Got: %s');
     $path = Path::makeAbsolute($options['path'], $options['root-dir']);
     $relPath = Path::makeRelative($path, $targetMethod->getClass()->getDirectory());
     $flags = array();
     if (!$options['serialize-strings']) {
         $flags[] = 'JsonFileStore::NO_SERIALIZE_STRINGS';
     }
     if (!$options['serialize-arrays']) {
         $flags[] = 'JsonFileStore::NO_SERIALIZE_ARRAYS';
     }
     if (!$options['serialize-arrays']) {
         $flags[] = 'JsonFileStore::NO_ESCAPE_SLASH';
     }
     if ($options['pretty-print']) {
         $flags[] = 'JsonFileStore::PRETTY_PRINT';
     }
     $targetMethod->getClass()->addImport(new Import('Webmozart\\KeyValueStore\\JsonFileStore'));
     $targetMethod->addBody(sprintf('$%s = new JsonFileStore(%s%s%s);', $varName, $flags ? "\n    " : '', '__DIR__.' . var_export('/' . $relPath, true), $flags ? ",\n    " . implode("\n        | ", $flags) . "\n" : ''));
 }
示例#6
0
 /**
  * Handles the "package --add" command.
  *
  * @param Args $args The console arguments.
  *
  * @return int The status code.
  */
 public function handleAdd(Args $args)
 {
     $packageName = $args->getArgument('name');
     $installPath = Path::makeAbsolute($args->getArgument('path'), getcwd());
     $installer = $args->getOption('installer');
     $this->packageManager->installPackage($installPath, $packageName, $installer);
     return 0;
 }
示例#7
0
 /**
  * Concat two path member only if the second is not absolute
  * and make the result relative to the last parameter.
  */
 public static function makeConfigPathRelative($config_path, $option_path, $current_path = null)
 {
     $current_path = $current_path === null ? getcwd() : $current_path;
     $config_path = Path::makeAbsolute($config_path, $current_path);
     $absolute_path = Path::makeAbsolute($option_path, $config_path);
     $relative_path = Path::makeRelative($absolute_path, $current_path);
     return $relative_path === '' ? '.' : $relative_path;
 }
示例#8
0
 /**
  * Handles the "package --install" command.
  *
  * @param Args $args The console arguments.
  *
  * @return int The status code.
  */
 public function handleInstall(Args $args)
 {
     $packageName = $args->getArgument('name');
     $installPath = Path::makeAbsolute($args->getArgument('path'), getcwd());
     $installer = $args->getOption('installer');
     $env = $args->isOptionSet('dev') ? Environment::DEV : Environment::PROD;
     $this->packageManager->installPackage($installPath, $packageName, $installer, $env);
     return 0;
 }
 /**
  * {@inheritdoc}
  */
 public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
 {
     Assert::keyExists($options, 'rootDir', 'The "rootDir" option is missing.');
     $options = array_replace(self::$defaultOptions, $options);
     $path = Path::makeAbsolute($options['path'], $options['rootDir']);
     $relPath = Path::makeRelative($path, $targetMethod->getClass()->getDirectory());
     $targetMethod->getClass()->addImport(new Import('Webmozart\\KeyValueStore\\JsonFileStore'));
     $targetMethod->addBody(sprintf('$%s = new JsonFileStore(%s, %s);', $varName, '__DIR__.' . var_export('/' . $relPath, true), $options['cache'] ? 'true' : 'false'));
 }
示例#10
0
 /**
  * @param string $path
  * @param string|null $configFile
  * @param AbstractLogger $logger
  * @return Result
  */
 public function analyse($path, $configFile = null, AbstractLogger $logger = null)
 {
     $logger = $logger ?: new NullLogger();
     $path = Path::makeAbsolute($path, getcwd());
     if (!$configFile) {
         $configFile = Path::join([$path, '.simpspector.yml']);
     }
     $config = $this->loader->load($configFile);
     return $this->executor->run($path, $config, $logger);
 }
示例#11
0
 /**
  * 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;
 }
示例#12
0
 /**
  * {@inheritdoc}
  */
 public function retrieve($uri)
 {
     if (isset($this->mappings[$uri])) {
         $uri = $this->mappings[$uri];
         if (Path::isLocal($uri)) {
             $uri = 'file://' . ($this->baseDir ? Path::makeAbsolute($uri, $this->baseDir) : $uri);
         }
         $this->lastUsedRetriever = $this->filesystemRetriever;
         return $this->filesystemRetriever->retrieve($uri);
     }
     $this->lastUsedRetriever = $this->fallbackRetriever;
     return $this->fallbackRetriever->retrieve($uri);
 }
示例#13
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;
 }
 /**
  * {@inheritdoc}
  */
 public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
 {
     Assert::keyExists($options, 'root-dir', 'The "root-dir" option is missing.');
     if (!isset($options['path'])) {
         $options['path'] = $targetMethod->getClass()->getDirectory() . '/change-stream.json';
     }
     Assert::stringNotEmpty($options['root-dir'], 'The "root-dir" option should be a non-empty string. Got: %s');
     Assert::stringNotEmpty($options['path'], 'The "path" option should be a non-empty string. Got: %s');
     $path = Path::makeAbsolute($options['path'], $options['root-dir']);
     $relPath = Path::makeRelative($path, $targetMethod->getClass()->getDirectory());
     $escPath = '__DIR__.' . var_export('/' . $relPath, true);
     $targetMethod->getClass()->addImport(new Import('Puli\\Repository\\ChangeStream\\JsonChangeStream'));
     $targetMethod->addBody(sprintf('$%s = new JsonChangeStream(%s);', $varName, $escPath));
 }
示例#15
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;
 }
示例#16
0
 public function def($glob = 'src/**.php')
 {
     $buildOk = true;
     echo "Linting {$glob}\n";
     $files = Glob::glob(Path::makeAbsolute($glob, getcwd()));
     foreach ($files as $file) {
         $output = '';
         $returnValue = $this->runCommandSilent('php', ['-l', $file], $output);
         if ($returnValue) {
             echo "Linting error: {$output}\n";
             $buildOk = false;
         }
     }
     return $buildOk;
 }
示例#17
0
 /**
  * {@inheritdoc}
  */
 public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
 {
     Assert::keyExists($options, 'root-dir', 'The "root-dir" option is missing.');
     if (!isset($options['path'])) {
         $options['path'] = $targetMethod->getClass()->getDirectory() . '/bindings.json';
     }
     Assert::stringNotEmpty($options['root-dir'], 'The "root-dir" option should be a non-empty string. Got: %s');
     Assert::stringNotEmpty($options['path'], 'The "path" option should be a non-empty string. Got: %s');
     $path = Path::makeAbsolute($options['path'], $options['root-dir']);
     $relPath = Path::makeRelative($path, $targetMethod->getClass()->getDirectory());
     $escPath = '__DIR__.' . var_export('/' . $relPath, true);
     $targetMethod->getClass()->addImport(new Import('Puli\\Discovery\\JsonDiscovery'));
     $targetMethod->getClass()->addImport(new Import('Puli\\Discovery\\Binding\\Initializer\\ResourceBindingInitializer'));
     $targetMethod->addBody(sprintf("\$%s = new JsonDiscovery(%s, array(\n    new ResourceBindingInitializer(\$repo),\n));", $varName, $escPath));
 }
示例#18
0
 public static function filterReferences($content, $callback)
 {
     return CssUtils::filterReferences($content, function ($matches) use($callback) {
         // The referenced path is a repository path
         // e.g. "/webmozart/puli/images/bg.png"
         $referencedPath = $matches['url'];
         // Ignore empty URLs
         if ('' === $referencedPath) {
             return $matches[0];
         }
         // Ignore non-local paths
         if (!Path::isLocal($referencedPath)) {
             return $matches[0];
         }
         // Ignore "data:" URLs
         if (0 === strpos($referencedPath, 'data:')) {
             return $matches[0];
         }
         // If the referenced path is not absolute, resolve it relative to
         // the directory of the source file
         if (!Path::isAbsolute($referencedPath)) {
             $referencedPath = Path::makeAbsolute($referencedPath, $repoDir);
         }
         // The referenced asset must be known
         if (!array_key_exists($referencedPath, $pathMap)) {
             throw new AssetException(sprintf('The asset "%s" referenced in "%s" could not be found.', $matches['url'], $repoPath));
         }
         // The target path of the referenced file must be set
         if (!$pathMap[$referencedPath]) {
             throw new AssetException(sprintf('The referenced path "%s" in "%s" cannot be resolved, because ' . 'the target path of "%s" is not set.', $matches['url'], $repoPath, $matches['url']));
         }
         // The target path of the source file must be set
         if (!$targetPath) {
             throw new AssetException(sprintf('The referenced path "%s" in "%s" cannot be resolved, because ' . 'the target path of "%s" is not set.', $matches['url'], $repoPath, $repoPath));
         }
         // Get the relative path from the source directory to the reference
         // e.g. "/css/style.css" + "/images/bg.png" = "../images/bg.png"
         $relativePath = Path::makeRelative($pathMap[$referencedPath], $targetDir);
         return str_replace($matches['url'], $relativePath, $matches[0]);
     });
 }
 /**
  * {@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;
 }
示例#20
0
 public function handleUpdate(Args $args)
 {
     $flags = $args->isOptionSet('force') ? AssetManager::OVERRIDE | AssetManager::IGNORE_SERVER_NOT_FOUND : AssetManager::OVERRIDE;
     $mappingToUpdate = $this->getMappingByUuidPrefix($args->getArgument('uuid'));
     $path = $mappingToUpdate->getGlob();
     $serverPath = $mappingToUpdate->getServerPath();
     $serverName = $mappingToUpdate->getServerName();
     if ($args->isOptionSet('path')) {
         $path = Path::makeAbsolute($args->getOption('path'), $this->currentPath);
     }
     if ($args->isOptionSet('server-path')) {
         $serverPath = $args->getOption('server-path');
     }
     if ($args->isOptionSet('server')) {
         $serverName = $args->getOption('server');
     }
     $updatedMapping = new AssetMapping($path, $serverName, $serverPath, $mappingToUpdate->getUuid());
     if ($this->mappingsEqual($mappingToUpdate, $updatedMapping)) {
         throw new RuntimeException('Nothing to update.');
     }
     $this->assetManager->addRootAssetMapping($updatedMapping, $flags);
     return 0;
 }
示例#21
0
 protected static function configureDir(Event $event, $name, $defaultInSkeleton, $prefix = '', $chmod = true)
 {
     $default = static::getOption($event, $name . '-dir', $defaultInSkeleton);
     $validator = function ($value) use($prefix, $name) {
         if ($prefix) {
             $basePath = Path::makeAbsolute($prefix, getcwd());
             $path = Path::makeAbsolute($value, $basePath);
             if (!Path::isBasePath($basePath, $path)) {
                 throw new \RuntimeException("The {$name} directory must be inside the {$prefix} directory.");
             }
         }
         return Path::canonicalize($value);
     };
     $default = $validator($default);
     $relative = $prefix ? '<comment>' . $prefix . '</comment>' : 'project root';
     $question = sprintf('<info>Where do you want your <comment>%s</comment> directory? (relative to %s) [default: <comment>%s</comment>] </info>', $name, $relative, $default);
     $dir = $event->getIO()->askAndValidate($question, $validator, null, $default);
     $fs = new Filesystem();
     $origin = $prefix . $defaultInSkeleton;
     $target = $prefix . $dir;
     $dirMode = static::configureDirMode($event);
     if ($dir !== $defaultInSkeleton) {
         $event->getIO()->writeError(sprintf('Moving <info>%s</info> directory from <info>%s</info> to <info>%s</info>', $name, $origin, $target));
         $fs->mkdir(dirname($target));
         // ensure parent directory exists
         $fs->rename($origin, $target);
     }
     if ($chmod) {
         $it = (new Finder())->directories()->in($target)->append([$target]);
         $fs->chmod($it, $dirMode);
     }
     return $target;
 }
 /**
  * Filters an asset just before it's dumped.
  *
  * @param AssetInterface $asset An asset
  */
 public function filterDump(AssetInterface $asset)
 {
     if (!$asset instanceof PuliAsset) {
         return;
     }
     $pathMap = array();
     // Get a map of repository paths to target paths
     // e.g. "/webmozart/puli/images/bg.png" => "/images/bg.png"
     foreach ($this->am->getNames() as $name) {
         $this->extractTargetPaths($this->am->get($name), $pathMap);
     }
     // Remember the repository dir of the current resource
     $repoPath = $asset->getSourcePath();
     $repoDir = Path::getDirectory($repoPath);
     // Get the target directory of the current resource
     // e.g. "css"
     $targetPath = $asset->getTargetPath();
     $targetDir = Path::getDirectory($targetPath);
     // Convert to an absolute path so that we can create a proper
     // relative path later on
     // e.g. "/css"
     if (!Path::isAbsolute($targetDir)) {
         $targetDir = '/' . $targetDir;
     }
     $content = CssUtils::filterReferences($asset->getContent(), function ($matches) use($pathMap, $repoDir, $repoPath, $targetDir, $targetPath) {
         // The referenced path is a repository path
         // e.g. "/webmozart/puli/images/bg.png"
         $referencedPath = $matches['url'];
         // Ignore empty URLs
         if ('' === $referencedPath) {
             return $matches[0];
         }
         // Ignore non-local paths
         if (!Path::isLocal($referencedPath)) {
             return $matches[0];
         }
         // Ignore "data:" URLs
         if (0 === strpos($referencedPath, 'data:')) {
             return $matches[0];
         }
         // If the referenced path is not absolute, resolve it relative to
         // the directory of the source file
         if (!Path::isAbsolute($referencedPath)) {
             $referencedPath = Path::makeAbsolute($referencedPath, $repoDir);
         }
         // The referenced asset must be known
         if (!array_key_exists($referencedPath, $pathMap)) {
             throw new AssetException(sprintf('The asset "%s" referenced in "%s" could not be found.', $referencedPath, $repoPath));
         }
         // The target path of the referenced file must be set
         if (!$pathMap[$referencedPath]) {
             throw new AssetException(sprintf('The referenced path "%s" in "%s" cannot be resolved, because ' . 'the target path of "%s" is not set.', $matches['url'], $repoPath, $matches['url']));
         }
         // The target path of the source file must be set
         if (!$targetPath) {
             throw new AssetException(sprintf('The referenced path "%s" in "%s" cannot be resolved, because ' . 'the target path of "%s" is not set.', $matches['url'], $repoPath, $repoPath));
         }
         // Get the relative path from the source directory to the reference
         // e.g. "/css/style.css" + "/images/bg.png" = "../images/bg.png"
         $relativePath = Path::makeRelative($pathMap[$referencedPath], $targetDir);
         return str_replace($matches['url'], $relativePath, $matches[0]);
     });
     $asset->setContent($content);
 }
示例#23
0
 /**
  * Prints the URL of a Puli path.
  *
  * @param string $path A Puli path.
  * @param IO     $io   The I/O.
  */
 private function printUrl($path, IO $io)
 {
     $path = Path::makeAbsolute($path, $this->currentPath);
     $io->writeLine($this->urlGenerator->generateUrl($path));
 }
示例#24
0
 /**
  * Loads a module for the given install info.
  *
  * @param InstallInfo $installInfo The install info.
  *
  * @return Module The module.
  */
 private function loadModule(InstallInfo $installInfo)
 {
     $installPath = Path::makeAbsolute($installInfo->getInstallPath(), $this->rootDir);
     $moduleFile = null;
     $loadError = null;
     try {
         $moduleFile = $this->loadModuleFile($installPath);
     } catch (InvalidConfigException $loadError) {
     } catch (UnsupportedVersionException $loadError) {
     } catch (FileNotFoundException $loadError) {
     } catch (NoDirectoryException $loadError) {
     }
     $loadErrors = $loadError ? array($loadError) : array();
     return new Module($moduleFile, $installPath, $installInfo, $loadErrors);
 }
示例#25
0
 public function postAutoloadDump(Event $event)
 {
     // Plugin has been uninstalled
     if (!file_exists(__FILE__)) {
         return;
     }
     if (!$this->initialized) {
         $this->initialize($event->getComposer(), $event->getIO());
     }
     // This method is called twice. Run it only once.
     if (!$this->runPostAutoloadDump) {
         return;
     }
     $this->runPostAutoloadDump = false;
     $io = $event->getIO();
     $compConfig = $event->getComposer()->getConfig();
     $vendorDir = $compConfig->get('vendor-dir');
     // On TravisCI, $vendorDir is a relative path. Probably an old Composer
     // build or something. Usually, $vendorDir should be absolute already.
     $vendorDir = Path::makeAbsolute($vendorDir, $this->rootDir);
     $autoloadFile = $vendorDir . '/autoload.php';
     $classMapFile = $vendorDir . '/composer/autoload_classmap.php';
     try {
         $factoryClass = $this->getConfigKey('factory.in.class');
         $factoryFile = $this->getConfigKey('factory.in.file');
     } catch (PuliRunnerException $e) {
         $this->printWarning($io, 'Could not load Puli configuration', $e);
         return;
     }
     $factoryFile = Path::makeAbsolute($factoryFile, $this->rootDir);
     $this->insertFactoryClassConstant($io, $autoloadFile, $factoryClass);
     $this->insertFactoryClassMap($io, $classMapFile, $vendorDir, $factoryClass, $factoryFile);
     $this->setBootstrapFile($io, $autoloadFile);
 }
示例#26
0
文件: Job.php 项目: guysyml/software
 public function try_file_filter()
 {
     if (!check_ajax_referer('my-wp-backup-fileFilter', 'nonce')) {
         wp_die(esc_html__('Nope! Security check failed!', 'my-wp-backup'));
     }
     if (!isset($_POST['filters'])) {
         // input var okay
         wp_die();
     }
     $filters = array_map('sanitize_text_field', preg_split("/\r\n|\n|\r/", $_POST['filters']));
     //input var okay;
     $excluded = array();
     /**
      * @param \SplFileInfo $file
      * @return bool True if you need to recurse or if the item is acceptable
      */
     $filter = function ($file) use($filters, &$excluded) {
         $filePath = $file->getPathname();
         $relativePath = substr($filePath, strlen(MyWPBackup::$info['root_dir']));
         if ($file->isDir()) {
             $relativePath .= '/';
         }
         foreach ($filters as $exclude) {
             if (Glob::match($filePath, Path::makeAbsolute($exclude, MyWPBackup::$info['root_dir']))) {
                 array_push($excluded, $relativePath);
                 return false;
             }
         }
         return true;
     };
     $files = new \RecursiveIteratorIterator(new RecursiveCallbackFilterIterator(new \RecursiveDirectoryIterator(MyWPBackup::$info['root_dir'], \RecursiveDirectoryIterator::SKIP_DOTS), $filter));
     iterator_to_array($files);
     wp_send_json($excluded);
 }
示例#27
0
 /**
  * @dataProvider provideAbsolutePathsWithDifferentRoots
  */
 public function testMakeAbsoluteDoesNotFailIfDifferentRoot($basePath, $absolutePath)
 {
     // If a path in partition D: is passed, but $basePath is in partition
     // C:, the path should be returned unchanged
     $this->assertSame(Path::canonicalize($absolutePath), Path::makeAbsolute($absolutePath, $basePath));
 }
示例#28
0
 /**
  * Check if target is linked and links to the given source.
  *
  * @return bool
  */
 public function targetLinksToSource()
 {
     if (!$this->targetIsLink()) {
         return FALSE;
     }
     $current_source = readlink($this->link);
     if (!Path::isAbsolute($current_source)) {
         $current_source = Path::makeAbsolute($current_source, dirname($this->link));
     }
     return $current_source == $this->source;
 }
示例#29
0
 /**
  * {@inheritdoc}
  */
 public function refreshFactoryClass($path = null, $className = null)
 {
     Assert::nullOrStringNotEmpty($path, 'The path to the generated factory file must be a non-empty string or null. Got: %s');
     Assert::nullOrStringNotEmpty($className, 'The class name of the generated factory must be a non-empty string or null. Got: %s');
     $path = Path::makeAbsolute($path ?: $this->config->get(Config::FACTORY_OUT_FILE), $this->rootDir);
     $className = $className ?: $this->config->get(Config::FACTORY_OUT_CLASS);
     if (!$this->config->get(Config::FACTORY_AUTO_GENERATE)) {
         return;
     }
     if (!file_exists($path)) {
         $this->generateFactoryClass($path, $className);
         return;
     }
     $rootModuleFile = $this->context->getRootModuleFile()->getPath();
     if (!file_exists($rootModuleFile)) {
         return;
     }
     // Regenerate file if the configuration has changed and
     // auto-generation is enabled
     clearstatcache(true, $rootModuleFile);
     $lastConfigChange = filemtime($rootModuleFile);
     $configFile = $this->context->getConfigFile() ? $this->context->getConfigFile()->getPath() : '';
     if (file_exists($configFile)) {
         clearstatcache(true, $configFile);
         $lastConfigChange = max(filemtime($configFile), $lastConfigChange);
     }
     clearstatcache(true, $path);
     $lastFactoryUpdate = filemtime($path);
     if ($lastConfigChange > $lastFactoryUpdate) {
         $this->generateFactoryClass($path, $className);
     }
 }
示例#30
0
文件: Puli.php 项目: xabbuh/manager
 /**
  * Starts the service container.
  */
 public function start()
 {
     if ($this->started) {
         throw new LogicException('Puli is already started');
     }
     if (null !== $this->rootDir) {
         $this->context = $this->createProjectContext($this->rootDir, $this->env);
         $bootstrapFile = $this->context->getConfig()->get(Config::BOOTSTRAP_FILE);
         // Run the project's bootstrap file to enable project-specific
         // autoloading
         if (null !== $bootstrapFile) {
             // Backup autoload functions of the PHAR
             $autoloadFunctions = spl_autoload_functions();
             foreach ($autoloadFunctions as $autoloadFunction) {
                 spl_autoload_unregister($autoloadFunction);
             }
             // Add project-specific autoload functions
             require_once Path::makeAbsolute($bootstrapFile, $this->rootDir);
             // Prepend autoload functions of the PHAR again
             // This is needed if the user specific autoload functions were
             // added with $prepend=true (as done by Composer)
             // Classes in the PHAR should always take precedence
             for ($i = count($autoloadFunctions) - 1; $i >= 0; --$i) {
                 spl_autoload_register($autoloadFunctions[$i], true, true);
             }
         }
     } else {
         $this->context = $this->createGlobalContext();
     }
     $this->dispatcher = $this->context->getEventDispatcher();
     $this->started = true;
     // Start plugins once the container is running
     if ($this->rootDir && $this->pluginsEnabled) {
         $this->activatePlugins();
     }
 }