During normalization, all slashes are replaced by forward slashes ("/").
Furthermore, all "." and ".." segments are removed as far as possible.
".." segments at the beginning of relative paths are not removed.
php
echo Path::canonicalize("\webmozart\puli\..\css\style.css");
=> /webmozart/css/style.css
echo Path::canonicalize("../css/./style.css");
=> ../css/style.css
This method is able to deal with both UNIX and Windows paths.
public static canonicalize ( string $path ) : string | ||
$path | string | A path string. |
return | string | The canonical path. |
public function __construct($baseDir = null, array $mappings = array(), UriRetrieverInterface $fallbackRetriever = null) { $this->baseDir = $baseDir ? Path::canonicalize($baseDir) : null; $this->mappings = $mappings; $this->filesystemRetriever = new FileGetContents(); $this->fallbackRetriever = $fallbackRetriever ?: $this->filesystemRetriever; }
/** * Creates the environment. * * @param string|null $homeDir The path to the home * directory or `null` if * none exists. * @param string $rootDir The path to the project's * root directory. * @param Config $config The configuration. * @param RootPackageFile $rootPackageFile The root package file. * @param ConfigFile $configFile The configuration file or * `null` if none exists. * @param EventDispatcherInterface $dispatcher The event dispatcher. */ public function __construct($homeDir, $rootDir, Config $config, RootPackageFile $rootPackageFile, ConfigFile $configFile = null, EventDispatcherInterface $dispatcher = null) { Assert::directory($rootDir, 'The root directory %s is not a directory.'); parent::__construct($homeDir, $config, $configFile, $dispatcher); $this->rootDir = Path::canonicalize($rootDir); $this->rootPackageFile = $rootPackageFile; }
/** * Creates the context. * * @param string|null $homeDir The path to the home directory * or `null` if none exists. * @param Config $config The configuration. * @param ConfigFile $configFile The configuration file or * `null` if none exists. * @param EventDispatcherInterface $dispatcher The event dispatcher. */ public function __construct($homeDir, Config $config, ConfigFile $configFile = null, EventDispatcherInterface $dispatcher = null) { Assert::nullOrDirectory($homeDir, 'The home directory %s is not a directory.'); $this->homeDir = $homeDir ? Path::canonicalize($homeDir) : null; $this->config = $config; $this->dispatcher = $dispatcher ?: new EventDispatcher(); $this->configFile = $configFile; }
/** * Creates the context. * * @param string|null $homeDir The path to the * home directory or * `null` if none * exists. * @param string $rootDir The path to the * project's root * directory. * @param Config $config The configuration. * @param RootModuleFile $rootModuleFile The root module * file. * @param ConfigFile|null $configFile The configuration * file or `null` if * none exists. * @param EventDispatcherInterface|null $dispatcher The event * dispatcher. * @param string $env The environment * that Puli is * running in. */ public function __construct($homeDir, $rootDir, Config $config, RootModuleFile $rootModuleFile, ConfigFile $configFile = null, EventDispatcherInterface $dispatcher = null, $env = Environment::DEV) { Assert::directory($rootDir, 'The root directory %s is not a directory.'); Assert::oneOf($env, Environment::all(), 'The environment must be one of: %2$s. Got: %s'); parent::__construct($homeDir, $config, $configFile, $dispatcher); $this->rootDir = Path::canonicalize($rootDir); $this->rootModuleFile = $rootModuleFile; $this->env = $env; }
/** * Return the path with the basePath prefix * if it has been set. * * @param string $path * * @return string */ protected function resolvePath($path) { Assert::stringNotEmpty($path, 'The path must be a non-empty string. Got: %s'); Assert::startsWith($path, '/', 'The path %s is not absolute.'); if ($this->basePath) { $path = $this->basePath . $path; } $path = Path::canonicalize($path); return $path; }
private function toAssetPath($filePath, $rootDirectory) { $canonicalRootDir = Path::canonicalize($rootDirectory); $asset = str_replace($canonicalRootDir, "", $filePath); // Strip leading slash if (substr($asset, 0, 1) === "/") { $asset = substr($asset, 1); } return $asset; }
private function phpunitConfig(array $argv) { if (count($argv) > 0) { $original = file_get_contents($argv[0]); $fix = Path::canonicalize('../' . $this->fs->relativePath(dirname($argv[0]))); } else { $original = '<phpunit />'; $fix = null; } return $this->phpunit_config_generator->generate($original, $fix); }
/** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.xml'); $container->setParameter('acme_php.domains_configurations', (array) $config['domains']); $container->setParameter('acme_php.certificate_dir', Path::canonicalize($config['certificate_dir'])); $container->setParameter('acme_php.certificate_authority', $config['certificate_authority']); $container->setParameter('acme_php.contact_email', $config['contact_email']); }
/** * * @param InputInterface $input * @param OutputInterface $output * @return int|null|void * @throws \Exception */ protected function execute(InputInterface $input, OutputInterface $output) { $logger = new ConsoleLogger($output); $from = Path::canonicalize($input->getArgument('from')); $to = Path::canonicalize($input->getArgument('to')); $fromResult = $this->getResult($from, $logger); $toResult = $this->getResult($to, $logger); $logger->writeln("generate diff"); $diff = $this->calculator->diff($fromResult, $toResult); $output->writeln($this->format($diff)); }
/** * @param string $path * @param array $config * @param AbstractLogger $logger * @return Result */ public function run($path, array $config, AbstractLogger $logger = null) { $path = Path::canonicalize($path); $logger = $logger ?: new NullLogger(); $event = new ExecutorEvent($path, $config, $logger); $this->eventDispatcher->dispatch(Events::PRE_EXECUTE, $event); $config = $event->getConfig(); $result = $this->executeGadgets($path, $config, $logger); $event = new ExecutorResultEvent($path, $config, $result, $logger); $this->eventDispatcher->dispatch(Events::POST_EXECUTE, $event); return $result; }
private function decode($json, $path = null) { $decoder = new JsonDecoder(); // We can't use realpath(), which doesn't work inside PHARs. // However, we want to display nice paths if the file is not found. $schema = $decoder->decodeFile(Path::canonicalize(__DIR__ . '/../../res/schema/package-schema-1.0.json')); $configSchema = $schema->properties->config; try { return $decoder->decode($json, $configSchema); } catch (ValidationFailedException $e) { throw new InvalidConfigException(sprintf("The configuration%s is invalid:\n%s", $path ? ' in ' . $path : '', $e->getErrorsAsString()), 0, $e); } catch (DecodingFailedException $e) { throw new InvalidConfigException(sprintf("The configuration%s could not be decoded:\n%s", $path ? ' in ' . $path : '', $e->getMessage()), $e->getCode(), $e); } }
/** * @param string $taskrc * @param string $taskData * @param array $rcOptions * @param string $bin * @throws TaskwarriorException */ public function __construct($taskrc = '~/.taskrc', $taskData = '~/.task', $rcOptions = [], $bin = 'task') { $this->bin = Path::canonicalize($bin); $this->taskrc = Path::canonicalize($taskrc); $this->taskData = Path::canonicalize($taskData); $this->rcOptions = array_merge(array('rc:' . $this->taskrc, 'rc.data.location=' . $this->taskData, 'rc.json.array=true', 'rc.json.depends.array=true', 'rc.confirmation=no'), $rcOptions); if (version_compare($this->version(), '2.5.0') < 0) { throw new TaskwarriorException(sprintf("Taskwarrior version %s isn't supported", $this->version())); } try { Assert::readable($this->taskrc); Assert::readable($this->taskData); Assert::writable($this->taskData); } catch (\InvalidArgumentException $e) { throw new TaskwarriorException($e->getMessage(), $e->getCode(), $e); } }
private function encodeFile($jsonData, $path) { if (!is_string($path) || !Path::isAbsolute($path)) { throw new IOException(sprintf('Cannot write "%s": Expected an absolute path.', $path)); } if (is_dir($path)) { throw new IOException(sprintf('Cannot write %s: Is a directory.', $path)); } $encoder = new JsonEncoder(); $encoder->setPrettyPrinting(true); $encoder->setEscapeSlash(false); $encoder->setTerminateWithLineFeed(true); $decoder = new JsonDecoder(); // We can't use realpath(), which doesn't work inside PHARs. // However, we want to display nice paths if the file is not found. $schema = $decoder->decodeFile(Path::canonicalize(__DIR__ . '/../../res/schema/package-schema-1.0.json')); $configSchema = $schema->properties->config; if (!is_dir($dir = Path::getDirectory($path))) { $filesystem = new Filesystem(); $filesystem->mkdir($dir); } $encoder->encodeFile($jsonData, $path, $configSchema); }
private function loadConfigFile($homeDir, Config $baseConfig) { if (null === $homeDir) { return null; } Assert::fileExists($homeDir, 'Could not load Puli context: The home directory %s does not exist.'); Assert::directory($homeDir, 'Could not load Puli context: The home directory %s is a file. Expected a directory.'); // Create a storage without the factory manager $configStorage = new ConfigFileStorage($this->getStorage(), $this->getConfigFileSerializer()); $configPath = Path::canonicalize($homeDir) . '/config.json'; try { return $configStorage->loadConfigFile($configPath, $baseConfig); } catch (FileNotFoundException $e) { // It's ok if no config.json exists. We'll work with // DefaultConfig instead return null; } }
public function testInsertFactoryClassIntoClassMap() { $listeners = $this->plugin->getSubscribedEvents(); $this->assertArrayHasKey(ScriptEvents::POST_AUTOLOAD_DUMP, $listeners); $listener = $listeners[ScriptEvents::POST_AUTOLOAD_DUMP]; $event = new CommandEvent(ScriptEvents::POST_AUTOLOAD_DUMP, $this->composer, $this->io); $this->io->expects($this->at(0))->method('write')->with('<info>Generating PULI_FACTORY_CLASS constant</info>'); $this->io->expects($this->at(1))->method('write')->with('<info>Registering Puli\\MyFactory with the class-map autoloader</info>'); $this->io->expects($this->never())->method('writeError'); $this->puliRunner->expects($this->at(0))->method('run')->with("config 'factory.in.class' --parsed")->willReturn("Puli\\MyFactory\n"); $this->puliRunner->expects($this->at(1))->method('run')->with("config 'factory.in.file' --parsed")->willReturn("My/Factory.php\n"); $this->plugin->{$listener}($event); $this->assertFileExists($this->tempDir . '/the-vendor/composer/autoload_classmap.php'); $classMap = (require $this->tempDir . '/the-vendor/composer/autoload_classmap.php'); $this->assertInternalType('array', $classMap); $this->assertArrayHasKey('Puli\\MyFactory', $classMap); $this->assertSame($this->tempDir . '/My/Factory.php', Path::canonicalize($classMap['Puli\\MyFactory'])); }
private function fixBootstrapPath($fix_path, DOMElement $node) { if ($node->hasAttribute('bootstrap')) { $node->setAttribute('bootstrap', Path::canonicalize($fix_path . '/' . $node->getAttribute('bootstrap'))); } }
/** * @return string */ public function getConfigFile() { return Path::canonicalize(__DIR__ . '/../Fixtures/simple.conf'); }
/** * Creates the context of a Puli project. * * The home directory is read from the context variable "PULI_HOME". * If this variable is not set, the home directory defaults to: * * * `$HOME/.puli` on Linux, where `$HOME` is the context variable * "HOME". * * `$APPDATA/Puli` on Windows, where `$APPDATA` is the context * variable "APPDATA". * * If none of these variables can be found, an exception is thrown. * * A .htaccess file is put into the home directory to protect it from web * access. * * @param string $rootDir The path to the project. * * @return ProjectContext The project context. */ private function createProjectContext($rootDir, $env) { Assert::fileExists($rootDir, 'Could not load Puli context: The root %s does not exist.'); Assert::directory($rootDir, 'Could not load Puli context: The root %s is a file. Expected a directory.'); $homeDir = self::parseHomeDirectory(); if (null !== $homeDir) { Assert::fileExists($homeDir, 'Could not load Puli context: The home directory %s does not exist.'); Assert::directory($homeDir, 'Could not load Puli context: The home directory %s is a file. Expected a directory.'); // Create a storage without the factory manager $configStorage = new ConfigFileStorage($this->getStorage(), $this->getConfigFileSerializer()); $configPath = Path::canonicalize($homeDir) . '/config.json'; $configFile = $configStorage->loadConfigFile($configPath, new DefaultConfig()); $baseConfig = $configFile->getConfig(); } else { $configFile = null; $baseConfig = new DefaultConfig(); } // Create a storage without the factory manager $packageFileStorage = new PackageFileStorage($this->getStorage(), $this->getPackageFileSerializer()); $rootDir = Path::canonicalize($rootDir); $rootFilePath = $this->rootDir . '/puli.json'; $rootPackageFile = $packageFileStorage->loadRootPackageFile($rootFilePath, $baseConfig); $config = new EnvConfig($rootPackageFile->getConfig()); return new ProjectContext($homeDir, $rootDir, $config, $rootPackageFile, $configFile, $this->dispatcher, $env); }
/** * Returns true if the path conatains any dotfile access * @param string $path * @return bool */ public static function containsDotfile($path) { $path = Path::canonicalize(Path::makeAbsolute($path, '/')); return preg_match('#/\\.#', $path) == 1; }
/** * Install the {@link http://onpub.com/pdfs/onpub_schema.pdf Onpub schema}. * * Calling this method will install the Onpub tables in the PDO-connected * database. * * @param int $version Optional argument to specify what version of the Onpub * schema to install. If NULL (the default), the latest version of the schema * will be added to the database. * @return mixed TRUE if the schema was successfully installed. An array * of PDOException objects will be returned if any errors occured. */ public function install($version = NULL) { $sqlfile = array(); $line = 0; $exceptions = array(); $sqlfile = file(Path::canonicalize(__DIR__ . '/../sql/createonpubtables-rev0.sql')); // advance past all comments while (strpos($sqlfile[$line], '--') !== FALSE) { $line++; while ($sqlfile[$line] == "\n") { $line++; } } for ($i = $line; $i < sizeof($sqlfile); $i++) { $query = ''; while (strpos($sqlfile[$i], ';') === FALSE) { $query .= $sqlfile[$i]; $i++; } $query .= $sqlfile[$i]; if ($i + 1 < sizeof($sqlfile)) { while ($sqlfile[$i + 1] == "\n") { $i++; } } $result = NULL; $result = $this->pdo->exec($query); try { OnpubDatabase::verifyExec($this->pdo, $result, FALSE); } catch (PDOException $e) { $exceptions[] = $e; } } if (sizeof($exceptions)) { return $exceptions; } return TRUE; }
/** * @return string */ public function getBackupDirectory() { return Path::canonicalize('~/.acmephp/backup'); }
/** * Splits a path into mount point and path. * * @param string $path The path to split. * * @return array An array with the mount point and the path. If no mount * point was found, both are `null`. */ private function splitPath($path) { Assert::stringNotEmpty($path, 'The path must be a non-empty string. Got: %s'); Assert::startsWith($path, '/', 'The path %s is not absolute.'); $path = Path::canonicalize($path); foreach ($this->repos as $mountPoint => $_) { if (Path::isBasePath($mountPoint, $path)) { // Special case "/": return the complete path if ('/' === $mountPoint) { return array($mountPoint, $path); } return array($mountPoint, substr($path, strlen($mountPoint))); } } return array(null, null); }
/** * @param string $basePath * @param string $path * * @return string */ private function canonicalize($basePath, $path) { return Path::canonicalize(Path::isAbsolute($path) ? $path : sprintf('%s/%s', $basePath, $path)); }
public function testFullProcess() { /* * Register */ $register = $this->application->find('register'); $registerTester = new CommandTester($register); $registerTester->execute(['command' => $register->getName(), 'email' => '*****@*****.**', '--server' => 'http://127.0.0.1:4000/directory', '--agreement' => 'http://*****:*****@acmephp.github.io']); $requestDisplay = $requestTest->getDisplay(); $this->assertContains('The SSL certificate was fetched successfully', $requestDisplay); $this->assertContains(Path::canonicalize(__DIR__ . '/Fixtures/local/master'), $requestDisplay); $this->assertFileExists(__DIR__ . '/../Cli/Fixtures/local/master/private/acmephp.com/private.pem'); $this->assertFileExists(__DIR__ . '/../Cli/Fixtures/local/master/private/acmephp.com/public.pem'); $this->assertFileExists(__DIR__ . '/../Cli/Fixtures/local/master/certs/acmephp.com/cert.pem'); $this->assertFileExists(__DIR__ . '/../Cli/Fixtures/local/master/certs/acmephp.com/combined.pem'); $this->assertFileExists(__DIR__ . '/../Cli/Fixtures/local/master/certs/acmephp.com/chain.pem'); $this->assertFileExists(__DIR__ . '/../Cli/Fixtures/local/master/certs/acmephp.com/fullchain.pem'); }
public function testSetFilePath() { $this->class->setFilePath(__DIR__ . '/../MyFile.php'); $this->assertSame(Path::canonicalize(__DIR__ . '/..'), $this->class->getDirectory()); $this->assertSame('MyFile.php', $this->class->getFileName()); }
/** * Return the path with the basePath prefix * if it has been set. * * @param string $path * * @return string */ protected function resolvePath($path) { $path = $this->sanitizePath($path); if ($this->basePath) { $path = $this->basePath . $path; } $path = Path::canonicalize($path); return $path; }
/** * @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)); }
/** * @return string */ public function getConfigFile() { return Path::canonicalize(__DIR__ . '/../Fixtures/sftp_nginxproxy.conf'); }
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; }
private function decodeFile($path) { $decoder = new JsonDecoder(); $validator = new JsonValidator(); // We can't use realpath(), which doesn't work inside PHARs. // However, we want to display nice paths if the file is not found. $schema = Path::canonicalize(__DIR__ . '/../../res/schema/package-schema-1.0.json'); if (!file_exists($path)) { throw FileNotFoundException::forPath($path); } try { $jsonData = $decoder->decodeFile($path); } catch (DecodingFailedException $e) { throw new InvalidConfigException(sprintf("The configuration in %s could not be decoded:\n%s", $path, $e->getMessage()), $e->getCode(), $e); } if (version_compare($jsonData->version, '1.0', '<')) { throw UnsupportedVersionException::versionTooLow($jsonData->version, '1.0', $path); } if (version_compare($jsonData->version, '1.0', '>')) { throw UnsupportedVersionException::versionTooHigh($jsonData->version, '1.0', $path); } $errors = $validator->validate($jsonData, $schema); if (count($errors) > 0) { throw new InvalidConfigException(sprintf("The configuration in %s is invalid:\n%s", $path, implode("\n", $errors))); } return $jsonData; }