You can use patterns (delimited with / sign), globs or simple strings.
$finder->name('*.php')
$finder->name('/\.php$/') // same as above
$finder->name('test.php')
/** * Create a map for a given path * * @param array $paths * @return array */ public function createMap(...$paths) { $classes = []; $this->finder->files()->ignoreUnreadableDirs()->in($paths); foreach ($this->excludePathPatterns as $exclude) { $this->finder->notPath($exclude); } foreach ($this->inPathPatterns as $inPath) { $this->finder->path($inPath); } foreach ($this->names as $name) { $this->finder->name($name); } /** @var SplFileInfo $file */ foreach ($this->finder as $file) { $content = file_get_contents($file->getPathname()); preg_match('^\\s*class ([\\S]*)\\s*(extends|implements|{)^', $content, $match, PREG_OFFSET_CAPTURE); if (isset($match[1])) { $className = '\\' . trim($match[1][0]); $offset = $match[1][1]; } else { continue; } preg_match('|\\s*namespace\\s*([\\S]*)\\s*;|', substr($content, 0, $offset), $match); if (isset($match[1]) && trim($match[1]) !== '') { $className = '\\' . trim($match[1]) . $className; } if ($className !== '\\') { $classes[$file->getPathname()] = $className; } } return $classes; }
/** * TYPO3 has a file called LocalConfiguration.php or localconf.php that can be used to search for working installations * * @param Finder $finder finder instance to append the criteria * * @return Finder */ public function appendDetectionCriteria(Finder $finder) { $finder->name('LocalConfiguration.php'); $finder->name('localconf.php'); // always skip typo3temp as it may contain leftovers from functional tests $finder->notPath('typo3temp'); return $finder; }
/** * fire. */ public function fire() { // set_time_limit(30); $path = $this->argument('path'); $name = $this->option('name'); $type = $this->option('type'); $maxDepth = $this->option('maxdepth'); $delete = $this->option('delete'); $root = $this->getLaravel()->basePath(); $path = realpath($root . '/' . $path); $this->finder->in($path); if ($name !== null) { $this->finder->name($name); } switch ($type) { case 'd': $this->finder->directories(); break; case 'f': $this->finder->files(); break; } if ($maxDepth !== null) { if ($maxDepth == '0') { $this->line($path); return; } $this->finder->depth('<' . $maxDepth); } foreach ($this->finder as $file) { $realPath = $file->getRealpath(); if ($delete === 'true' && $filesystem->exists($realPath) === true) { try { if ($filesystem->isDirectory($realPath) === true) { $deleted = $filesystem->deleteDirectory($realPath, true); } else { $deleted = $filesystem->delete($realPath); } } catch (Exception $e) { } if ($deleted === true) { $this->info('removed ' . $realPath); } else { $this->error('removed ' . $realPath . ' fail'); } } else { $this->line($file->getRealpath()); } } }
/** * Executes the current command. * * @param InputInterface $input An InputInterface instance * @param OutputInterface $output An OutputInterface instance * * @return null|integer null or 0 if everything went fine, or an error code */ protected function execute(InputInterface $input, OutputInterface $output) { $paths = $input->getArgument('paths'); $finder = new Finder(); $finder->files(); $finder->name('*.php'); foreach ($paths as $path) { $finder->in($path); } try { $files = $finder->getIterator(); } catch (\Exception $ex) { return 1; } if (empty($files)) { $output->writeln('No files to analyze'); return 1; } $analyzer = new Analyzer(); $result = $analyzer->run($files); $output->writeln('<html><body><pre>'); $output->writeln(print_r($result, true)); $output->writeln('</pre></body></html>'); return 0; }
/** * @return array */ public function findFiles() { $files = array(); $finder = new Finder(); $iterate = false; $finder->ignoreUnreadableDirs(); foreach ($this->items as $item) { if (!is_file($item)) { $finder->in($item); $iterate = true; } else { $files[] = realpath($item); } } foreach ($this->excludes as $exclude) { $finder->exclude($exclude); } foreach ($this->names as $name) { $finder->name($name); } foreach ($this->notNames as $notName) { $finder->notName($notName); } foreach ($this->regularExpressionsExcludes as $regularExpressionExclude) { $finder->notPath($regularExpressionExclude); } if ($iterate) { foreach ($finder as $file) { $files[] = $file->getRealpath(); } } return $files; }
/** * Prepares test environment. */ public function setUp() { $finder = new Finder(); $finder->files()->in(__DIR__ . '/config/'); $finder->name('*.yml'); $this->dummyParser = $this->getMock('Symfony\\Component\\Yaml\\Parser'); $this->dummyDumper = $this->getMock('Symfony\\Component\\Yaml\\Dumper'); $this->dummyFilesystem = $this->getMock('Symfony\\Component\\Filesystem\\Filesystem'); $dummyDispatcher = $this->getMock('Symfony\\Component\\EventDispatcher\\EventDispatcherInterface'); $dummyDispatcher->expects($this->once())->method('dispatch')->willReturnCallback(function ($name, $event) { /** @var GroupOptionTypeEvent $event */ $optionTypes = ['acp' => ['twomartens.core' => ['access' => new BooleanOptionType()]]]; $event->addOptions($optionTypes); }); $this->yamlData = []; $this->optionData = []; foreach ($finder as $file) { /** @var SplFileInfo $file */ $basename = $file->getBasename('.yml'); $this->yamlData[$basename] = Yaml::parse($file->getContents()); $this->optionData[$basename] = ConfigUtil::convertToOptions($this->yamlData[$basename]); } $this->dummyParser->expects($this->any())->method('parse')->willReturnCallback(function ($content) { return Yaml::parse($content); }); /** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $dummyDispatcher */ $this->groupService = new GroupService($finder, $this->dummyParser, $this->dummyDumper, $this->dummyFilesystem, $dummyDispatcher); }
public function testNotName() { $finder = new Finder(); $this->assertSame($finder, $finder->notName('*.php')); $this->assertIterator($this->toAbsolute(array('foo', 'foo/bar.tmp', 'test.py', 'toto')), $finder->in(self::$tmpDir)->getIterator()); $finder = new Finder(); $finder->notName('*.php'); $finder->notName('*.py'); $this->assertIterator($this->toAbsolute(array('foo', 'foo/bar.tmp', 'toto')), $finder->in(self::$tmpDir)->getIterator()); $finder = new Finder(); $finder->name('test.ph*'); $finder->name('test.py'); $finder->notName('*.php'); $finder->notName('*.py'); $this->assertIterator(array(), $finder->in(self::$tmpDir)->getIterator()); }
protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument('name'); if (is_numeric($name)) { $name = (int) $name; } $appliedMigrations = $this->getAppliedMigration('DESC'); $i = 0; foreach ($appliedMigrations as $appliedMigration => $v) { $finder = new Finder(); /** @var SplFileInfo $file */ $file = array_values(iterator_to_array($finder->name($appliedMigration . '.php')->in($this->config['migration_path'])))[0]; $appliedMigration = $this->getAppliedMigration(); if (!isset($appliedMigration[$file->getBasename('.php')])) { continue; } if (!($migration = $this->isMigration($file))) { continue; } ++$i; $className = $file->getBasename('.php'); $output->writeln('Запущен откат миграции: ' . $className); $this->runMigration($className, $migration->down(), 'down'); $this->unsetAppliedMigration($className); $output->writeln('Отменена миграция: ' . $className); if (!is_null($name) && ($className == $name || $name === $i)) { break; } } }
public function updateModules() { $finder = new Finder(); $finder->name('module.xml')->in($this->baseModuleDir . '/*/Config'); $descriptorValidator = new ModuleDescriptorValidator(); foreach ($finder as $file) { $content = $descriptorValidator->getDescriptor($file->getRealPath()); $reflected = new \ReflectionClass((string) $content->fullnamespace); $code = basename(dirname($reflected->getFileName())); $con = Propel::getWriteConnection(ModuleTableMap::DATABASE_NAME); $con->beginTransaction(); try { $module = ModuleQuery::create()->filterByCode($code)->findOne(); if (null === $module) { $module = new Module(); $module->setCode($code)->setFullNamespace((string) $content->fullnamespace)->setType($this->getModuleType($reflected))->setActivate(0)->save($con); } $this->saveDescription($module, $content, $con); $con->commit(); } catch (PropelException $e) { $con->rollBack(); throw $e; } } }
/** * Load, instantiate and sort all fixture files found * within the given paths. * * @param array $paths * * @return DocumentFixtureInterface[] */ public function load(array $paths) { $finder = new Finder(); $finder->in($paths); $finder->name('*Fixture.php'); foreach ($finder as $file) { $declaredClasses = get_declared_classes(); require_once $file; $declaredClassesDiff = array_diff(get_declared_classes(), $declaredClasses); $fixtureClass = array_pop($declaredClassesDiff); if (!$fixtureClass) { throw new \InvalidArgumentException(sprintf('Could not determine class from included file "%s". Class detection will only work once per request.', $file)); } $refl = new \ReflectionClass($fixtureClass); if ($refl->isAbstract()) { continue; } if (false === $refl->isSubclassOf(DocumentFixtureInterface::class)) { continue; } $fixture = new $fixtureClass(); if ($fixture instanceof ContainerAwareInterface) { $fixture->setContainer($this->container); } $fixtures[] = $fixture; } usort($fixtures, function (DocumentFixtureInterface $fixture1, DocumentFixtureInterface $fixture2) { return $fixture1->getOrder() > $fixture2->getOrder(); }); return $fixtures; }
/** * @see Command * * @throws \InvalidArgumentException When the target directory does not exist */ protected function execute(InputInterface $input, OutputInterface $output) { $this->writeSection($output, '[Propel] You are running the command: propel:build-sql'); if ($input->getOption('verbose')) { $this->additionalPhingArgs[] = 'verbose'; } $finder = new Finder(); $filesystem = new Filesystem(); $sqlDir = $this->getApplication()->getKernel()->getRootDir() . DIRECTORY_SEPARATOR . 'propel' . DIRECTORY_SEPARATOR . 'sql'; $filesystem->remove($sqlDir); $filesystem->mkdir($sqlDir); // Execute the task $ret = $this->callPhing('build-sql', array('propel.sql.dir' => $sqlDir)); if (true === $ret) { $files = $finder->name('*')->in($sqlDir); $nbFiles = 0; foreach ($files as $file) { $this->writeNewFile($output, (string) $file); if ('sql' === pathinfo($file->getFilename(), PATHINFO_EXTENSION)) { $nbFiles++; } } $this->writeSection($output, sprintf('<comment>%d</comment> <info>SQL file%s ha%s been generated.</info>', $nbFiles, $nbFiles > 1 ? 's' : '', $nbFiles > 1 ? 've' : 's'), 'bg=black'); } else { $this->writeSection($output, array('[Propel] Error', '', 'An error has occured during the "build-sql" task process. To get more details, run the command with the "--verbose" option.'), 'fg=white;bg=red'); } }
protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument('name'); if (is_numeric($name)) { $name = (int) $name; } $finder = new Finder(); $finder->name(BaseMigrationCommand::PREFIX_MIGRATION_NAME . '*' . '.php')->in($this->config['migration_path'])->sortByName(); $i = 0; /** @var SplFileInfo $file */ foreach ($finder as $file) { $appliedMigration = $this->getAppliedMigration(); if (isset($appliedMigration[$file->getBasename('.php')])) { continue; } if (!($migration = $this->isMigration($file))) { continue; } ++$i; $className = $file->getBasename('.php'); $output->writeln('Запущена миграция: ' . $className); $this->runMigration($className, $migration->up(), 'up'); $this->setAppliedMigration($className); $output->writeln('Применена миграция: ' . $className); if (!is_null($name) && ($className == $name || $name === $i)) { break; } } }
/** * Gets the file(s) to process from the given path * * @param string $path The path to the source file(s) * * @return SplFileInfo[] */ private function getFiles($path) { if (is_file($path)) { return [new SplFileInfo($path, '', '')]; } return $this->finder->name('*.php')->in(realpath($path)); }
/** * * @param SpritePackageInterface[]|Package[] $packages * @return SpriteImage */ public function find($packages) { // Get icons $sprites = []; foreach ($packages as $package) { foreach ($package->getPaths() as $path) { $finder = new Finder(); $finder->sortByChangedTime(); $finder->sortByAccessedTime(); $finder->name('/\\.(png|jpg|gif)$/'); foreach ($finder->in($path) as $fileInfo) { $sprite = new SpriteImage($path, $fileInfo); if (!array_key_exists($sprite->hash, $sprites)) { // Add new sprite to set if hash does not exists $sprites[$sprite->hash] = $sprite; } // Sprite with selected hash exists, just add package if (!in_array($package, $sprites[$sprite->hash]->packages)) { $sprites[$sprite->hash]->packages[] = $package; } } } } return $sprites; }
/** * Execute the console command. * * @return void */ public function fire() { $vendorDir = realpath($this->argument('dir')); $this->info("Cleaning dir: {$vendorDir}"); $rules = Config::get('laravel-vendor-cleanup::rules'); $filesystem = new Filesystem(); foreach ($rules as $packageDir => $rule) { if (!file_exists($vendorDir . '/' . $packageDir)) { continue; } $patterns = explode(' ', $rule); foreach ($patterns as $pattern) { try { $finder = new Finder(); $finder->name($pattern)->in($vendorDir . '/' . $packageDir); // we can't directly iterate over $finder if it lists dirs we're deleting $files = iterator_to_array($finder); /** @var \SplFileInfo $file */ foreach ($files as $file) { if ($file->isDir()) { $filesystem->deleteDirectory($file); } elseif ($file->isFile()) { $filesystem->delete($file); } } } catch (\Exception $e) { $this->error("Could not parse {$packageDir} ({$pattern}): " . $e->getMessage()); } } } }
public function getCollection() { if ($this->collection) { return $this->collection; } $versions = array(); $finder = new Finder(); $finder->name('/Version[0-9]{12}.php/'); $finder->files(); foreach ($this->paths as $path) { $finder->in($path); } foreach ($finder as $versionFile) { $className = $versionFile->getBasename('.php'); require_once $versionFile->getRealPath(); $classFqn = MigratorUtil::getClassNameFromFile($versionFile->getRealPath()); $version = new $classFqn(); if (!$version instanceof VersionInterface) { throw new MigratorException(sprintf('Version class "%s" must implement VersionInterface', $className)); } $versionTimestamp = substr($versionFile->getBaseName(), 7, 12); $versions[$versionTimestamp] = $version; } $this->collection = new VersionCollection($versions); return $this->collection; }
/** * @param array $filters * @return $this */ public function withFilters(array $filters) { if (!empty($filters)) { foreach ($filters as $currentFilter) { if (!strpos($currentFilter, ':')) { throw new \InvalidArgumentException(sprintf('The filter "%s" is not a valid filter. A valid filter has the format <name>:<value>.', $currentFilter)); } $currentFilterElements = explode(':', $currentFilter, 2); switch (trim($currentFilterElements[0])) { case 'exclude': $this->finder->exclude($currentFilterElements[1]); break; case 'name': $this->finder->name($currentFilterElements[1]); break; case 'notName': $this->finder->notName($currentFilterElements[1]); break; case 'path': $this->finder->path($currentFilterElements[1]); break; case 'size': $this->finder->size($currentFilterElements[1]); } } } return $this; }
public function index(Silex\Application $app, Request $request) { $finder = new Finder(); $finder->name('/(.*)\\.resultdb\\.json/')->in($app->dataDir()); $results = array(); foreach ($finder as $file) { $path = $file->getRealpath(); $content = $file->getContents(); $data = (object) json_decode($content, true); if ($data->progress == 'failed' || $data->status == 'failed') { continue; } preg_match('/^.*[\\/\\\\]{1}(.*)\\.resultdb\\.json$/', $path, $regex); $out = (object) array('name' => $regex[1], 'urn' => $data->urn, 'date' => $data->startedAt, 'hasThumbnail' => isset($data->hasThumbnail) ? $data->hasThumbnail : false, 'status' => $data->status, 'success' => $data->success, 'progress' => $data->progress); array_push($results, $out); } // $response =new Response () ; // $response->setStatusCode (Response::HTTP_OK) ; // $response->headers->set ('Content-Type', 'application/json') ; // $response->setContent (json_encode (array ( 'name' => 'cyrille' ))) ; /*return (new Response ( json_encode ($results), Response::HTTP_OK, [ 'Content-Type' => 'application/json' ] )) ;*/ return new JsonResponse($results, Response::HTTP_OK); }
/** * @param Bundle $bundle * @return array */ protected function scanRoutes(Bundle $bundle) { $path = $bundle->getRootPath() . '/Controllers'; if (!is_dir($path)) { return []; } $baseNamespace = $bundle->getNamespace() . '\\Controllers\\'; $finder = new Finder(); $files = $finder->name('*.php')->in($path)->files(); $routes = []; foreach ($files as $file) { $className = $baseNamespace . pathinfo($file->getFileName(), PATHINFO_FILENAME); if (!class_exists($className)) { continue; } $annotation = new Annotation($className, self::FILTER); foreach ($annotation as $annotator) { if (null === ($route = $annotator->getParameter('Route'))) { continue; } if (!isset($route['name'])) { $route['name'] = $route[0]; } $parameters = [$route['name'], str_replace('//', '/', $route[0]), $annotator->getClassName() . '@' . $annotator->getName(), isset($route['defaults']) ? $route['defaults'] : [], isset($route['requirements']) ? $route['requirements'] : []]; $method = null === $annotator->getParameter('Method') ? 'any' : strtolower($annotator->getParameter('Method')[0]); $routes[$bundle->getName()][] = ['method' => $method, 'parameters' => $parameters]; unset($route, $method, $parameters, $parent); } } return $routes; }
private function getServerFiles($config, $destination) { $path = Path::assemble(BASE_PATH, $destination); $finder = new Finder(); // Set folder location $finder->in($path); // Limit by depth $finder->depth('<' . array_get($config, 'depth', '1')); // Limit by file extension foreach (array_get($config, array('allowed', 'types'), array()) as $ext) { $finder->name("/\.{$ext}/i"); } // Fetch matches $matches = $finder->files()->followLinks(); // Build array $files = array(); foreach ($matches as $file) { $filename = Path::trimSubdirectory(Path::toAsset($file->getPathname(), false)); $display_name = ltrim(str_replace($path, '', $file->getPathname()), '/'); $value = (Config::get('prepend_site_root_to_uploads', false)) ? '{{ _site_root }}' . ltrim($filename, '/') : $filename; $files[] = compact('value', 'display_name'); } return $files; }
private function makeFileSelect($selected_file = null) { $html = "<span class='btn btn-file-browse'><span class='ss-icon'>openfolder</span></span>"; $html .= "<p><select name='{$this->fieldname}' style='display:none'>"; $html .= "<option value=''>Select a file...</option>"; $path = Path::assemble(BASE_PATH, array_get($this->field_config, 'destination')); $finder = new Finder(); // Set folder location $finder->in($path); // Limit by depth $finder->depth = array_get($this->field_config, 'depth', '<1'); // Limit by file extension foreach (array_get($this->field_config, array('allowed', 'types'), array()) as $ext) { $finder->name("*.{$ext}"); } // Fetch matches $matches = $finder->files()->followLinks(); // Build HTML options foreach ($matches as $file) { $filename = Path::toAsset($file->getPathname(), false); $display_name = ltrim(str_replace($path, '', $file->getPathname()), '/'); $selected = $selected_file === $filename ? 'selected' : ''; $html .= "<option value='{$filename}' {$selected}>" . $display_name . "</option>"; } $html .= '</select></p>'; return $html; }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $application = $this->getApplication(); $config = $application->getConfig(); $message = $this->getMessageHelper(); $userPath = sprintf('%s/.console/', $config->getUserHomeDir()); $copiedFiles = []; $override = false; if ($input->hasOption('override')) { $override = $input->getOption('override'); } $finder = new Finder(); $finder->in(sprintf('%s/config/dist', $application->getDirectoryRoot())); $finder->name("*.yml"); foreach ($finder as $configFile) { $source = sprintf('%s/config/dist/%s', $application->getDirectoryRoot(), $configFile->getRelativePathname()); $destination = sprintf('%s/%s', $userPath, $configFile->getRelativePathname()); if ($this->copyFile($source, $destination, $override)) { $copiedFiles[] = $configFile->getRelativePathname(); } } if ($copiedFiles) { $message->showCopiedFiles($output, $copiedFiles); } $this->createAutocomplete(); $output->writeln($this->trans('application.console.messages.autocomplete')); }
/** * {@inheritdoc} */ public function load(ObjectManager $om) { $finder = new Finder(); $finder->name('ticket*.yml')->in(__DIR__ . '/../Data')->sortByName(); foreach ($finder as $file) { $ticket = Yaml::parse(file_get_contents($file)); $ticketEntity = new Ticket(); $this->setTicketParameters($ticketEntity, $ticket); $om->persist($ticketEntity); $messages = $ticket['messages']; if (is_array($messages)) { foreach ($messages as $item) { $message = new Message(); if (!empty($item['message'])) { $message->setMessage($item['message']); } if (!empty($item['mediaFile'])) { $this->setMessageImage($message, $item); } $message->setUser($this->getReference($item['user']))->setStatus($item['status'])->setPriority($item['priority'])->setCreatedAt(new \DateTime($item['createdAt']))->setTicket($ticketEntity); $om->persist($message); } } } $om->flush(); }
/** * Creates a Kernel. * * If you run tests with the PHPUnit CLI tool, everything will work as expected. * If not, override this method in your test classes. * * Available options: * * * environment * * debug * * @param array $options An array of options * * @return HttpKernelInterface A HttpKernelInterface instance */ protected function createKernel(array $options = array()) { // black magic below, you have been warned! $dir = getcwd(); if (!isset($_SERVER['argv']) || false === strpos($_SERVER['argv'][0], 'phpunit')) { throw new \RuntimeException('You must override the WebTestCase::createKernel() method.'); } // find the --configuration flag from PHPUnit $cli = implode(' ', $_SERVER['argv']); if (preg_match('/\\-\\-configuration[= ]+([^ ]+)/', $cli, $matches)) { $dir = $dir . '/' . $matches[1]; } elseif (preg_match('/\\-c +([^ ]+)/', $cli, $matches)) { $dir = $dir . '/' . $matches[1]; } else { throw new \RuntimeException('Unable to guess the Kernel directory.'); } if (!is_dir($dir)) { $dir = dirname($dir); } $finder = new Finder(); $finder->name('*Kernel.php')->in($dir); if (!count($finder)) { throw new \RuntimeException('You must override the WebTestCase::createKernel() method.'); } $file = current(iterator_to_array($finder)); $class = $file->getBasename('.php'); unset($finder); require_once $file; return new $class(isset($options['environment']) ? $options['environment'] : 'test', isset($options['debug']) ? $debug : true); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $message = $this->getMessageHelper(); $application = $this->getApplication(); $sitesDirectory = $application->getConfig()->getSitesDirectory(); if (!is_dir($sitesDirectory)) { $message->addErrorMessage(sprintf($this->trans('commands.site.debug.messages.directory-not-found'), $sitesDirectory)); return; } // Get the target argument $target = $input->getArgument('target'); if ($target && $application->getConfig()->loadTarget($target)) { $targetConfig = $application->getConfig()->getTarget($target); $dumper = new Dumper(); $yaml = $dumper->dump($targetConfig, 5); $output->writeln($yaml); return; } $finder = new Finder(); $finder->in($sitesDirectory); $finder->name("*.yml"); $table = new Table($output); $table->setHeaders([$this->trans('commands.site.debug.messages.site'), $this->trans('commands.site.debug.messages.host'), $this->trans('commands.site.debug.messages.root')]); foreach ($finder as $site) { $siteConfiguration = $site->getBasename('.yml'); $application->getConfig()->loadSite($siteConfiguration); $environments = $application->getConfig()->get('sites.' . $siteConfiguration); foreach ($environments as $env => $config) { $table->addRow([$siteConfiguration . '.' . $env, array_key_exists('host', $config) ? $config['host'] : 'local', array_key_exists('root', $config) ? $config['root'] : '']); } } $table->render(); }
/** * Execute the console command. * * @return mixed */ public function fire() { $name = $this->argument('name'); $force = $this->option('force'); $basePath = realpath(__DIR__ . '/../../..'); $namespace = config('admin-generator.namespace'); $engine = config("admin-generator.instances.{$name}.engine"); if (!$namespace) { $this->error("The config 'namespace' in 'config/admin-generator.php' can not be empty, general set it to 'admin'"); exit; } if (!$name) { $this->error('The name can not be empty'); exit; } if (!config("admin-generator.instances.{$name}")) { $this->warn("The config of instance '{$name}' is not exist, check the typo or add it to config/admin-generator.php first"); exit; } if (!$engine) { $this->warn("The engine option is empty, use --engine"); exit; } if (!is_dir($basePath . "/engines/{$engine}")) { $this->warn("The engine '{$engine}' is not support."); exit; } /** * */ $finder = new Finder(); $path = $basePath . "/engines/{$engine}"; $copies = []; $s = DIRECTORY_SEPARATOR; foreach ($finder->name('*')->ignoreDotFiles(false)->in($path) as $file) { /** * @var \SplFileInfo $file */ if ($file->isFile()) { $relativePath = str_replace($basePath . "{$s}engines{$s}{$engine}{$s}", '', $file->getRealPath()); $dest = base_path("resources{$s}" . $relativePath); $dest = $this->replaceKeyword($dest); if (is_file($dest) && !$force) { $this->warn(sprintf("The file '%s' exists, use '--force' option to overwrite it.", str_replace(base_path(), '', $dest))); exit; } $copies[] = [$file->getRealPath(), $dest]; } } foreach ($copies as $copy) { if (!is_dir(dirname($copy[1]))) { mkdir(dirname($copy[1]), 0755, true); } $this->info('Copy file to: ' . str_replace(base_path(), '', $copy[1])); File::copy($copy[0], $copy[1]); } $this->warn("Done! run 'gulp default && gulp watch' to generate assets"); }
/** * Find every schema files. * * @param string|array $directory Path to the input directory * @param bool $recursive Search for file inside the input directory and all subdirectories * * @return array List of schema files */ protected function getSchemas($directory, $recursive = false) { $finder = new Finder(); $finder->name('*schema.xml')->sortByName()->in($directory); if (!$recursive) { $finder->depth(0); } return iterator_to_array($finder->files()); }
public function findParts($inputPath) { $files = []; $finder = new Finder(); $finder->name(str_replace('.7z.001', '', basename($inputPath)) . '.7z.*')->in(dirname($inputPath)); foreach ($finder as $file) { $files[] = $file->getRealpath(); } return $files; }
/** * @return mixed */ public function run() { $this->inputParameter['level_filename'] = (array) $this->inputParameter['level_filename']; foreach ($this->inputParameter['level_filename'] as $key => $urn) { if (is_dir($urn)) { $this->fileFinder->files()->in($urn); foreach ($this->gridFactory->getFileExtensions() as $ext) { $this->fileFinder->name('*.' . $ext); } foreach ($this->fileFinder as $file) { $this->inputParameter['level_filename'][] = $file->getRealpath(); } unset($this->inputParameter['level_filename'][$key]); } elseif (1 === preg_match(self::FILENAME_WILDCARD_REGEX, $urn, $matches)) { $lowerBorder = (int) $matches[1]; $upperBorder = (int) $matches[2]; foreach (range($lowerBorder, $upperBorder) as $number) { $this->inputParameter['level_filename'][] = preg_replace(self::FILENAME_WILDCARD_REGEX, $number, $urn); } unset($this->inputParameter['level_filename'][$key]); } } foreach ($this->inputParameter['level_filename'] as $urn) { try { $grid = $this->gridFactory->get($urn); $this->view->setGrid($grid); if (!($this->view instanceof ViewWritableInterface && $this->view->supportsMultiple())) { //execute after adding one $this->executeAction($urn); } } catch (\Exception $e) { echo $e->getMessage() . ': ' . $urn . PHP_EOL; continue; } } if ($this->view instanceof ViewWritableInterface && $this->view->supportsMultiple()) { //execute after adding multiple $this->executeAction($urn); } if (method_exists($this, 'finallyExecute')) { $this->finallyExecute(); } }
/** * @return KernelInterface */ protected function createKernel() { $finder = new Finder(); $finder->name('*Kernel.php')->depth(0)->in($this->args['kernel.root_dir']); $results = iterator_to_array($finder); $file = current($results); $class = $file->getBasename('.php'); require_once $file; return new $class(isset($this->args['kernel.environment']) ? $this->args['kernel.environment'] : 'dev', isset($this->args['kernel.debug']) ? $this->args['kernel.debug'] : TRUE); }