Пример #1
0
 /**
  * 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;
 }
Пример #2
0
 /**
  * 
  * @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;
 }
Пример #3
0
 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();
             }
         }
     }
 }
Пример #4
0
 /**
  * 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;
 }
Пример #5
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();
             }
         }
     }
 }
Пример #6
0
 /**
  * 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;
 }
Пример #7
0
 /**
  * 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;
 }
Пример #8
0
 public function testFileCanReflectFileWithInterface()
 {
     $fileToReflect = __DIR__ . '/TestAsset/TestSampleInterface.php';
     include_once $fileToReflect;
     $reflectionFile = new FileReflection($fileToReflect);
     $class = $reflectionFile->getClass();
     $this->assertEquals('ZendTest\\Code\\Reflection\\TestAsset\\TestSampleInterface', $class->getName());
     $this->assertTrue($class->isInterface());
 }
Пример #9
0
 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);
     }
 }