It is a thin wrapper around several specialized iterator classes.
All rules may be invoked several times.
All methods return the current Finder object to allow easy chaining:
$finder = Finder::create()->files()->name('*.php')->in(__DIR__);
/** * Parse a csv file * * @return array */ public function parseCSV() { $finder = new Finder(); $rows = array(); $convert_utf8 = function ($s) { if (!mb_check_encoding($s, 'UTF-8')) { $s = utf8_encode($s); } return $s; }; $finder->files()->in($this->path)->name($this->fileName); foreach ($finder as $file) { $csv = $file; } if (($handle = fopen($csv->getRealPath(), "r")) !== false) { $i = 0; while (($data = fgetcsv($handle, null, ";")) !== false) { $i++; if ($this->ignoreFirstLine && $i == 1) { continue; } $rows[] = array_map($convert_utf8, $data); } fclose($handle); } return $rows; }
public function tearDown() { // Delete local files $finder = new Finder(); $fs = new Filesystem(); $fs->remove($finder->files()->in($this->tmpDir . "/download")); $fs->remove($finder->files()->in($this->tmpDir)); $fs->remove($this->tmpDir . "/download"); $fs->remove($this->tmpDir); // Delete file uploads $options = new ListFilesOptions(); $options->setTags(["docker-bundle-test"]); $files = $this->client->listFiles($options); foreach ($files as $file) { $this->client->deleteFile($file["id"]); } if ($this->client->bucketExists("in.c-docker-test")) { // Delete tables foreach ($this->client->listTables("in.c-docker-test") as $table) { $this->client->dropTable($table["id"]); } // Delete bucket $this->client->dropBucket("in.c-docker-test"); } if ($this->client->bucketExists("in.c-docker-test-redshift")) { // Delete tables foreach ($this->client->listTables("in.c-docker-test-redshift") as $table) { $this->client->dropTable($table["id"]); } // Delete bucket $this->client->dropBucket("in.c-docker-test-redshift"); } }
/** * Compiles phar archive. * * @param string $version */ public function compile($version) { if (file_exists($package = "behat-{$version}.phar")) { unlink($package); } // create phar $phar = new \Phar($package, 0, 'behat.phar'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $finder = new Finder(); $finder->files()->ignoreVCS(true)->name('*.php')->name('*.xsd')->name('*.xml')->name('LICENSE')->notName('PharCompiler.php')->notName('PearCompiler.php')->in($this->libPath . '/src')->in($this->libPath . '/vendor'); foreach ($finder as $file) { // don't compile test suites if (!preg_match('/\\/tests\\/|\\/test\\//i', $file->getRealPath())) { $this->addFileToPhar($file, $phar); } } // license and autoloading $this->addFileToPhar(new \SplFileInfo($this->libPath . '/LICENSE'), $phar); $this->addFileToPhar(new \SplFileInfo($this->libPath . '/i18n.php'), $phar); // stub $phar->setStub($this->getStub($version)); $phar->stopBuffering(); unset($phar); }
/** * 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); }
protected function warmup($warmupDir) { $this->getContainer()->get('filesystem')->remove($warmupDir); $parent = $this->getContainer()->get('kernel'); $class = get_class($parent); $namespace = ''; if (false !== ($pos = strrpos($class, '\\'))) { $namespace = substr($class, 0, $pos); $class = substr($class, $pos + 1); } $kernel = $this->getTempKernel($parent, $namespace, $class, $warmupDir); $kernel->boot(); $warmer = $kernel->getContainer()->get('cache_warmer'); $warmer->enableOptionalWarmers(); $warmer->warmUp($warmupDir); // fix container files and classes $regex = '/' . preg_quote($this->getTempKernelSuffix(), '/') . '/'; $finder = new Finder(); foreach ($finder->files()->name(get_class($kernel->getContainer()) . '*')->in($warmupDir) as $file) { $content = file_get_contents($file); $content = preg_replace($regex, '', $content); // fix absolute paths to the cache directory $content = preg_replace('/' . preg_quote($warmupDir, '/') . '/', preg_replace('/_new$/', '', $warmupDir), $content); file_put_contents(preg_replace($regex, '', $file), $content); unlink($file); } // fix meta references to the Kernel foreach ($finder->files()->name('*.meta')->in($warmupDir) as $file) { $content = preg_replace('/C\\:\\d+\\:"' . preg_quote($class . $this->getTempKernelSuffix(), '"/') . '"/', sprintf('C:%s:"%s"', strlen($class), $class), file_get_contents($file)); file_put_contents($file, $content); } }
/** * Compile new composer.phar * @param string $filename */ public function compile($filename = 'codecept.phar') { if (file_exists($filename)) { unlink($filename); } $phar = new \Phar($filename, 0, 'codecept.phar'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $finder = new Finder(); $finder->files()->ignoreVCS(true)->name('*.php')->name('*.tpl.dist')->name('*.html.dist')->in($this->compileDir . '/src'); foreach ($finder as $file) { $this->addFile($phar, $file); } $finder = new Finder(); $finder->files()->ignoreVCS(true)->name('*.php')->name('*.js')->name('*.css')->name('*.png')->name('*.tpl.dist')->name('*.html.dist')->exclude('Tests')->exclude('tests')->exclude('benchmark')->exclude('demo')->in($this->compileDir . '/plugins/frameworks'); foreach ($finder as $file) { $this->addFile($phar, $file); } $finder = new Finder(); $finder->files()->ignoreVCS(true)->name('*.php')->name('*.css')->name('*.png')->name('*.js')->name('*.css')->name('*.png')->name('*.tpl.dist')->name('*.html.dist')->exclude('Tests')->exclude('tests')->exclude('benchmark')->exclude('demo')->in($this->compileDir . '/vendor'); foreach ($finder as $file) { $this->addFile($phar, $file); } $this->addFile($phar, new \SplFileInfo($this->compileDir . '/autoload.php')); $this->setMainExecutable($phar); $this->setStub($phar); $phar->stopBuffering(); unset($phar); }
/** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $destDir = $this->getDestDir(); $finder = new Finder(); $fs = new Filesystem(); try { $fs->mkdir($destDir); } catch (IOException $e) { $output->writeln(sprintf('<error>Could not create directory %s.</error>', $destDir)); return; } $srcDir = $this->getSrcDir(); if (false === file_exists($srcDir)) { $output->writeln(sprintf('<error>Fonts directory "%s" does not exist. Did you install twbs/bootstrap? ' . 'If you used something other than Composer you need to manually change the path in ' . '"braincrafted_bootstrap.assets_dir". If you want to use Font Awesome you need to install the font and change the option "braincrafted_bootstrap.fontawesome_dir".</error>', $srcDir)); return; } $finder->files()->in($srcDir); foreach ($finder as $file) { $dest = sprintf('%s/%s', $destDir, $file->getBaseName()); try { $fs->copy($file, $dest); } catch (IOException $e) { $output->writeln(sprintf('<error>Could not copy %s</error>', $file->getBaseName())); return; } } $output->writeln(sprintf('Copied icon fonts to <comment>%s</comment>.', $destDir)); }
/** * @return array (string $file => string $class) */ static function findTestClasses($paths) { $testClasses = array(); $finder = new Finder(); foreach ($paths as $path) { if (is_dir($path)) { foreach ($finder->files()->in($paths)->name('*Test.php') as $file) { $testClass = self::_findTestClasses((string) $file); if (count($testClass) == 1) { $testClasses[(string) $file] = array_shift($testClass); } elseif (count($testClass) > 1) { throw new \Exception("Too many classes in {$file}"); } else { throw new \Exception("Too few classes in {$file}"); } } } elseif (is_file($path)) { $testClass = self::_findTestClasses($path); if (count($testClass) == 1) { $testClasses[$path] = array_shift($testClass); } elseif (count($testClass) > 1) { throw new \Exception("Too many classes in {$path}"); } else { throw new \Exception("Too few classes in {$path}"); } } } return $testClasses; }
protected function collectBundles() { $finder = new Finder(); $bundles = array(); $finder->files()->followLinks()->in(array($this->getRootDir() . '/../src', $this->getRootDir() . '/../vendor'))->name('bundles.yml'); foreach ($finder as $file) { $import = Yaml::parse($file->getRealpath()); foreach ($import['bundles'] as $bundle) { $kernel = false; $priority = 0; if (is_array($bundle)) { $class = $bundle['name']; $kernel = isset($bundle['kernel']) && true == $bundle['kernel']; $priority = isset($bundle['priority']) ? (int) $bundle['priority'] : 0; } else { $class = $bundle; } if (!isset($bundles[$class])) { $bundles[$class] = array('name' => $class, 'kernel' => $kernel, 'priority' => $priority); } } } uasort($bundles, array($this, 'compareBundles')); return $bundles; }
/** * Compiles composer into a single phar file * * @throws \RuntimeException */ public function compile() { $pharFile = 'refactor.phar'; if (file_exists($pharFile)) { unlink($pharFile); } $process = new Process('git log --pretty="%H" -n1 HEAD', $this->directory); if ($process->run() != 0) { throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from git repository clone and that git binary is available.'); } $this->version = trim($process->getOutput()); $process = new Process('git describe --tags HEAD'); if ($process->run() == 0) { $this->version = trim($process->getOutput()); } $phar = new \Phar($pharFile, 0, 'refactor.phar'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $finder = new Finder(); $finder->files()->ignoreVCS(true)->name('*.php')->notName('Compiler.php')->in($this->directory . '/src/main'); foreach ($finder as $file) { $this->addFile($phar, $file); } $finder = new Finder(); $finder->files()->ignoreVCS(true)->name('*.php')->exclude('test')->exclude('features')->in($this->directory . '/vendor/'); foreach ($finder as $file) { $this->addFile($phar, $file); } $this->addRefactorBin($phar); // Stubs $phar->setStub($this->getStub()); $phar->stopBuffering(); unset($phar); }
protected function getThemeFiles($code) { $files = array(); $DS = DIRECTORY_SEPARATOR; $admin = str_replace(DIR_ROOT, '', DIR_ADMIN); $catalog = str_replace(DIR_ROOT, '', DIR_CATALOG); $image = str_replace(DIR_ROOT, '', DIR_IMAGE); // Theme files $theme_dir = $catalog . 'view' . $DS . 'theme' . $DS . $code; $finder = new SFinder(); $finder->files()->in(DIR_ROOT . $theme_dir); foreach ($finder as $file) { $files[] = $theme_dir . $DS . $file->getRelativePathname(); } // Thumbnail $thumbnail = 'templates' . $DS . $code . '.png'; if (file_exists(DIR_IMAGE . $thumbnail)) { $files[] = $image . $thumbnail; } // Language $language = 'language' . $DS . 'en-GB' . $DS . 'theme' . $DS . $code . '.php'; if (file_exists(DIR_ADMIN . $language)) { $files[] = $admin . $language; } return $files; }
protected function executeTags(InputInterface $input, OutputInterface $output) { $this->tagsRepo = $this->dm->getRepository("PumukitSchemaBundle:Tag"); $finder = new Finder(); $finder->files()->in(__DIR__ . '/' . $this->tagsPath); $file = $input->getArgument('file'); if (0 == strcmp($file, "") && !$finder) { $output->writeln("<error>Tags: There's no data to initialize</error>"); return -1; } $publishingDecisionTag = $this->tagsRepo->findOneByCod("PUBDECISIONS"); if (null == $publishingDecisionTag) { throw new \Exception("Trying to add children tags to the not created Publishing Decision Tag. Please init pumukit tags"); } $rootTag = $this->tagsRepo->findOneByCod("ROOT"); if (null == $rootTag) { throw new \Exception("Trying to add children tags to the not created ROOT Tag. Please init pumukit tags"); } foreach ($finder as $tagFile) { if (0 < strpos(pathinfo($tagFile, PATHINFO_EXTENSION), '~')) { continue; } $parentTag = $this->getParentTag($tagFile, $rootTag, $publishingDecisionTag); $this->createFromFile($tagFile, $parentTag, $output); } if ($file) { $parentTag = $this->getParentTag($tagFile, $rootTag, $publishingDecisionTag); $this->createFromFile($file, $parentTag, $output); } return 0; }
public function process(ContainerBuilder $container) { $dirs = array(); foreach ($container->getParameter('kernel.bundles') as $bundle) { $reflection = new \ReflectionClass($bundle); if (is_dir($dir = dirname($reflection->getFilename()) . '/Resources/config/validation')) { $dirs[] = $dir; } } if (is_dir($dir = $container->getParameter('kernel.root_dir') . '/Resources/config/validation')) { $dirs[] = $dir; } $newFiles = array(); if ($dirs) { $finder = new Finder(); $finder->files()->name('*.xml')->in($dirs); foreach ($finder as $file) { $newFiles[] = $file->getPathName(); } } $validatorBuilder = $container->getDefinition('validator.builder'); if (count($newFiles) > 0) { $validatorBuilder->addMethodCall('addXmlMappings', array($newFiles)); } }
/** * 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); }
protected function execute(InputInterface $input, OutputInterface $output) { $argument = $input->getArgument('argument'); if ($input->getOption('option')) { // ... } //extract all files from a folder $path = __DIR__ . "/../../../var/data/"; $em = $this->getContainer()->get('doctrine')->getManager(); $finder = new Finder(); $finder->files()->in($path); $extractor = $this->getContainer()->get('excel.extractor.catalunyacaixa'); $entryExcels = $extractor->extractFromPath($finder); $entryExcelManager = $this->getContainer()->get('entry.excel.manager'); $totalUpdated = 0; foreach ($entryExcels as $entryExcel) { if (!$entryExcelManager->existsEntryExcel($entryExcel)) { $totalUpdated++; $entry = $entryExcelManager->createEntryEntity($entryExcel); $em->persist($entry); } } $em->flush(); $output->writeln('Created: ' . $totalUpdated); }
/** * {@inheritdoc} */ public function locate($name, $currentPath = null, $first = true) { if (empty($name)) { throw new \InvalidArgumentException('An empty file name is not valid to be located.'); } if ($this->isAbsolutePath($name)) { if (!file_exists($name)) { throw new \InvalidArgumentException(sprintf('The file "%s" does not exist.', $name)); } return $name; } $directories = $this->paths; if (null !== $currentPath) { $directories[] = $currentPath; $directories = array_values(array_unique($directories)); } $filepaths = []; $finder = new Finder(); $finder->files()->name($name)->ignoreUnreadableDirs()->in($directories); /** @var SplFileInfo $file */ if ($first && null !== ($file = $finder->getIterator()->current())) { return $file->getPathname(); } foreach ($finder as $file) { $filepaths[] = $file->getPathname(); } if (!$filepaths) { throw new \InvalidArgumentException(sprintf('The file "%s" does not exist (in: %s).', $name, implode(', ', $directories))); } return array_values(array_unique($filepaths)); }
/** * @param string $repository * @param PriorityHandlerInterface $priorityHandler * @param Filesystem $fs * @param Finder $finder * @param LockHandlerFactoryInterface $lockHandlerFactory */ public function __construct($repository, PriorityHandlerInterface $priorityHandler = null, Filesystem $fs = null, Finder $finder = null, LockHandlerFactoryInterface $lockHandlerFactory = null) { if (empty($repository)) { throw new InvalidArgumentException('Argument repository empty or not defined.'); } if (null === $fs) { $fs = new Filesystem(); } if (null === $finder) { $finder = new Finder(); } if (null === $lockHandlerFactory) { $lockHandlerFactory = new LockHandlerFactory(); } if (null === $priorityHandler) { $priorityHandler = new StandardPriorityHandler(); } $this->fs = $fs; if (!$this->fs->exists($repository)) { try { $this->fs->mkdir($repository); } catch (IOExceptionInterface $e) { throw new InvalidArgumentException('An error occurred while creating your directory at ' . $e->getPath()); } } $this->priorityHandler = $priorityHandler; $this->repository = $repository; $this->finder = $finder; $this->finder->files()->in($repository); $this->lockHandlerFactory = $lockHandlerFactory; return $this; }
public function compile($pharFile = 'onesky.phar') { if (file_exists($pharFile)) { unlink($pharFile); } $phar = new \Phar($pharFile, 0, 'onesky.phar'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $finders = array(); $finder = new Finder(); $finder->files()->ignoreVCS(true)->name('*.php')->notName('Compiler.php')->in(__DIR__); $finders[] = $finder; $finder = new Finder(); $finder->files()->ignoreVCS(true)->name('*.php')->in(dirname(__DIR__) . "/vendor"); $finders[] = $finder; foreach ($finders as $finder) { foreach ($finder as $file) { $this->addFile($phar, $file); } } $this->addBin($phar); // Stubs $phar->setStub($this->getStub()); $phar->stopBuffering(); $phar->compressFiles(\Phar::GZ); unset($phar); }
/** * @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'); } }
/** * @param string $bundle * @return array */ protected function scanFixtures($bundle = null) { $finder = new Finder(); $fixtures = []; if (null !== $bundle) { $bundle = $this->getContainer()->singleton('kernel')->getBundle($bundle); $path = $bundle->getRootPath() . '/Fixtures'; $files = $finder->in($path)->name('*Fixture.php')->files(); foreach ($files as $file) { $fixtures[] = $bundle->getNamespace() . '\\Fixtures\\' . pathinfo($file->getFilename(), PATHINFO_FILENAME); } return $fixtures; } $bundles = $this->getContainer()->singleton('kernel')->getBundles(); foreach ($bundles as $bundle) { $path = $bundle->getRootPath() . '/Fixtures'; if (!file_exists($path)) { continue; } $files = $finder->in($path)->name('*Fixture.php')->files(); foreach ($files as $file) { $fixtures[$bundle->getName()] = $bundle->getNamespace() . '\\Fixtures\\' . pathinfo($file->getFilename(), PATHINFO_FILENAME); } } return $fixtures; }
public function testFinderBuilderClear() { $finder = FinderBuilder::create()->in(sys_get_temp_dir())->name('*.php')->notName('*.js')->path('/plugin')->notPath('/vendor')->exclude('/js')->clearPath()->clearNotPath()->clearExclude()->build(); $expectedFinder = new Finder(); $expectedFinder->in(sys_get_temp_dir())->name('*.php')->notName('*.js'); self::assertEquals($expectedFinder, $finder); }
/** * Track a set of paths * * @param array $paths the list of directories or files to track / follow */ public function __construct(array $paths) { //Filter out the files, the Finder class can not handle files in the ->in() call. $files = array_filter($paths, function ($possible_file) { return is_file($possible_file); }); //Filter out the directories to be used for searching using the Filter class. $dirs = array_filter($paths, function ($possible_dir) { return is_dir($possible_dir); }); $finder = new Finder(); //Add the given 'stand-alone-files' $finder->append($files); //Add the Directores recursively $finder = $finder->in($dirs); //Filter out non readable files $finder = $finder->filter(function (SplFileInfo $finder) { return $finder->isReadable(); }); //Loop through all the files and save the latest modification time. foreach ($finder->files() as $file) { /*@var $file \SplFileInfo */ if ($this->modification_time < $file->getMTime()) { $this->modification_time = $file->getMTime(); } } }
/** * Compiles satis into a single phar file * * @param string $pharFile The full path to the file to create * * @throws \RuntimeException */ public function compile($pharFile = 'satis.phar') { if (file_exists($pharFile)) { unlink($pharFile); } $phar = new \Phar($pharFile, 0, 'satis.phar'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $finders = array(); $finder = new Finder(); $finder->files()->ignoreVCS(true)->name('*.php')->notName('Compiler.php')->in(__DIR__ . '/../../'); $finders[] = $finder; $finder = new Finder(); $finder->files()->name('*')->in(__DIR__ . '/../../../views/'); $finders[] = $finder; $finder = new Finder(); $finder->files()->ignoreVCS(true)->name('*.php')->name('composer-schema.json')->exclude(array('phpunit', 'mikey179', 'phpdocumentor', 'sebastian', 'phpspec', 'doctrine', 'test', 'tests', 'Tests'))->in(__DIR__ . '/../../../vendor/'); $finders[] = $finder; foreach ($finders as $finder) { foreach ($finder as $file) { $this->addFile($phar, $file); } } $this->addSatisBin($phar); // Stubs $phar->setStub($this->getStub()); $phar->stopBuffering(); $phar->compressFiles(\Phar::GZ); $this->addFile($phar, new \SplFileInfo(__DIR__ . '/../../../LICENSE'), false); $this->addFile($phar, new \SplFileInfo(__DIR__ . '/../../../res/satis-schema.json'), false); unset($phar); }
public static function followLinks(array $paths, $excludePatterns) { $finder = new Finder(); $finder->directories(); foreach ($excludePatterns as $excludePattern) { if (substr($excludePattern, 0, 1) == '/') { $excludePattern = substr($excludePattern, 1); } $excludePattern = '/' . preg_quote($excludePattern, '/') . '/'; $excludePattern = str_replace(preg_quote('*', '/'), '.*', $excludePattern); $finder->notPath($excludePattern); } foreach ($paths as $p) { $finder->in($p); } foreach ($finder as $i) { if ($i->isLink()) { $realPath = $i->getRealPath(); foreach ($paths as $k => $p2) { if (substr($realPath, 0, strlen($p2) + 1) == $p2 . '/') { continue 2; } } $paths[] = $realPath; } } return $paths; }
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); }
/** * Compiles the Silex source code into one single Phar file. * * @param string $pharFile Name of the output Phar file */ public function compile($pharFile = 'silex.phar') { if (file_exists($pharFile)) { unlink($pharFile); } $process = new Process('git log --pretty="%h %ci" -n1 HEAD'); if ($process->run() > 0) { throw new \RuntimeException('The git binary cannot be found.'); } $this->version = trim($process->getOutput()); $phar = new \Phar($pharFile, 0, 'silex.phar'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $finder = new Finder(); $finder->files()->ignoreVCS(true)->name('*.php')->notName('Compiler.php')->in(__DIR__ . '/..')->in(__DIR__ . '/../../vendor/pimple/pimple/lib')->in(__DIR__ . '/../../vendor/symfony/class-loader/Symfony/Component/ClassLoader')->in(__DIR__ . '/../../vendor/symfony/event-dispatcher/Symfony/Component/EventDispatcher')->in(__DIR__ . '/../../vendor/symfony/http-foundation/Symfony/Component/HttpFoundation')->in(__DIR__ . '/../../vendor/symfony/http-kernel/Symfony/Component/HttpKernel')->in(__DIR__ . '/../../vendor/symfony/routing/Symfony/Component/Routing')->in(__DIR__ . '/../../vendor/symfony/browser-kit/Symfony/Component/BrowserKit')->in(__DIR__ . '/../../vendor/symfony/css-selector/Symfony/Component/CssSelector')->in(__DIR__ . '/../../vendor/symfony/dom-crawler/Symfony/Component/DomCrawler'); foreach ($finder as $file) { $this->addFile($phar, $file); } $this->addFile($phar, new \SplFileInfo(__DIR__ . '/../../LICENSE'), false); $this->addFile($phar, new \SplFileInfo(__DIR__ . '/../../vendor/.composer/autoload.php')); $this->addFile($phar, new \SplFileInfo(__DIR__ . '/../../vendor/.composer/ClassLoader.php')); $this->addFile($phar, new \SplFileInfo(__DIR__ . '/../../vendor/.composer/autoload_namespaces.php')); // Stubs $phar->setStub($this->getStub()); $phar->stopBuffering(); // $phar->compressFiles(\Phar::GZ); unset($phar); }
/** * @return \Symfony\Component\Finder\Finder|\Symfony\Component\Finder\SplFileInfo[] */ private function getBundleTransferSchemas() { $testBundleSchemaDirectory = Configuration::projectDir() . DIRECTORY_SEPARATOR . 'src'; $finder = new Finder(); $finder->files()->in($testBundleSchemaDirectory)->name('*.transfer.xml'); return $finder; }
public function configure() { parent::configure(); $filePath = $this->getFilePath(); $mode = $this->getOpenMode(); if ($this->fh) { @fclose($this->fh); } if (filesize($filePath) > 1024 * $this->getConfig(self::VAR_MAX_FILE_SIZE_KB, self::MAX_FILE_SIZE_KB_DEFAULT)) { $backupFile = $filePath . '.' . strftime('%Y-%m-%d_%H-%M-%S'); @rename($filePath, $backupFile); @touch($filePath); @chmod($filePath, 0666); // Keep the number of files below VAR_MAX_FILE_COUNT $maxCount = $this->getConfig(self::VAR_MAX_FILE_COUNT, self::MAX_FILE_COUNT_DEFAULT); $finder = new Finder(); $files = $finder->in(dirname($filePath))->files()->name(basename($filePath) . '.*')->sortByModifiedTime(); $deleteCount = 1 + $files->count() - $maxCount; if ($deleteCount > 0) { foreach ($files as $file) { @unlink($file); if (--$deleteCount <= 0) { break; } } } } $this->fh = fopen($filePath, $mode); }
public function findTranslations($path = null) { $path = $path ?: base_path(); $keys = array(); $functions = array('trans', 'trans_choice', 'Lang::get', 'Lang::choice', 'Lang::trans', 'Lang::transChoice', '@lang', '@choice'); $pattern = "(" . implode('|', $functions) . ")" . "\\(" . "[\\'\"]" . "(" . "[a-zA-Z0-9_-]+" . "([.][^)]+)+" . ")" . "[\\'\"]" . "[\\),]"; // Close parentheses or new parameter // Find all PHP + Twig files in the app folder, except for storage $finder = new Finder(); $finder->in($path)->exclude('storage')->name('*.php')->name('*.twig')->files(); /** @var \Symfony\Component\Finder\SplFileInfo $file */ foreach ($finder as $file) { // Search the current file for the pattern if (preg_match_all("/{$pattern}/siU", $file->getContents(), $matches)) { // Get all matches foreach ($matches[2] as $key) { $keys[] = $key; } } } // Remove duplicates $keys = array_unique($keys); // Add the translations to the database, if not existing. foreach ($keys as $key) { // Split the group and item list($group, $item) = explode('.', $key, 2); $this->missingKey('', $group, $item); } // Return the number of found translations return count($keys); }
/** * Generate Remote API from a list of controllers */ public function generateRemotingApi() { $list = array(); foreach ($this->remotingBundles as $bundle) { $bundleRef = new \ReflectionClass($bundle); $controllerDir = new Finder(); $controllerDir->files()->in(dirname($bundleRef->getFileName()) . '/Controller/')->name('/.*Controller\\.php$/'); foreach ($controllerDir as $controllerFile) { /** @var SplFileInfo $controllerFile */ $controller = $bundleRef->getNamespaceName() . "\\Controller\\" . substr($controllerFile->getFilename(), 0, -4); $controllerRef = new \ReflectionClass($controller); foreach ($controllerRef->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { /** @var $methodDirectAnnotation Direct */ $methodDirectAnnotation = $this->annoReader->getMethodAnnotation($method, 'Tpg\\ExtjsBundle\\Annotation\\Direct'); if ($methodDirectAnnotation !== null) { $nameSpace = str_replace("\\", ".", $bundleRef->getNamespaceName()); $className = str_replace("Controller", "", $controllerRef->getShortName()); $methodName = str_replace("Action", "", $method->getName()); $list[$nameSpace][$className][] = array('name' => $methodName, 'len' => count($method->getParameters())); } } } } return $list; }