private function sendError($msg) { $m = new ConsoleModel(); $m->setErrorLevel(2); $m->setResult($msg . PHP_EOL); return $m; }
/** * Create a console view model representing a "not found" action * * @return ConsoleModel */ public function __invoke() { $viewModel = new ConsoleModel(); $viewModel->setErrorLevel(1); $viewModel->setResult('Page not found'); return $viewModel; }
/** @noinspection PhpHierarchyChecksInspection * * Create a console view model representing a "not found" action * * @return ConsoleModel */ protected function createConsoleNotFoundModel() { $viewModel = new ConsoleModel(); $viewModel->setErrorLevel(1); $viewModel->setResult('Page not found'); return $viewModel; }
/** * Send an error message to the console * * @param string $msg * @return ConsoleModel */ protected function sendError($msg) { $m = new ConsoleModel(); $m->setErrorLevel(2); $m->setResult('ERROR: ' . $msg . PHP_EOL); return $m; }
public function generateAction() { $model = new ConsoleModel(); $files = $this->getSitemapService()->renderStaticSiteMap(); $text = 'Generated the site map success.' . PHP_EOL . 'New/update files:' . PHP_EOL . implode(PHP_EOL, $files) . PHP_EOL; $model->setResult($text); return $model; }
/** * Display messages on console * * @param MvcEvent $e * @param string $validationMessages * @return void */ private function displayMessages(MvcEvent $e, $validationMessages) { /** @var \Zend\Console\Adapter\AdapterInterface $console */ $console = $e->getApplication()->getServiceManager()->get('console'); $validationMessages = $console->colorize($validationMessages, ColorInterface::RED); $model = new ConsoleModel(); $model->setErrorLevel(1); $model->setResult($validationMessages); $e->setResult($model); }
public function listAction() { $sm = $this->getServiceLocator(); try { /* @var $mm \Zend\ModuleManager\ModuleManager */ $mm = $sm->get('modulemanager'); } catch (ServiceNotFoundException $e) { $m = new ConsoleModel(); $m->setErrorLevel(1); $m->setResult('Cannot get Zend\\ModuleManager\\ModuleManager instance. Is your application using it?'); return $m; } return print_r(array_keys($mm->getLoadedModules(false)), true); }
public function runAction() { $exectutionService = $this->getServiceLocator()->get('CronTask\\Service\\Execution'); $execute = $this->params("execute", null); if ($execute) { foreach (explode(",", $execute) as $taskId) { $exectutionService->executeTask($taskId); } } else { $response = $exectutionService->executeTasks(); } $model = new ConsoleModel(); $model->setResult($response); return $model; }
public function listAction() { $model = new ConsoleModel(); /** @var \Continuous\DeployAgent\Application\ApplicationManager $applicationManager */ $applicationManager = $this->getServiceLocator()->get('application/application-manager'); $applications = $applicationManager->findAll(); $output = new ConsoleOutput(); if (empty($applications)) { $model->setResult('No application found' . PHP_EOL); } else { $table = new Table($output); $table->setHeaders([]); foreach ($applications as $application) { /** @var Application $application */ /** @var Continuousphp $provider */ $provider = $application->getProvider(); $table->setHeaders(['name', 'path', 'provider', 'source']); $table->addRow([$application->getName(), $application->getPath(), 'continuousphp', $provider ? $provider->getRepositoryProvider() . '/' . $provider->getRepository() . '::' . $provider->getReference() : '']); } $table->render(); } return $model; }
/** * Create an exception view model, and set the HTTP status code * * @todo dispatch.error does not halt dispatch unless a response is * returned. As such, we likely need to trigger rendering as a low * priority dispatch.error event (or goto a render event) to ensure * rendering occurs, and that munging of view models occurs when * expected. * @param MvcEvent $e * @return void */ public function prepareExceptionViewModel(MvcEvent $e) { // Do nothing if no error in the event $error = $e->getError(); if (empty($error)) { return; } // Do nothing if the result is a response object $result = $e->getResult(); if ($result instanceof Response) { return; } switch ($error) { case Application::ERROR_CONTROLLER_NOT_FOUND: case Application::ERROR_CONTROLLER_INVALID: case Application::ERROR_ROUTER_NO_MATCH: // Specifically not handling these because they are handled by routeNotFound strategy return; case Application::ERROR_EXCEPTION: default: // Prepare error message $exception = $e->getParam('exception'); if (is_callable($this->message)) { $callback = $this->message; $message = (string) $callback($exception, $this->displayExceptions); } elseif ($this->displayExceptions && $exception instanceof \Exception) { $previous = ''; $previousException = $exception->getPrevious(); while ($previousException) { $previous .= str_replace(array(':className', ':message', ':code', ':file', ':line', ':stack'), array(get_class($previousException), $previousException->getMessage(), $previousException->getCode(), $previousException->getFile(), $previousException->getLine(), $exception->getTraceAsString()), $this->previousMessage); $previousException = $previousException->getPrevious(); } /* @var $exception \Exception */ $message = str_replace(array(':className', ':message', ':code', ':file', ':line', ':stack', ':previous'), array(get_class($exception), $exception->getMessage(), $exception->getCode(), $exception->getFile(), $exception->getLine(), $exception->getTraceAsString(), $previous), $this->message); } else { $message = str_replace(array(':className', ':message', ':code', ':file', ':line', ':stack', ':previous'), array('', '', '', '', '', '', ''), $this->message); } // Prepare view model $model = new ConsoleModel(); $model->setResult($message); $model->setErrorLevel(1); // Inject it into MvcEvent $e->setResult($model); break; } }
/** * Detect if an error is a route not found condition * * If a "controller not found" or "invalid controller" error type is * encountered, sets the response status code to 404. * * @param MvcEvent $e * @throws RuntimeException * @throws ServiceNotFoundException * @return void */ public function handleRouteNotFoundError(MvcEvent $e) { $error = $e->getError(); if (empty($error)) { return; } $response = $e->getResponse(); $request = $e->getRequest(); switch ($error) { case Application::ERROR_CONTROLLER_NOT_FOUND: case Application::ERROR_CONTROLLER_INVALID: case Application::ERROR_ROUTER_NO_MATCH: $this->reason = $error; if (!$response) { $response = new ConsoleResponse(); $e->setResponse($response); } $response->setMetadata('error', $error); break; default: return; } $result = $e->getResult(); if ($result instanceof Response) { // Already have a response as the result return; } // Prepare Console View Model $model = new ConsoleModel(); $model->setErrorLevel(1); // Fetch service manager $sm = $e->getApplication()->getServiceManager(); // Try to fetch module manager $mm = null; try { $mm = $sm->get('ModuleManager'); } catch (ServiceNotFoundException $e) { // The application does not have or use module manager, so we cannot use it } // Try to fetch current console adapter try { $console = $sm->get('console'); if (!$console instanceof ConsoleAdapter) { throw new ServiceNotFoundException(); } } catch (ServiceNotFoundException $e) { // The application does not have console adapter throw new RuntimeException('Cannot access Console adapter - is it defined in ServiceManager?'); } // Try to fetch router $router = null; try { $router = $sm->get('Router'); } catch (ServiceNotFoundException $e) { // The application does not have a router } // Retrieve the script's name (entry point) $scriptName = ''; if ($request instanceof ConsoleRequest) { $scriptName = basename($request->getScriptName()); } // Get application banner $banner = $this->getConsoleBanner($console, $mm); // Get application usage information $usage = $this->getConsoleUsage($console, $scriptName, $mm); // Inject the text into view $result = $banner ? rtrim($banner, "\r\n") : ''; $result .= $usage ? "\n\n" . trim($usage, "\r\n") : ''; $result .= "\n"; // to ensure we output a final newline $result .= $this->reportNotFoundReason($e); $model->setResult($result); // Inject the result into MvcEvent $e->setResult($model); }
public function runAction() { $sm = $this->getServiceLocator(); /* @var $console AdapterInterface */ /* @var $config array */ /* @var $mm ModuleManager */ $console = $sm->get('console'); $config = $sm->get('Configuration'); $mm = $sm->get('ModuleManager'); $verbose = $this->params()->fromRoute('verbose', false); $debug = $this->params()->fromRoute('debug', false); $quiet = !$verbose && !$debug && $this->params()->fromRoute('quiet', false); $breakOnFailure = $this->params()->fromRoute('break', false); $checkGroupName = $this->params()->fromRoute('filter', false); // Get basic diag configuration $config = isset($config['diagnostics']) ? $config['diagnostics'] : array(); // Collect diag tests from modules $modules = $mm->getLoadedModules(false); foreach ($modules as $moduleName => $module) { if (is_callable(array($module, 'getDiagnostics'))) { $checks = $module->getDiagnostics(); if (is_array($checks)) { $config[$moduleName] = $checks; } // Exit the loop early if we found check definitions for // the only check group that we want to run. if ($checkGroupName && $moduleName == $checkGroupName) { break; } } } // Filter array if a check group name has been provided if ($checkGroupName) { $config = array_intersect_ukey($config, array($checkGroupName => 1), 'strcasecmp'); if (empty($config)) { $m = new ConsoleModel(); $m->setResult($console->colorize(sprintf("Unable to find a group of diagnostic checks called \"%s\". Try to use module name (i.e. \"%s\").\n", $checkGroupName, 'Application'), ColorInterface::YELLOW)); $m->setErrorLevel(1); return $m; } } // Check if there are any diagnostic checks defined if (empty($config)) { $m = new ConsoleModel(); $m->setResult($console->colorize("There are no diagnostic checks currently enabled for this application - please add one or more " . "entries into config \"diagnostics\" array or add getDiagnostics() method to your Module class. " . "\n\nMore info: https://github.com/zendframework/ZFTool/blob/master/docs/" . "DIAGNOSTICS.md#adding-checks-to-your-module\n", ColorInterface::YELLOW)); $m->setErrorLevel(1); return $m; } // Analyze check definitions and construct check instances $checkCollection = array(); foreach ($config as $checkGroupName => $checks) { foreach ($checks as $checkLabel => $check) { // Do not use numeric labels. if (!$checkLabel || is_numeric($checkLabel)) { $checkLabel = false; } // Handle a callable. if (is_callable($check)) { $check = new Callback($check); if ($checkLabel) { $check->setLabel($checkGroupName . ': ' . $checkLabel); } $checkCollection[] = $check; continue; } // Handle check object instance. if (is_object($check)) { if (!$check instanceof CheckInterface) { throw new RuntimeException('Cannot use object of class "' . get_class($check) . '" as check. ' . 'Expected instance of ZendDiagnostics\\Check\\CheckInterface'); } // Use duck-typing for determining if the check allows for setting custom label if ($checkLabel && is_callable(array($check, 'setLabel'))) { $check->setLabel($checkGroupName . ': ' . $checkLabel); } $checkCollection[] = $check; continue; } // Handle an array containing callback or identifier with optional parameters. if (is_array($check)) { if (!count($check)) { throw new RuntimeException('Cannot use an empty array() as check definition in "' . $checkGroupName . '"'); } // extract check identifier and store the remainder of array as parameters $testName = array_shift($check); $params = $check; } elseif (is_scalar($check)) { $testName = $check; $params = array(); } else { throw new RuntimeException('Cannot understand diagnostic check definition "' . gettype($check) . '" in "' . $checkGroupName . '"'); } // Try to expand check identifier using Service Locator if (is_string($testName) && $sm->has($testName)) { $check = $sm->get($testName); // Try to use the ZendDiagnostics namespace } elseif (is_string($testName) && class_exists('ZendDiagnostics\\Check\\' . $testName)) { $class = new \ReflectionClass('ZendDiagnostics\\Check\\' . $testName); $check = $class->newInstanceArgs($params); // Try to use the ZFTool namespace } elseif (is_string($testName) && class_exists('ZFTool\\Diagnostics\\Check\\' . $testName)) { $class = new \ReflectionClass('ZFTool\\Diagnostics\\Check\\' . $testName); $check = $class->newInstanceArgs($params); // Check if provided with a callable inside an array } elseif (is_callable($testName)) { $check = new Callback($testName, $params); if ($checkLabel) { $check->setLabel($checkGroupName . ': ' . $checkLabel); } $checkCollection[] = $check; continue; // Try to expand check using class name } elseif (is_string($testName) && class_exists($testName)) { $class = new \ReflectionClass($testName); $check = $class->newInstanceArgs($params); } else { throw new RuntimeException('Cannot find check class or service with the name of "' . $testName . '" (' . $checkGroupName . ')'); } if (!$check instanceof CheckInterface) { // not a real check throw new RuntimeException('The check object of class ' . get_class($check) . ' does not implement ' . 'ZendDiagnostics\\Check\\CheckInterface'); } // Use duck-typing for determining if the check allows for setting custom label if ($checkLabel && is_callable(array($check, 'setLabel'))) { $check->setLabel($checkGroupName . ': ' . $checkLabel); } $checkCollection[] = $check; } } // Configure check runner $runner = new Runner(); $runner->addChecks($checkCollection); $runner->getConfig()->setBreakOnFailure($breakOnFailure); if (!$quiet && $this->getRequest() instanceof ConsoleRequest) { if ($verbose || $debug) { $runner->addReporter(new VerboseConsole($console, $debug)); } else { $runner->addReporter(new BasicConsole($console)); } } // Run tests $results = $runner->run(); $request = $this->getRequest(); // Return result if ($request instanceof ConsoleRequest) { return $this->processConsoleRequest($results); } if ($request instanceof Request) { return $this->processHttpRequest($request, $results); } }
public function generateAction() { /* @var $request \Zend\Console\Request */ /* @var $console \Zend\Console\AdapterInterface */ $request = $this->getRequest(); $console = $this->getServiceLocator()->get('console'); $relativePath = ''; $usingStdout = false; $directory = $request->getParam('directory'); $appending = $request->getParam('append', false) || $request->getParam('a', false); $overwrite = $request->getParam('overwrite', false) || $request->getParam('w', false); // Validate directory if (!is_dir($directory)) { $m = new ConsoleModel(); $m->setErrorLevel(2); $m->setResult('Invalid library directory provided "' . $directory . '"' . PHP_EOL); return $m; } $directory = realpath($directory); // Determine output file name $output = $request->getParam('destination', $directory . '/autoload_classmap.php'); if ('-' == $output) { $output = STDOUT; $usingStdout = true; } elseif (is_dir($output)) { $m = new ConsoleModel(); $m->setErrorLevel(2); $m->setResult('Invalid output file provided' . PHP_EOL); return $m; } elseif (!is_writeable(dirname($output))) { $m = new ConsoleModel(); $m->setErrorLevel(2); $m->setResult("Cannot write to '{$output}'; aborting." . PHP_EOL); return $m; } elseif (file_exists($output) && !$overwrite && !$appending) { $m = new ConsoleModel(); $m->setErrorLevel(2); $m->setResult("Autoload file already exists at '{$output}'," . PHP_EOL . "but 'overwrite' or 'appending' flag was not specified; aborting." . PHP_EOL); return $m; } 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($output))); // 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] . '/'; } } } if (!$usingStdout) { if ($appending) { $console->write('Appending to class file map '); $console->write($output, Color::LIGHT_WHITE); $console->write(' for library in '); $console->writeLine($directory, Color::LIGHT_WHITE); } else { $console->write('Creating classmap file for library in '); $console->writeLine($directory, Color::LIGHT_WHITE); } $console->write('Scanning for files containing PHP classes '); } // Get the ClassFileLocator, and pass it the library path $l = new ClassFileLocator($directory); // Iterate over each element in the path, and create a map of // classname => filename, where the filename is relative to the library path $map = new \stdClass(); $count = 0; foreach ($l as $file) { $filename = str_replace($directory . '/', '', str_replace(DIRECTORY_SEPARATOR, '/', $file->getPath()) . '/' . $file->getFilename()); // Add in relative path to library $filename = $relativePath . $filename; foreach ($file->getClasses() as $class) { $map->{$class} = $filename; } $count++; $console->write('.'); } if (!$usingStdout) { $console->writeLine(" DONE", Color::GREEN); $console->write('Found '); $console->write((int) $count, Color::LIGHT_WHITE); $console->writeLine(' PHP classes'); $console->write('Creating classmap code ...'); } // Check if we have found any PHP classes. if (!$count) { $console->writeLine('Cannot find any PHP classes in ' . $directory . '. Aborting!', Color::YELLOW); exit(1); } if ($appending) { $content = var_export((array) $map, true) . ';'; // Prefix with __DIR__; modify the generated content $content = preg_replace("#(=> ')#", "=> __DIR__ . '/", $content); // Fix \' strings from injected DIRECTORY_SEPARATOR usage in iterator_apply op $content = str_replace("\\'", "'", $content); // Convert to an array and remove the first "array(" $content = explode(PHP_EOL, $content); array_shift($content); // Load existing class map file and remove the closing "bracket ");" from it $existing = file($output, FILE_IGNORE_NEW_LINES); array_pop($existing); // Merge $content = implode(PHP_EOL, array_merge($existing, $content)); } else { // Create a file with the class/file map. // Stupid syntax highlighters make separating < from PHP declaration necessary $content = '<' . "?php\n" . "// Generated by Zend Framework 2\n" . 'return ' . var_export((array) $map, true) . ';'; // Prefix with __DIR__; modify the generated content $content = preg_replace("#(=> ')#", "=> __DIR__ . '/", $content); // Fix \' strings from injected DIRECTORY_SEPARATOR usage in iterator_apply op $content = str_replace("\\'", "'", $content); } // Remove unnecessary double-backslashes $content = str_replace('\\\\', '\\', $content); // Exchange "array (" width "array(" $content = str_replace('array (', 'array(', $content); // Align "=>" operators to match coding standard preg_match_all('(\\n\\s+([^=]+)=>)', $content, $matches, PREG_SET_ORDER); $maxWidth = 0; foreach ($matches as $match) { $maxWidth = max($maxWidth, strlen($match[1])); } $content = preg_replace_callback('(\\n\\s+([^=]+)=>)', function ($match) use($maxWidth) { return "\n " . $match[1] . str_repeat(' ', $maxWidth - strlen($match[1])) . '=>'; }, $content); if (!$usingStdout) { $console->writeLine(" DONE" . PHP_EOL, Color::GREEN); $console->write('Writing classmap to '); $console->write($output, Color::LIGHT_WHITE); $console->write('... '); } // Write the contents to disk file_put_contents($output, $content); if (!$usingStdout) { $console->writeLine(" DONE", Color::GREEN); $console->writeLine('Wrote classmap to ' . realpath($output), Color::LIGHT_WHITE); } }
/** * Create an exception view model, and set the console status code * * @param MvcEvent $e * @return void */ public function prepareExceptionViewModel(MvcEvent $e) { // Do nothing if no error in the event $error = $e->getError(); if (empty($error)) { return; } // Do nothing if the result is a response object $result = $e->getResult(); if ($result instanceof ResponseInterface) { return; } // Proceed to showing an error page with or without exception switch ($error) { case Application::ERROR_CONTROLLER_NOT_FOUND: case Application::ERROR_CONTROLLER_INVALID: case Application::ERROR_ROUTER_NO_MATCH: // Specifically not handling these return; case Application::ERROR_EXCEPTION: default: // Prepare error message $exception = $e->getParam('exception'); // Log exception to sentry by triggering an exception event $e->getApplication()->getEventManager()->trigger('logException', $this, array('exception' => $exception)); if (is_callable($this->message)) { $callback = $this->message; $message = (string) $callback($exception, $this->displayExceptions); } elseif ($this->displayExceptions && $exception instanceof \Exception) { /* @var $exception \Exception */ $message = str_replace(array(':className', ':message', ':code', ':file', ':line', ':stack', ':previous'), array(get_class($exception), $exception->getMessage(), $exception->getCode(), $exception->getFile(), $exception->getLine(), $exception->getTraceAsString(), $exception->getPrevious()), $this->message); } else { $message = $this->defaultExceptionMessage; } // Prepare view model $model = new ConsoleModel(); $model->setResult($message); $model->setErrorLevel(1); // Inject it into MvcEvent $e->setResult($model); break; } }