Пример #1
0
 /**
  * Create service
  *
  * @param ServiceLocatorInterface $serviceLocator
  *
  * @return mixed
  */
 public function createService(ServiceLocatorInterface $serviceLocator)
 {
     $mvcEvent = $serviceLocator->get('application')->getMvcEvent();
     $parameters = new Parameters($mvcEvent->getRouteMatch()->getParams());
     $options = new RequestOptions();
     $options->setFromRequest($parameters);
     return $options;
 }
Пример #2
0
 /**
  * Get path to ZF2
  *
  * @return bool|string
  */
 protected function getZF2Path()
 {
     // check for ZF2 path
     if (getenv('ZF2_PATH')) {
         return getenv('ZF2_PATH');
     } elseif (get_cfg_var('zf2_path')) {
         return get_cfg_var('zf2_path');
     } elseif (is_dir('vendor/ZF2/library')) {
         return 'vendor/ZF2/library';
     } elseif (is_dir('vendor/zendframework/zendframework/library')) {
         return 'vendor/zendframework/zendframework/library';
     } elseif (is_dir('vendor/zendframework/zend-version')) {
         return 'vendor/zendframework/zend-version';
     } elseif (is_dir($this->requestOptions->getPath() . '/vendor/zendframework/zendframework/library')) {
         return $this->requestOptions->getPath() . '/vendor/zendframework/zendframework/library';
     }
     return false;
 }
Пример #3
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;
 }
Пример #4
0
 /**
  * Add configuration for a new view helper factory
  *
  * @return bool|mixed
  */
 public function addViewHelperFactoryConfig()
 {
     // check for no config flag
     if ($this->flagNoConfig) {
         return false;
     }
     // get needed options to shorten code
     $modulePath = $this->requestOptions->getModulePath();
     $viewHelperName = lcfirst($this->requestOptions->getViewHelperName());
     $viewHelperKey = $this->requestOptions->getViewHelperKey();
     // Read module configuration
     $moduleConfigOld = (require $modulePath . '/config/module.config.php');
     $moduleConfigNew = $moduleConfigOld;
     // check for view_helpers configuration
     if (!isset($moduleConfigNew['view_helpers'])) {
         $moduleConfigNew['view_helpers'] = array();
     }
     // check for view_helpers invokables configuration
     if (!isset($moduleConfigNew['view_helpers']['invokables'])) {
         $moduleConfigNew['view_helpers']['invokables'] = array();
     }
     // check for view_helpers invokables configuration
     if (!isset($moduleConfigNew['view_helpers']['factories'])) {
         $moduleConfigNew['view_helpers']['factories'] = array();
     }
     // check if factory key is already there
     if (!in_array($viewHelperName, $moduleConfigNew['view_helpers']['factories'])) {
         $moduleConfigNew['view_helpers']['factories'][$viewHelperName] = $viewHelperKey . 'Factory';
     }
     // check if invokable key is there
     if (isset($moduleConfigNew['view_helpers']['invokables']) && isset($moduleConfigNew['view_helpers']['invokables'][$viewHelperName])) {
         unset($moduleConfigNew['view_helpers']['invokables'][$viewHelperName]);
     }
     // set config dir
     $configDir = realpath($modulePath . '/config');
     // reset constant compilation
     $moduleConfigNew = $this->resetConfigDirCompilation($moduleConfigNew, $configDir);
     // check for module config updates
     if ($moduleConfigNew !== $moduleConfigOld) {
         return $moduleConfigNew;
     } else {
         return false;
     }
 }
Пример #5
0
 /**
  * Set configuration by key
  */
 public function setAction()
 {
     // check for help mode
     if ($this->requestOptions->getFlagHelp()) {
         return $this->setHelp();
     }
     // output header
     $this->consoleHeader('Setting requested configuration');
     // get needed options to shorten code
     $path = realpath($this->requestOptions->getPath());
     $configName = $this->requestOptions->getConfigName();
     $configValue = $this->requestOptions->getConfigValue();
     $configFile = $path . '/config/autoload/local.php';
     // check for config name
     if (!$configName) {
         return $this->sendError('config get <configName> was not provided');
     }
     // start output
     $this->console->write('       => Reading configuration file ');
     $this->console->writeLine($configFile, Color::GREEN);
     $this->console->write('       => Changing configuration data for key ');
     $this->console->write($configName, Color::GREEN);
     $this->console->write(' to value ');
     $this->console->writeLine($configValue, Color::GREEN);
     $this->console->write('       => Writing configuration file ');
     $this->console->writeLine($configFile, Color::GREEN);
     $this->console->writeLine();
     // check for value
     if ($configValue === 'null') {
         $configValue = null;
     }
     // write local config file
     $configData = new ModuleConfig($configFile);
     $configData->write($configName, $configValue);
     // continue output
     $this->console->write(' Done ', Color::NORMAL, Color::CYAN);
     $this->console->write(' ');
     $this->console->writeLine('Configuration data was changed.');
     // output footer
     $this->consoleFooter('requested configuration was successfully changed');
 }
Пример #6
0
 /**
  * Generate classmap
  *
  * @return ConsoleModel
  */
 public function classmapAction()
 {
     // check for help mode
     if ($this->requestOptions->getFlagHelp()) {
         return $this->classmapHelp();
     }
     // output header
     $this->consoleHeader('Generating classmap');
     // get needed options to shorten code
     $directory = $this->requestOptions->getDirectory();
     $destination = $this->requestOptions->getDestination();
     $relativePath = '';
     $usingStdout = false;
     // check if directory provided
     if (is_null($directory)) {
         return $this->sendError(array(array(Color::NORMAL => 'Please provide the directory to create the classmap in')));
     }
     // Validate directory
     if (!is_dir($directory)) {
         return $this->sendError(array(array(Color::NORMAL => 'Invalid library directory provided '), array(Color::RED => $directory), array(Color::NORMAL => '.')));
     }
     // check that destination file is not a directory
     if (is_dir($destination)) {
         return $this->sendError(array(array(Color::RED => $destination), array(Color::NORMAL => ' is not a valid output file.')));
     }
     // check that destination file is writable
     if (!is_writeable(dirname($destination))) {
         return $this->sendError(array(array(Color::NORMAL => 'Cannot write to '), array(Color::RED => $destination), array(Color::NORMAL => '.')));
     }
     // Determine output
     if ('-' == $destination) {
         $destination = STDOUT;
         $usingStdout = true;
     } else {
         // We need to add the $libraryPath into the relative path that is created in the classmap file.
         $classmapPath = str_replace(DIRECTORY_SEPARATOR, '/', realpath(dirname($destination)));
         // Simple case: $libraryPathCompare is in $classmapPathCompare
         if (strpos($directory, $classmapPath) === 0) {
             if ($directory !== $classmapPath) {
                 // prevent double dash in filepaths when using "." as directory
                 $relativePath = substr($directory, strlen($classmapPath) + 1) . '/';
             }
         } else {
             $libraryPathParts = explode('/', $directory);
             $classmapPathParts = explode('/', $classmapPath);
             // Find the common part
             $count = count($classmapPathParts);
             for ($i = 0; $i < $count; $i++) {
                 if (!isset($libraryPathParts[$i]) || $libraryPathParts[$i] != $classmapPathParts[$i]) {
                     // Common part end
                     break;
                 }
             }
             // Add parent dirs for the subdirs of classmap
             $relativePath = str_repeat('../', $count - $i);
             // Add library subdirs
             $count = count($libraryPathParts);
             for (; $i < $count; $i++) {
                 $relativePath .= $libraryPathParts[$i] . '/';
             }
         }
     }
     // start output
     if (!$usingStdout) {
         $this->console->writeLine('       => Scanning for files containing PHP classes ');
     }
     // generate new classmap
     $classMap = $this->moduleConfigurator->buildClassmapConfig($relativePath);
     // Check if we have found any PHP classes.
     if (!$classMap) {
         return $this->sendError(array(array(Color::NORMAL => 'Cannot find any PHP classes in '), array(Color::RED => $directory), array(Color::NORMAL => '.')));
     }
     // continue output
     if (!$usingStdout) {
         $this->console->write('       => Found ');
         $this->console->write(count($classMap), Color::GREEN);
         $this->console->writeLine(' PHP classes');
         $this->console->writeLine('       => Writing classmap');
     }
     // update module configuration
     $this->moduleGenerator->updateConfiguration($classMap, $destination, true);
     // update module class with classmap autoloading
     $updateFlag = $this->moduleGenerator->updateModuleWithClassmapAutoloader();
     // continue output
     if (!$usingStdout) {
         if ($updateFlag) {
             $this->console->writeLine('       => Update module class to use classmap for autoloading');
         } else {
             $this->console->writeLine();
             $this->console->write(' Warn ', Color::NORMAL, Color::RED);
             $this->console->write(' ');
             $this->console->writeLine('=> Could not find a module class in directory to update the autoloading for the new classmap', Color::RED);
         }
     }
     // end output
     if (!$usingStdout) {
         $this->console->writeLine();
         $this->console->write(' Done ', Color::NORMAL, Color::CYAN);
         $this->console->write(' ');
         $this->console->write('Wrote classmap to ');
         $this->console->writeLine($destination, Color::GREEN);
     }
     // output footer
     $this->consoleFooter('classmap was successfully generated');
 }
Пример #7
0
 /**
  * @return mixed
  */
 public function zfAction()
 {
     // check for help mode
     if ($this->requestOptions->getFlagHelp()) {
         return $this->zfHelp();
     }
     // output header
     $this->consoleHeader('Installing Zend Framework 2 library');
     // check for zip extension
     if (!extension_loaded('zip')) {
         return $this->sendError(array(array(Color::NORMAL => 'You need to install the ZIP extension of PHP.')));
     }
     // get needed options to shorten code
     $path = $this->requestOptions->getPath();
     $tmpDir = $this->requestOptions->getTmpDir();
     $version = $this->requestOptions->getVersion();
     // check if path provided
     if ($path == '.') {
         return $this->sendError(array(array(Color::NORMAL => 'Please provide the path to install the ZF2 library in.')));
     }
     // check if path exists
     if (file_exists($path)) {
         return $this->sendError(array(array(Color::NORMAL => 'The directory '), array(Color::RED => $path), array(Color::NORMAL => ' already exists. '), array(Color::NORMAL => 'You cannot install the ZF2 library here.')));
     }
     // check version
     if (empty($version)) {
         $version = Zf::getLastVersion();
         if (false === $version) {
             return $this->sendError(array(array(Color::NORMAL => 'I cannot connect to the Zend Framework website.')));
         }
     } else {
         if (!Zf::checkVersion($version)) {
             return $this->sendError(array(array(Color::NORMAL => 'The specified ZF version, '), array(Color::RED => $version), array(Color::NORMAL => ' does not exist.')));
         }
     }
     // get tmp file and check it
     $tmpFile = ZF::getTmpFileName($tmpDir, $version);
     if (!file_exists($tmpFile)) {
         if (!Zf::downloadZip($tmpFile, $version)) {
             return $this->sendError(array(array(Color::NORMAL => 'I cannot download the ZF2 library from GitHub.')));
         }
     }
     // unzip archive
     $zip = new \ZipArchive();
     if ($zip->open($tmpFile)) {
         $zipFolders = $zip->statIndex(0);
         $zipFolder = $tmpDir . '/' . rtrim($zipFolders['name'], "/");
         if (!$zip->extractTo($tmpDir)) {
             return $this->sendError(array(array(Color::NORMAL => 'Error during the unzip of '), array(Color::RED => $tmpFile)));
         }
         $result = Utility::copyFiles($zipFolder, $path);
         if (file_exists($zipFolder)) {
             Utility::deleteFolder($zipFolder);
         }
         $zip->close();
         if (false === $result) {
             return $this->sendError(array(array(Color::NORMAL => 'Error during the copy of the files in '), array(Color::RED => $path)));
         }
     }
     $this->console->write(' Done ', Color::NORMAL, Color::CYAN);
     $this->console->write(' ');
     $this->console->write('The ZF library ');
     $this->console->write($version, Color::GREEN);
     $this->console->write(' has been installed in ');
     $this->console->writeLine(realpath($path), Color::GREEN);
     // output footer
     $this->consoleFooter('library was successfully installed');
 }
Пример #8
0
 /**
  * Create a view helper
  *
  * @return ConsoleModel
  */
 public function viewHelperAction()
 {
     // check for help mode
     if ($this->requestOptions->getFlagHelp()) {
         return $this->viewHelperHelp();
     }
     // output header
     $this->consoleHeader('Creating new view helper');
     // get needed options to shorten code
     $path = $this->requestOptions->getPath();
     $flagWithFactory = $this->requestOptions->getFlagWithFactory();
     $moduleName = $this->requestOptions->getModuleName();
     $modulePath = $this->requestOptions->getModulePath();
     $viewHelperName = $this->requestOptions->getViewHelperName();
     $viewHelperPath = $this->requestOptions->getViewHelperPath();
     $viewHelperClass = $this->requestOptions->getViewHelperClass();
     $viewHelperFile = $this->requestOptions->getViewHelperFile();
     // check for module path and application config
     if (!file_exists($path . '/module') || !file_exists($path . '/config/application.config.php')) {
         return $this->sendError(array(array(Color::NORMAL => 'The path '), array(Color::RED => $path), array(Color::NORMAL => ' doesn\'t contain a ZF2 application.')));
     }
     // check if helper name provided
     if (!$viewHelperName) {
         return $this->sendError(array(array(Color::NORMAL => 'Please provide the view helper name as parameter.')));
     }
     // check if module name provided
     if (!$moduleName) {
         return $this->sendError(array(array(Color::NORMAL => 'Please provide the module name as parameter.')));
     }
     // set mode
     if (file_exists($viewHelperPath . $viewHelperFile)) {
         $mode = 'update';
     } else {
         $mode = 'insert';
     }
     // check if view helper exists already in module
     if ($mode == 'update' && !$flagWithFactory) {
         return $this->sendError(array(array(Color::NORMAL => 'The view helper '), array(Color::RED => $viewHelperName), array(Color::NORMAL => ' already exists in module '), array(Color::RED => $moduleName), array(Color::NORMAL => '.')));
     }
     // create view helper
     if ($mode == 'insert') {
         // write start message
         $this->console->write('       => Creating view helper ');
         $this->console->write($viewHelperName, Color::GREEN);
         $this->console->write(' in module ');
         $this->console->writeLine($moduleName, Color::GREEN);
         // create view helper class
         $viewHelperFlag = $this->moduleGenerator->createViewHelper();
         // write start message
         $this->console->write('       => Adding view helper configuration for ');
         $this->console->writeLine($moduleName, Color::GREEN);
         // add view helper configuration to module
         $moduleConfig = $this->moduleConfigurator->addViewHelperConfig();
     }
     // check for factory flag
     if ($flagWithFactory) {
         // create view helper factory class
         try {
             $factoryFlag = $this->moduleGenerator->createViewHelperFactory();
         } catch (GeneratorException $e) {
             return $this->sendError(array(array(Color::NORMAL => 'The factory for the view helper '), array(Color::RED => $viewHelperName), array(Color::NORMAL => ' of module '), array(Color::RED => $moduleName), array(Color::NORMAL => ' exists already.')));
         }
         // write start message
         $this->console->write('       => Creating factory for view helper ');
         $this->console->write($viewHelperName, Color::GREEN);
         $this->console->write(' in module ');
         $this->console->writeLine($moduleName, Color::GREEN);
         // add view helper factory configuration to module
         $moduleConfig = $this->moduleConfigurator->addViewHelperFactoryConfig();
     } else {
         $factoryFlag = false;
     }
     // check for module config updates
     if ($moduleConfig) {
         // update module configuration
         $this->moduleGenerator->updateConfiguration($moduleConfig, $modulePath . '/config/module.config.php');
         // write start message
         $this->console->write('       => Updating configuration for module ');
         $this->console->writeLine($moduleName, Color::GREEN);
     }
     $this->console->writeLine();
     $this->console->write(' Done ', Color::NORMAL, Color::CYAN);
     $this->console->write(' ');
     // write message
     if ($factoryFlag) {
         $this->console->write('The view helper ');
         $this->console->write($viewHelperName, Color::GREEN);
         $this->console->write(' has been created with a factory in module ');
         $this->console->writeLine($moduleName, Color::GREEN);
     } else {
         $this->console->write('The view helper ');
         $this->console->write($viewHelperName, Color::GREEN);
         $this->console->write(' has been created in module ');
         $this->console->writeLine($moduleName, Color::GREEN);
     }
     $this->console->writeLine();
     $this->console->writeLine('       => In order to use the view helper add the following code to any view script.');
     $this->console->writeLine('          <?php echo $this->' . lcfirst($viewHelperName) . '(); ?>', Color::CYAN);
     // output footer
     $this->consoleFooter('view helper was successfully created');
 }
Пример #9
0
 /**
  * Run diagnostics
  *
  * @return ConsoleModel|ViewModel
  * @throws \ZFTool\Diagnostics\Exception\RuntimeException
  */
 public function runAction()
 {
     // check for help mode
     if ($this->requestOptions->getFlagHelp()) {
         return $this->runHelp();
     }
     // get needed options to shorten code
     $flagVerbose = $this->requestOptions->getFlagVerbose();
     $flagDebug = $this->requestOptions->getFlagDebug();
     $flagQuiet = $this->requestOptions->getFlagQuiet();
     $flagBreak = $this->requestOptions->getFlagBreak();
     $testGroupName = $this->requestOptions->getTestGroupName();
     // output header
     if (!$flagQuiet) {
         $this->consoleHeader('Starting diagnostics for Zend Framework 2 project');
     }
     // start output
     if (!$flagQuiet) {
         $this->console->writeLine('       => Get basic diag configuration');
     }
     // Get basic diag configuration
     $config = isset($this->configuration['diagnostics']) ? $this->configuration['diagnostics'] : array();
     // start output
     if (!$flagQuiet) {
         $this->console->writeLine('       => Collect diag tests from modules ');
     }
     // Collect diag tests from modules
     $modules = $this->moduleManager->getLoadedModules(false);
     foreach ($modules as $moduleName => $module) {
         if (is_callable(array($module, 'getDiagnostics'))) {
             $tests = $module->getDiagnostics();
             if (is_array($tests)) {
                 $config[$moduleName] = $tests;
             }
             // Exit the loop early if we found test definitions for
             // the only test group that we want to run.
             if ($testGroupName && $moduleName == $testGroupName) {
                 break;
             }
         }
     }
     // Filter array if a test group name has been provided
     if ($testGroupName) {
         $config = array_intersect_key($config, array($testGroupName => 1));
     }
     // start output
     if (!$flagQuiet) {
         $this->console->writeLine('       => Analyze test definitions and construct test instances');
     }
     // Analyze test definitions and construct test instances
     $testCollection = array();
     foreach ($config as $testGroupName => $tests) {
         foreach ($tests as $testLabel => $test) {
             // Do not use numeric labels.
             if (!$testLabel || is_numeric($testLabel)) {
                 $testLabel = false;
             }
             // Handle a callable.
             if (is_callable($test)) {
                 $test = new Callback($test);
                 if ($testLabel) {
                     $test->setLabel($testGroupName . ': ' . $testLabel);
                 }
                 $testCollection[] = $test;
                 continue;
             }
             // Handle test object instance.
             if (is_object($test)) {
                 if (!$test instanceof TestInterface) {
                     throw new RuntimeException('Cannot use object of class "' . get_class($test) . '" as test. ' . 'Expected instance of ZFTool\\Diagnostics\\Test\\TestInterface');
                 }
                 if ($testLabel) {
                     $test->setLabel($testGroupName . ': ' . $testLabel);
                 }
                 $testCollection[] = $test;
                 continue;
             }
             // Handle an array containing callback or identifier with optional parameters.
             if (is_array($test)) {
                 if (!count($test)) {
                     throw new RuntimeException('Cannot use an empty array() as test definition in "' . $testGroupName . '"');
                 }
                 // extract test identifier and store the remainder of array as parameters
                 $testName = array_shift($test);
                 $params = $test;
             } elseif (is_scalar($test)) {
                 $testName = $test;
                 $params = array();
             } else {
                 throw new RuntimeException('Cannot understand diagnostic test definition "' . gettype($test) . '" in "' . $testGroupName . '"');
             }
             // Try to expand test identifier using Service Locator
             if (is_string($testName) && $this->getServiceLocator()->has($testName)) {
                 $test = $this->getServiceLocator()->get($testName);
                 // Try to use the built-in test class
             } elseif (is_string($testName) && class_exists('ZFTool\\Diagnostics\\Test\\' . $testName)) {
                 $class = new \ReflectionClass('ZFTool\\Diagnostics\\Test\\' . $testName);
                 $test = $class->newInstanceArgs($params);
                 // Check if provided with a callable inside the array
             } elseif (is_callable($testName)) {
                 $test = new Callback($testName, $params);
                 if ($testLabel) {
                     $test->setLabel($testGroupName . ': ' . $testLabel);
                 }
                 $testCollection[] = $test;
                 continue;
                 // Try to expand test using class name
             } elseif (is_string($testName) && class_exists($testName)) {
                 $class = new \ReflectionClass($testName);
                 $test = $class->newInstanceArgs($params);
             } else {
                 throw new RuntimeException('Cannot find test class or service with the name of "' . $testName . '" (' . $testGroupName . ')');
             }
             if (!$test instanceof TestInterface) {
                 // not a real test
                 throw new RuntimeException('The test object of class ' . get_class($test) . ' does not implement ' . 'ZFTool\\Diagnostics\\Test\\TestInterface');
             }
             // Apply label
             if ($testLabel) {
                 $test->setLabel($testGroupName . ': ' . $testLabel);
             }
             $testCollection[] = $test;
         }
     }
     if (!$flagQuiet) {
         $this->console->writeLine();
         $this->console->write(' Diag ', Color::NORMAL, Color::CYAN);
         $this->console->write(' ');
     }
     // Configure test runner
     $runner = new Runner();
     $runner->addTests($testCollection);
     $runner->getConfig()->setBreakOnFailure($flagBreak);
     if (!$flagQuiet && $this->getRequest() instanceof ConsoleRequest) {
         if ($flagVerbose || $flagDebug) {
             $runner->addReporter(new VerboseConsole($this->console, $flagDebug));
         } else {
             $runner->addReporter(new BasicConsole($this->console));
         }
     }
     // Run tests
     $results = $runner->run();
     // Return result
     if ($this->getRequest() instanceof ConsoleRequest) {
         // Return appropriate error code in console
         $model = new ConsoleModel();
         $model->setVariable('results', $results);
         if ($results->getFailureCount() > 0) {
             $model->setErrorLevel(1);
         } else {
             $model->setErrorLevel(0);
         }
     } else {
         // Display results as a web page
         $model = new ViewModel();
         $model->setVariable('results', $results);
     }
     return $model;
 }