depth() public méthode

Usage: $finder->depth('> 1') // the Finder will start matching at level 1. $finder->depth('< 3') // the Finder will descend at most 3 levels of directories below the starting point.
See also: DepthRangeFilterIterator
See also: NumberComparator
public depth ( string | integer $level ) : Finder | Symfony\Component\Finder\SplFileInfo[]
$level string | integer The depth level expression
Résultat Finder | Symfony\Component\Finder\SplFileInfo[] The current Finder instance
 /**
  * @Route("/inbox", defaults={"_format"="json"})
  */
 public function dirAction(Request $request)
 {
     $dir = $request->query->get("dir", "");
     $type = $request->query->get("type", "file");
     $baseDir = realpath($this->container->getParameter('pumukit2.inbox'));
     /*
     if(0 !== strpos($dir, $baseDir)) {
         throw $this->createAccessDeniedException();
     }
     */
     $finder = new Finder();
     $res = array();
     if ("file" == $type) {
         $finder->depth('< 1')->followLinks()->in($dir);
         $finder->sortByName();
         foreach ($finder as $f) {
             $res[] = array('path' => $f->getRealpath(), 'relativepath' => $f->getRelativePathname(), 'is_file' => $f->isFile(), 'hash' => hash('md5', $f->getRealpath()), 'content' => false);
         }
     } else {
         $finder->depth('< 1')->directories()->followLinks()->in($dir);
         $finder->sortByName();
         foreach ($finder as $f) {
             if (0 !== count(glob("{$f}/*"))) {
                 $contentFinder = new Finder();
                 $contentFinder->files()->in($f->getRealpath());
                 $res[] = array('path' => $f->getRealpath(), 'relativepath' => $f->getRelativePathname(), 'is_file' => $f->isFile(), 'hash' => hash('md5', $f->getRealpath()), 'content' => $contentFinder->count());
             }
         }
     }
     return new JsonResponse($res);
 }
Exemple #2
0
 /**
  * @param bool $isRecursive
  * @return $this
  */
 public function isRecursive($isRecursive = true)
 {
     if ($isRecursive === false) {
         $this->finder->depth(0);
     } else {
         $this->finder->depth('>= 0');
     }
     return $this;
 }
Exemple #3
0
 /**
  * @return array
  */
 public function getReleases()
 {
     $releases = [];
     $this->finder->depth('== 2')->name('*.zip');
     /** @var SplFileInfo $file */
     foreach ($this->finder as $file) {
         $releases[] = new Release($file);
     }
     return $releases;
 }
Exemple #4
0
 public function indexAction(Request $request)
 {
     $form = $request->request->all();
     $no_js = $request->query->get('no-js') || 0;
     $script = $no_js == 1 ? 0 : 1;
     $db_dir = $this->get('kernel')->getBundle('EUREKAG6KBundle', true)->getPath() . "/Resources/data/databases";
     try {
         $this->datasources = new \SimpleXMLElement($db_dir . "/DataSources.xml", LIBXML_NOWARNING, true);
         $datasourcesCount = $this->datasources->DataSource->count();
     } catch (\Exception $e) {
         $datasourcesCount = 0;
     }
     $userManager = $this->get('fos_user.user_manager');
     $users = $userManager->findUsers();
     $finder = new Finder();
     $simu_dir = $this->get('kernel')->getBundle('EUREKAG6KBundle', true)->getPath() . "/Resources/data/simulators";
     $finder->depth('== 0')->files()->name('*.xml')->in($simu_dir);
     $simulatorsCount = $finder->count();
     $finder = new Finder();
     $views_dir = $this->get('kernel')->getBundle('EUREKAG6KBundle', true)->getPath() . "/Resources/views";
     $finder->depth('== 0')->ignoreVCS(true)->exclude(array('admin', 'base', 'Theme'))->directories()->in($views_dir);
     $viewsCount = $finder->count();
     $hiddens = array();
     $hiddens['script'] = $script;
     $silex = new Application();
     $silex->register(new MobileDetectServiceProvider());
     try {
         return $this->render('EUREKAG6KBundle:admin/pages:index.html.twig', array('ua' => $silex["mobile_detect"], 'path' => $request->getScheme() . '://' . $request->getHttpHost(), 'nav' => 'home', 'datasourcesCount' => $datasourcesCount, 'usersCount' => count($users), 'simulatorsCount' => $simulatorsCount, 'viewsCount' => $viewsCount, 'hiddens' => $hiddens));
     } catch (\Exception $e) {
         echo $e->getMessage();
         throw $this->createNotFoundException($this->get('translator')->trans("This template does not exist"));
     }
 }
 public function fix()
 {
     // Clear the cache beforehand, ar this will make sure we have a lot less files to deal with.
     $result = $this->app['cache']->clearCache();
     $files = '';
     $finder = new Finder();
     $finder->depth('<4');
     foreach ($this->locations as $loc) {
         $finder->in($loc);
     }
     foreach ($finder as $file) {
         $perms = substr(sprintf('%o', $file->getPerms()), -3);
         if ($file->isDir() && $perms != '777') {
             @chmod($file, 0777);
             if (!$file->isWritable()) {
                 $res = $this->getPrintInfoFile($file);
                 $files .= $res;
             }
         } else {
             if (!$file->isDir() && !$this->checkFilePerms($perms)) {
                 // echo "joe! " . $this->checkFilePerms($perms);
                 @chmod($file, 0666);
                 $res = $this->getPrintInfoFile($file);
                 $files .= $res;
             }
         }
     }
     $msg = "Below you'll see the output of the changes. If there are lines\n        left with a red '<i class='fa fa-close red'></i>', then these files /\n        folders could not be modified by Bolt or the Chmodinator. You should use\n        the command-line or your (S)FTP client to make sure these files are set\n        correctly.";
     $data = array('files' => $files, 'msg' => $msg);
     return $this->render('index.twig', $data);
 }
 protected function ensureProjectRoot()
 {
     if (!($this->rootDir = $this->input->getOption('project-root'))) {
         $this->rootDir = getcwd();
     }
     $this->rootDir = realpath($this->rootDir);
     $this->fs->mkdir($this->rootDir);
     $finder = new Finder();
     $finder->in($this->rootDir);
     $finder->depth(0);
     $finder->ignoreVCS(false);
     $rootFiles = [];
     /** @var SplFileInfo $splInfo */
     foreach ($finder as $splInfo) {
         $rootFiles[] = $splInfo->getFilename();
     }
     $requiredFiles = ['composer.json', 'composer.lock'];
     $requiredDirs = ['vendor'];
     foreach (array_merge($requiredFiles, $requiredDirs) as $file) {
         if (!in_array($file, $rootFiles)) {
             // possibly not root
             $this->output->writeln("<error>You should either run this script under your project root directory, or provide the '--project-root' option.</error>");
             $this->output->writeln("The project root directory should contain at least the following files and directories:");
             foreach ($requiredFiles as $requiredFile) {
                 $this->output->writeln("\t- <comment>{$requiredFile}</comment>");
             }
             foreach ($requiredDirs as $requiredDir) {
                 $this->output->writeln("\t- <comment>{$requiredDir}/</comment>");
             }
             exit(1);
         }
     }
 }
Exemple #7
0
 /**
  * Finds all the files for the given config
  *
  * @param array $source
  *
  * @return SplFileInfo[]
  *
  * @throws \Exception
  */
 protected function getFiles(array $source)
 {
     $fileSet = [];
     foreach ($source as $set) {
         if (!array_key_exists('files', $set)) {
             throw new \Exception("`src` must have a `files` option");
         }
         if (!array_key_exists('path', $set)) {
             $set['path'] = getcwd();
         }
         if (!array_key_exists('recursive', $set)) {
             $set['recursive'] = false;
         }
         $paths = is_array($set['path']) ? $set['path'] : [$set['path']];
         $files = is_array($set['files']) ? $set['files'] : [$set['files']];
         foreach ($paths as $path) {
             foreach ($files as $file) {
                 $finder = new Finder();
                 $finder->files()->in($path)->name($file);
                 if (!$set['recursive']) {
                     $finder->depth('== 0');
                 }
                 $fileSet = $this->appendFileSet($finder, $fileSet);
             }
         }
     }
     return $fileSet;
 }
 public function checkDirAction()
 {
     $paths = array('/' => array('depth' => '<1', 'dir' => true), 'app' => array('depth' => '<1', 'dir' => true), 'src' => array(), 'plugins' => array(), 'api' => array(), 'vendor' => array('depth' => '<1', 'dir' => true), 'vendor2' => array('depth' => '<1', 'dir' => true), 'vendor_user' => array('depth' => '<1', 'dir' => true), 'web' => array('depth' => '<1', 'dir' => true));
     $errorPaths = array();
     if (PHP_OS !== 'WINNT') {
         foreach ($paths as $folder => $opts) {
             $finder = new Finder();
             if (!empty($opts['depth'])) {
                 $finder->depth($opts['depth']);
             }
             if (!empty($opts['dir'])) {
                 $finder->directories();
             }
             try {
                 $finder->in($this->container->getParameter('kernel.root_dir') . '/../' . $folder);
                 foreach ($finder as $fileInfo) {
                     $relaPath = $fileInfo->getRealPath();
                     if (!(is_writable($relaPath) && is_readable($relaPath))) {
                         $errorPaths[] = $relaPath;
                     }
                 }
             } catch (\Exception $e) {
             }
         }
     }
     return $this->render('TopxiaAdminBundle:System:Report/dir-permission.html.twig', array('errorPaths' => $errorPaths));
 }
Exemple #9
0
	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;
	}
 /**
  * execute this command
  *
  * @param   InputInterface   $input   CLI input data
  * @param   OutputInterface  $output  CLI output data
  *
  * @return  int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $startTime = microtime(true);
     // Create a new Finder instance
     $finder = new Finder();
     // Search for files in the directory specified in the CLI argument
     $finder->files();
     // Get paths to scan in; Either from file or from the CLI arguments
     if ($input->getOption('readfromfile')) {
         $paths = $input->getArgument('paths');
         $pathFile = reset($paths);
         $paths = $this->readPathsFromFile($pathFile);
     } else {
         $paths = $input->getArgument('paths');
     }
     foreach ($paths as $path) {
         $finder->in($path);
     }
     // Limit search to recursion level
     if ($input->getOption('depth')) {
         $finder->depth("<= " . $input->getOption('depth'));
     }
     // Append system specific search criteria
     foreach ($this->adapters as $adapterName => $adapter) {
         $finder = $adapter->appendDetectionCriteria($finder);
     }
     $results = array();
     // Iterate through results
     foreach ($finder as $file) {
         // Iterate through system adapters
         foreach ($this->adapters as $adapterName => $adapter) {
             // Pass the search result to the system adapter to verify the result
             if (!($system = $adapter->detectSystem($file))) {
                 // search result doesn't match with system
                 continue;
             }
             // If enabled, try to determine the used CMS version
             if ($input->getOption('versions')) {
                 $system->version = $adapter->detectVersion($system->getPath());
             }
             // Append successful result to array
             $results[] = $system;
         }
     }
     // Generate stats array
     $stats = $this->generateStats($results, $input->getOption('versions'));
     // Write output to command line
     $output->writeln('<info>Successfully finished scan!</info>');
     $output->writeln(sprintf('CMSScanner found %d CMS installations!', count($results)));
     // Write stats to command line
     $this->outputStats($stats, $input->getOption('versions'), $output);
     // Write report file
     if ($input->getOption('report')) {
         $this->writeReport($results, $input->getOption('report'));
         $output->writeln(sprintf("Report was written to %s", $input->getOption('report')));
     }
     $this->outputProfile($startTime, $output);
 }
Exemple #11
0
 /**
  * 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());
 }
Exemple #12
0
 public function compile(ImportEvent $importEvent)
 {
     $results = ['constants' => [], 'handlers' => []];
     $wildcards = [];
     foreach (['constants', 'handlers'] as $type) {
         $e = $type === 'constants';
         foreach (['App', 'Minute'] as $dir) {
             $prefix = $e ? "{$dir}\\Event\\" : "{$dir}\\EventHandler\\";
             $dirs = $this->resolver->find($prefix);
             if (!empty($dirs)) {
                 $finder = new Finder();
                 $fix = function ($path, $replacement) use($prefix) {
                     return preg_replace('/\\.php$/', '', preg_replace(sprintf('/^.*%s/i', preg_quote($prefix)), $replacement, $path));
                 };
                 $files = $finder->depth('< 3')->files()->in($dirs)->name('*.php')->contains($e ? 'const ' : 'function ');
                 foreach ($files as $file) {
                     $classPath = $this->utils->dosPath((string) $file);
                     $classPath = $fix($classPath, $prefix);
                     $basename = $fix($classPath, '');
                     if ($reflector = new ReflectionClass($classPath)) {
                         if ($e) {
                             foreach ($reflector->getConstants() as $value => $constant) {
                                 $parts = explode('.', $constant);
                                 for ($i = 0, $j = count($parts) - 1; $i < $j; $i++) {
                                     $wildcard = join('.', array_slice($parts, 0, $i + 1)) . '.*';
                                     $wildcards[$wildcard] = ['name' => sprintf('%s', strtr($wildcard, '.', '_')), 'value' => $wildcard, 'group' => 'Wildcard events'];
                                 }
                                 $results['constants'][] = ['name' => sprintf('%s in %s', $this->utils->filename($value), $basename), 'value' => $constant, 'group' => $parts[0]];
                             }
                         } else {
                             foreach ($reflector->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
                                 if (!preg_match('/^\\_/', $method->name)) {
                                     $value = sprintf("%s@%s", $method->class, $method->name);
                                     $parts = explode('\\', $classPath);
                                     $results['handlers'][] = ['name' => sprintf('%s@%s', $basename, $method->name), 'value' => $value, 'group' => $parts[2] ?? 'App'];
                                 }
                             }
                         }
                     }
                 }
             }
         }
         usort($results[$type], function ($a, $b) {
             return $a['group'] === $b['group'] ? $a['value'] <=> $b['value'] : $a['group'] <=> $b['group'];
         });
     }
     usort($wildcards, function ($a, $b) {
         return $a['value'] <=> $b['value'];
     });
     foreach ($wildcards as $wildcard => $event) {
         $results['constants'][] = $event;
     }
     $importEvent->addContent($results);
 }
Exemple #13
0
 public function schemaProvider()
 {
     $finder = new Finder();
     $finder->directories()->in(__DIR__ . '/fixtures');
     $finder->depth('< 1');
     $data = array();
     foreach ($finder as $directory) {
         $data[] = [$directory];
     }
     return $data;
 }
 public function resourceProvider()
 {
     $finder = new Finder();
     $finder->directories()->in(__DIR__ . '/fixtures');
     $finder->depth('< 1');
     $data = array();
     foreach ($finder as $directory) {
         $data[] = [file_get_contents($directory->getRealPath() . '/Resource/TestResource.php'), $directory->getRealPath() . '/swagger.json', $directory->getFilename()];
     }
     return $data;
 }
Exemple #15
0
 protected function findManifest()
 {
     $finder = new Finder();
     $finder->depth('==0')->name('*.xml')->files();
     foreach ($finder->in($this->path) as $file) {
         /* @var $file \SplFileObject */
         $this->manifest = new \SimpleXMLElement($file->getContents());
         $this->installFile = $file->getBasename();
         return true;
     }
     return false;
 }
 /**
  * @return array
  */
 private function loadFixtures()
 {
     $parser = new Parser();
     $finder = new Finder();
     $files = $finder->depth('< 3')->in(__DIR__ . '/../../../fixtures')->files()->name('*.yml');
     $fixtures = array();
     /** @var \Symfony\Component\Finder\SplFileInfo $file */
     foreach ($files as $file) {
         $fixtures = array_merge($fixtures, $parser->parse($file->getContents()));
     }
     return $fixtures;
 }
 /**
  *
  * @param string $path        	
  * @return \Symfony\Component\Finder\Finder
  */
 protected function getFinder($path)
 {
     $finder = new Finder();
     $finder->ignoreDotFiles(TRUE);
     $finder->depth(0);
     $finder->exclude($this->excludeDirs);
     if (!is_dir($path)) {
         return $finder;
     }
     $finder->in($path);
     return $finder;
 }
 /**
  * Get all paths to repositories from config
  *
  * @return array
  */
 public function getPaths()
 {
     $paths = array();
     if (!$this->paths) {
         $repositoriesPath = Config::get('git-pretty-stats.repositoriesPath');
         // Repositories are specified as array in config
         if (is_array($repositoriesPath)) {
             $paths = array();
             foreach ($repositoriesPath as $path) {
                 $paths[] = $this->getFullPath($path);
             }
             $directories = $this->finder->depth(0)->directories()->append($paths);
         } elseif (!is_null($repositoriesPath)) {
             $directories = $this->finder->depth(0)->directories()->in($this->getFullPath($repositoriesPath));
         }
         // Real paths for all repositories
         foreach ($directories as $key => $directory) {
             $this->paths[$key] = $directory->getRealPath();
         }
     }
     return $this->paths;
 }
Exemple #19
0
 /**
  * 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());
         }
     }
 }
 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;
 }
Exemple #21
0
 /**
  * Получить относительный путь до Сущности из директории Entity
  * Возвращает последнюю найденную по названию сущность
  * 
  * @return string
  */
 public function getEntityLocationInEntityDirectory()
 {
     $root = $this->getContainer()->get('kernel')->getRootDir();
     $finder = new Finder();
     $finder->name($this->getName() . '.php');
     $finder->depth('< 3');
     $finder->files()->in($root . '/../src/AppBundle/Entity');
     $path = false;
     foreach ($finder as $file) {
         // Удалим из пути все, до директории Entity
         $path = str_replace('/', '\\', str_replace('.php', '', preg_replace('/^.*AppBundle\\/Entity\\//i', '', $file->getRealpath())));
     }
     return $path;
 }
 public function agenteAtivo($em)
 {
     $logger = $this->get('logger');
     // Encontra agentes ativos
     $rootDir = $this->container->get('kernel')->getRootDir();
     $webDir = $rootDir . "/../web/";
     $downloadsDir = $webDir . "downloads/";
     if (!is_dir($downloadsDir)) {
         mkdir($downloadsDir);
     }
     $cacicDir = $downloadsDir . "cacic/";
     if (!is_dir($cacicDir)) {
         mkdir($cacicDir);
     }
     // Varre diretório do Cacic
     $finder = new Finder();
     $finder->depth('== 0');
     $finder->directories()->in($cacicDir);
     $tipo_so = $em->getRepository('CacicCommonBundle:TipoSo')->findAll();
     $found = false;
     $platforms = 0;
     foreach ($finder as $version) {
         //$logger->debug("1111111111111111111111111111111 ".$version->getFileName());
         if ($version->getFileName() == 'current') {
             $found = true;
             foreach ($tipo_so as $so) {
                 $agentes_path = $version->getRealPath() . "/" . $so->getTipo();
                 $agentes = new Finder();
                 try {
                     $agentes->files()->in($agentes_path);
                 } catch (\InvalidArgumentException $e) {
                     $logger->error($e->getMessage());
                     $platforms += 1;
                     $this->get('session')->getFlashBag()->add('notice', '<p>Não foram encontrados agentes para a plataforma ' . $so->getTipo() . '. Por favor, faça upload dos agentes na interface.</p>');
                     continue;
                 }
                 if ($agentes->count() == 0) {
                     $platforms += 1;
                     $this->get('session')->getFlashBag()->add('notice', '<p>Não foram encontrados agentes para a plataforma ' . $so->getTipo() . '. Por favor, faça upload dos agentes na interface.</p>');
                 }
             }
         }
     }
     if (!$found) {
         $this->get('session')->getFlashBag()->add('notice', 'Não existe nenhum agente ativo. Por favor, faça upload dos agentes na interface.');
         return sizeof($tipo_so);
     } else {
         return $platforms;
     }
 }
 public function getHomeEntriesPager()
 {
     $finder = new Finder();
     $finder->files()->name('*.' . $this->file_extension)->in($this->datadir)->sort(function ($file1, $file2) {
         return $file2->getMTime() - $file1->getMTime();
     });
     if ($this->depth > 0) {
         $finder->depth('<= ' . ($this->depth - 1));
     }
     $entries = array();
     foreach ($finder as $file) {
         $entries[] = new Entry($file, $this);
     }
     return new Pagerfanta(new ArrayAdapter($entries));
 }
Exemple #24
0
 public function testDepth()
 {
     $finder = new Finder();
     $this->assertSame($finder, $finder->depth('< 1'));
     $this->assertIterator($this->toAbsolute(array('foo', 'test.php', 'test.py', 'toto')), $finder->in(self::$tmpDir)->getIterator());
     $finder = new Finder();
     $this->assertSame($finder, $finder->depth('<= 0'));
     $this->assertIterator($this->toAbsolute(array('foo', 'test.php', 'test.py', 'toto')), $finder->in(self::$tmpDir)->getIterator());
     $finder = new Finder();
     $this->assertSame($finder, $finder->depth('>= 1'));
     $this->assertIterator($this->toAbsolute(array('foo/bar.tmp')), $finder->in(self::$tmpDir)->getIterator());
     $finder = new Finder();
     $finder->depth('< 1')->depth('>= 1');
     $this->assertIterator(array(), $finder->in(self::$tmpDir)->getIterator());
 }
Exemple #25
0
 private function getAvailableTools()
 {
     static $tools;
     if (!$tools) {
         $tools = [];
         $finder = new Finder();
         $scriptDir = realpath(__DIR__ . '/../Resources/scripts/tools');
         $finder->depth(0)->files()->in($scriptDir);
         foreach ($finder as $file) {
             $tools[$file->getBasename('.php')] = $file->getPathname();
         }
         if (count($tools) === 0) {
             throw new \Exception("No tool available (no script found in {$scriptDir})");
         }
     }
     return $tools;
 }
Exemple #26
0
 private function listPlugins(Application $app)
 {
     $finder = new Finder();
     $finder->depth(0)->in($app['plugins.directory'])->directories();
     $plugins = [];
     foreach ($finder as $pluginDir) {
         $manifest = $error = null;
         $name = $pluginDir->getBasename();
         try {
             $manifest = $app['plugins.plugins-validator']->validatePlugin((string) $pluginDir);
         } catch (PluginValidationException $e) {
             $error = $e;
         }
         $plugins[$name] = new Plugin($name, $manifest, $error);
     }
     return $plugins;
 }
 /**
  * @see \Src\RouterBoard\BackupFilesystem\IBackupFilesystem::fileRotate()
  */
 public function rotateBackupFiles($directory, $extension, $rotate)
 {
     if ($rotate < 5) {
         throw new Exception("Value of the 'backup-rotate' is too low. Minimum is 5.");
     }
     $finder = new Finder();
     $finder->depth('0')->name('*.' . $extension)->sortByModifiedTime()->files()->in($directory);
     $files = array();
     foreach ($finder as $file) {
         $files[] = $file->getRealpath();
     }
     if (($cnt = count($files)) > $rotate) {
         $bfs = new Filesystem();
         for ($i = 0; $i < $cnt - $rotate; $i++) {
             $bfs->remove($files[$i]);
         }
     }
 }
 private function listFiles($rootPath, $currentPath)
 {
     $path = '';
     if (!empty($rootPath)) {
         $path .= "{$rootPath}/";
     }
     if (!empty($currentPath)) {
         $path .= "{$currentPath}/";
     }
     $finder = new Finder();
     $extensionRegex = '/^[^\\.]*$|\\.' . implode('|', array_map('preg_quote', $this->app['config']->get('general/accept_file_types'))) . '$/';
     $rootDir = $this->app['paths']['filespath'] . "/{$path}";
     if (!is_dir($rootDir)) {
         return array();
     }
     $files = $finder->depth('== 0')->name($extensionRegex)->notName('*.exe')->notName('*.php')->notName('*.html')->notName('*.js')->sortByName()->sortByType()->in($rootDir);
     return iterator_to_array($files);
 }
 public function getFiles($path)
 {
     $path = trim($path, '/');
     $files = array();
     $finder = new Finder();
     $finder->depth('==0');
     try {
         /* @var $file \SplFileInfo */
         foreach ($finder->in($this->scheme . '/' . $path) as $file) {
             if (!$file->isDir()) {
                 $item = array();
                 $item['id'] = trim($path . '/' . $file->getFilename(), '/');
                 $item['name'] = $file->getFilename();
                 $item['urls'] = array();
                 $item['type'] = 'binary';
                 $item['size'] = $file->getSize();
                 $extension = strtolower($extension = pathinfo($file->getFilename(), PATHINFO_EXTENSION));
                 // To be compatible with some older PHP 5.3 versions
                 if (in_array($extension, array('gif', 'png', 'jpg', 'jpeg'))) {
                     $item['type'] = 'image';
                     if ($this->imagesize == true) {
                         $content = $file->getContents();
                         if (function_exists('imagecreatefromstring')) {
                             $image = @imagecreatefromstring($content);
                             if ($image) {
                                 $item['width'] = imagesx($image);
                                 $item['height'] = imagesy($image);
                             }
                         }
                     }
                 }
                 $item['timestamp_lastchange'] = $file->getMTime();
                 if ($this->baseUrl != null) {
                     $item['urls']['default'] = $this->baseUrl . '/' . $item['id'];
                 }
                 $files[$file->getFilename()] = $item;
             }
         }
     } catch (\Exception $e) {
         return false;
     }
     return $files;
 }
Exemple #30
0
 /**
  * lint the content of a directory, recursive if defined
  * @param string $dir path/to/dir
  * @return bool
  */
 private function lintDir($dir)
 {
     $finder = new Finder();
     $finder->files()->name('*.xml')->name('*.xml.dist')->in($dir);
     if (!$this->input->getOption(self::OPTION_RECURSIVE)) {
         $finder->depth(0);
     }
     $totalFiles = $finder->count();
     $counter = 0;
     $ret = true;
     /** @var SplFileInfo $file */
     foreach ($finder as $file) {
         $ret = $this->lintFile($file->getRealPath()) && $ret;
         if (++$counter % 30 == 0) {
             $this->output->writeln(sprintf('    (%s/%s %s%%)', $counter, $totalFiles, round($counter / $totalFiles * 100, 0)));
         }
     }
     return $ret;
 }