sortByName() 공개 메소드

This can be slow as all the matching files and directories must be retrieved for comparison.
또한 보기: SortableIterator
public sortByName ( ) : Finder | Symfony\Component\Finder\SplFileInfo[]
리턴 Finder | Symfony\Component\Finder\SplFileInfo[] The current Finder instance
예제 #1
2
 /**
  * @param string|callable $by
  * @return $this
  */
 public function sortBy($by = self::SORT_BY_NAME)
 {
     if (is_callable($by)) {
         $this->finder->sort($by);
         return $this;
     }
     switch (strtolower($by)) {
         case self::SORT_BY_NAME:
         case 'name':
             $this->finder->sortByName();
             break;
         case self::SORT_BY_CHANGED_TIME:
         case 'ctime':
             $this->finder->sortByChangedTime();
             break;
         case self::SORT_BY_ACCESSED_TIME:
         case 'atime':
             $this->finder->sortByAccessedTime();
             break;
         case self::SORT_BY_TYPE:
         case 'type':
             $this->finder->sortByType();
             break;
         case self::SORT_BY_MODIFIED_TIME:
         case 'mtime':
             $this->finder->sortByModifiedTime();
             break;
         default:
             throw new \InvalidArgumentException($by . ' is not a supported argument for sorting.');
     }
     return $this;
 }
예제 #2
0
 /**
  * @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);
 }
예제 #3
0
 /**
  * Gather data from annotations.js and *.md files found in source/_annotations
  *
  * @return {Array}        populates Annotations::$store
  */
 public static function gather()
 {
     // set-up default var
     $annotationsDir = Config::getOption("annotationsDir");
     // set-up the dispatcher
     $dispatcherInstance = Dispatcher::getInstance();
     // dispatch that the data gather has started
     $dispatcherInstance->dispatch("annotations.gatherStart");
     // set-up the comments store
     self::$store["comments"] = array();
     // create the annotations dir if it doesn't exist
     if (!is_dir($annotationsDir)) {
         mkdir($annotationsDir);
     }
     // find the markdown-based annotations
     $finder = new Finder();
     $finder->files()->name("*.md")->in($annotationsDir);
     $finder->sortByName();
     foreach ($finder as $name => $file) {
         $data = array();
         $data[0] = array();
         $text = file_get_contents($file->getPathname());
         $matches = strpos($text, PHP_EOL . "~*~" . PHP_EOL) !== false ? explode(PHP_EOL . "~*~" . PHP_EOL, $text) : array($text);
         foreach ($matches as $match) {
             list($yaml, $markdown) = Documentation::parse($match);
             if (isset($yaml["el"]) || isset($yaml["selector"])) {
                 $data[0]["el"] = isset($yaml["el"]) ? $yaml["el"] : $yaml["selector"];
             } else {
                 $data[0]["el"] = "#someimpossibleselector";
             }
             $data[0]["title"] = isset($yaml["title"]) ? $yaml["title"] : "";
             $data[0]["comment"] = $markdown;
             self::$store["comments"] = array_merge(self::$store["comments"], $data);
         }
     }
     // read in the old style annotations.js, modify the data and generate JSON array to merge
     $data = array();
     $oldStyleAnnotationsPath = $annotationsDir . DIRECTORY_SEPARATOR . "annotations.js";
     if (file_exists($oldStyleAnnotationsPath)) {
         $text = trim(file_get_contents($oldStyleAnnotationsPath));
         $text = str_replace("var comments = ", "", $text);
         if ($text[strlen($text) - 1] == ";") {
             $text = rtrim($text, ";");
         }
         $data = json_decode($text, true);
         if ($jsonErrorMessage = JSON::hasError()) {
             JSON::lastErrorMsg(Console::getHumanReadablePath($oldStyleAnnotationsPath), $jsonErrorMessage, $data);
         }
     }
     // merge in any data from the old file if the json decode was successful
     if (is_array($data) && isset($data["comments"])) {
         self::$store["comments"] = array_merge(self::$store["comments"], $data["comments"]);
     }
     $dispatcherInstance->dispatch("annotations.gatherEnd");
 }
예제 #4
0
 /**
  * Create ProcessSet from given files, optionally filtering by given $groups and $excludeGroups
  *
  * @param Finder $files
  * @param array $groups Groups to be run
  * @param array $excludeGroups Groups to be excluded
  * @param string $filter filter test cases by name
  * @return ProcessSet
  */
 public function createFromFiles(Finder $files, array $groups = null, array $excludeGroups = null, $filter = null)
 {
     $files->sortByName();
     $processSet = $this->getProcessSet();
     if ($groups || $excludeGroups || $filter) {
         $this->output->writeln('Filtering testcases:');
     }
     if ($groups) {
         $this->output->writeln(sprintf(' - by group(s): %s', implode(', ', $groups)));
     }
     if ($excludeGroups) {
         $this->output->writeln(sprintf(' - excluding group(s): %s', implode(', ', $excludeGroups)));
     }
     if ($filter) {
         $this->output->writeln(sprintf(' - by testcase/test name: %s', $filter));
     }
     $testCasesNum = 0;
     foreach ($files as $file) {
         $fileName = $file->getRealpath();
         // Parse classes from the testcase file
         $classes = AnnotationsParser::parsePhp(\file_get_contents($fileName));
         // Get annotations for the first class in testcase (one file = one class)
         $annotations = AnnotationsParser::getAll(new \ReflectionClass(key($classes)));
         // Filter out test-cases having any of excluded groups
         if ($excludeGroups && array_key_exists('group', $annotations) && count($excludingGroups = array_intersect($excludeGroups, $annotations['group']))) {
             if ($this->output->isDebug()) {
                 $this->output->writeln(sprintf('Excluding testcase file %s with group %s', $fileName, implode(', ', $excludingGroups)));
             }
             continue;
         }
         // Filter out test-cases without any matching group
         if ($groups) {
             if (!array_key_exists('group', $annotations) || !count($matchingGroups = array_intersect($groups, $annotations['group']))) {
                 continue;
             }
             if ($this->output->isDebug()) {
                 $this->output->writeln(sprintf('Found testcase file #%d in group %s: %s', ++$testCasesNum, implode(', ', $matchingGroups), $fileName));
             }
         } else {
             if ($this->output->isDebug()) {
                 $this->output->writeln(sprintf('Found testcase file #%d: %s', ++$testCasesNum, $fileName));
             }
         }
         $phpunitArgs = ['--log-junit=logs/' . Strings::webalize(key($classes), null, $lower = false) . '.xml', '--configuration=' . realpath(__DIR__ . '/../phpunit.xml')];
         if ($filter) {
             $phpunitArgs[] = '--filter=' . $filter;
         }
         // If ANSI output is enabled, turn on colors in PHPUnit
         if ($this->output->isDecorated()) {
             $phpunitArgs[] = '--colors=always';
         }
         $processSet->add($this->buildProcess($fileName, $phpunitArgs), key($classes), $delayAfter = !empty($annotations['delayAfter']) ? current($annotations['delayAfter']) : '', $delayMinutes = !empty($annotations['delayMinutes']) ? current($annotations['delayMinutes']) : null);
     }
     return $processSet;
 }
 protected function getListaIframes()
 {
     $iframeDir = $this->container->getParameter('iframe_dir');
     $finder = new Finder();
     $finder->files()->in($iframeDir);
     $finder->sortByName();
     $iframes = array();
     foreach ($finder as $file) {
         $iframes[] = $file->getRelativePathname();
     }
     return $iframes;
 }
 /**
  * Gather data from annotations.js and *.md files found in source/_annotations
  *
  * @return {Array}        populates Annotations::$store
  */
 public static function gather()
 {
     // set-up default var
     $sourceDir = Config::getOption("sourceDir");
     // set-up the dispatcher
     $dispatcherInstance = Dispatcher::getInstance();
     // dispatch that the data gather has started
     $dispatcherInstance->dispatch("annotations.gatherStart");
     // set-up the comments store
     self::$store["comments"] = array();
     // iterate over all of the files in the annotations dir
     if (!is_dir($sourceDir . "/_annotations")) {
         Console::writeWarning("<path>_annotations/</path><warning> doesn't exist so you won't have annotations...");
         mkdir($sourceDir . "/_annotations");
     }
     // find the markdown-based annotations
     $finder = new Finder();
     $finder->files()->name("*.md")->in($sourceDir . "/_annotations");
     $finder->sortByName();
     foreach ($finder as $name => $file) {
         $data = array();
         $data[0] = array();
         $text = file_get_contents($file->getPathname());
         $matches = strpos($text, PHP_EOL . "~*~" . PHP_EOL) !== false ? explode(PHP_EOL . "~*~" . PHP_EOL, $text) : array($text);
         foreach ($matches as $match) {
             list($yaml, $markdown) = Documentation::parse($match);
             if (isset($yaml["el"]) || isset($yaml["selector"])) {
                 $data[0]["el"] = isset($yaml["el"]) ? $yaml["el"] : $yaml["selector"];
             } else {
                 $data[0]["el"] = "#someimpossibleselector";
             }
             $data[0]["title"] = isset($yaml["title"]) ? $yaml["title"] : "";
             $data[0]["comment"] = $markdown;
             self::$store["comments"] = array_merge(self::$store["comments"], $data);
         }
     }
     // read in the old style annotations.js, modify the data and generate JSON array to merge
     if (file_exists($sourceDir . "/_annotations/annotations.js")) {
         $text = file_get_contents($sourceDir . "/_annotations/annotations.js");
         $text = str_replace("var comments = ", "", $text);
         $text = rtrim($text, ";");
         $data = json_decode($text, true);
         if ($jsonErrorMessage = JSON::hasError()) {
             JSON::lastErrorMsg("_annotations/annotations.js", $jsonErrorMessage, $data);
         }
     }
     // merge in any data from the old file
     self::$store["comments"] = array_merge(self::$store["comments"], $data["comments"]);
     $dispatcherInstance->dispatch("annotations.gatherEnd");
 }
예제 #7
0
 /**
  * @Route("/catalog/{slug}/{tag}/", name="spb_shop_catalog_category")
  */
 public function categoryAction($slug)
 {
     $em = $this->getDoctrine()->getManager();
     $repo = $em->getRepository('SpbShopBundle:Category');
     $entity = $repo->findOneBySlug($slug);
     $parents = $repo->getPath($entity);
     if ($repo->childCount($entity) > 0) {
         $children = $repo->children($entity, true);
         return $this->render('SpbShopBundle:Catalog:category.html.twig', array('entity' => $entity, 'parents' => $parents, 'items' => $children));
     } else {
         $finder = new Finder();
         $finder->files()->in($this->container->getParameter('catalog_img') . $entity->getTag());
         $finder->sortByName();
         return $this->render('SpbShopBundle:Catalog:product.html.twig', array('entity' => $entity, 'parents' => $parents, 'finder' => $finder));
     }
 }
예제 #8
0
 /**
  * Find patch files in good order
  *
  * @param string $dir
  * @return array
  */
 protected function findPatchsFiles($dir)
 {
     if (is_dir($dir) === false) {
         return array();
     }
     $finderFiles = new Finder();
     $finderFiles->files();
     $finderFiles->in($dir);
     $finderFiles->name('Patch*.php');
     $finderFiles->sortByName();
     // we want first patch in first, but sortByName sort first patch in last
     $return = array();
     foreach ($finderFiles as $file) {
         $return = array_merge($return, array($file));
     }
     return $return;
 }
예제 #9
0
 /**
  * @return void
  */
 protected function listAllDumps()
 {
     $finder = new Finder();
     $finder->files()->in($this->getDumpsPath());
     if ($finder->count() === 0) {
         return $this->line($this->colors->getColoredString("\n" . 'You haven\'t saved any dumps.' . "\n", 'brown'));
     }
     $finder->sortByName();
     $count = count($finder);
     $i = 0;
     foreach ($finder as $dump) {
         $i++;
         $fileName = $dump->getFilename();
         if ($i === $count - 1) {
             $fileName .= "\n";
         }
         $this->line($this->colors->getColoredString($fileName, 'brown'));
     }
 }
예제 #10
0
파일: Util.php 프로젝트: biberlabs/mocker
 /**
  * Build a Symfony Finder object that scans the given $directory.
  *
  * @param string|array|Finder $directory The directory(s) or filename(s)
  * @param null|string|array $exclude The directory(s) or filename(s) to exclude (as absolute or relative paths)
  * @throws InvalidArgumentException
  */
 public static function finder($directory, $exclude = null)
 {
     if ($directory instanceof Finder) {
         return $directory;
     } else {
         $finder = new Finder();
         $finder->sortByName();
     }
     $finder->files();
     if (is_string($directory)) {
         if (is_file($directory)) {
             // Scan a single file?
             $finder->append([$directory]);
         } else {
             // Scan a directory
             $finder->in($directory);
         }
     } elseif (is_array($directory)) {
         foreach ($directory as $path) {
             if (is_file($path)) {
                 // Scan a file?
                 $finder->append([$path]);
             } else {
                 $finder->in($path);
             }
         }
     } else {
         throw new InvalidArgumentException('Unexpected $directory value:' . gettype($directory));
     }
     if ($exclude !== null) {
         if (is_string($exclude)) {
             $finder->notPath(Util::getRelativePath($exclude, $directory));
         } elseif (is_array($exclude)) {
             foreach ($exclude as $path) {
                 $finder->notPath(Util::getRelativePath($path, $directory));
             }
         } else {
             throw new InvalidArgumentException('Unexpected $exclude value:' . gettype($exclude));
         }
     }
     return $finder;
 }
예제 #11
0
 protected function listAllDumps()
 {
     $finder = new Finder();
     $finder->files()->in($this->getDumpsPath());
     if ($finder->count() > 0) {
         $this->line($this->colors->getColoredString("\n" . 'Please select one of the following dumps:' . "\n", 'white'));
         $finder->sortByName();
         $count = count($finder);
         $i = 0;
         foreach ($finder as $dump) {
             $i++;
             if ($i != $count) {
                 $this->line($this->colors->getColoredString($dump->getFilename(), 'brown'));
             } else {
                 $this->line($this->colors->getColoredString($dump->getFilename() . "\n", 'brown'));
             }
         }
     } else {
         $this->line($this->colors->getColoredString("\n" . 'You haven\'t saved any dumps.' . "\n", 'brown'));
     }
 }
 /**
  * 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;
 }
예제 #13
0
 /**
  * Load functions for the Twig PatternEngine
  * @param  {Instance}       an instance of the twig engine
  *
  * @return {Instance}       an instance of the twig engine
  */
 public static function loadTests($instance)
 {
     // load defaults
     $testDir = Config::getOption("sourceDir") . DIRECTORY_SEPARATOR . "_twig-components/tests";
     $testExt = Config::getOption("twigTestExt");
     $testExt = $testExt ? $testExt : "test.php";
     if (is_dir($testDir)) {
         // loop through the test dir...
         $finder = new Finder();
         $finder->files()->name("*\\." . $testExt)->in($testDir);
         $finder->sortByName();
         foreach ($finder as $file) {
             // see if the file should be ignored or not
             $baseName = $file->getBasename();
             if ($baseName[0] != "_") {
                 include $file->getPathname();
                 // $test should be defined in the included file
                 if (isset($test)) {
                     $instance->addTest($test);
                     unset($test);
                 }
             }
         }
     }
     return $instance;
 }
예제 #14
0
 /**
  * Find all files to merge.
  *
  * @param string $directory
  * @param array  $names
  * @param array  $ignoreNames
  *
  * @return Finder
  */
 private function findFiles($directory, array $names, array $ignoreNames)
 {
     $finder = new Finder();
     $finder->files()->in($directory);
     foreach ($names as $name) {
         $finder->name($name);
     }
     foreach ($ignoreNames as $name) {
         $finder->notName($name);
     }
     $finder->sortByName();
     return $finder;
 }
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return bool|int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     if ($input->isInteractive()) {
         $this->writeCommandHeader($output, 'Looking for videos...');
         $confPath = $this->getConfigurationHelper()->getConfigurationFilePath();
         $sysPath = $this->getConfigurationHelper()->getSysPathFromConfigurationFile($confPath);
         $dir = $input->getArgument('source');
         //1 if the option was set
         if (substr($dir, 0, 1) != '/') {
             $dir = $sysPath . $dir;
         }
         if (!is_dir($dir)) {
             $output->writeln($dir . ' was not confirmed as a directory (if not starting with /, it is considered as relative to Chamilo\'s root folder)');
             return;
         }
         $this->ext = $input->getOption('ext');
         if (empty($this->ext)) {
             $this->ext = 'webm';
         }
         $this->origExt = $input->getOption('orig-ext');
         if (empty($this->origExt)) {
             $this->origExt = 'orig';
         }
         $fps = $input->getOption('fps');
         if (empty($fps)) {
             $fps = '24';
         }
         $bitRate = $input->getOption('bitrate');
         if (empty($bitRate)) {
             $bitRate = '512';
         }
         $vcodec = 'copy';
         if ($this->ext == 'webm') {
             $vcodec = 'libvpx';
         }
         // Find the files we want to treat, using Finder selectors
         $finder = new Finder();
         $filter = function (\SplFileInfo $file, $ext, $orig) {
             $combinedExt = '.' . $orig . '.' . $ext;
             $combinedExtLength = strlen($combinedExt);
             $extLength = strlen('.' . $ext);
             if (substr($file->getRealPath(), -$combinedExtLength) == $combinedExt) {
                 return false;
             }
             if (is_file(substr($file->getRealPath(), 0, -$extLength) . $combinedExt)) {
                 $this->excluded[] = $file;
                 return false;
             }
         };
         $finder->sortByName()->files()->in($dir)->name('*.' . $this->ext)->filter($filter, $this->ext, $this->origExt);
         // Print the list of matching files we found
         if (count($finder) > 0) {
             $output->writeln('Videos found for conversion: ');
             foreach ($finder as $file) {
                 $output->writeln($file->getRealpath());
             }
         } else {
             if (count($this->excluded) > 0) {
                 $output->writeln('The system has detected several videos already converted: ');
                 foreach ($this->excluded as $file) {
                     $output->writeln('- ' . $file->getRealPath());
                 }
             }
             $output->writeln('No video left to convert');
             return;
         }
         $dialog = $this->getHelperSet()->get('dialog');
         if (!$dialog->askConfirmation($output, '<question>All listed videos will be altered and a copy of the original will be taken with a .orig.webm extension. Are you sure you want to proceed? (y/N)</question>', false)) {
             return;
         }
         $fs = new Filesystem();
         $time = time();
         $counter = 0;
         $sizeNew = $sizeOrig = 0;
         foreach ($finder as $file) {
             $sizeOrig += $file->getSize();
             $origName = $file->getRealPath();
             $newName = substr($file->getRealPath(), 0, -4) . 'orig.webm';
             $fs->rename($origName, $newName);
             $out = array();
             $newNameCommand = preg_replace('/\\s/', '\\ ', $newName);
             $newNameCommand = preg_replace('/\\(/', '\\(', $newNameCommand);
             $newNameCommand = preg_replace('/\\)/', '\\)', $newNameCommand);
             $origNameCommand = preg_replace('/\\s/', '\\ ', $origName);
             $origNameCommand = preg_replace('/\\(/', '\\(', $origNameCommand);
             $origNameCommand = preg_replace('/\\)/', '\\)', $origNameCommand);
             $output->writeln('ffmpeg -i ' . $newNameCommand . ' -b ' . $bitRate . 'k -f ' . $this->ext . ' -vcodec ' . $vcodec . ' -acodec copy -r ' . $fps . ' ' . $origNameCommand);
             $exec = @system('ffmpeg -i ' . $newNameCommand . ' -b ' . $bitRate . 'k -f ' . $this->ext . ' -vcodec ' . $vcodec . ' -acodec copy -r ' . $fps . ' ' . $origNameCommand, $out);
             $sizeNew += filesize($origName);
             $counter++;
         }
     }
     $output->writeln('');
     $output->writeln('Done converting all videos from ' . $dir);
     $output->writeln('Total videos converted: ' . $counter . ' videos in ' . (time() - $time) . ' seconds');
     $output->writeln('Total size of old videos combined: ' . round($sizeOrig / (1024 * 1024)) . 'M');
     $output->writeln('Total size of all new videos combined: ' . round($sizeNew / (1024 * 1024)) . 'M');
     //$this->removeFiles($files, $output);
 }
예제 #16
0
 /**
  * @param ThemeInterface $theme
  * @param string $originDir
  * @param string $targetDir
  * @param integer $symlinkMask
  *
  * @return integer
  */
 protected function installThemedBundleAssets(ThemeInterface $theme, $originDir, $targetDir, $symlinkMask)
 {
     $effectiveSymlinkMask = $symlinkMask;
     $finder = new Finder();
     $finder->sortByName()->ignoreDotFiles(false)->in($originDir);
     /** @var SplFileInfo[] $finder */
     foreach ($finder as $originFile) {
         $targetFile = $targetDir . '/' . $originFile->getRelativePathname();
         $targetFile = $this->pathResolver->resolve($targetFile, $theme);
         if (file_exists($targetFile)) {
             continue;
         }
         $this->filesystem->mkdir(dirname($targetFile));
         $effectiveSymlinkMask = min($effectiveSymlinkMask, $this->installAsset($originFile->getPathname(), $targetFile, $symlinkMask));
     }
     return $effectiveSymlinkMask;
 }
예제 #17
0
 /**
  * Returns the fixtures files to load.
  *
  * @param string $type  The extension of the files.
  * @param string $in    The directory in which we search the files. If null,
  *                      we'll use the absoluteFixturesPath property.
  *
  * @return \Iterator An iterator through the files.
  */
 protected function getFixtureFiles($type = 'sql', $in = null)
 {
     $finder = new Finder();
     $finder->sortByName()->name('*.' . $type);
     $files = $finder->in(null !== $in ? $in : $this->absoluteFixturesPath);
     if (null === $this->bundle) {
         return $files;
     }
     $finalFixtureFiles = array();
     foreach ($files as $file) {
         $fixtureFilePath = str_replace($this->getFixturesPath($this->bundle) . DIRECTORY_SEPARATOR, '', $file->getRealPath());
         $logicalName = sprintf('@%s/Resources/fixtures/%s', $this->bundle->getName(), $fixtureFilePath);
         $finalFixtureFiles[] = new \SplFileInfo($this->getFileLocator()->locate($logicalName));
     }
     return new \ArrayIterator($finalFixtureFiles);
 }
예제 #18
0
 /**
  * Get a list of integration helper classes
  *
  * @param array|string $services
  * @param array        $withFeatures
  * @param bool         $alphabetical
  * @param null|int     $addonFilter
  *
  * @return mixed
  */
 public function getIntegrationObjects($services = null, $withFeatures = null, $alphabetical = false, $addonFilter = null)
 {
     static $integrations, $available;
     if (empty($integrations)) {
         $em = $this->factory->getEntityManager();
         $available = $integrations = array();
         // And we'll be scanning the addon bundles for additional classes, so have that data on standby
         $addons = $this->factory->getEnabledAddons();
         // Quickly figure out which addons are enabled so we only process those
         /** @var \Mautic\AddonBundle\Entity\AddonRepository $addonRepo */
         $addonRepo = $em->getRepository('MauticAddonBundle:Addon');
         $addonStatuses = $addonRepo->getBundleStatus(true);
         // Scan the addons for integration classes
         foreach ($addons as $addon) {
             if (is_dir($addon['directory'] . '/Integration')) {
                 $finder = new Finder();
                 $finder->files()->name('*Integration.php')->in($addon['directory'] . '/Integration')->ignoreDotFiles(true);
                 if ($alphabetical) {
                     $finder->sortByName();
                 }
                 $id = $addonStatuses[$addon['bundle']]['id'];
                 foreach ($finder as $file) {
                     $available[] = array('addon' => $em->getReference('MauticAddonBundle:Addon', $id), 'integration' => substr($file->getBaseName(), 0, -15), 'namespace' => str_replace('MauticAddon', '', $addon['bundle']));
                 }
             }
         }
         $integrationSettings = $this->getIntegrationSettings();
         // Get all the addon integrations
         foreach ($available as $id => $a) {
             if ($addonFilter && $a['addon']->getId() != $addonFilter) {
                 continue;
             }
             if (!isset($integrations[$a['integration']])) {
                 $class = "\\MauticAddon\\" . $a['namespace'] . "\\Integration\\" . $a['integration'] . "Integration";
                 $reflectionClass = new \ReflectionClass($class);
                 if ($reflectionClass->isInstantiable()) {
                     $integrations[$a['integration']] = new $class($this->factory);
                     if (!isset($integrationSettings[$a['integration']])) {
                         $integrationSettings[$a['integration']] = new Integration();
                         $integrationSettings[$a['integration']]->setName($a['integration']);
                     }
                     $integrationSettings[$a['integration']]->setAddon($a['addon']);
                     $integrations[$a['integration']]->setIntegrationSettings($integrationSettings[$a['integration']]);
                 }
             }
         }
         if (empty($alphabetical)) {
             // Sort by priority
             uasort($integrations, function ($a, $b) {
                 $aP = (int) $a->getPriority();
                 $bP = (int) $b->getPriority();
                 if ($aP === $bP) {
                     return 0;
                 }
                 return $aP < $bP ? -1 : 1;
             });
         }
     }
     if (!empty($services)) {
         if (!is_array($services) && isset($integrations[$services])) {
             return array($services => $integrations[$services]);
         } elseif (is_array($services)) {
             $specific = array();
             foreach ($services as $s) {
                 if (isset($integrations[$s])) {
                     $specific[$s] = $integrations[$s];
                 }
             }
             return $specific;
         } else {
             throw new MethodNotAllowedHttpException(array_keys($available));
         }
     } elseif (!empty($withFeatures)) {
         if (!is_array($withFeatures)) {
             $withFeatures = array($withFeatures);
         }
         $specific = array();
         foreach ($integrations as $n => $d) {
             $settings = $d->getIntegrationSettings();
             $features = $settings->getSupportedFeatures();
             foreach ($withFeatures as $f) {
                 if (in_array($f, $features)) {
                     $specific[$n] = $d;
                     break;
                 }
             }
         }
         return $specific;
     }
     return $integrations;
 }
예제 #19
0
 private function scanFolders($path, $parent)
 {
     $finder = new Finder();
     $finder->in($path);
     $finder->directories();
     $finder->ignoreDotFiles(true);
     $finder->depth(0);
     $finder->sortByName();
     foreach ($finder as $entity) {
         /* @var $entity SplFileInfo */
         $name = $entity->getFilename();
         // Skip items starting with underscore
         if (preg_match('~^_~', $name)) {
             continue;
         }
         // Skip items starting with dot
         if (preg_match('~^\\.~', $name)) {
             continue;
         }
         $this->scanFiles($entity->getPathname(), $parent);
     }
 }
예제 #20
0
 /**
  * Generates the data that powers the index page
  */
 protected function generateIndex()
 {
     // bomb if missing index.html
     if (!file_exists(Config::getOption("publicDir") . "/index.html")) {
         $index = Console::getHumanReadablePath(Config::getOption("publicDir")) . DIRECTORY_SEPARATOR . "index.html";
         Console::writeError("<path>" . $index . "</path> is missing. grab a copy from your StyleguideKit...");
     }
     // set-up the dispatcher
     $dispatcherInstance = Dispatcher::getInstance();
     // note the start of the operation
     $dispatcherInstance->dispatch("builder.generateIndexStart");
     // default var
     $dataDir = Config::getOption("publicDir") . "/styleguide/data";
     // double-check that the data directory exists
     if (!is_dir($dataDir)) {
         FileUtil::makeDir($dataDir);
     }
     $output = "";
     // load and write out the config options
     $config = array();
     $exposedOptions = Config::getOption("exposedOptions");
     foreach ($exposedOptions as $exposedOption) {
         $config[$exposedOption] = Config::getOption($exposedOption);
     }
     $output .= "var config = " . json_encode($config) . ";\n";
     // load the ish Controls
     $ishControls = array();
     $controlsToHide = array();
     $ishControlsHide = Config::getOption("ishControlsHide");
     if ($ishControlsHide) {
         foreach ($ishControlsHide as $controlToHide) {
             $controlsToHide[$controlToHide] = "true";
         }
     }
     $ishControls["ishControlsHide"] = $controlsToHide;
     $output .= "var ishControls = " . json_encode($ishControls) . ";\n";
     // load and write out the items for the navigation
     $niExporter = new NavItemsExporter();
     $navItems = $niExporter->run();
     $output .= "var navItems = " . json_encode($navItems) . ";\n";
     // load and write out the items for the pattern paths
     $patternPaths = array();
     $ppdExporter = new PatternPathDestsExporter();
     $patternPaths = $ppdExporter->run();
     $output .= "var patternPaths = " . json_encode($patternPaths) . ";\n";
     // load and write out the items for the view all paths
     $viewAllPaths = array();
     $vapExporter = new ViewAllPathsExporter();
     $viewAllPaths = $vapExporter->run($navItems);
     $output .= "var viewAllPaths = " . json_encode($viewAllPaths) . ";\n";
     // gather plugin package information
     $packagesInfo = array();
     $componentDir = Config::getOption("componentDir");
     if (!is_dir($componentDir)) {
         mkdir($componentDir);
     }
     $componentPackagesDir = $componentDir . "/packages";
     if (!is_dir($componentDir . "/packages")) {
         mkdir($componentDir . "/packages");
     }
     $finder = new Finder();
     $finder->files()->name("*.json")->in($componentPackagesDir);
     $finder->sortByName();
     foreach ($finder as $file) {
         $filename = $file->getFilename();
         if ($filename[0] != "_") {
             $javascriptPaths = array();
             $packageInfo = json_decode(file_get_contents($file->getPathname()), true);
             foreach ($packageInfo["templates"] as $templateKey => $templatePath) {
                 $templatePathFull = $componentDir . "/" . $packageInfo["name"] . "/" . $templatePath;
                 $packageInfo["templates"][$templateKey] = file_exists($templatePathFull) ? file_get_contents($templatePathFull) : "";
             }
             foreach ($packageInfo["javascripts"] as $key => $javascriptPath) {
                 $javascriptPaths[] = "patternlab-components/" . $packageInfo["name"] . "/" . $javascriptPath;
             }
             $packageInfo["javascripts"] = $javascriptPaths;
             $packagesInfo[] = $packageInfo;
         }
     }
     $output .= "var plugins = " . json_encode($packagesInfo) . ";";
     // write out the data
     file_put_contents($dataDir . "/patternlab-data.js", $output);
     // note the end of the operation
     $dispatcherInstance->dispatch("builder.generateIndexEnd");
 }
예제 #21
0
 /**
  * Gather data from any JSON and YAML files in source/_data
  *
  * Reserved attributes:
  *    - Data::$store["listItems"] : listItems from listitems.json, duplicated into separate arrays for Data::$store["listItems"]["one"], Data::$store["listItems"]["two"]... etc.
  *    - Data::$store["link"] : the links to each pattern
  *    - Data::$store["cacheBuster"] : the cache buster value to be appended to URLs
  *    - Data::$store["patternSpecific"] : holds attributes from the pattern-specific data files
  *
  * @return {Array}        populates Data::$store
  */
 public static function gather($options = array())
 {
     // set-up the dispatcher
     $dispatcherInstance = Dispatcher::getInstance();
     // dispatch that the data gather has started
     $dispatcherInstance->dispatch("data.gatherStart");
     // default vars
     $found = false;
     $dataJSON = array();
     $dataYAML = array();
     $listItemsJSON = array();
     $listItemsYAML = array();
     $sourceDir = Config::getOption("sourceDir");
     // iterate over all of the other files in the source directory
     if (!is_dir($sourceDir . "/_data/")) {
         Console::writeWarning("<path>_data/</path> doesn't exist so you won't have dynamic data...");
         mkdir($sourceDir . "/_data/");
     }
     // find the markdown-based annotations
     $finder = new Finder();
     $finder->files()->in($sourceDir . "/_data/");
     $finder->sortByName();
     foreach ($finder as $name => $file) {
         $ext = $file->getExtension();
         $data = array();
         $fileName = $file->getFilename();
         $hidden = $fileName[0] == "_";
         $isListItems = strpos($fileName, "listitems");
         $pathName = $file->getPathname();
         $pathNameClean = str_replace($sourceDir . "/", "", $pathName);
         if (!$hidden && ($ext == "json" || $ext == "yaml")) {
             if ($isListItems === false) {
                 if ($ext == "json") {
                     $file = file_get_contents($pathName);
                     $data = json_decode($file, true);
                     if ($jsonErrorMessage = JSON::hasError()) {
                         JSON::lastErrorMsg($pathNameClean, $jsonErrorMessage, $data);
                     }
                 } else {
                     if ($ext == "yaml") {
                         $file = file_get_contents($pathName);
                         try {
                             $data = YAML::parse($file);
                         } catch (ParseException $e) {
                             printf("unable to parse " . $pathNameClean . ": %s..\n", $e->getMessage());
                         }
                         // single line of text won't throw a YAML error. returns as string
                         if (gettype($data) == "string") {
                             $data = array();
                         }
                     }
                 }
                 if (is_array($data)) {
                     self::$store = array_replace_recursive(self::$store, $data);
                 }
             } else {
                 if ($isListItems !== false) {
                     $data = $ext == "json" ? self::getListItems("_data/" . $fileName) : self::getListItems("_data/" . $fileName, "yaml");
                     if (!isset(self::$store["listItems"])) {
                         self::$store["listItems"] = array();
                     }
                     self::$store["listItems"] = array_replace_recursive(self::$store["listItems"], $data);
                 }
             }
         }
     }
     if (is_array(self::$store)) {
         foreach (self::$reservedKeys as $reservedKey) {
             if (array_key_exists($reservedKey, self::$store)) {
                 Console::writeWarning("\"" . $reservedKey . "\" is a reserved key in Pattern Lab. the data using that key will be overwritten. please choose a new key...");
             }
         }
     }
     self::$store["cacheBuster"] = Config::getOption("cacheBuster");
     self::$store["link"] = array();
     self::$store["patternSpecific"] = array();
     $dispatcherInstance->dispatch("data.gatherEnd");
 }
 public function index()
 {
     /*
     |--------------------------------------------------------------------------
     | Paramers
     |--------------------------------------------------------------------------
     |
     | Match overrides Extension. Exclusion applies in both cases.
     |
     */
     $match = $this->fetchParam('match', false);
     $exclude = $this->fetchParam('exclude', false);
     $extension = $this->fetchParam(array('extension', 'type'), false);
     $in = $this->fetchParam(array('in', 'folder', 'from'), false);
     $not_in = $this->fetchParam('not_in', false);
     $file_size = $this->fetchParam('file_size', false);
     $file_date = $this->fetchParam('file_date', false);
     $depth = $this->fetchParam('depth', false);
     $sort_by = $this->fetchParam(array('sort_by', 'order_by'), false);
     $sort_dir = $this->fetchParam(array('sort_dir', 'sort_direction'), 'asc');
     $limit = $this->fetchParam('limit', false);
     if ($in) {
         $in = Helper::explodeOptions($in);
     }
     if ($not_in) {
         $not_in = Helper::explodeOptions($not_in);
     }
     if ($file_size) {
         $file_size = Helper::explodeOptions($file_size);
     }
     if ($extension) {
         $extension = Helper::explodeOptions($extension);
     }
     /*
     |--------------------------------------------------------------------------
     | Finder
     |--------------------------------------------------------------------------
     |
     | Get_Files implements most of the Symfony Finder component as a clean
     | tag wrapper mapped to matched filenames.
     |
     */
     $finder = new Finder();
     if ($in) {
         foreach ($in as $location) {
             $finder->in(Path::fromAsset($location));
         }
     }
     /*
     |--------------------------------------------------------------------------
     | Name
     |--------------------------------------------------------------------------
     |
     | Match is the "native" Finder name() method, which is supposed to
     | implement string, glob, and regex. The glob support is only partial,
     | so "extension" is a looped *single* glob rule iterator.
     |
     */
     if ($match) {
         $finder->name($match);
     } elseif ($extension) {
         foreach ($extension as $ext) {
             $finder->name("*.{$ext}");
         }
     }
     /*
     |--------------------------------------------------------------------------
     | Exclude
     |--------------------------------------------------------------------------
     |
     | Exclude directories from matching. Remapped to "not in" to allow more
     | intuitive differentiation between filename and directory matching.
     |
     */
     if ($not_in) {
         foreach ($not_in as $location) {
             $finder->exclude($location);
         }
     }
     /*
     |--------------------------------------------------------------------------
     | Not Name
     |--------------------------------------------------------------------------
     |
     | Exclude files matching a given pattern: string, regex, or glob.
     | By default we don't allow looking for PHP files. Be smart.
     |
     */
     if ($this->fetchParam('allow_php', false) !== TRUE) {
         $finder->notName("*.php");
     }
     if ($exclude) {
         $finder->notName($exclude);
     }
     /*
     |--------------------------------------------------------------------------
     | File Size
     |--------------------------------------------------------------------------
     |
     | Restrict files by size. Can be chained and allows comparison operators.
     |
     */
     if ($file_size) {
         foreach ($file_size as $size) {
             $finder->size($size);
         }
     }
     /*
     |--------------------------------------------------------------------------
     | File Date
     |--------------------------------------------------------------------------
     |
     | Restrict files by last modified date. Can use comparison operators, and
     | since/after is aliased to >, and until/before to <.
     |
     */
     if ($file_date) {
         $finder->date($file_date);
     }
     /*
     |--------------------------------------------------------------------------
     | Depth
     |--------------------------------------------------------------------------
     |
     | Recursively traverse directories, starting at 0.
     |
     */
     if ($depth) {
         $finder->depth($depth);
     }
     /*
     |--------------------------------------------------------------------------
     | Sort By
     |--------------------------------------------------------------------------
     |
     | Sort by name, file, or type
     |
     */
     if ($sort_by) {
         if ($sort_by === 'file' || $sort_by === 'name') {
             $finder->sortByName();
         } elseif ($sort_by === 'type') {
             $finder->sortByType();
         }
     }
     /*
     |--------------------------------------------------------------------------
     | Assemble File Array
     |--------------------------------------------------------------------------
     |
     | Select the important bits of data on the list of files.
     |
     */
     $matches = $finder->files()->followLinks();
     $files = array();
     foreach ($matches as $file) {
         $files[] = array('extension' => $file->getExtension(), 'filename' => $file->getFilename(), 'file' => Path::toAsset($file->getPathname()), 'name' => Path::toAsset($file->getPathname()), 'size' => File::getHumanSize($file->getSize()), 'size_bytes' => $file->getSize(), 'size_kilobytes' => number_format($file->getSize() / 1024, 2), 'size_megabytes' => number_format($file->getSize() / 1048576, 2), 'size_gigabytes' => number_format($file->getSize() / 1073741824, 2), 'is_image' => File::isImage($file->getPathname()));
     }
     /*
     |--------------------------------------------------------------------------
     | Sort Direction
     |--------------------------------------------------------------------------
     |
     | Set the sort direction, defaulting to "asc" (ascending)
     |
     */
     if ($sort_dir === 'desc') {
         $files = array_reverse($files);
     }
     /*
     |--------------------------------------------------------------------------
     | Randomizing
     |--------------------------------------------------------------------------
     |
     | You can't sort randomly using Symfony finder, so we'll do it manually.
     |
     */
     if ($sort_by === 'random') {
         shuffle($files);
     }
     /*
     |--------------------------------------------------------------------------
     | Limit Files
     |--------------------------------------------------------------------------
     |
     | Limit the number of files returned. Needs to be run after sort_dir to 
     | ensure consistency.
     |
     */
     if ($limit) {
         $files = array_slice($files, 0, $limit);
     }
     return Parse::tagLoop($this->content, $files, true, $this->context);
 }
예제 #23
0
 /**
  * Generates the data that powers the index page
  */
 protected function generateIndex()
 {
     // set-up the dispatcher
     $dispatcherInstance = Dispatcher::getInstance();
     // note the start of the operation
     $dispatcherInstance->dispatch("builder.generateIndexStart");
     // default var
     $dataDir = Config::getOption("publicDir") . "/styleguide/data";
     // double-check that the data directory exists
     if (!is_dir($dataDir)) {
         mkdir($dataDir);
     }
     $output = "";
     // load and write out the config options
     $config = array();
     $exposedOptions = Config::getOption("exposedOptions");
     foreach ($exposedOptions as $exposedOption) {
         $config[$exposedOption] = Config::getOption($exposedOption);
     }
     $output .= "var config = " . json_encode($config) . ";";
     // load the ish Controls
     $ishControls = array();
     $controlsToHide = array();
     $ishControlsHide = Config::getOption("ishControlsHide");
     if ($ishControlsHide) {
         foreach ($ishControlsHide as $controlToHide) {
             $controlsToHide[$controlToHide] = "true";
         }
     }
     $ishControls["ishControlsHide"] = $controlsToHide;
     $ishControls["mqs"] = $this->gatherMQs();
     $output .= "var ishControls = " . json_encode($ishControls) . ";";
     // load and write out the items for the navigation
     $niExporter = new NavItemsExporter();
     $navItems = $niExporter->run();
     $output .= "var navItems = " . json_encode($navItems) . ";";
     // load and write out the items for the pattern paths
     $patternPaths = array();
     $ppdExporter = new PatternPathDestsExporter();
     $patternPaths = $ppdExporter->run();
     $output .= "var patternPaths = " . json_encode($patternPaths) . ";";
     // load and write out the items for the view all paths
     $viewAllPaths = array();
     $vapExporter = new ViewAllPathsExporter();
     $viewAllPaths = $vapExporter->run($navItems);
     $output .= "var viewAllPaths = " . json_encode($viewAllPaths) . ";";
     // gather plugin package information
     $packagesInfo = array();
     $componentDir = Config::getOption("componentDir");
     if (!is_dir($componentDir)) {
         mkdir($componentDir);
     }
     $componentPackagesDir = $componentDir . "/packages";
     if (!is_dir($componentDir . "/packages")) {
         mkdir($componentDir . "/packages");
     }
     $finder = new Finder();
     $finder->files()->name("*.json")->in($componentPackagesDir);
     $finder->sortByName();
     foreach ($finder as $file) {
         $filename = $file->getFilename();
         if ($filename[0] != "_") {
             $javascriptPaths = array();
             $packageInfo = json_decode(file_get_contents($file->getPathname()), true);
             foreach ($packageInfo["templates"] as $templateKey => $templatePath) {
                 $templatePathFull = $componentDir . "/" . $packageInfo["name"] . "/" . $templatePath;
                 $packageInfo["templates"][$templateKey] = file_exists($templatePathFull) ? file_get_contents($templatePathFull) : "";
             }
             foreach ($packageInfo["javascripts"] as $key => $javascriptPath) {
                 $javascriptPaths[] = "patternlab-components/" . $packageInfo["name"] . "/" . $javascriptPath;
             }
             $packageInfo["javascripts"] = $javascriptPaths;
             $packagesInfo[] = $packageInfo;
         }
     }
     $output .= "var plugins = " . json_encode($packagesInfo) . ";";
     // write out the data
     file_put_contents($dataDir . "/patternlab-data.js", $output);
     // Load and write out the items for the partials lookup
     $lpExporter = new LookupPartialsExporter();
     $lookup = $lpExporter->run();
     $lookupData = "module.exports = { lookup: " . json_encode($lookup) . "};";
     file_put_contents($dataDir . "/patternLabPartials.js", $lookupData);
     // note the end of the operation
     $dispatcherInstance->dispatch("builder.generateIndexEnd");
 }
예제 #24
0
}
$directoryIterator = $directoryFinder->in($path->path);
$directoryArray = array();
foreach ($directoryIterator as $directory) {
    $directoryArray[] = array("path" => $directory->getRelativePathname(), "name" => $directory->getBasename());
}
$fileFinder = new Finder();
$fileFinder->files()->ignoreUnreadableDirs()->depth(0);
$allowedImageTypes = loadPicFile("helpers/imagetypes.php");
foreach ($allowedImageTypes as $imageType) {
    $fileFinder->name("*.{$imageType}");
}
foreach (array_map("strtoupper", $allowedImageTypes) as $imageType) {
    $fileFinder->name("*.{$imageType}");
}
$fileFinder->sortByName();
if ($path->hasPermission("symlinks")) {
    $fileFinder->followLinks();
}
if (!empty($relpath)) {
    $fileFinder->path($relpath)->depth(substr_count($relpath, "/") + 1);
}
if ($path->hasPermission("nsfw") === false) {
    $fileFinder->notPath("/.*\\/NSFW\\/.*/")->notPath("/NSFW\\/.*/")->notPath("/.*\\/NSFW/");
}
$fileIterator = $fileFinder->in($path->path);
$fileArray = array();
foreach ($fileIterator as $file) {
    $fileArray[] = array("filename" => $file->getBasename(), "relpath" => $file->getRelativePathname(), "size" => humanFilesize($file->getSize()), "mtime" => date("Y-m-d H:i:s", $file->getMTime()));
}
header("Content-type: application/json");
예제 #25
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     try {
         $dialog = $this->getDialogHelper();
         $dir = $input->getArgument('dir');
         $this->orgId = $input->getOption('org');
         $this->schoolLegacyId = $input->getOption('school');
         $this->manager = $this->getContainer()->get('doctrine.orm.entity_manager');
         $this->org = $this->manager->getRepository('TSKUserBundle:Organization')->find($this->orgId);
         // $manager = $this->getContainer()->get('doctrine.orm.entity_manager');
         $accountRepo = $this->manager->getRepository('TSK\\PaymentBundle\\Entity\\Account');
         $this->incomeAccount = $accountRepo->findOneBy(array('name' => 'Inc Fm Students', 'organization' => $this->org));
         $this->deferralAccount = $accountRepo->findOneBy(array('name' => 'Deferred Income', 'organization' => $this->org));
         $incomeTypeRepo = $this->manager->getRepository('TSK\\PaymentBundle\\Entity\\IncomeType');
         $this->tuitionIncomeType = $incomeTypeRepo->findOneBy(array('name' => 'TUITION', 'organization' => $this->org));
         $school = $this->manager->getRepository('TSKSchoolBundle:School')->findOneBy(array('legacyId' => $this->schoolLegacyId));
         $scheduleEntityRepo = $this->manager->getRepository('TSK\\ScheduleBundle\\Entity\\ScheduleEntity');
         $this->dummyScheduleEntity = $scheduleEntityRepo->findOneBy(array('title' => 'Dummy Entity'));
         if (!$school) {
             print 'Invalid school with legacy id ' . $this->schoolLegacyId;
             exit;
             throw new \Exception('Invalid school with legacy id ' . $this->schoolLegacyId);
         } else {
             $this->school = $school;
         }
         if (!is_readable($dir)) {
             throw new \Exception('Unable to read directory ' . $dir);
         }
         $finder = new Finder();
         $finder->files()->in($dir);
         $finder->sortByName();
         $schoolProcessed = 0;
         $programsProcessed = 0;
         $paymentPlansProcessed = 0;
         $contractsProcessed = 0;
         $usersProcessed = 0;
         $loops = 0;
         foreach ($finder as $file) {
             if (!$schoolProcessed && $file->getFilename() == 'TSK_01.CSV') {
                 // schools
                 try {
                     $dialog->writeSection($output, 'Processing School Data ...');
                     $school = $this->processSchool($file);
                     $schoolProcessed = 1;
                     $dialog->writeSection($output, 'School Data Complete ...');
                 } catch (\Exception $e) {
                     throw $e;
                 }
             }
             if ($schoolProcessed && $file->getFilename() == 'TSK_02.CSV') {
                 // programs
                 try {
                     $dialog->writeSection($output, 'Processing Program Data ...');
                     $programs = $this->processPrograms($file);
                     $programsProcessed = 1;
                     $dialog->writeSection($output, 'Program Data Complete ...');
                     // attach programs to schools
                 } catch (\Exception $e) {
                     throw $e;
                 }
             }
             if ($file->getFilename() == 'TSK_03.CSV') {
                 // program payment plans
                 try {
                     $dialog->writeSection($output, 'Processing Program Payment Plan Data ...');
                     $paymentPlans = $this->processProgramPaymentPlans($file);
                     $paymentPlansProcessed = 1;
                     $dialog->writeSection($output, 'Program Payment Plan Data Complete ...');
                 } catch (\Exception $e) {
                     throw $e;
                 }
             }
             if ($file->getFilename() == 'TSK_04.CSV') {
                 // students
                 try {
                     $dialog->writeSection($output, 'Processing Student Data ...');
                     $contracts = $this->processStudents($file, $dialog, $output);
                     $studentsProcessed = 1;
                     $dialog->writeSection($output, 'Student Data Complete ...');
                 } catch (\Exception $e) {
                     $dialog = $this->getDialogHelper();
                     $dialog->writeSection($output, $e->getMessage(), 'bg=red;fg=white');
                     // throw $e;
                 }
             }
             if ($file->getFilename() == 'TSK_05.CSV') {
                 // contracts
                 try {
                     $dialog->writeSection($output, 'Processing Contract Data ...');
                     $contracts = $this->processContracts($file, $dialog, $output);
                     $contractsProcessed = 1;
                     $dialog->writeSection($output, 'Contract Data Complete ...');
                 } catch (\Exception $e) {
                     throw $e;
                 }
             }
             if ($file->getFilename() == 'TSK_06.CSV') {
                 // charges
                 try {
                     $dialog->writeSection($output, 'Processing Charge Data ...');
                     $charges = $this->processCharges($file, $dialog, $output);
                     $chargesProcessed = 1;
                     $dialog->writeSection($output, 'Charge Data Complete ...');
                 } catch (\Exception $e) {
                     throw $e;
                 }
             }
             if ($file->getFilename() == 'TSK_07.CSV') {
                 // payments
                 try {
                     $dialog->writeSection($output, 'Processing Payment Data ...');
                     $payments = $this->processPayments($file, $dialog, $output);
                     $paymentsProcessed = 1;
                     $dialog->writeSection($output, 'Charge Payment Complete ...');
                 } catch (\Exception $e) {
                     throw $e;
                 }
             }
             if ($file->getFilename() == 'TSK_08.CSV') {
                 // deferred payments
                 try {
                     $dialog->writeSection($output, 'Processing Deferred Payments Data ...');
                     $attendances = $this->processDeferrals($file, $dialog, $output);
                     $dialog->writeSection($output, 'Deferred Payments Complete ...');
                 } catch (\Exception $e) {
                     throw $e;
                 }
             }
             if ($file->getFilename() == 'TSK_09.CSV') {
                 // attendance
                 try {
                     $dialog->writeSection($output, 'Processing Attendance Data ...');
                     $attendances = $this->processAttendances($file, $dialog, $output);
                     $dialog->writeSection($output, 'Attendance Complete ...');
                 } catch (\Exception $e) {
                     throw $e;
                 }
             }
             if ($file->getFilename() == 'TSK_10.CSV') {
                 // attendance
                 try {
                     $dialog->writeSection($output, 'Processing Training Family Member Data ...');
                     $attendances = $this->processFamilies($file, $dialog, $output);
                     $dialog->writeSection($output, 'Training Family Member Data Complete ...');
                 } catch (\Exception $e) {
                     throw $e;
                 }
             }
             // print $file->getFilename() . "\n";
             $loops++;
         }
     } catch (\Exception $e) {
         $dialog = $this->getDialogHelper();
         $dialog->writeSection($output, $e->getMessage(), 'bg=red;fg=white');
     }
     if (!empty($results['errors'])) {
         $dialog = $this->getDialogHelper();
         $dialog->writeSection($output, $results['errors'][0], 'bg=yellow;fg=white');
     }
 }
예제 #26
0
파일: Finder.php 프로젝트: stopsopa/utils
 /**
  * @return Finder
  */
 public function sortByName()
 {
     return parent::sortByName();
 }
예제 #27
0
 public function clean()
 {
     $this->logger->debug('Cleaning old deploys...');
     $finder = new Finder();
     $finder->in($this->getLocalCodeDir());
     $finder->directories();
     $finder->sortByName();
     $finder->depth(0);
     $directoryList = array();
     foreach ($finder as $file) {
         $directoryList[] = $file->getBaseName();
     }
     $sudo = $this->sudo ? 'sudo ' : '';
     while (count($directoryList) > $this->cleanMaxDeploys) {
         $path = array_shift($directoryList);
         $this->exec('rm -rf ' . $this->getLocalCodeDir() . '/' . $path);
         $this->execRemoteServers($sudo . 'rm -rf ' . $this->getRemoteCodeDir() . '/' . $path);
     }
 }
예제 #28
0
 private static function getConfigFromFile(Extension $extension, $alias, $filename = null)
 {
     $configDir = self::configDir($extension);
     $filename = self::configDir($extension) . "//" . ($filename === null ? $alias . '.yml' : $filename);
     $yaml = new Parser();
     $resourceFile = null;
     if (file_exists($filename)) {
         $configs = $yaml->parse(file_get_contents($filename));
         $resourceFile = $filename;
     } else {
         if (file_exists($configDir . "//" . $alias) && is_dir($configDir . "//" . $alias)) {
             $configs = array();
             if (file_exists($configDir . "//" . $alias . "//filelist.yml")) {
                 $order = $yaml->parse(file_get_contents($configDir . "//" . $alias . "//filelist.yml"));
                 foreach ($order['list'] as $fn) {
                     $configs = array_merge($configs, $yaml->parse(file_get_contents($configDir . "//" . $alias . "//" . $fn)));
                 }
             } else {
                 $finder = new Finder();
                 $finder->sortByName()->files()->in($configDir . "//" . $alias);
                 foreach ($finder as $file) {
                     $configs = array_merge($configs, $yaml->parse($file->getContents()));
                 }
             }
         } else {
             throw new \LogicException("Cannot find config file " . $filename . " for extension " . $alias . ".");
         }
     }
     return array('config' => $configs, 'resource_file' => $resourceFile);
 }