in() public method

Searches files and directories which match defined rules.
public in ( string | array $dirs ) : Finder | Symfony\Component\Finder\SplFileInfo[]
$dirs string | array A directory path or an array of directories
return Finder | Symfony\Component\Finder\SplFileInfo[] The current Finder instance
コード例 #1
0
 /**
  * Build the BenchmarkMetadata collection.
  *
  * @param string $path
  * @param array $subjectFilter
  * @param array $groupFilter
  */
 public function findBenchmarks($path, array $subjectFilter = [], array $groupFilter = [])
 {
     $finder = new Finder();
     $path = PhpBench::normalizePath($path);
     if (!file_exists($path)) {
         throw new \InvalidArgumentException(sprintf('File or directory "%s" does not exist (cwd: %s)', $path, getcwd()));
     }
     if (is_dir($path)) {
         $finder->in($path)->name('*.php');
     } else {
         // the path is already a file, just restrict the finder to that.
         $finder->in(dirname($path))->depth(0)->name(basename($path));
     }
     $benchmarks = [];
     foreach ($finder as $file) {
         if (!is_file($file)) {
             continue;
         }
         $benchmark = $this->factory->getMetadataForFile($file->getPathname());
         if (null === $benchmark) {
             continue;
         }
         if ($groupFilter) {
             $benchmark->filterSubjectGroups($groupFilter);
         }
         if ($subjectFilter) {
             $benchmark->filterSubjectNames($subjectFilter);
         }
         if (false === $benchmark->hasSubjects()) {
             continue;
         }
         $benchmarks[] = $benchmark;
     }
     return $benchmarks;
 }
コード例 #2
0
ファイル: Drupal.php プロジェクト: ecolinet/platformsh-cli
 /**
  * Detect if there are any Drupal applications in a folder.
  *
  * @param string $directory
  * @param mixed  $depth
  *
  * @return bool
  */
 public static function isDrupal($directory, $depth = '< 2')
 {
     if (!is_dir($directory)) {
         return false;
     }
     $finder = new Finder();
     // Look for at least one Drush make file.
     $finder->in($directory)->files()->depth($depth)->name('project.make*')->name('drupal-org.make*');
     foreach ($finder as $file) {
         return true;
     }
     // Check whether there is an index.php file whose first few lines
     // contain the word "Drupal".
     $finder->in($directory)->files()->depth($depth)->name('index.php');
     foreach ($finder as $file) {
         $f = fopen($file, 'r');
         $beginning = fread($f, 3178);
         fclose($f);
         if (strpos($beginning, 'Drupal') !== false) {
             return true;
         }
     }
     // Check whether there is a composer.json file requiring Drupal core.
     $finder->in($directory)->files()->depth($depth)->name('composer.json');
     foreach ($finder as $file) {
         $composerJson = json_decode(file_get_contents($file), true);
         if (isset($composerJson['require']['drupal/core']) || isset($composerJson['require']['drupal/phing-drush-task'])) {
             return true;
         }
     }
     return false;
 }
コード例 #3
0
 public function getFinderData($searchElement)
 {
     ini_set('memory_limit', '-1');
     $searchResult = explode(' ', $searchElement);
     $finalDataArr = array();
     // define the path in which file is resides.
     $dir = $this->get('kernel')->getRootDir() . '/../web/uploads/files/';
     // if csv dir does not exist create new one
     if (!is_dir($dir)) {
         mkdir($dir);
     }
     // call the finder class.
     $finder = new Finder();
     $finder->in($dir)->ignoreDotFiles(false);
     $finder->in($dir);
     $finder->in($dir)->files()->name('*.*');
     foreach ($searchResult as $value) {
         $finder->in($dir)->files()->contains($value);
     }
     foreach ($finder as $file) {
         $finalDataArr[] = $file->getRelativePathname();
     }
     $finalDataArr = array_unique($finalDataArr);
     return $finalDataArr;
 }
コード例 #4
0
 /**
  * call execute on found commands
  *
  * @param InputInterface  $input  user input
  * @param OutputInterface $output command output
  *
  * @return void
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $this->finder->in(strpos(getcwd(), 'vendor/') === false ? getcwd() : getcwd() . '/../../../../')->path('Resources/config')->name('/migrations.(xml|yml)/')->files();
     foreach ($this->finder as $file) {
         if (!$file->isFile()) {
             continue;
         }
         $output->writeln('Found ' . $file->getRelativePathname());
         $command = $this->getApplication()->find('mongodb:migrations:migrate');
         $helperSet = $command->getHelperSet();
         $helperSet->set($this->documentManager, 'dm');
         $command->setHelperSet($helperSet);
         $configuration = $this->getConfiguration($file->getPathname(), $output);
         self::injectContainerToMigrations($this->container, $configuration->getMigrations());
         $command->setMigrationConfiguration($configuration);
         $arguments = $input->getArguments();
         $arguments['command'] = 'mongodb:migrations:migrate';
         $arguments['--configuration'] = $file->getPathname();
         $migrateInput = new ArrayInput($arguments);
         $returnCode = $command->run($migrateInput, $output);
         if ($returnCode !== 0) {
             $output->writeln('<error>Calling mongodb:migrations:migrate failed for ' . $file->getRelativePathname() . '</error>');
             return $returnCode;
         }
     }
 }
コード例 #5
0
ファイル: CollectionBuilder.php プロジェクト: stof/phpbench
 /**
  * Build the BenchmarkMetadata collection.
  *
  * @param string $path
  * @param array $subjectFilter
  * @param array $groupFilter
  */
 public function buildCollection($path, array $filters = array(), array $groupFilter = array())
 {
     if (!file_exists($path)) {
         throw new \InvalidArgumentException(sprintf('File or directory "%s" does not exist (cwd: %s)', $path, getcwd()));
     }
     if (is_dir($path)) {
         $this->finder->in($path)->name('*Bench.php');
     } else {
         // the path is already a file, just restrict the finder to that.
         $this->finder->in(dirname($path))->depth(0)->name(basename($path));
     }
     $benchmarks = array();
     foreach ($this->finder as $file) {
         if (!is_file($file)) {
             continue;
         }
         $benchmarkMetadata = $this->factory->getMetadataForFile($file->getPathname());
         if (null === $benchmarkMetadata) {
             continue;
         }
         if ($groupFilter) {
             $benchmarkMetadata->filterSubjectGroups($groupFilter);
         }
         if ($filters) {
             $benchmarkMetadata->filterSubjectNames($filters);
         }
         if (false === $benchmarkMetadata->hasSubjects()) {
             continue;
         }
         $benchmarks[] = $benchmarkMetadata;
     }
     return new Collection($benchmarks);
 }
コード例 #6
0
 /**
  * @return array
  * @throws \InvalidArgumentException
  */
 private function getLayouts()
 {
     $layouts = new \ArrayIterator(array());
     if (is_dir($this->baseDir . '/layouts')) {
         $layouts = $this->finder->in($this->baseDir . '/layouts/')->files()->name('authors.*.twig');
     }
     $layouts = iterator_to_array($layouts);
     if (empty($layouts)) {
         throw new \InvalidArgumentException('Could not find layout for author pages.');
     }
     return $layouts;
 }
コード例 #7
0
ファイル: Find.php プロジェクト: recca0120/laravel-terminal
 /**
  * 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());
         }
     }
 }
コード例 #8
0
ファイル: Finder.php プロジェクト: drickferreira/rastreador
 /**
  * Find the specified theme by searching a 'theme.json' file as identifier.
  *
  * @param string $path
  * @param string $filename
  *
  * @return $this
  */
 public function scan()
 {
     if ($this->scanned == true) {
         return $this;
     }
     if (is_dir($path = $this->getPath())) {
         $found = $this->finder->in($path)->files()->name(self::FILENAME)->depth('<= 3')->followLinks();
         foreach ($found as $file) {
             $this->themes[] = new Theme($this->getInfo($file));
         }
     }
     $this->scanned = true;
     return $this;
 }
コード例 #9
0
 protected function loadMetadata()
 {
     $bundles = $this->kernel->getBundles();
     $finder = new Finder();
     foreach ($bundles as $bundle) {
         $finder->in($bundle->getPath());
     }
     $finder->in($this->kernel->getRootDir());
     $finder->name("*.fs.yml");
     foreach ($finder as $file) {
         $fsData = $this->frontSynchroniserManager->getMetadataFromPath($file->getPathname());
         $metadata = $this->buildMetadata($fsData, $file);
         $this->storeMetadata($metadata);
     }
 }
コード例 #10
0
 /**
  * Fetch drupal project from source code
  *
  * @return Sauron\Core\Drupal\Project\Entity\Project a Drupal project
  */
 public function getProject()
 {
     $project = new Project();
     if (file_exists($this->drupalRootPath . '/core')) {
         //looks like drupal >= 8 core
         $moduleSystemPath = $this->drupalRootPath . '/core/modules/system';
     } else {
         $moduleSystemPath = $this->drupalRootPath . '/modules/system';
     }
     //get core version
     $finder = new Finder();
     $systemInfoFile = $finder->in($moduleSystemPath)->files()->name('system.info*');
     $coreVersion = null;
     foreach ($systemInfoFile as $file) {
         $coreVersion = $this->getVersion($file->getRealpath());
     }
     //get module version
     if ($coreVersion !== null) {
         $project->drupalVersion = $coreVersion;
         $project->coreVersion = substr($coreVersion, 0, 1) . '.x';
         foreach ($this->extensionPaths as $contribPath) {
             $finder = new Finder();
             $moduleFiles = $finder->in($this->drupalRootPath . '/' . $contribPath)->files()->name('/\\.info(\\.yml)*$/')->depth('== 1');
             foreach ($moduleFiles as $file) {
                 $module = new Module();
                 $module->machineName = $file->getBasename('.info');
                 $module->version = $this->getVersion($file->getRealpath());
                 $project->modules[] = $module;
             }
         }
     }
     return $project;
 }
コード例 #11
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $path = $input->getArgument('path');
     if (!file_exists($path)) {
         throw new FileNotFoundException($path);
     }
     /** @var EntityManager $em */
     $em = $this->app['orm.em'];
     // Disable SQL Logger
     $em->getConnection()->getConfiguration()->setSQLLogger(null);
     if (!$input->getOption('append')) {
         $output->writeln('Purging database');
         $em->getConnection()->executeUpdate("DELETE FROM address");
     }
     if (is_dir($path)) {
         $finder = new Finder();
         $finder->in($path)->name('/\\.csv/i');
         $output->writeln('Loading CSV from ' . $path . ' (' . $finder->count() . ' files)');
         /** @var SplFileInfo $file */
         foreach ($finder as $file) {
             $this->loadFile($output, $file->getPathname());
         }
     } else {
         $this->loadFile($output, $path);
     }
     return 0;
 }
コード例 #12
0
 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;
 }
コード例 #13
0
ファイル: FinderBuilderTest.php プロジェクト: rafrsr/licenser
 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);
 }
コード例 #14
0
 public function boot()
 {
     if (true === $this->booted) {
         return;
     }
     $this->booted = true;
     $moduleConfigCacheFile = $this->getParameter('kernel.root_dir') . '/cache/' . $this->environment . '/modules_config.php';
     if (file_exists($moduleConfigCacheFile)) {
         $this->_moduleConfig = (include $moduleConfigCacheFile);
     } else {
         $finder = new Finder();
         $finder->directories()->depth('== 0');
         foreach ($this->_moduleDirectories as $dir) {
             if (glob($dir . '/*/Service', GLOB_ONLYDIR)) {
                 $finder->in($dir . '/*/Service');
             }
         }
         foreach ($finder as $dir) {
             $filepath = $dir->getRealPath() . '/module_config.php';
             if (file_exists($filepath)) {
                 $this->_moduleConfig = array_merge_recursive($this->_moduleConfig, include $filepath);
             }
         }
         if (!$this->debug) {
             $cache = "<?php \nreturn " . var_export($this->_moduleConfig, true) . ';';
             file_put_contents($moduleConfigCacheFile, $cache);
         }
     }
     $subscribers = empty($this->_moduleConfig['event_subscriber']) ? array() : $this->_moduleConfig['event_subscriber'];
     foreach ($subscribers as $subscriber) {
         $this->dispatcher()->addSubscriber(new $subscriber());
     }
 }
コード例 #15
0
ファイル: ImageFinder.php プロジェクト: maslosoft/sprite
 /**
  *
  * @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;
 }
コード例 #16
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $path = $this->container->getParameter('path.module');
     $oxidPath = $this->container->getParameter('path.oxid');
     include "{$oxidPath}/bootstrap.php";
     $finder = new Finder();
     $finder->in($path)->name('*.php')->depth(1);
     /** @var TokenParser $tokenParser */
     $tokenParser = $this->container->get('compiler.token_parser');
     foreach ($finder as $file) {
         $tokenParser->parse(file_get_contents($file));
         $className = $tokenParser->getFullClassName();
         if (!class_exists($className, false)) {
             include $file;
         }
         /** @var Metadata $moduleMetadata */
         $compiler = $this->container->get('compiler.module');
         $mappings = $compiler->compile(dirname($file));
         $output->writeln('Generating OXID modules.');
         /** @var Generator $generator */
         $generator = $this->container->get('compiler.generator');
         $generator->addMappings($mappings);
         $generator->generate($className);
     }
 }
コード例 #17
0
ファイル: tasks.file.php プロジェクト: jalmelb/24hl2015
	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;
	}
コード例 #18
0
ファイル: AddressbookTest.php プロジェクト: thefox/phpchat
 public function testSaveLoad()
 {
     $runName = uniqid('', true);
     $fileName = 'testfile_addressbook_' . date('Ymd_His') . '_' . $runName . '.yml';
     $book = new Addressbook('test_data/' . $fileName);
     $contact = new Contact();
     $contact->setId(1);
     $contact->setNodeId('cafed00d-2131-4159-8e11-0b4dbadb1738');
     $contact->setUserNickname('nick1');
     $contact->setTimeCreated(24);
     $book->contactAdd($contact);
     $contact = new Contact();
     $contact->setId(2);
     $contact->setNodeId('cafed00d-2131-4159-8e11-0b4dbadb1739');
     $contact->setUserNickname('nick2');
     $contact->setTimeCreated(25);
     $book->contactAdd($contact);
     $book->save();
     $finder = new Finder();
     $files = $finder->in('test_data')->depth(0)->name($fileName)->files();
     $this->assertEquals(1, count($files));
     $book = new Addressbook('test_data/' . $fileName);
     $this->assertTrue($book->load());
     $book = new Addressbook('test_data/not_existing.yml');
     $this->assertFalse($book->load());
 }
コード例 #19
0
 /**
  * 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();
 }
コード例 #20
0
 /**
  * Gets the list of class names in the given directory.
  *
  * @param string $directory
  *
  * @return array
  */
 private function getClasses($directory)
 {
     $classes = [];
     $directoryList = [];
     $includedFiles = [];
     $finder = new Finder();
     try {
         $finder->in($directory)->files()->name('*.php');
     } catch (\InvalidArgumentException $e) {
         return [[], []];
     }
     foreach ($finder as $file) {
         $directoryList[$file->getPath()] = true;
         $sourceFile = $file->getRealpath();
         if (!preg_match('(^phar:)i', $sourceFile)) {
             $sourceFile = realpath($sourceFile);
         }
         require_once $sourceFile;
         $includedFiles[$sourceFile] = true;
     }
     $declared = get_declared_classes();
     foreach ($declared as $className) {
         $reflectionClass = new \ReflectionClass($className);
         $sourceFile = $reflectionClass->getFileName();
         if ($reflectionClass->isAbstract()) {
             continue;
         }
         if (isset($includedFiles[$sourceFile])) {
             $classes[$className] = true;
         }
     }
     return [array_keys($classes), $directoryList];
 }
コード例 #21
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $distribution = $input->getArgument('distribution');
     $version = $input->getArgument('version');
     $download = $this->downloadProject($distribution, $version);
     $process = new Process("tar -xzf {$download['location']} -C /tmp/");
     $process->start();
     if (substr($version, 0, 3) == '7.x') {
         $finder = new Finder();
         $process->wait();
         // Find all modules dropped in to the distribution.
         $finder->files()->name("*.info");
         $filename = array();
         foreach ($finder->in($download['locationUncompressed']) as $file) {
             $filename[] = array('path' => $file->getRealPath(), 'filename' => $file->getFileName());
         }
         // Create the array for the containing modules.
         $return = array();
         foreach ($filename as $file) {
             $contents = $this->parse_info_file(file_get_contents($file['path']));
             $machine_name = substr($file['filename'], 0, strpos($file['filename'], '.'));
             $return[$machine_name] = array('name' => $contents['name'], 'machine_name' => substr($file['filename'], 0, strpos($file['filename'], '.')), 'core' => $contents['core'], 'version' => $contents['version'], 'status' => 'Enabled', 'package' => isset($contents['package']) ? $contents['package'] : null);
         }
         $output->write(json_encode($return));
     }
 }
コード例 #22
0
ファイル: FinderFacade.php プロジェクト: sakshika/ATM
 /**
  * @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;
 }
コード例 #23
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $application = $this->getApplication();
     $config = $application->getConfig();
     $showFileHelper = $application->getShowFileHelper();
     $userPath = sprintf('%s/.console/', $config->getUserHomeDir());
     $copiedFiles = [];
     $override = false;
     if ($input->hasOption('override')) {
         $override = $input->getOption('override');
     }
     $finder = new Finder();
     $finder->in(sprintf('%sconfig/dist/', $application->getDirectoryRoot()));
     $finder->files();
     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) {
         $showFileHelper->copiedFiles($io, $copiedFiles);
     }
     $this->createAutocomplete();
     $io->newLine(1);
     $io->writeln($this->trans('application.messages.autocomplete'));
 }
 public function viewAction(Request $request)
 {
     $accept = AcceptHeader::fromString($request->headers->get('accept'));
     $finder = new Finder();
     $userFiles = $finder->in(STORAGE_PATH)->name('*.json')->sortByModifiedTime()->files();
     $users = function () use($userFiles) {
         foreach ($userFiles as $userFile) {
             /** @var SplFileInfo $userFile */
             $data = json_decode($userFile->getContents(), true);
             $data['dob'] = new \DateTime($data['dob']['date']);
             $data['id'] = $userFile->getBasename('.json');
             (yield $data);
         }
     };
     $response = new Response();
     if ($accept->has('text/html')) {
         $response->setContent($this->getTwig()->render('crud/view.html.twig', ['users' => $users(), 'urlGenerator' => $this->urlGenerator(), 'translator' => TranslationFactory::createTranslator($request), 'user' => $this->getUser()]));
     } elseif ($accept->has('application/json')) {
         $response = new Response('', Response::HTTP_OK, ['Content-Type' => 'application/json']);
         $userList = iterator_to_array($users());
         $response->setContent(json_encode($userList));
     } elseif ($accept->has('text/xml')) {
         $response = new Response('', Response::HTTP_OK, ['Content-Type' => 'text/xml']);
         $userList = iterator_to_array($users());
         $xml = new \SimpleXMLElement('<root />');
         array_walk($userList, function ($userData) use($xml) {
             $user = $xml->addChild('user');
             $user->addChild('username', $userData['username']);
         });
         $response->setContent($xml->asXML());
     }
     return $response;
 }
コード例 #25
0
 /**
  * @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;
 }
コード例 #26
0
ファイル: DebugCommand.php プロジェクト: GoZOo/DrupalConsole
 /**
  * {@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();
 }
コード例 #27
0
 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);
 }
コード例 #28
0
 /**
  * @depends testDeleteGeneratedTransferObjectsShouldDeleteAllGeneratedTransferObjects
  *
  * @return void
  */
 public function testGenerateTransferObjectsShouldGenerateTransferObjects()
 {
     $this->getFacade()->generateTransferObjects($this->getMessenger());
     $finder = new Finder();
     $finder->in($this->getConfig()->getClassTargetDirectory())->name('*Transfer.php');
     $this->assertTrue($finder->count() > 0);
 }
コード例 #29
0
 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);
 }
コード例 #30
0
 /**
  * Get list of existing translation locales for current translation domain
  *
  * @return array
  */
 protected function getTranslationLocales()
 {
     if (null === $this->translationLocales) {
         $translationDirectory = str_replace('/', DIRECTORY_SEPARATOR, $this->translationDirectory);
         $translationDirectories = array();
         foreach ($this->container->getParameter('kernel.bundles') as $bundle) {
             $reflection = new \ReflectionClass($bundle);
             $bundleTranslationDirectory = dirname($reflection->getFilename()) . $translationDirectory;
             if (is_dir($bundleTranslationDirectory) && is_readable($bundleTranslationDirectory)) {
                 $translationDirectories[] = realpath($bundleTranslationDirectory);
             }
         }
         $domainFileRegExp = $this->getDomainFileRegExp();
         $finder = new Finder();
         $finder->in($translationDirectories)->name($domainFileRegExp);
         $this->translationLocales = array();
         /** @var $file \SplFileInfo */
         foreach ($finder as $file) {
             preg_match($domainFileRegExp, $file->getFilename(), $matches);
             if ($matches) {
                 $this->translationLocales[] = $matches[1];
             }
         }
         $this->translationLocales = array_unique($this->translationLocales);
     }
     return $this->translationLocales;
 }