/** * {@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" : '')); }
/** * Assure that matching version-specific command files are loaded and others are ignored. */ function testCommandVersionSpecific() { $path = Path::join(UNISH_SANDBOX, 'commandUnitCase'); $major = $this->drush_major_version(); $major_plus1 = $major + 1; // Write matched and unmatched files to the system search path. $files = array(Path::join($path, "{$major}.drush{$major}.inc"), Path::join($path, "drush{$major}/drush{$major}.drush.inc"), Path::join($path, "{$major_plus1}.drush{$major_plus1}.inc"), Path::join($path, "drush{$major_plus1}/drush{$major_plus1}.drush.inc")); $this->mkdir(Path::join($path, 'drush' . $major)); $this->mkdir(Path::join($path, 'drush' . $major_plus1)); foreach ($files as $file) { $contents = <<<EOD <?php // Written by Unish. This file is safe to delete. \$GLOBALS['unish_foo'][] = '{$file}'; EOD; $return = file_put_contents($file, $contents); } drush_set_context('DRUSH_INCLUDE', array($path)); drush_preflight(); $loaded = drush_commandfile_list(); $this->assertContains($files[0], $loaded); //Loaded a version-specific command file. $this->assertContains($files[1], $loaded); //Loaded a version-specific command directory. $this->assertNotContains($files[2], $loaded); //Did not load a mismatched version-specific command file. $this->assertNotContains($files[3], $loaded); //Did not load a a mismatched version-specific command directory. }
/** * 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; }
/** * {@inheritdoc} * * @throws \InvalidArgumentException * @throws \RuntimeException * @throws \LogicException * @throws BadMethodCallException */ public function load($resource, $type = null) { $path = $this->locator->locate($resource); $this->container->addResource(new FileResource($path)); $file = new JsonFile($path); $content = $file->read(); $extension = pathinfo($resource, PATHINFO_FILENAME); if (array_key_exists('parameters', $content)) { foreach ($content['parameters'] as $name => $parameter) { $this->container->setParameter($name, $parameter); } unset($content['parameters']); } if (array_key_exists('imports', $content)) { foreach ($content['imports'] as $import) { $importFilename = $import; if (!Path::isAbsolute($importFilename)) { $importFilename = Path::join([dirname($path), $import]); } $this->import($importFilename, null, false, $file); } unset($content['imports']); } $this->container->loadFromExtension($extension, $content); }
/** * {@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))); }
/** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('nanando'); $rootNode->children()->scalarNode('name')->defaultValue('nanbando')->end()->arrayNode('application')->addDefaultsIfNotSet()->children()->scalarNode('name')->defaultNull()->end()->scalarNode('version')->defaultNull()->end()->arrayNode('options')->prototype('scalar')->end()->end()->end()->end()->scalarNode('temp')->defaultValue(sys_get_temp_dir())->end()->arrayNode('backup')->useAttributeAsKey('name')->prototype('array')->children()->scalarNode('plugin')->end()->arrayNode('parameter')->prototype('variable')->end()->end()->end()->end()->end()->arrayNode('storage')->addDefaultsIfNotSet()->children()->scalarNode('local_directory')->defaultValue(Path::join([Path::getHomeDirectory(), 'nanbando']))->end()->scalarNode('remote_service')->end()->end()->end()->arrayNode('require')->prototype('variable')->end()->end()->arrayNode('presets')->prototype('array')->children()->scalarNode('application')->end()->scalarNode('version')->end()->arrayNode('options')->prototype('scalar')->end()->end()->arrayNode('backup')->prototype('array')->children()->scalarNode('plugin')->end()->arrayNode('parameter')->prototype('variable')->end()->end()->end()->end()->end()->end()->end()->end()->end(); return $treeBuilder; }
/** * Rebuild the puli dependencies for symfony container. */ protected function rebuild(InputInterface $input, OutputInterface $output) { $puli = new Puli(Path::join([getcwd(), NANBANDO_DIR])); $puli->start(); /** @var EmbeddedComposerInterface $embeddedComposer */ $embeddedComposer = $this->getApplication()->getEmbeddedComposer(); $packageManager = $puli->getPackageManager(); $io = new ConsoleIO($input, $output, $this->getApplication()->getHelperSet()); $composer = $embeddedComposer->createComposer($io); $installationManager = $composer->getInstallationManager(); $rootPackage = $composer->getPackage(); $repository = $composer->getRepositoryManager()->getLocalRepository(); $packages = []; foreach ($repository->getPackages() as $package) { $packages[$package->getName()] = $package; } foreach ($rootPackage->getRequires() as $require) { if (!array_key_exists($require->getTarget(), $packages)) { continue; } $packageManager->installPackage(Path::normalize($installationManager->getInstallPath($packages[$require->getTarget()])), $require->getTarget(), 'nanbando'); } $filesystem = new Filesystem(); $filesystem->remove(Path::join([getcwd(), NANBANDO_DIR, '.puli'])); $discoveryManager = $puli->getDiscoveryManager(); if (!$discoveryManager->hasRootTypeDescriptor('nanbando/bundle')) { $discoveryManager->addRootTypeDescriptor(new BindingTypeDescriptor(new BindingType('nanbando/bundle')), 0); } $discoveryManager->clearDiscovery(); $discoveryManager->buildDiscovery(); $filesystem = new Filesystem(); $filesystem->remove(Path::join([getcwd(), NANBANDO_DIR, 'app', 'cache'])); }
/** * {@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, '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)); } }
/** * Creates a new runner. * * @param string|null $binDir The path to Composer's "bin-dir". */ public function __construct($binDir = null) { $phpFinder = new PhpExecutableFinder(); if (!($php = $phpFinder->find())) { throw new RuntimeException('The "php" command could not be found.'); } $puliFinder = new ExecutableFinder(); // Search: // 1. in the current working directory // 2. in Composer's "bin-dir" // 3. in the system path $searchPath = array_merge(array(getcwd()), (array) $binDir); // Search "puli.phar" in the PATH and the current directory if (!($puli = $puliFinder->find('puli.phar', null, $searchPath))) { // Search "puli" in the PATH and Composer's "bin-dir" if (!($puli = $puliFinder->find('puli', null, $searchPath))) { throw new RuntimeException('The "puli"/"puli.phar" command could not be found.'); } } if (Path::hasExtension($puli, '.bat', true)) { $this->puli = $puli; } else { $this->puli = $php . ' ' . $puli; } }
/** * {@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); }
/** * 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; }
/** * 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; }
/** * {@inheritdoc} */ public function guess($path) { $ext = Path::getExtension($path, true); if ('' == trim($ext)) { return null; } return isset($this->mimes[$ext]) ? $this->mimes[$ext] : null; }
/** * 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; }
/** * 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; }
/** * 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 collect() : AssetCollection { $templates = []; $this->finder->files()->ignoreDotFiles(false)->in((string) $this->srcDir)->name('/\\.twig$/')->sortByType(); foreach ($this->finder as $template) { $templates[] = new TwigTemplateFile(Path::makeRelative($template->getPathname(), (string) $this->srcDir), $this->twigData, $this->twig, $this->filesystem); } return new AssetCollection($templates); }
/** * {@inheritDoc} */ public function collect() : AssetCollection { $files = []; $this->finder->files()->ignoreDotFiles(false)->in((string) $this->srcDir)->name('/\\.txt$/')->sortByType(); foreach ($this->finder as $file) { $files[] = new TextFile(new File($file->getPathname()), $this->filesystem, dirname(Path::makeRelative($file->getPathname(), (string) $this->srcDir))); } return new AssetCollection($files); }
/** * {@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')); }
/** * @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); }
/** * 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; }
/** * @param GadgetResultEvent $event */ public function onGadgetResult(GadgetResultEvent $event) { $result = $event->getResult(); $path = $event->getPath(); foreach ($result->getIssues() as $issue) { if (!$issue->getFile()) { continue; } $issue->setFile(Path::makeRelative($issue->getFile(), $path)); } }
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); }
/** * @param string $path * @param Issue $issue * @param int $around * @param bool $attr * @return string */ public static function createCodeSnippet($path, Issue $issue, $around = 5, $attr = false) { $snippet = SnippetHelper::createSnippetByFile(Path::join($path, $issue->getFile()), $issue->getLine(), $around); $extension = pathinfo($issue->getFile(), PATHINFO_EXTENSION); $offset = max($issue->getLine() - $around, 1); $options = []; if ($attr) { $options = ['file' => $issue->getFile(), 'line' => $issue->getLine(), 'offset' => $offset]; } return (new MarkdownBuilder())->code($snippet, $extension, $options)->getMarkdown(); }
public function testParameters() { $path = Path::join([DATAFIXTURES_DIR, 'config', 'test-parameters.json']); $this->locator->locate('test-parameters.json')->willReturn($path); $this->container->addResource(Argument::that(function (FileResource $resource) use($path) { return $resource->getResource() === $path; }))->shouldBeCalled(); $this->container->loadFromExtension('test-parameters', ['name' => 'test'])->shouldBeCalled(); $this->container->setParameter('test', 'value')->shouldBeCalled(); $this->loader->load('test-parameters.json'); }
public function testRestore() { $path = Path::join([DATAFIXTURES_DIR, 'backups', '13-21-2016-05-29_success.zip']); $nanbando = $this->getNanbando(['uploads' => ['plugin' => 'directory', 'parameter' => ['directory' => 'uploads']]]); $filesystem = new Filesystem(new ZipArchiveAdapter($path)); $this->storage->open('13-21-45-2016-05-29')->willReturn($filesystem); $this->eventDispatcher->dispatch(Events::PRE_RESTORE_EVENT, Argument::type(PreRestoreEvent::class))->shouldBeCalled(); $this->eventDispatcher->dispatch(Events::RESTORE_EVENT, Argument::type(RestoreEvent::class))->shouldBeCalled(); $this->eventDispatcher->dispatch(Events::POST_RESTORE_EVENT, Argument::type(Event::class))->shouldBeCalled(); $nanbando->restore('13-21-45-2016-05-29'); }
/** * 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; }
/** * {@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']); }