/** * @see ContentModifierInterface::modify() */ public function modify(SplFileInfo $generatedFile, array $data, Inflector $inflector, SplFileInfo $templateFile) { $options = $this->resolver->resolve($data); // retrieve target location $targetConfigFilepath = $this->resolveTargetFilePath($options['target'], $generatedFile->getPath()); $emBundleDefinition = sprintf(' %s: type: yml dir: %s prefix: %s alias: %s ', $options['bundle'], $options['relative_schema_directory'], $options['prefix'], $options['alias']); $configsFile = new SplFileInfo($targetConfigFilepath, '', ''); $configsContent = $configsFile->getContents(); // are configs not already registered ? if (strpos($configsContent, trim($emBundleDefinition)) !== false) { $this->logger->debug(sprintf('Config file "%s" is already registered into "%s". Abording.', $generatedFile->getFilename(), $targetConfigFilepath)); return $generatedFile->getContents(); } $this->filesystem->dumpFile($configsFile->getPathname(), str_replace(sprintf(' entity_managers: %s: mappings:', $options['em']), sprintf(' entity_managers: %s: mappings:%s', $options['em'], $emBundleDefinition), $configsContent)); $this->logger->info(sprintf('file updated : %s', $configsFile->getPathname())); return $generatedFile->getContents(); }
/** * @return string */ public function read() { if ($this->contents) { return $this->contents; } return $this->contents = $this->file->getContents(); }
/** * Get the content of the file after rendering. * * @param SplFileInfo $file * * @return string */ protected function getFileContent() { if (ends_with($this->file->getFilename(), '.blade.php')) { return $this->renderBlade(); } elseif (ends_with($this->file->getFilename(), '.md')) { return $this->renderMarkdown(); } return $this->file->getContents(); }
/** * try to verify a search result * * @param SplFileInfo $file file to examine * * @return bool|System */ public function detectSystem(SplFileInfo $file) { if ($file->getFilename() == "system.info" && stripos($file->getContents(), 'project = "drupal"') !== false) { $path = new \SplFileInfo(dirname(dirname($file->getPath()))); return new System($this->getName(), $path); } if ($file->getFilename() == "system.info.yml" && stripos($file->getContents(), "project: 'drupal'") !== false) { $path = new \SplFileInfo(dirname(dirname(dirname($file->getPath())))); return new System($this->getName(), $path); } return false; }
/** * @param SplFileInfo $fileInfo * * @todo make it event driven * * @return mixed|string * */ protected function parseFeature($fileInfo) { $feature = $fileInfo->getContents(); $scenarios = explode('Szenario:', $feature); $feature = array_shift($scenarios); $lines = explode(PHP_EOL, $feature); if (0 === strpos($feature, '#')) { array_shift($lines); } $title = array_shift($lines); $title = str_replace('Funktionalität: ', '## ', $title); $userStory = trim(implode(PHP_EOL, $lines)); $userStory = preg_replace('/\\n[\\s]*/', "\n", $userStory); $imageFile = $fileInfo->getPath() . '/' . $fileInfo->getBasename('.feature') . '.png'; $output = $title . PHP_EOL . PHP_EOL; $output .= $userStory . PHP_EOL . PHP_EOL; if (is_readable($imageFile)) { $output .= '![' . basename($imageFile, '.png') . '](./' . $fileInfo->getRelativePath() . basename($fileInfo->getPath()) . '/' . basename($imageFile) . ')' . PHP_EOL . PHP_EOL; } foreach ($scenarios as $scenario) { $scenario = trim($scenario); if (!$scenario) { continue; } $output .= $this->parseScenario($scenario, $fileInfo); } return $output; }
/** * @param SplFileInfo $file * * @return string */ private function getFileContents(SplFileInfo $file) { $content = $file->getContents(); if ($file->getExtension() === 'js' && substr($content, -1) !== ';') { $content .= ';'; } return $content; }
/** * @param SplFileInfo $file * * @return void * * @throws InvalidContentFile */ protected function verifyFrontMatterSeparatorExists(SplFileInfo $file) { $content = $file->getContents(); $fileName = $file->getFilename(); if (false === strpos($content, FrontMatter::SEPARATOR)) { throw new InvalidContentFile("Missing '---' deliminator in " . $fileName); } }
/** * Parse the contents of the file. * * Example: * * --- * title: Title * date: 2016-07-29 * --- * Lorem Ipsum. * * @throws \RuntimeException * * @return $this */ public function parse() { if ($this->file->isFile()) { if (!$this->file->isReadable()) { throw new \RuntimeException('Cannot read file'); } // parse front matter preg_match('/' . self::PATTERN . '/s', $this->file->getContents(), $matches); // if not front matter, set body only if (!$matches) { $this->body = $this->file->getContents(); return $this; } $this->frontmatter = trim($matches[1]); $this->body = trim($matches[2]); } return $this; }
/** * Load and parse data from cache file */ public function load() { $files = new Filesystem(); if ($files->exists($this->source)) { $file = new SplFileInfo($this->source, null, null); return unserialize($file->getContents()); } return array(); }
/** * @param SplFileInfo $file * * @return array */ public function extractRegisterInformation(SplFileInfo $file) { $content = Yaml::parse($file->getContents()); $result = array('namespace' => $content['namespace'], 'source_dir' => rtrim($file->getPathInfo()->getRealPath(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($content['source_dir'], DIRECTORY_SEPARATOR)); $name = array(); preg_match('#(?P<name>[a-z\\-]*)/?$#i', $file->getPath(), $name); $key = $name['name']; $this->moduleList[$key] = $result; return $result; }
/** * Parses a .platform.app.yaml file. * * @param \Symfony\Component\Finder\SplFileInfo $configFile * The file to parse. * * @return array|null * An array of configurations found in the file or null. */ private function parseConfigFile(SplFileInfo $configFile) { $yaml = new Parser(); try { return $yaml->parse($configFile->getContents()); } catch (ParseException $e) { printf('Unable to parse the platform configuration file: %s', $configFile->getFilename()); } return null; }
/** * @Route("/file_manager/edit-file", name="spliced_cms_admin_file_manager_edit_file") * @Template("SplicedCmsBundle:Admin/FileManagement:edit_file.html.twig") */ public function editFileAction() { $this->loadContext(); if (!$this->file instanceof \SplFileInfo || !$this->file->getRealPath()) { return $this->redirect($this->generateUrl('spliced_cms_admin_file_manager', array('dir' => $this->baseDir->getRelativePath()))); } $fileFormData = array('content' => $this->file->getContents()); $fileForm = $this->createForm(new FileFormType($this->file), $fileFormData); return array_merge($this->getViewContext(), array('fileForm' => $fileForm->createView())); }
private function getVersionFromComposerJson($dir) { $version = '_._._'; /** @var SplFileInfo $composerFile */ $composerFile = new SplFileInfo($dir . '/composer.json', '', ''); if ($composerFile->isFile()) { $composerJson = json_decode($composerFile->getContents()); return $composerJson->version; } return $version; }
/** * verify a search result by making sure that the file has the correct name and $wp_version is in there * * @param SplFileInfo $file file to examine * * @return bool|System */ public function detectSystem(SplFileInfo $file) { if ($file->getFilename() != "version.php") { return false; } if (stripos($file->getContents(), '$wp_version =') === false) { return false; } $path = new \SplFileInfo(dirname($file->getPath())); return new System($this->getName(), $path); }
/** * @param $lock * * @return mixed * * @throws \RunTimeException */ private function getComposerObject($lock) { if (!is_file($lock)) { throw new \RuntimeException('Lock file does not exist.'); } $file = new SplFileInfo($lock, null, null); $composer = json_decode($file->getContents()); if (null === $composer || !isset($composer->packages)) { throw new \RuntimeException('Lock file is not valid.'); } return $composer; }
/** * @param $lock * * @return mixed * * @throws CouldNotLoadRuleSetException */ private function getComposerObject($lock) { if (!is_file($lock)) { throw new CouldNotLoadRuleSetException(sprintf('composer.lock file "%s" does not exist', $lock)); } $file = new SplFileInfo($lock, null, null); $composer = json_decode($file->getContents()); if (null === $composer || !isset($composer->packages)) { throw new CouldNotLoadRuleSetException(sprintf('composer.lock file "$s" is not valid.', $lock)); } return $composer; }
/** * Transform a taxonomy YAML into a TaxonomyFile object * * @param SplFileInfo $file * * @return \Skimpy\Contracts\Entity|TaxonomyFile */ public function transform(SplFileInfo $file) { $data = $this->parser->parse($file->getContents()); $missingFields = $this->getMissingFields($data); if (false === empty($missingFields)) { throw new TransformationFailure(sprintf('Missing required fields (%s) in taxonomy file: %s', implode(', ', $this->getMissingFields($data)), $file->getRealPath())); } $filename = $file->getFilename(); $ext = $file->getExtension(); $slug = explode('.' . $ext, $filename)[0]; return new TaxonomyFile($slug, $data['name'], $data['plural_name'], $data['terms']); }
/** * {@inheritdoc} */ public function loadRuleSet($path) { if (!is_file($path)) { throw new CouldNotLoadRuleSetException(sprintf('Ruleset "%s" does not exist, aborting.', $path)); } $file = new SplFileInfo($path, null, null); $ruleSet = unserialize($file->getContents()); if (!$ruleSet instanceof RuleSet) { throw new CouldNotLoadRuleSetException(sprintf('Ruleset "$s" is invalid, aborting.', $path)); } return $ruleSet; }
/** * @param \Symfony\Component\Finder\SplFileInfo $composerJsonFile * * @return void */ protected function updateComposerJsonFile(SplFileInfo $composerJsonFile) { exec('./composer.phar validate ' . $composerJsonFile->getPathname(), $output, $return); if ($return !== 0) { throw new \RuntimeException('Invalid composer file ' . $composerJsonFile->getPathname() . ': ' . print_r($output, true)); } $composerJson = json_decode($composerJsonFile->getContents(), true); $composerJson = $this->updater->update($composerJson, $composerJsonFile); $composerJson = $this->clean($composerJson); $composerJson = json_encode($composerJson, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); $composerJson = preg_replace(self::REPLACE_4_WITH_2_SPACES, '$1', $composerJson) . PHP_EOL; file_put_contents($composerJsonFile->getPathname(), $composerJson); }
/** * {@inheritdoc} */ public function loadRuleSet($path) { $this->eventDispatcher->dispatch(ProgressEvent::RULESET, new ProgressEvent(0, 1)); if (!is_file($path)) { throw new \RuntimeException(sprintf('Rule set file "%s" does not exist.', $path)); } $file = new SplFileInfo($path, null, null); $ruleSet = unserialize($file->getContents()); if (!$ruleSet instanceof RuleSet) { throw new \RuntimeException('Rule set file is not valid.'); } $this->eventDispatcher->dispatch(ProgressEvent::RULESET, new ProgressEvent(1, 1)); return $ruleSet; }
/** * Builds the cache * * @param PhpClass $phpClass * @param SplFileInfo $fileInfo * @return \Synga\InheritanceFinder\PhpClass[] */ public function parse(PhpClass $phpClass, SplFileInfo $fileInfo) { try { $this->nodeVisitor->setPhpClass($phpClass); $this->traverse($fileInfo->getContents(), [$this->nodeVisitor]); $phpClass->setFile($fileInfo); $phpClass->setLastModified((new \DateTime())->setTimestamp($fileInfo->getMTime())); } catch (\Exception $e) { return false; } if ($phpClass->isValid()) { return $phpClass; } return false; }
/** * try to verify a search result and work around some well known false positives * * @param SplFileInfo $file file to examine * * @return bool|System */ public function detectSystem(SplFileInfo $file) { if ($file->getFilename() != "configuration.php") { return false; } if (stripos($file->getContents(), "JConfig") === false) { return false; } // False positive "Akeeba Backup Installer" if (stripos($file->getContents(), "class ABIConfiguration") !== false) { return false; } // False positive mock file in unit test folder if (stripos($file->getContents(), "Joomla.UnitTest") !== false) { return false; } // False positive mock file in unit test folder if (stripos($file->getContents(), "Joomla\\Framework\\Test") !== false) { return false; } $path = new \SplFileInfo($file->getPath()); // Return result if working return new System($this->getName(), $path); }
/** * Add a file into the phar package. * * @param Phar $phar Phar object * @param SplFileInfo $file File to add * @param bool $strip strip * * @return Compiler self Object */ protected function addFile(Phar $phar, SplFileInfo $file, $strip = true) { $path = strtr(str_replace(dirname(dirname(dirname(__DIR__))) . DIRECTORY_SEPARATOR, '', $file->getRealPath()), '\\', '/'); $content = $file->getContents(); if ($strip) { $content = $this->stripWhitespace($content); } elseif ('LICENSE' === $file->getBasename()) { $content = "\n" . $content . "\n"; } if ($path === 'src/Composer/Composer.php') { $content = str_replace('@package_version@', $this->version, $content); $content = str_replace('@release_date@', $this->versionDate, $content); } $phar->addFromString($path, $content); return $this; }
/** * @see ContentModifierInterface::modify() */ public function modify(SplFileInfo $generatedFile, array $data, Inflector $inflector, SplFileInfo $templateFile) { $options = $this->resolver->resolve($data); // retrieve target location $targetServicesFilepath = $this->resolveTargetFilePath($options['target'], $generatedFile->getPath()); // build content $import = sprintf('<import resource="%s" />', $inflector->translate($options['resource'])); $servicesFile = new SplFileInfo($targetServicesFilepath, '', ''); $servicesContent = $servicesFile->getContents(); // are services not already registered ? if (strpos($servicesContent, $import) !== false) { $this->logger->debug(sprintf('Service file "%s" is already registered into "%s". Abording.', $generatedFile->getFilename(), $targetServicesFilepath)); return $generatedFile->getContents(); } $this->filesystem->dumpFile($servicesFile->getRealpath(), str_replace(' </imports>', sprintf(" %s\n </imports>", $import), $servicesContent)); $this->logger->info(sprintf('file updated : %s', $servicesFile->getRealpath())); return $generatedFile->getContents(); }
/** * @param \Symfony\Component\Finder\SplFileInfo $fileInfo * * @return void */ public function addDependencies(SplFileInfo $fileInfo) { $content = $fileInfo->getContents(); if (!preg_match_all('/->(?<bundle>.*?)\\(\\)->facade\\(\\)/', $content, $matches, PREG_SET_ORDER)) { return; } foreach ($matches as $match) { $toBundle = $match[self::BUNDLE]; if (preg_match('/->/', $toBundle)) { $foundParts = explode('->', $toBundle); $toBundle = array_pop($foundParts); } $toBundle = ucfirst($toBundle); $foreignClassName = $this->getClassName($toBundle); $dependencyInformation = [DependencyTree::META_FOREIGN_LAYER => self::LAYER_BUSINESS, DependencyTree::META_FOREIGN_CLASS_NAME => $foreignClassName]; $this->addDependency($fileInfo, $toBundle, $dependencyInformation); } }
public function analyze(SplFileInfo $file) { $analysis = new Analysis($file); try { if ($stmts = $this->parser->parse($file->getContents())) { $this->adtTraverser->bindFile($file); $adtStmts = $this->adtTraverser->getAdtStmtsBy($stmts); foreach ($adtStmts as $node) { $this->nodeTraverser->setAdt($analysis->createAdt()); $this->nodeTraverser->traverse(array($node)); } } } catch (Error $error) { $this->logger->error($error->getMessage(), array($file)); } $this->getAnalysisCollection()->attach($analysis); return $analysis; }
/** * @param \Symfony\Component\Finder\SplFileInfo $fileInfo * * @return void */ public function addDependencies(SplFileInfo $fileInfo) { $content = $fileInfo->getContents(); $_SERVER['argv'] = []; if (!defined('STDIN')) { define('STDIN', fopen(__FILE__, 'r')); } $file = new \PHP_CodeSniffer_File($fileInfo->getPathname(), [], [], new \PHP_CodeSniffer()); $file->start($content); $tokens = $file->getTokens(); $pointer = 0; $classNames = []; while ($foundPosition = $file->findNext([T_NEW, T_USE, T_DOUBLE_COLON], $pointer)) { $pointer = $foundPosition + 1; $currentToken = $tokens[$foundPosition]; if ($currentToken['type'] === 'T_NEW' || $currentToken['type'] === 'T_USE') { $pointer = $foundPosition + 2; $endOfNew = $file->findNext([T_SEMICOLON, T_OPEN_PARENTHESIS, T_WHITESPACE, T_DOUBLE_COLON], $pointer); $classNameParts = array_slice($tokens, $pointer, $endOfNew - $foundPosition - 2); $classNames[] = $this->buildClassName($classNameParts); } if ($currentToken['type'] === 'T_DOUBLE_COLON') { $pointer = $foundPosition + 1; $startOf = $file->findPrevious([T_OPEN_PARENTHESIS, T_WHITESPACE, T_OPEN_SQUARE_BRACKET], $foundPosition - 1) + 1; $classNameParts = array_slice($tokens, $startOf, $foundPosition - $startOf); $classNames[] = $this->buildClassName($classNameParts); } } $classNames = array_unique($classNames); foreach ($classNames as $className) { $className = ltrim($className, '\\'); if (strpos($className, '_') === false && strpos($className, '\\') === false) { continue; } if (strpos($className, 'Spryker') !== false || strpos($className, 'Generated') !== false || strpos($className, 'Orm') !== false || strpos($className, 'static') !== false || strpos($className, 'self') !== false) { continue; } $dependencyInformation[DependencyTree::META_FOREIGN_LAYER] = 'external'; $dependencyInformation[DependencyTree::META_FOREIGN_CLASS_NAME] = $className; $dependencyInformation[DependencyTree::META_FOREIGN_IS_EXTERNAL] = true; $this->addDependency($fileInfo, 'external', $dependencyInformation); } $this->cleanAutoloader(); }
private function migrateModelOrm(SplFileInfo $file) { $content = $file->getContents(); // Change class signature if (!preg_match('/\\$_table_name = \'(.+?)\';/', $content, $match)) { $this->migrateModelGeneric($file); return; } $tableName = $match[1]; $className = Str::studly($tableName); $content = preg_replace('/class\\s(\\S+)\\sextends\\s+ORM/i', 'class ' . $className . ' extends \\Eloquent', $content); // Change _table_name & _primary_key $content = strtr($content, ['$_table_name' => '$table', '$_primary_key' => '$pk']); // Update rules // Update relations // Save new model $targetPath = $this->laravelPath . '/app/models/' . $className . '.php'; file_put_contents($targetPath, $content); }
public function process(SplFileInfo $controller) { $controllerPath = $controller->getPathName(); $controllerClass = $this->getClassName($controller->getContents()); if (!$controllerClass) { return $this; } $resource = $this->getResource($controllerClass); if (!$resource) { return $this; } $operations = $this->getOperations($controllerClass); if (!$operations) { return $this; } $resourceModel = Entities\Resources::findFirstByResourceKey($resource['resourceKey']); if (!$resourceModel) { $resourceModel = new Entities\Resources(); } $resourceModel->assign($resource); $operationModels = array(); foreach ($operations as $operation) { $operationModel = Entities\Operations::findFirst(array("conditions" => "resourceKey = :resourceKey: AND operationKey = :operationKey:", "bind" => array('resourceKey' => $operation['resourceKey'], 'operationKey' => $operation['operationKey']))); if (!$operationModel) { $operationModel = new Entities\Operations(); } $operationModel->assign($operation); $operationModels[] = $operationModel; } $resourceModel->operations = $operationModels; if ($resourceModel->save()) { echo sprintf("Resource %s already added to DB\n", $resource['resourceKey']); } else { print_r($resourceModel->getMessages()); } /* p($resource); p($operations); p('-----------------'); */ return $this; }
/** * @param \Symfony\Component\Finder\SplFileInfo $fileInfo * * @return void */ public function addDependencies(SplFileInfo $fileInfo) { $content = $fileInfo->getContents(); if (preg_match_all('/use (Spryker|Orm)\\\\(?<application>.*?)\\\\(?<bundle>.*?)\\\\(?<layerOrFileName>.*?);/', $content, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { $className = str_replace(['use ', ';'], '', $match[0]); $toBundle = $match[self::BUNDLE]; $layer = $this->getLayerFromUseStatement($match); $dependencyInformation[DependencyTree::META_FOREIGN_LAYER] = $layer; $dependencyInformation[DependencyTree::META_FOREIGN_CLASS_NAME] = $className; $this->addDependency($fileInfo, $toBundle, $dependencyInformation); } } if (preg_match('/use Spryker\\\\Shared\\\\Config/', $content)) { $toBundle = 'Config'; $dependencyInformation[DependencyTree::META_FOREIGN_LAYER] = ''; $dependencyInformation[DependencyTree::META_FOREIGN_CLASS_NAME] = 'Spryker\\Shared\\Config'; $this->addDependency($fileInfo, $toBundle, $dependencyInformation); } }