getIterator() public method

This method implements the IteratorAggregate interface.
public getIterator ( ) : Iterator | Symfony\Component\Finder\SplFileInfo[]
return Iterator | Symfony\Component\Finder\SplFileInfo[] An iterator
 /**
  * import
  *
  * @param string                $sourceDir
  * @param DocumentNodeInterface $targetNode
  * @param array                 $excludes
  */
 public function import($sourceDir, DocumentNodeInterface $targetNode, array $excludes = array())
 {
     if (!is_dir($sourceDir)) {
         throw new \InvalidArgumentException(sprintf('The directory %s does not exist', $sourceDir));
     }
     $this->emn->persist($targetNode);
     $currentNode = array(0 => $targetNode);
     $finder = new Finder();
     $finder->in($sourceDir);
     $files = $finder->getIterator();
     foreach ($files as $file) {
         foreach ($excludes as $exclude) {
             if (strpos($file->getRelativePathname(), $exclude) !== false) {
                 continue 2;
             }
         }
         $depth = $files->getDepth();
         if ($file->isDir()) {
             $currentNode[$depth + 1] = $this->importDir($currentNode, $depth, $file, $targetNode);
         } elseif ($file->isFile()) {
             $this->importFile($currentNode, $depth, $file);
         }
     }
     $this->emn->flush();
 }
Esempio n. 2
0
 /**
  * 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;
 }
 /**
  * {@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));
 }
Esempio n. 4
0
 /**
  * Test is files or directories passed as arguments are empty.
  * Only valid for regular files and directories.
  *
  * @param mixed $files String or array of strings of path to files and directories.
  *
  * @return boolean True if all arguments are empty. (Size 0 for files and no children for directories).
  */
 public function isEmpty($files)
 {
     if (!$files instanceof \Traversable) {
         $files = new \ArrayObject(is_array($files) ? $files : array($files));
     }
     foreach ($files as $file) {
         if (!$this->exists($file)) {
             throw new FileNotFoundException(null, 0, null, $file);
         }
         if (is_file($file)) {
             $file_info = new \SplFileInfo($file);
             if ($file_info->getSize() !== 0) {
                 return false;
             }
         } elseif (is_dir($file)) {
             $finder = new Finder();
             $finder->in($file);
             $it = $finder->getIterator();
             $it->rewind();
             if ($it->valid()) {
                 return false;
             }
         } else {
             throw new IOException(sprintf('File "%s" is not a directory or a regular file.', $file), 0, null, $file);
         }
     }
     return true;
 }
 protected function fetchFromCache($dimensions)
 {
     $fs = new Filesystem();
     $cacheDir = $_SERVER['HOME'] . '/.symfony/media';
     if (!$fs->exists($cacheDir)) {
         $fs->mkdir($cacheDir, 0777);
     } else {
         $cacheDir .= '/' . $dimensions['w'] . '-' . $dimensions['h'];
         if (!$fs->exists($cacheDir)) {
             $fs->mkdir($cacheDir, 0777);
         } else {
             $finder = new Finder();
             $files = $finder->in($cacheDir . '/')->files();
             if ($files->count() === 3) {
                 $iterator = $finder->getIterator();
                 $iterator->rewind();
                 for ($i = 0; $i < rand(0, 2); $i++) {
                     $iterator->next();
                 }
                 $file = new File($iterator->current());
                 $fs->copy($file->getRealPath(), sys_get_temp_dir() . '/' . $file->getFilename());
                 return new File(sys_get_temp_dir() . '/' . $file->getFilename());
             }
         }
     }
 }
Esempio n. 6
0
 /**
  * Return available art
  * @return array
  */
 protected function availableArt()
 {
     // Find all of the art in the assets directory.
     $finder = new Finder();
     $finder->files()->in($this->config->get('assets_dir'))->depth('== 0')->name('*.txt')->sortbyname();
     return array_values(array_map(function ($file) {
         return $file->getBasename('.txt');
     }, (array) $finder->getIterator()));
 }
 /**
  * Available file reflections. Generator.
  *
  *
  * @generate ReflectionFile[]
  */
 protected function availableReflections()
 {
     /**
      * @var SplFileInfo $file
      */
     foreach ($this->finder->getIterator() as $file) {
         $reflection = $this->tokenizer->fileReflection((string) $file);
         //We are not analyzing files which has includes, it's not safe to require such reflections
         if ($reflection->hasIncludes()) {
             $this->logger()->warning("File '{filename}' has includes and will be excluded from analysis.", ['filename' => (string) $file]);
             continue;
         }
         /**
          * @var ReflectionFile $reflection
          */
         (yield $reflection);
     }
 }
Esempio n. 8
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln($this->getDescription() . PHP_EOL);
     $target = $input->getArgument('target');
     $sources = $this->createArrayBy($input->getOption('source'));
     $excludes = $this->createArrayBy($input->getOption('exclude'));
     $noComments = (bool) $input->getOption('nocomments');
     $this->writer->setTarget($target);
     $this->finder->in($sources)->exclude($excludes);
     if ($notName = $input->getOption('notname')) {
         $this->finder->notName($notName);
     }
     $output->writeln(sprintf(Message::PROGRESS_FILTER, $this->finder->count()));
     $classMap = $this->filter->extractClassMapFrom($this->finder->getIterator());
     $output->writeln(sprintf(Message::PROGRESS_WRITE, $target));
     $this->writer->minify($classMap, $noComments);
     $output->writeln(PHP_EOL . Message::PROGRESS_DONE . PHP_EOL);
 }
Esempio n. 9
0
 private function isEmptyDir($path)
 {
     if ($this->fs->exists($path) === true) {
         $finder = new Finder();
         $finder->in($path);
         $iterator = $finder->getIterator();
         $iterator->next();
         return iterator_count($iterator) === 0;
     }
     return true;
 }
Esempio n. 10
0
 public function getRepositoryFiles()
 {
     try {
         $f = new Finder();
         $f->name('*Repository.php');
         $f->in($this->getDocumentDirectory());
         return $f->getIterator();
     } catch (\Exception $e) {
         return array();
     }
 }
Esempio n. 11
0
 /**
  * {@inheritDoc}
  */
 public function matches(Repo $repo)
 {
     $directory = $repo->getGitRepo()->getDir();
     $finder = new Finder();
     $finder->files()->name('*Kernel.php')->in($directory)->depth('< 3');
     $candidates = $finder->getIterator();
     foreach ($candidates as $candidate) {
         if (preg_match('/public function registerBundles/s', file_get_contents($candidate))) {
             return true;
         }
     }
     return false;
 }
 /**
  * Initializes the internal Symfony Finder with appropriate filters
  *
  * @param string $sources  Path to source files to be archived
  * @param array  $excludes Composer's own exclude rules from composer.json
  */
 public function __construct($sources, array $excludes)
 {
     $fs = new Filesystem();
     $sources = $fs->normalizePath($sources);
     $filters = array(new HgExcludeFilter($sources), new GitExcludeFilter($sources), new ComposerExcludeFilter($sources, $excludes));
     $this->finder = new Finder();
     $filter = function (\SplFileInfo $file) use($sources, $filters, $fs) {
         if ($file->isLink() && strpos($file->getLinkTarget(), $sources) !== 0) {
             return false;
         }
         $relativePath = preg_replace('#^' . preg_quote($sources, '#') . '#', '', $fs->normalizePath($file->getRealPath()));
         $exclude = false;
         foreach ($filters as $filter) {
             $exclude = $filter->filter($relativePath, $exclude);
         }
         return !$exclude;
     };
     if (method_exists($filter, 'bindTo')) {
         $filter = $filter->bindTo(null);
     }
     $this->finder->in($sources)->filter($filter)->ignoreVCS(true)->ignoreDotFiles(false);
     parent::__construct($this->finder->getIterator());
 }
 private function calculateDirVersion(Resource $resource)
 {
     // Adjust finder
     $dir = $resource->getMetadata('dir');
     if (!is_dir($dir)) {
         throw new \InvalidArgumentException(sprintf('Directory "%s" not found.', $dir));
     }
     $this->finder->files()->in($dir);
     if ($resource->hasMetadata('filter')) {
         $this->finder->name($resource->getMetadata('filter'));
     }
     if ($resource->hasMetadata('depth')) {
         $this->finder->depth($resource->getMetadata('depth'));
     } else {
         $this->finder->depth('>= 0');
     }
     $version = array();
     /** @var \SplFileInfo $file */
     foreach ($this->finder->getIterator() as $file) {
         $version[md5($file->getRealPath())] = filemtime($file);
     }
     return $version;
 }
 /**
  * @Route("s/", name="admin_file_home", defaults={"page" = 1})
  * @Route("s/page-{page}", name="admin_file_home_page", requirements={"page" : "\d+"})
  */
 public function indexAction($page)
 {
     $page = $page < 1 ? 1 : $page;
     $itemsPerPage = 10;
     $finder = new Finder();
     $finder->files()->in($this->getParameter('uploads_directory'));
     $iterator = iterator_to_array($finder->getIterator());
     $total = $finder->count();
     $totalPages = ceil($total / $itemsPerPage);
     if ($totalPages != 0 && $page > $totalPages) {
         throw new NotFoundHttpException('There are only ' . $totalPages . ' pages to show');
     }
     $start = ($page - 1) * $itemsPerPage;
     return $this->render('/admin/file/admin_file_index.html.twig', ['files' => array_slice($iterator, $start, $itemsPerPage), 'total' => $total, 'totalPages' => $totalPages, 'page' => $page]);
 }
Esempio n. 15
0
 public function testSomeEdge()
 {
     $nsVertex = 'Trismegiste\\Mondrian\\Transform\\Vertex\\';
     $scan = new Finder();
     $scan->files()->in(__DIR__ . '/../Fixtures/Project/');
     $this->compiler->run($scan->getIterator());
     $result = $this->graph;
     $classVertex = $this->findVertex($result, $nsVertex . 'ClassVertex', 'Project\\Concrete');
     $this->assertNotNull($classVertex);
     $signature = $this->findVertex($result, $nsVertex . 'MethodVertex', 'Project\\Concrete::simple');
     $this->assertNotNull($signature);
     $this->assertNotNull($result->searchEdge($classVertex, $signature));
     $impl = $this->findVertex($result, $nsVertex . 'ImplVertex', 'Project\\Concrete::simple');
     $this->assertNotNull($impl);
     $this->assertNotNull($result->searchEdge($signature, $impl));
 }
Esempio n. 16
0
 public function getIterator()
 {
     $iterator = parent::getIterator();
     if ($iterator instanceof Base) {
         $iterator = $iterator->getIterator();
     }
     $list = $iterator->getArrayCopy();
     if ($this->max) {
         $list = array_slice($list, 0, $this->max);
     }
     if (!$this->order) {
         $list = array_reverse($list);
     }
     //        $finder = new ArrayIterator(array_reverse($finder->getIterator()->getArrayCopy())); // dowracam kolejność
     return new ArrayIterator($list);
 }
Esempio n. 17
0
 /**
  * @Route("/files/{fileName}/meta")
  * @Method("GET")
  */
 public function GetFileMeta($fileName)
 {
     $finder = new Finder();
     $finder->files()->name($fileName)->in('../data');
     if ($finder->count() == 0) {
         //throw new FileNotFoundException($fileName);
         return new Response("File " . $fileName . " not found", Response::HTTP_NOT_FOUND);
     }
     $iterator = $finder->getIterator();
     $iterator->rewind();
     $file = $iterator->current();
     $array = ["name" => $file->getFileName(), "extension" => $file->getExtension(), "size" => filesize($file), "type" => $file->getType()];
     $response = new Response(json_encode($array));
     $response->headers->set('Content-Type', 'application/json');
     return $response;
 }
Esempio n. 18
0
 /**
  * Returns an Iterator for the current Finder configuration.
  *
  * This method implements the IteratorAggregate interface.
  *
  * @return \Iterator An iterator
  *
  * @throws \LogicException if the setContainer() method has not been called
  */
 public function getIterator($ns = 'BackBee\\Console\\Command')
 {
     if (null === $this->container) {
         throw new \LogicException('You must call setContainer() before iterating over this finder.');
     }
     $iterator = parent::getIterator();
     $result = new \ArrayIterator();
     foreach ($iterator as $file) {
         if ($relativePath = $file->getRelativePath()) {
             $ns .= '\\' . strtr($relativePath, '/', '\\');
         }
         $r = new \ReflectionClass($ns . '\\' . $file->getBasename('.php'));
         if ($r->isSubclassOf('BackBee\\Console\\AbstractCommand') && !$r->isAbstract() && !$r->getConstructor()->getNumberOfRequiredParameters()) {
             $result->append($r->newInstance());
         }
     }
     return $result;
 }
Esempio n. 19
0
 /**
  * {@inheritdoc}
  */
 public function loadLocale($locale)
 {
     $domains = [];
     $finder = new Finder();
     $finder->in($this->config->localeDirectory($locale));
     /**
      * @var SplFileInfo $file
      */
     foreach ($finder->getIterator() as $file) {
         $this->logger()->info("Found locale domain file '{file}'", ['file' => $file->getFilename()]);
         //Per application agreement domain name must present in filename
         $domain = strstr($file->getFilename(), '.', true);
         if ($this->config->hasLoader($file->getExtension())) {
             $loader = $this->config->loaderClass($file->getExtension());
             $domains[$domain] = $this->loadCatalogue($locale, $domain, $file, new $loader());
         }
     }
     return $domains;
 }
 /**
  * @todo Find objects in vendor dir
  */
 protected function getGeneratorYml($controller)
 {
     preg_match('/(.+)?Controller.+::.+/', $controller, $matches);
     $dir = str_replace('\\', DIRECTORY_SEPARATOR, $matches[1]);
     $generatorName = $this->getBaseGeneratorName($controller) ? $this->getBaseGeneratorName($controller) . '-' : '';
     $generatorName .= 'generator.yml';
     $finder = new Finder();
     $finder->files()->name($generatorName);
     $namespace_directory = realpath($this->container->getParameter('kernel.root_dir') . '/../src/' . $dir . '/Resources/config');
     if (is_dir($namespace_directory)) {
         $finder->in($namespace_directory);
         $it = $finder->getIterator();
         $it->rewind();
         if ($it->valid()) {
             return $it->current()->getRealpath();
         }
     }
     throw new NotAdminGeneratedException();
 }
 function it_detects_the_violations_of_files($ruleChecker, $nodeExtractorResolver, $eventDispatcher, NodeInterface $node, ViolationInterface $violation, Finder $finder, RuleInterface $rule1, RuleInterface $rule2, NodeParserInterface $extractor)
 {
     $file = new \SplFileObject(__FILE__);
     $finder->getIterator()->willReturn(new \ArrayIterator(array($file)));
     $nodeExtractorResolver->resolve(Argument::any())->willReturn($extractor);
     $extractor->parse($file)->willReturn($node);
     $ruleChecker->check($rule1, $node)->willReturn(null);
     $ruleChecker->check($rule2, $node)->willReturn($violation);
     $eventDispatcher->dispatch(Events::PRE_NODES_PARSED, Argument::type('Akeneo\\CouplingDetector\\Event\\PreNodesParsedEvent'))->shouldBeCalled();
     $eventDispatcher->dispatch(Events::NODE_PARSED, Argument::type('Akeneo\\CouplingDetector\\Event\\NodeParsedEvent'))->shouldBeCalled();
     $eventDispatcher->dispatch(Events::POST_NODES_PARSED, Argument::type('Akeneo\\CouplingDetector\\Event\\PostNodesParsedEvent'))->shouldBeCalled();
     $eventDispatcher->dispatch(Events::PRE_RULES_CHECKED, Argument::type('Akeneo\\CouplingDetector\\Event\\PreRulesCheckedEvent'))->shouldBeCalled();
     $eventDispatcher->dispatch(Events::NODE_CHECKED, Argument::type('Akeneo\\CouplingDetector\\Event\\NodeChecked'))->shouldBeCalledTimes(2);
     $eventDispatcher->dispatch(Events::RULE_CHECKED, Argument::type('Akeneo\\CouplingDetector\\Event\\RuleCheckedEvent'))->shouldBeCalledTimes(2);
     $eventDispatcher->dispatch(Events::POST_RULES_CHECKED, Argument::type('Akeneo\\CouplingDetector\\Event\\PostRulesCheckedEvent'))->shouldBeCalled();
     $violations = $this->detect($finder, array($rule1, $rule2));
     $violations->shouldHaveCount(1);
     $violations->shouldBeArray();
     $violations[0]->shouldBeAnInstanceOf('Akeneo\\CouplingDetector\\Domain\\ViolationInterface');
 }
Esempio n. 22
0
 private function prepareFinder()
 {
     if (!isset($this->resource)) {
         throw new \RuntimeException('Resource not set.');
     }
     $dir = $this->resource->getMetadata('dir');
     if (!is_dir($dir)) {
         throw new \InvalidArgumentException(sprintf('Directory "%s" not found.', $dir));
     }
     $this->finder->files()->in($dir);
     if ($this->resource->hasMetadata('filter')) {
         $this->finder->name($this->resource->getMetadata('filter'));
     }
     if ($this->resource->hasMetadata('depth')) {
         $this->finder->depth($this->resource->getMetadata('depth'));
     } else {
         $this->finder->depth('>= 0');
     }
     $this->iterator = $this->finder->getIterator();
     $this->iterator->rewind();
 }
Esempio n. 23
0
 public function find2Classes($directory, $namespace, $ignoreSuffix = array())
 {
     if (false === $this->filesystem->exists($directory)) {
         return array();
     }
     $classes = array();
     $finder = new Finder();
     $finder->files();
     if (count($ignoreSuffix)) {
         $finder->name(sprintf('/(?<!%s)\\.php$/', implode('|', $ignoreSuffix)));
     } else {
         $finder->name('*.php');
     }
     $finder->in($directory);
     foreach ($finder->getIterator() as $name) {
         $baseName = substr($name, strlen($directory) + 1, -4);
         $baseClassName = str_replace('/', '\\', $baseName);
         $classes[] = $namespace . '\\' . $baseClassName;
     }
     return $classes;
 }
 /**
  * Get the most recent schema
  *
  * @param type $configuration
  */
 protected function getLastSchemaDefinition($configuration)
 {
     $migrationDirectoryHelper = new \Doctrine\DBAL\Migrations\Tools\Console\Helper\MigrationDirectoryHelper($configuration);
     $dir = $migrationDirectoryHelper->getMigrationDirectory() . '/SchemaVersion';
     //create the directory if required
     $fs = new Filesystem();
     $fs->mkdir($dir);
     //get the files containing the schema
     $finder = new Finder();
     $finder->in($dir);
     $finder->sortByName();
     $filesIterator = $finder->getIterator();
     $filesArray = iterator_to_array($filesIterator);
     if (count($filesArray) === 0) {
         $lastSchema = new \Doctrine\DBAL\Schema\Schema();
     } else {
         //get last entry
         $lastSchemaFile = end($filesArray);
         $content = $lastSchemaFile->getContents();
         $lastSchema = unserialize($content);
     }
     return $lastSchema;
 }
Esempio n. 25
0
 /**
  * @return array|\Iterator
  */
 public function getSerializerFiles()
 {
     try {
         $f = new Finder();
         $f->name('*.xml.skeleton');
         $f->name('*.yml.skeleton');
         $f->in($this->getMappingSerializerDirectory());
         return $f->getIterator();
     } catch (\Exception $e) {
         return array();
     }
 }
Esempio n. 26
0
 public function testGetIterator()
 {
     $finder = new Finder();
     try {
         $finder->getIterator();
         $this->fail('->getIterator() throws a \\LogicException if the in() method has not been called');
     } catch (\Exception $e) {
         $this->assertInstanceOf('LogicException', $e, '->getIterator() throws a \\LogicException if the in() method has not been called');
     }
     $finder = new Finder();
     $dirs = array();
     foreach ($finder->directories()->in(self::$tmpDir) as $dir) {
         $dirs[] = (string) $dir;
     }
     $expected = $this->toAbsolute(array('foo', 'toto'));
     sort($dirs);
     sort($expected);
     $this->assertEquals($expected, $dirs, 'implements the \\IteratorAggregate interface');
     $finder = new Finder();
     $this->assertEquals(2, iterator_count($finder->directories()->in(self::$tmpDir)), 'implements the \\IteratorAggregate interface');
     $finder = new Finder();
     $a = iterator_to_array($finder->directories()->in(self::$tmpDir));
     $a = array_values(array_map(function ($a) {
         return (string) $a;
     }, $a));
     sort($a);
     $this->assertEquals($expected, $a, 'implements the \\IteratorAggregate interface');
 }
 /**
  * @return int
  */
 public function count()
 {
     return iterator_count(parent::getIterator());
 }
Esempio n. 28
0
 /**
  * {@inheritdoc}
  */
 public function publishDirectory($directory, $destination, $merge = self::OVERWRITE, $mode = FilesInterface::READONLY)
 {
     if (!$this->files->isDirectory($directory)) {
         throw new PublishException("Given '{$directory}' is not valid directory.");
     }
     $finder = new Finder();
     $finder->files()->in($directory);
     /**
      * @var SplFileInfo $file
      */
     foreach ($finder->getIterator() as $file) {
         $this->publish((string) $file, $destination . '/' . $file->getRelativePathname(), $merge, $mode);
     }
 }
Esempio n. 29
0
 public function testAppendWithAnArray()
 {
     $finder = new Finder();
     $finder->files()->in(self::$tmpDir . DIRECTORY_SEPARATOR . 'foo');
     $finder->append($this->toAbsolute(array('foo', 'toto')));
     $this->assertIterator($this->toAbsolute(array('foo', 'foo/bar.tmp', 'toto')), $finder->getIterator());
 }
Esempio n. 30
0
 /**
  * @return \Iterator
  */
 public function getIterator()
 {
     return $this->finder->getIterator();
 }