/** * Parse and compile all custom elements in elements folder. * * @return Response */ public function customElements() { $elements = array(); $files = $this->finder->in($this->app['base_dir'] . '/elements')->files(); foreach ($files as $file) { $contents = $file->getContents(); preg_match('/<script>(.+?)<\\/script>/s', $contents, $config); preg_match('/<style.*?>(.+?)<\\/style>/s', $contents, $css); preg_match('/<\\/style.*?>(.+?)<script>/s', $contents, $html); if (!isset($config[1]) || !isset($html[1])) { continue; } $elements[] = array('css' => isset($css[1]) ? trim($css[1]) : '', 'html' => trim($html[1]), 'config' => trim($config[1])); } return new Response(json_encode($elements)); }
/** * 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\Finder(); $this->finder->in($sources)->filter(function (\SplFileInfo $file) use($sources, $filters, $fs) { $relativePath = preg_replace('#^' . preg_quote($sources, '#') . '#', '', $fs->normalizePath($file->getRealPath())); $exclude = false; foreach ($filters as $filter) { $exclude = $filter->filter($relativePath, $exclude); } return !$exclude; })->ignoreVCS(true)->ignoreDotFiles(false); parent::__construct($this->finder->getIterator()); }
protected function loadConfigurationsFolder($folder) { $confs = array(); $finder = new \Symfony\Component\Finder\Finder(); foreach ($finder->in($folder) as $configuration) { $confs[] = array(file_get_contents($configuration->getPathname())); } return $confs; }
function getFilesFromPathByEnv(\LaravelSeed\Contracts\ProviderInterface $provider) { $finder = new Symfony\Component\Finder\Finder(); $files = []; $finder->name("/\\_" . $provider->getEnv() . "\\.(\\w{1,4})\$/i"); foreach ($finder->in($provider->getConfig('path')) as $file) { $files[] = $file->getPath() . '/' . $file->getFilename(); } return $files; }
/** * @return array */ public function provideResources() { $finder = new \Symfony\Component\Finder\Finder(); $finder->in(__DIR__ . '/../Resources/Text')->files()->name('*.out'); $files = array(); /* @var \Symfony\Component\Finder\SplFileInfo $file */ foreach ($finder as $file) { $files[] = array(str_replace('.out', '.twig', $file->getFilename()), $file->getContents()); } return $files; }
/** * @return $this */ public function clearTheReportsDir() { $reportsDir = codecept_data_dir('actual'); if (is_dir($reportsDir)) { $finder = new \Symfony\Component\Finder\Finder(); $finder->in($reportsDir); foreach ($finder->files() as $file) { unlink($file->getPathname()); } } return $this; }
public function clearCache() { $container = $this->getConfigurationPool()->getContainer(); $cacheDir = $container->get('kernel')->getCacheDir(); $finder = new \Symfony\Component\Finder\Finder(); $finder->in(array($cacheDir . "/../*/translations"))->files(); foreach ($finder as $file) { unlink($file->getRealpath()); } if (is_dir($cacheDir . '/translations')) { rmdir($cacheDir . '/translations'); } }
/** * 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\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 clearCache() { try { $sf2Refresh = new \PrestaShopBundle\Service\Cache\Refresh(); $sf2Refresh->addCacheClear(); $sf2Refresh->execute(); } catch (\Exception $exception) { $finder = new \Symfony\Component\Finder\Finder(); $fs = new \Symfony\Component\Filesystem\Filesystem(); foreach ($finder->in(_PS_ROOT_DIR_ . '/app/cache') as $file) { $fs->remove($file->getFilename()); } } }
private static function _buildTubePress() { $finder = new \Symfony\Component\Finder\Finder(); $distDir = sprintf('%s/build/dist', self::_getProjectRoot()); $matches = iterator_to_array($finder->in($distDir)->files()->name('*.zip')->getIterator()); if (count($matches) !== 1) { self::_runProcess('php build/php/scripts/build.php package', false, self::_getProjectRoot()); $finder = new \Symfony\Component\Finder\Finder(); $matches = iterator_to_array($finder->in($distDir)->files()->name('*.zip')->getIterator()); if (count($matches) !== 1) { throw new RuntimeException('Failed to build TubePress'); } } }
function convert($dir_path) { $html_dir_path = $dir_path . "/html"; if (!is_dir()) { system("mkdir -p {$html_dir_path}"); } else { system("rm -R {$html_dir_path}/*"); } $finder = new \Symfony\Component\Finder\Finder(); $finder->in($dir_path)->files()->name("SRMN*.docx"); print "<!DOCTYPE html><html><head></head><body>"; foreach ($finder as $file) { $this->convertOneFile($file, $html_dir_path); } return "</body></html>"; }
protected function execute(InputInterface $input, OutputInterface $output) { $dir = __DIR__ . '/../../../../'; $projectHome = realpath($dir); $output->writeln($projectHome); $finder = new \Symfony\Component\Finder\Finder(); $finder->in($projectHome . '/Tekstove'); $finder->name('*.php'); $finder->path('/\\/Base\\//')->path('/\\/Map\\//'); $this->handleFinder($finder, $output, $projectHome); $finderNewFiles = new \Symfony\Component\Finder\Finder(); $finderNewFiles->in($projectHome . '/Tekstove'); $finderNewFiles->name('*.php'); $this->handleFinder($finderNewFiles, $output, $projectHome, false); $fs = new \Symfony\Component\Filesystem\Filesystem(); $fs->remove($projectHome . '/Tekstove'); $output->writeln('<info>Command result.</info>'); }
function convert($dir_path) { $html_dir_path = $dir_path ."/html"; $json_dir_path = $dir_path ."/json"; ensure_clean_dir($html_dir_path); ensure_clean_dir($json_dir_path); $finder = new \Symfony\Component\Finder\Finder(); $finder->in($dir_path)->files()->name("SRMN*.docx"); print "Beginning convertsion\n"; foreach($finder as $file){ $this->convertOneFile($file, $html_dir_path, $json_dir_path); } return "</body></html>"; }
public function clearCache($dayOld) { $finder = new \Symfony\Component\Finder\Finder(); $it = $finder->in($this->cacheDir)->files()->date("< now - {$dayOld} days")->getIterator(); $cpt = 0; foreach ($it as $file) { /* @var $file \Symfony\Component\Finder\SplFileInfo */ $ret = @unlink($file->getPathname()); if ($ret) { $cpt++; } } return $cpt; }
/** * @param array $directories * @param array $excludes * @param array $suffixes * @return array * @since Method available since Release 1.7.0 */ protected function findFiles(array $directories, array $excludes, array $suffixes) { $files = array(); $finder = new Symfony\Component\Finder\Finder(); $iterate = FALSE; try { foreach ($directories as $directory) { if (!is_file($directory)) { $finder->in($directory); $iterate = TRUE; } else { $files[] = realpath($directory); } } foreach ($excludes as $exclude) { $finder->exclude($exclude); } foreach ($suffixes as $suffix) { $finder->name('*' . $suffix); } } catch (Exception $e) { $this->showError($e->getMessage() . "\n"); exit(1); } if ($iterate) { foreach ($finder as $file) { $files[] = $file->getRealpath(); } } return $files; }
private function isCacheExpired($cache_path, $path) { if (!file_exists($cache_path)) { return __LINE__; } if (!file_exists($path)) { return __LINE__; } $cache_time = filemtime($path); $this->cache_expired_time = $cache_time; $dirs = (include $path); $cache_dir = $this->container->getParameter('kernel.root_dir') . '/Resources/SymforceAdminBundle/src/'; $root_dir = dirname($this->container->getParameter('kernel.root_dir')) . '/'; foreach ($dirs as $dir => $entities) { if ($dir) { foreach ($entities as $entity_path => $admin_path) { $_entity_path = $root_dir . $dir . $entity_path; if (!file_exists($_entity_path)) { return __LINE__; } if (filemtime($_entity_path) > $cache_time) { return __LINE__; } } } else { foreach ($entities as $resource_path => $_file_expire_time) { $resource_full_path = $root_dir . $resource_path; if (!file_exists($resource_full_path)) { return __LINE__; } if (filemtime($resource_full_path) > $cache_time) { return __LINE__; } } } } if ($this->container->getParameter('kernel.debug')) { foreach ($dirs as $dir => $_files) { if ($dir) { $finder = new \Symfony\Component\Finder\Finder(); $finder->name('*.php'); foreach ($finder->in($root_dir . '/' . $dir) as $file) { $_file = $file->getRelativePathname(); if (!isset($_files[$_file])) { return __LINE__; } } } } } return $this->container->getParameter('sf.admin.debug'); }
<?php $rootDir = __DIR__ . '/../../../../'; $output = __DIR__ . '/../config/doctrine/optimized_resolve.php'; require $rootDir . 'vendor/autoload.php'; $finder = new \Symfony\Component\Finder\Finder(); $finder->in($rootDir . '/src/*/Resources/config/doctrine')->name('resolve.php'); $globalResolves = array(); foreach ($finder as $file) { $resolves = (require $file->getPathName()); foreach ($resolves as $interface => $class) { $globalResolves[$interface] = $class; } } $content = sprintf("<?php\n\nreturn %s;\n", var_export($globalResolves, true)); file_put_contents($output, $content);
/** * Test Get Umpteenth First * * @param integer $n Umpteenth Number * * @return void * * @dataProvider providerTestUmpteenth */ public function testGetUmpteenthFirst($n) { $path = realpath(__DIR__ . "/../../resources/") . "/"; $newFinder = new NachoNerd\Silex\Finder\Extensions\Finder(); $oldFinder = new Symfony\Component\Finder\Finder(); $oldFinder->in($path); $newFinder->in($path); $newFinder = $newFinder->getNFirst($n); $filesOldWay = array(); $j = 0; foreach ($oldFinder as $files) { if ($j == $n) { break; } $j++; $filesOldWay[] = $files; } $filesNewWay = array(); foreach ($newFinder as $files) { $filesNewWay[] = $files; } $this->assertEquals($filesOldWay, $filesNewWay); }
function run() { $config = $this->config; $context = $this->context; /* @var $context ExecutionContext */ $write = function ($s) { echo $s; }; $writeln = function ($s) { $d = new \DateTime(); echo $d->format(\DateTime::ISO8601) . ' ' . $s . "\n"; }; $c = $color = new \Colors\Color(); /* @var $c \Colors\Color */ $writeln($c('Running agent `' . $this->name)->bold() . '`'); // generate an array with handlers $writeln('Loading handlers'); $handlers = []; $handlersDir = $config->handlers_dir; if ($handlersDir) { $finder = new \Symfony\Component\Finder\Finder(); foreach ($finder->in($handlersDir)->name('*.php')->sortByName() as $file) { /* @var $file \SplFileInfo */ $handlerId = $file->getBasename('.php'); $handler = (include $file); $handlers[$handlerId] = $handler; $writeln(' setting up handler ' . $color($handlerId)->bold() . $color->yellow(' (in ' . $file . ')')); $eventName = SqsEvents::generateEventForAgentId(SqsEvents::EVENT_SQSAGENT_SQSMESSAGERECEIVED, $this->getId()); $context->getEventDispatcher()->addListener($eventName, function (\T24\Event\SqsMessageReceivedEvent $event) use($write, $writeln, $color, $handler, $handlerId, $eventName) { $writeln($color->bg('blue', $color->white('invoking handler ' . $handlerId . ' for event ' . $eventName))); /* @var Callable $handler */ $result = $handler($event); // write comments $comments = $event->getComments(); foreach ($comments as $comment) { $writeln($color(' comment: ')->yellow() . $comment); } $writeln(' - handler ' . $handlerId . ' had been invoked.'); if ($event->isPropagationStopped()) { $writeln(' - ' . $color->red('the event was stopped from further propagation.')); } else { $writeln(' - the event was not stopped. proceed to next handler'); } return $result; }); } $writeln('Loaded ' . count($handlers) . ' handlers.'); } else { $writeln('default handlers dir not specified, no handlers defined..'); } // @todo: get aws params. $region = ''; $sqsQueueUrl = ''; $sqs = SqsClient::factory(['region' => $config->aws_region, 'version' => '2012-11-05', 'credentials' => ['key' => $config->aws_key, 'secret' => $config->aws_secret]]); // start the process $ttl = (int) $config->ttl; $ttl = min($ttl, 300); $ttl = max($ttl, 5); $sleep = (int) $config->sleep; $sleep = min($sleep, $ttl - 5); $sleep = max($sleep, 0); $stopwatch = new \Symfony\Component\Stopwatch\Stopwatch(); $b = $stopwatch->start('loop'); while ($b->getDuration() < $ttl * 1000) { // get an sqs message from the queue $writeln($c('Polling Sqs for messages')); $result = $sqs->receiveMessage(['QueueUrl' => $config->sqs_queue_url, 'AttributeNames' => ['All'], 'MessageAttributeNames' => ['All'], 'MaxNumberOfMessages' => 1]); /* @var $result \Aws\Result */ if (!$result['Messages'] || $result['Messages'] == 0) { $writeln($c('no messages found in sqs queue')); } else { $writeln($c(sprintf('%d message(s) retrieved from queue.', count($result['Messages'])))); foreach ($result['Messages'] as $message) { // set up an event that the message is received. // the default subscriber will pass the event to the event handlers in the handlers dir $event = new SqsMessageReceivedEvent($context, $message); $context->getEventDispatcher()->dispatch(SqsEvents::EVENT_SQSAGENT_SQSMESSAGERECEIVED, $event); $context->getEventDispatcher()->dispatch(SqsEvents::generateEventForAgentId(SqsEvents::EVENT_SQSAGENT_SQSMESSAGERECEIVED, $this->getId()), $event); /* $context->getEventDispatcher()->dispatch(SqsEvents::EVENT_SQSAGENT_SQSMESSAGEHANDLED, $event2); if ($event->isProcessed()) { $context->getEventDispatcher()->dispatch(SqsEvents::EVENT_SQSAGENT_SQSMESSAGEPROCESSED, $event2); } */ if ($event->getRemoveFromQueue()) { $writeln(' - the event handlers indicate the sqs message should be removed from the queue.'); // remove from sqs $sqsMessage = $event->getSqsMessage(); $removed = $sqs->deleteMessage(['QueueUrl' => $config->sqs_queue_url, 'ReceiptHandle' => $sqsMessage['ReceiptHandle']]); $writeln(' - ' . ($removed ? $c->green('succesfully removed the message from SQS') : $c->red('failed to remove the message from SQS'))); } else { $writeln(' - the event handlers indicate the sqs messageshould not be removed from the queue.'); } } } $writeln($color->cyan('sleeping for ' . $sleep . ' seconds')); sleep($sleep); } // end stopwatch while loop $writeln('Stopped after ' . (int) ($b->getDuration() / 1000) . ' secs.'); // send the finish event. $event = new \T24\Event\AgentEvent($context); $context->getEventDispatcher()->dispatch(SqsEvents::EVENT_SQSAGENT_FINISH, $event); $context->getEventDispatcher()->dispatch(SqsEvents::generateEventForAgentId(SqsEvents::EVENT_SQSAGENT_FINISH, $this->getId()), $event); }
/** * Return the contents of `$directory` as a single depth list ordered by total filesize. * * Will schedule background threads to recursively calculate the filesize of subdirectories. * The total filesize of each directory and subdirectory is cached in a transient for 1 week. * * @param string $directory The directory to list * * @todo doesn't really belong in this class, should just be a function * @return array returns an array of files ordered by filesize */ function list_directory_by_total_filesize($directory, Excludes $excludes) { $files = $files_with_no_size = $empty_files = $files_with_size = $unreadable_files = array(); if (!is_dir($directory)) { return $files; } $finder = new \Symfony\Component\Finder\Finder(); $finder->followLinks(); $finder->ignoreDotFiles(false); $finder->ignoreUnreadableDirs(); $finder->depth('== 0'); $site_size = new Site_Size('file', $excludes); $files = $finder->in($directory); foreach ($files as $entry) { // Get the total filesize for each file and directory $filesize = $site_size->filesize($entry); if ($filesize) { // If there is already a file with exactly the same filesize then let's keep increasing the filesize of this one until we don't have a clash while (array_key_exists($filesize, $files_with_size)) { $filesize++; } $files_with_size[$filesize] = $entry; } elseif (0 === $filesize) { $empty_files[] = $entry; } else { $files_with_no_size[] = $entry; } } // Sort files by filesize, largest first krsort($files_with_size); // Add 0 byte files / directories to the bottom $files = $files_with_size + array_merge($empty_files, $unreadable_files); // Add directories that are still calculating to the top if ($files_with_no_size) { // We have to loop as merging or concatenating the array would re-flow the keys which we don't want because the filesize is stored in the key foreach ($files_with_no_size as $entry) { array_unshift($files, $entry); } } return $files; }
private function generateExpireCheckCache($expire_check_path) { $root_dir = dirname($this->container->getParameter('kernel.root_dir')); $fs = new \Symfony\Component\Filesystem\Filesystem(); $bundles = array(); foreach ($this->admin_generators as $key => $admin) { if (isset($bundles[$admin->bundle_name])) { continue; } $file = $admin->getFilename(); $file = trim($fs->makePathRelative($file, $root_dir), '/'); $bundles[$admin->bundle_name] = dirname($file) . '/'; continue; if (!isset($dirs[$_dir])) { $dirs[$_dir] = array(); } $_entity_file = basename($file); $dirs[$_dir][$_entity_file] = filemtime($admin->getFilename()); } $dirs = array(); foreach ($bundles as $entity_dir) { $finder = new \Symfony\Component\Finder\Finder(); $finder->name('*.php'); foreach ($finder->in($root_dir . '/' . $entity_dir) as $file) { $dirs[$entity_dir][$file->getRelativePathname()] = filemtime($file->getRealpath()); } } $default_resources = array('app/config/symforce/admin.yml'); foreach ($default_resources as $file) { $dirs[0][$file] = filemtime($root_dir . '/' . $file); } foreach ($this->expire_check_resources as $file) { $_file = trim($fs->makePathRelative($file, $root_dir), '/'); if (!in_array($_file, $dirs[0])) { $dirs[0][$_file] = filemtime($file); } } /** * @todo add yml configure check */ \Dev::write_file($expire_check_path, '<' . '?php return ' . var_export($dirs, 1) . ';'); }
<?php require_once __DIR__ . '/vendor/autoload.php'; $f = new Symfony\Component\Finder\Finder(); $f->in('country')->name('country.php'); $countries = []; foreach ($f as $file) { $raw = (require $file); foreach ($raw as $code => $name) { $countries[mb_strtolower($name)] = $code; } } file_put_contents('countries.aggregate.php', sprintf("<?php\n return %s;", var_export($countries, true)));
/** * Main method. */ public static function main() { $input = new ezcConsoleInput(); $input->registerOption(new ezcConsoleOption('', 'clover', ezcConsoleInput::TYPE_STRING)); $input->registerOption(new ezcConsoleOption('', 'html', ezcConsoleInput::TYPE_STRING)); $input->registerOption(new ezcConsoleOption('', 'php', ezcConsoleInput::TYPE_STRING)); $input->registerOption(new ezcConsoleOption('', 'text', ezcConsoleInput::TYPE_STRING)); $input->registerOption(new ezcConsoleOption('', 'blacklist', ezcConsoleInput::TYPE_STRING, array(), TRUE)); $input->registerOption(new ezcConsoleOption('', 'whitelist', ezcConsoleInput::TYPE_STRING, array(), TRUE)); $input->registerOption(new ezcConsoleOption('', 'merge', ezcConsoleInput::TYPE_NONE, FALSE)); $input->registerOption(new ezcConsoleOption('', 'add-uncovered', ezcConsoleInput::TYPE_NONE, FALSE)); $input->registerOption(new ezcConsoleOption('', 'process-uncovered', ezcConsoleInput::TYPE_NONE, FALSE)); $input->registerOption(new ezcConsoleOption('h', 'help', ezcConsoleInput::TYPE_NONE, NULL, FALSE, '', '', array(), array(), FALSE, FALSE, TRUE)); $input->registerOption(new ezcConsoleOption('v', 'version', ezcConsoleInput::TYPE_NONE, NULL, FALSE, '', '', array(), array(), FALSE, FALSE, TRUE)); try { $input->process(); } catch (ezcConsoleOptionException $e) { print $e->getMessage() . "\n"; exit(1); } if ($input->getOption('help')->value) { self::showHelp(); exit(0); } else { if ($input->getOption('version')->value) { self::printVersionString(); exit(0); } } $arguments = $input->getArguments(); $clover = $input->getOption('clover')->value; $html = $input->getOption('html')->value; $php = $input->getOption('php')->value; $text = $input->getOption('text')->value; $blacklist = $input->getOption('blacklist')->value; $whitelist = $input->getOption('whitelist')->value; $addUncovered = $input->getOption('add-uncovered')->value; $processUncovered = $input->getOption('process-uncovered')->value; $merge = $input->getOption('merge')->value; if (count($arguments) == 1) { self::printVersionString(); $coverage = new PHP_CodeCoverage(); $filter = $coverage->filter(); if (empty($whitelist)) { $c = new ReflectionClass('ezcBase'); $filter->addDirectoryToBlacklist(dirname($c->getFileName())); $c = new ReflectionClass('ezcConsoleInput'); $filter->addDirectoryToBlacklist(dirname($c->getFileName())); foreach ($blacklist as $item) { if (is_dir($item)) { $filter->addDirectoryToBlacklist($item); } else { if (is_file($item)) { $filter->addFileToBlacklist($item); } } } } else { $coverage->setAddUncoveredFilesFromWhitelist($addUncovered); $coverage->setProcessUncoveredFilesFromWhitelist($processUncovered); foreach ($whitelist as $item) { if (is_dir($item)) { $filter->addDirectoryToWhitelist($item); } else { if (is_file($item)) { $filter->addFileToWhitelist($item); } } } } if (!$merge) { $coverage->start('phpcov'); require $arguments[0]; $coverage->stop(); } else { $finder = new Symfony\Component\Finder\Finder(); $finder->in($arguments[0])->name('*.cov'); foreach ($finder as $file) { $coverage->merge(unserialize(file_get_contents($file->getRealpath()))); } } if ($clover) { $writer = new PHP_CodeCoverage_Report_Clover(); $writer->process($coverage, $clover); } if ($html) { $writer = new PHP_CodeCoverage_Report_HTML(); $writer->process($coverage, $html); } if ($php) { $writer = new PHP_CodeCoverage_Report_PHP(); $writer->process($coverage, $php); } if ($text) { $writer = new PHP_CodeCoverage_Report_Text(); $writer->process($coverage, $text); } } else { self::showHelp(); exit(1); } }
/** * @TODO */ public function fromRoute($route) { // $this->route = $route; // Find the files that match the route. $finder = new \Symfony\Component\Finder\Finder(); $glob = '#^default\\.(?:md|markdown|textile|html|htm|txt)$#'; if ($route !== '') { $glob = '#^(?:\\d\\d\\.)?' . implode('\\/(?:\\d\\d\\.)?', explode('/', $route)) . '(?:\\/default)?\\.(?:md|markdown|textile|html|htm|txt)' . '$#'; } $finder->in($this->documentPath)->path($glob); $files = []; foreach ($finder as $file) { $files[] = $file->getRelativePathname(); } // Work out if we have *any* matching documents. If not, throw an // exception. if (empty($files)) { throw new Exceptions\NoCandidatesException($route); } // Sort functions. $indexSort = function ($a, $b) { // return 0; return $a > $b; }; $extensionSort = function ($a, $b) { $allowedExtensions = explode('|', 'md|markdown|textile|html|htm|txt'); $aExt = pathinfo($a, PATHINFO_EXTENSION); $bExt = pathinfo($b, PATHINFO_EXTENSION); $aExtPos = array_search($aExt, $allowedExtensions); $bExtPos = array_search($bExt, $allowedExtensions); return $aExtPos > $bExtPos; }; $isDefaultSort = function ($a, $b) { $aHasDefault = strpos($a, 'default.'); $bHasDefault = strpos($b, 'default.'); return $aHasDefault < $bHasDefault; }; // Sort the documents according to their priority. $complexSort = \pjdietz\ComplexSort\ComplexSort::makeComplexSortFunction([$indexSort, $extensionSort, $isDefaultSort]); usort($files, $complexSort); // Read the file content from the filesystem. $fileReader = new FileReader(new \League\Flysystem\Filesystem(new \League\Flysystem\Adapter\Local($this->documentPath))); $filepath = $files[0]; $content = $fileReader->read($filepath); // Create a document from the file content. $document = new Document($content); $document->filepath = $filepath; $document->parse(); return $document; }