/** * @param FileReflection $fileReflection * @return FileGenerator */ public static function fromReflection(FileReflection $fileReflection) { $file = new static(); $file->setSourceContent($fileReflection->getContents()); $file->setSourceDirty(false); $uses = $fileReflection->getUses(); foreach ($fileReflection->getClasses() as $class) { $phpClass = ClassGenerator::fromReflection($class); $phpClass->setContainingFileGenerator($file); foreach ($uses as $fileUse) { $phpClass->addUse($fileUse['use'], $fileUse['as']); } $file->setClass($phpClass); } $namespace = $fileReflection->getNamespace(); if ($namespace != '') { $file->setNamespace($namespace); } if ($uses) { $file->setUses($uses); } if ($fileReflection->getDocComment() != '') { $docBlock = $fileReflection->getDocBlock(); $file->setDocBlock(DocBlockGenerator::fromReflection($docBlock)); } return $file; }
/** * Process the command * * @return integer */ public function processCommandTask() { // output message $this->console->writeTaskLine('task_delete_action_method_deleting'); // set controller file and action method $controllerFile = $this->params->controllerDir . '/' . $this->params->paramController . 'Controller.php'; // get file and class reflection $fileReflection = new FileReflection($controllerFile, true); $classReflection = $fileReflection->getClass($this->params->paramModule . '\\' . $this->params->config['namespaceController'] . '\\' . $this->params->paramController . 'Controller'); // setup class generator with reflected class $class = ClassGenerator::fromReflection($classReflection); // set method to check $actionMethod = strtolower($this->params->paramAction) . 'action'; // check for action method if (!$class->hasMethod($actionMethod)) { $this->console->writeFailLine('task_delete_action_method_not_exists', [$this->console->colorize($this->params->paramAction, Color::GREEN), $this->console->colorize($this->params->paramController, Color::GREEN), $this->console->colorize($this->params->paramModule, Color::GREEN)]); return 1; } // fix namespace usage $class->addUse('Zend\\Mvc\\Controller\\AbstractActionController'); $class->addUse('Zend\\View\\Model\\ViewModel'); $class->setExtendedClass('AbstractActionController'); $class->removeMethod($actionMethod); // create file $file = new ClassFileGenerator($class->generate(), $this->params->config); // write file file_put_contents($controllerFile, $file->generate()); return 0; }
public function testCheckDependencies() { $invoker = new \Magento\Framework\App\Utility\AggregateInvoker($this); $invoker(function ($file) { $componentRegistrar = new ComponentRegistrar(); $fileReflection = new FileReflection($file); $tokens = new Tokens($fileReflection->getContents(), new ParserFactory()); $tokens->parseContent(); $dependencies = array_merge((new Injectable())->getDependencies($fileReflection), $tokens->getDependencies()); $pattern = '#^(\\\\|)' . implode('|', $this->getForbiddenNamespaces()) . '\\\\#'; foreach ($dependencies as $dependency) { $dependencyPaths = explode('/', $dependency); $dependencyPaths = array_slice($dependencyPaths, 2); $dependency = implode('\\', $dependencyPaths); $libraryPaths = $componentRegistrar->getPaths(ComponentRegistrar::LIBRARY); foreach ($libraryPaths as $libraryPath) { $filePath = str_replace('\\', '/', $libraryPath . '/' . $dependency . '.php'); if (preg_match($pattern, $dependency) && !file_exists($filePath)) { $this->errors[$fileReflection->getFileName()][] = $dependency; } } } if (!empty($this->errors)) { $this->fail($this->getFailMessage()); } }, $this->libraryDataProvider()); }
/** * @param FileReflection $fileReflection * @return \ReflectionException[] * @throws \ReflectionException */ public function getDependencies(FileReflection $fileReflection) { foreach ($fileReflection->getClasses() as $class) { /** @var ClassReflection $class */ foreach ($class->getMethods() as $method) { /** @var \Zend\Code\Reflection\MethodReflection $method */ if ($method->getDeclaringClass()->getName() != $class->getName()) { continue; } foreach ($method->getParameters() as $parameter) { try { /** @var ParameterReflection $parameter */ $dependency = $parameter->getClass(); if ($dependency instanceof ClassReflection) { $this->dependencies[] = $dependency->getName(); } } catch (\ReflectionException $e) { if (preg_match('#^Class ([A-Za-z0-9_\\\\]+) does not exist$#', $e->getMessage(), $result)) { $this->dependencies[] = $result[1]; } else { throw $e; } } } } } return $this->dependencies; }
/** * @param FileReflection $fileReflection * @return FileGenerator */ public static function fromReflection(FileReflection $fileReflection) { $file = new static(); $file->setSourceContent($fileReflection->getContents()); $file->setSourceDirty(false); $body = $fileReflection->getContents(); $uses = $fileReflection->getUses(); foreach ($fileReflection->getClasses() as $class) { $phpClass = ClassGenerator::fromReflection($class); $phpClass->setContainingFileGenerator($file); foreach ($uses as $fileUse) { $phpClass->addUse($fileUse['use'], $fileUse['as']); } $file->setClass($phpClass); $classStartLine = $class->getStartLine(true); $classEndLine = $class->getEndLine(); $bodyLines = explode("\n", $body); $bodyReturn = array(); for ($lineNum = 1, $count = count($bodyLines); $lineNum <= $count; $lineNum++) { if ($lineNum == $classStartLine) { $bodyReturn[] = str_replace('?', $class->getName(), '/* Zend_Code_Generator_Php_File-ClassMarker: {?} */'); $lineNum = $classEndLine; } else { $bodyReturn[] = $bodyLines[$lineNum - 1]; // adjust for index -> line conversion } } $body = implode("\n", $bodyReturn); unset($bodyLines, $bodyReturn, $classStartLine, $classEndLine); } $namespace = $fileReflection->getNamespace(); if ($namespace != '') { $file->setNamespace($namespace); } if ($uses) { $file->setUses($uses); } if ($fileReflection->getDocComment() != '') { $docBlock = $fileReflection->getDocBlock(); $file->setDocBlock(DocBlockGenerator::fromReflection($docBlock)); $bodyLines = explode("\n", $body); $bodyReturn = array(); for ($lineNum = 1, $count = count($bodyLines); $lineNum <= $count; $lineNum++) { if ($lineNum == $docBlock->getStartLine()) { $bodyReturn[] = str_replace('?', $class->getName(), '/* Zend_Code_Generator_FileGenerator-DocBlockMarker */'); $lineNum = $docBlock->getEndLine(); } else { $bodyReturn[] = $bodyLines[$lineNum - 1]; // adjust for index -> line conversion } } $body = implode("\n", $bodyReturn); unset($bodyLines, $bodyReturn, $classStartLine, $classEndLine); } $file->setBody($body); return $file; }
/** * @param FileReflection $declaringFile * @return array */ public function getUseNames(FileReflection $declaringFile) { $usesNames = array(); if (!count($uses = $declaringFile->getUses())) { return $usesNames; } foreach ($uses as $use) { $usesNames[$use['use']] = $use['as']; } return $usesNames; }
/** * @inheritdoc */ public function setUp() { $this->injectable = new Injectable(); $this->fileReflection = $this->getMockBuilder('Zend\\Code\\Reflection\\FileReflection')->disableOriginalConstructor()->getMock(); $classReflection = $this->getMockBuilder('Zend\\Code\\Reflection\\ClassReflection')->disableOriginalConstructor()->getMock(); $methodReflection = $this->getMockBuilder('Zend\\Code\\Reflection\\MethodReflection')->disableOriginalConstructor()->getMock(); $this->parameterReflection = $this->getMockBuilder('Zend\\Code\\Reflection\\ParameterReflection')->disableOriginalConstructor()->getMock(); $this->declaredClass = $this->getMockBuilder('Zend\\Code\\Reflection\\ClassReflection')->disableOriginalConstructor()->getMock(); $methodReflection->expects($this->once())->method('getDeclaringClass')->will($this->returnValue($this->declaredClass)); $methodReflection->expects($this->any())->method('getParameters')->will($this->returnValue([$this->parameterReflection])); $classReflection->expects($this->once())->method('getMethods')->will($this->returnValue([$methodReflection])); $this->fileReflection->expects($this->once())->method('getClasses')->will($this->returnValue([$classReflection])); }
/** * Test check dependencies in library from application * * @test * @dataProvider libraryDataProvider */ public function testCheckDependencies($file) { $fileReflection = new FileReflection($file); $tokens = new Tokens($fileReflection->getContents(), new ParserFactory()); $tokens->parseContent(); $dependencies = array_merge((new Injectable())->getDependencies($fileReflection), $tokens->getDependencies()); foreach ($dependencies as $dependency) { if (preg_match('#^(\\\\|)' . implode('|', $this->getForbiddenNamespaces()) . '\\\\#', $dependency) && !file_exists(BP . '/lib/internal/' . str_replace('\\', '/', $dependency) . '.php')) { $this->errors[$fileReflection->getFileName()][] = $dependency; } } if ($this->hasErrors()) { $this->fail($this->getFailMessage()); } }
/** * * @param array $directories * @return array */ public function scanForControllers(array $directories) { $subclass = 'Boyhagemann\\Crud\\CrudController'; $controllers = array(); $files = $this->globFolders('*Controller.php', $directories); foreach ($files as $filename) { require_once $filename; $file = new FileReflection($filename); $class = $file->getClass(); if ($class->isSubclassOf($subclass)) { $key = str_replace('\\', '/', $class->getName()); $controllers[$key] = $class; } } return $controllers; }
protected function execute(InputInterface $input, OutputInterface $output) { $ymlParser = new Parser(); $config = $ymlParser->parse(file_get_contents($input->getOption('config'))); $directoryIterator = new RegexIterator(new DirectoryIterator($config['path']), '/.php$/'); $versionTable = $config['version_table']; foreach ($this->getConnections($config) as $connection) { if (!$connection->getSchemaManager()->tablesExist($versionTable)) { $schema = $connection->getSchemaManager()->createSchema(); $table = $schema->createTable($versionTable); $table->addColumn('id', 'integer', array('autoincrement')); $table->addColumn('name', 'string', array('notnull', 'customSchemaOptions' => array('unique'))); $table->addColumn('status', 'integer'); $table->addColumn('error', 'string'); $diff = new SchemaDiff(array($table)); $queries = $diff->toSql($connection->getDatabasePlatform()); foreach ($queries as $query) { $connection->exec($query); } } foreach ($directoryIterator as $classFile) { if ($classFile->isDot()) { continue; } $fileName = $classFile->getPathname(); require_once $fileName; $reflection = new FileReflection($classFile->getPathname()); $migration = $reflection->getClass()->newInstance(); $executed = (bool) $connection->createQueryBuilder()->select(array('count(1)'))->from($versionTable)->where('name = :name')->setParameter('name', $fileName)->setMaxResults(1)->execute()->fetchColumn(); if (!$executed) { $output->writeln("<info>executing migration {$fileName}</info>"); try { $connection->exec($migration->getUpSql()); $output->writeln("<info>{$fileName} executed succesfuly!</info>"); } catch (Exception $exception) { $connection->createQueryBuilder()->insert($versionTable)->values(array('name' => ":name", 'status' => 2, 'error' => ":error"))->setParameter('error', $exception->getMessage())->setParameter('name', $fileName)->execute(); $output->writeln("<error>error executing migration {$fileName}</error>"); $output->writeln("<error>{$exception->getMessage()}</error>"); continue; } $connection->createQueryBuilder()->insert($versionTable)->values(array('name' => ":name", 'status' => 1))->setParameter('name', $fileName)->execute(); } } } }
/** * Process the command * * @return integer */ public function processCommandTask() { // output message $this->console->writeTaskLine('task_crud_load_entity_class', [$this->console->colorize($this->params->paramEntityClass, Color::GREEN), $this->console->colorize($this->params->paramEntityModule, Color::GREEN)]); if (!file_exists($this->params->entityModuleDir)) { $this->console->writeFailLine('task_crud_load_entity_module_not_found', [$this->console->colorize($this->params->paramEntityModule, Color::GREEN)]); return 1; } if (!file_exists($this->params->entityFile)) { $this->console->writeFailLine('task_crud_load_entity_entity_not_found', [$this->console->colorize($this->params->paramEntityClass, Color::GREEN), $this->console->colorize($this->params->paramEntityModule, Color::GREEN)]); return 1; } require_once $this->params->entityFile; $entityClass = new FileReflection($this->params->entityFile); $this->params->loadedEntity = $entityClass->getClass(); /** @var Adapter $dbAdapter */ $dbAdapter = $this->params->dbAdapter; // get Metadata for database adapter $metaData = new Metadata($dbAdapter); // init loaded tables $loadedTables = []; /** @var TableObject $tableObject */ foreach ($metaData->getTables() as $tableObject) { $columns = []; $primaryKey = []; $foreignKeys = []; /** @var ColumnObject $columnObject */ foreach ($tableObject->getColumns() as $columnObject) { $columns[$columnObject->getName()] = $columnObject; } /** @var ConstraintObject $constraintObject */ foreach ($tableObject->getConstraints() as $constraintObject) { if ($constraintObject->isPrimaryKey()) { $primaryKey = $constraintObject; } elseif ($constraintObject->isForeignKey()) { $foreignKeys[$constraintObject->getName()] = $constraintObject; } } $loadedTables[$tableObject->getName()] = ['columns' => $columns, 'primaryKey' => $primaryKey, 'foreignKeys' => $foreignKeys]; } $this->params->loadedTables = $loadedTables; return 0; }
protected function execute(InputInterface $input, OutputInterface $output) { $ymlParser = new Parser(); $config = $ymlParser->parse(file_get_contents($input->getOption('config'))); $version = $input->getArgument('version'); $versionTable = $config['version_table']; $directoryIterator = new RegexIterator(new ReverseDirectoryIterator(new DirectoryIterator($config['path']), '/.php$/')); foreach ($this->getConnections($config) as $connection) { foreach ($directoryIterator as $file) { if ($file->isDot() || $file->isDir()) { continue; } list($migrationVersion, ) = explode('_', $file->getBasename(), 1); if ($version < $migrationVersion) { continue; } $fileName = $classFile->getPathname(); require_once $fileName; $reflection = new FileReflection($classFile->getPathname()); $migration = $reflection->getClass()->newInstance(); $executed = (bool) $connection->createQueryBuilder()->select(array('count(1)'))->from($versionTable)->where('name = :name')->andWhere('status = 1')->setParameter('name', $fileName)->setMaxResults(1)->execute()->fetchColumn(); if ($executed) { $output->writeln("<info> executing migration down for {$fileName} </info>"); try { $connection->exec($migration->getDownSql()); $output->writeln("<info> {$fileName} down executed succesfuly! </info>"); } catch (Exception $exception) { $output->writeln("<error> error executing migration down for {$fileName}</error>"); $output->writeln("<error> {$exception->getMessage()} </error>"); continue; } $connection->createQueryBuilder()->delete($versionTable)->where('name = :name')->setParameter('name', $fileName)->execute(); } } } }
/** * Gets SK ITCBundle Code Generator PHPUnit Abstract Generator Generator Class Reflection * * @return ClassReflection[] */ public function getClassReflections() { if (NULL === $this->classReflections) { $classReflections = array(); $directoryScanner = $this->getDirectoryScanner(); /* @var $fileScanners FileScanner[] */ $fileScanners = $directoryScanner->getFiles(TRUE); /* @var $classScanner FileScanner */ foreach ($fileScanners as $fileScanner) { $file = new FileReflection($fileScanner->getFile(), TRUE); $classReflections = array_merge($classReflections, $file->getClasses()); } $this->setClassReflections($classReflections); } return $this->classReflections; }
public function methodAction() { $console = $this->getServiceLocator()->get('console'); $request = $this->getRequest(); $action = $request->getParam('name'); $controller = $request->getParam('controllerName'); $module = $request->getParam('module'); $path = $request->getParam('path', '.'); $ucController = ucfirst($controller); $controllerPath = sprintf('%s/module/%s/src/%s/Controller/%sController.php', $path, $module, $module, $ucController); $class = sprintf('%s\\Controller\\%sController', $module, $ucController); $console->writeLine("Creating action '{$action}' in controller '{$module}\\Controller\\{$controller}'.", Color::YELLOW); if (!file_exists("{$path}/module") || !file_exists("{$path}/config/application.config.php")) { return $this->sendError("The path {$path} doesn't contain a ZF2 application. I cannot create a controller action."); } if (!file_exists($controllerPath)) { return $this->sendError("The controller {$controller} does not exists in module {$module}. I cannot create a controller action."); } $fileReflection = new Reflection\FileReflection($controllerPath, true); $classReflection = $fileReflection->getClass($class); $classGenerator = Generator\ClassGenerator::fromReflection($classReflection); $classGenerator->addUse('Zend\\Mvc\\Controller\\AbstractActionController')->addUse('Zend\\View\\Model\\ViewModel')->setExtendedClass('AbstractActionController'); if ($classGenerator->hasMethod($action . 'Action')) { return $this->sendError("The action {$action} already exists in controller {$controller} of module {$module}."); } $classGenerator->addMethods(array(new Generator\MethodGenerator($action . 'Action', array(), Generator\MethodGenerator::FLAG_PUBLIC, 'return new ViewModel();'))); $fileGenerator = new Generator\FileGenerator(array('classes' => array($classGenerator))); $filter = new CamelCaseToDashFilter(); $phtmlPath = sprintf('%s/module/%s/view/%s/%s/%s.phtml', $path, $module, strtolower($filter->filter($module)), strtolower($filter->filter($controller)), strtolower($filter->filter($action))); if (!file_exists($phtmlPath)) { $contents = sprintf("Module: %s\nController: %s\nAction: %s", $module, $controller, $action); if (file_put_contents($phtmlPath, $contents)) { $console->writeLine(sprintf("Created view script at %s", $phtmlPath), Color::GREEN); } else { $console->writeLine(sprintf("An error occurred when attempting to create view script at location %s", $phtmlPath), Color::RED); } } if (file_put_contents($controllerPath, $fileGenerator->generate())) { $console->writeLine(sprintf('The action %s has been created in controller %s\\Controller\\%s.', $action, $module, $controller), Color::GREEN); } else { $console->writeLine("There was an error during action creation.", Color::RED); } }
/** * Update module class with class map autoloading * * @return bool * @throws \Zend\Code\Generator\Exception */ public function updateModuleWithClassmapAutoloader() { // get needed options to shorten code $path = realpath($this->requestOptions->getPath()); $directory = $this->requestOptions->getDirectory(); $destination = $this->requestOptions->getDestination(); $moduleFile = $directory . '/Module.php'; $moduleClass = str_replace($path . '/module/', '', $directory) . '\\Module'; $moduleName = str_replace($path . '/module/', '', $directory); // check for module file if (!file_exists($moduleFile)) { return false; } // get file and class reflection $fileReflection = new FileReflection($moduleFile, true); $classReflection = $fileReflection->getClass($moduleClass); // setup class generator with reflected class $code = ClassGenerator::fromReflection($classReflection); // check for action method if ($code->hasMethod('getAutoloaderConfig')) { $code->removeMethod('getAutoloaderConfig'); } // add getAutoloaderConfig method with class map $code->addMethodFromGenerator($this->generateGetAutoloaderConfigMethod($destination, $moduleName)); // create file with file generator $file = new FileGenerator(); $file->setClass($code); // add optional doc block if ($this->flagCreateApiDocs) { $file->setDocBlock(new DocBlockGenerator('This file was generated by FrilleZFTool.', null, array($this->generatePackageTag($moduleName), $this->generateSeeTag()))); } // create file with file generator $file = new FileGenerator(); $file->setClass($code); // add optional doc block if ($this->flagCreateApiDocs) { $file->setDocBlock(new DocBlockGenerator('This file was generated by FrilleZFTool.', null, array($this->generatePackageTag($moduleName), $this->generateSeeTag()))); } // write module class if (!file_put_contents($moduleFile, $file->generate())) { return false; } return true; }
/** * Get actions for a controller * * @return array */ protected function getActionsForController($controllerPath, $controllerKey) { // get file and class reflection $fileReflection = new FileReflection($controllerPath, true); $classReflection = $fileReflection->getClass($controllerKey . 'Controller'); // setup class generator with reflected class $code = ClassGenerator::fromReflection($classReflection); // initialize controllers $actions = array(); // lop through methods foreach (array_keys($code->getMethods()) as $methodName) { if (substr($methodName, -6) == 'Action') { $actions[] = $methodName; } } // sort actions sort($actions); return $actions; }
public function testFileCanReflectFileWithUses() { $fileToReflect = __DIR__ . '/TestAsset/TestSampleClass8.php'; include_once $fileToReflect; $reflectionFile = new FileReflection($fileToReflect); $expected = array(array('use' => 'Zend\\Config', 'as' => 'ZendConfig'), array('use' => 'FooBar\\Foo\\Bar', 'as' => null), array('use' => 'One\\Two\\Three\\Four\\Five', 'as' => 'ottff')); $this->assertSame($expected, $reflectionFile->getUses()); }