Example #1
0
 /**
  * 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;
 }
Example #2
0
 private function sendError($msg)
 {
     $m = new ConsoleModel();
     $m->setErrorLevel(2);
     $m->setResult($msg . PHP_EOL);
     return $m;
 }
 /** @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;
 }
 /**
  * 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;
 }
 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;
 }
 /**
  * 
  * @return ConsoleModel
  */
 public function runAction()
 {
     $exitCode = $this->application->run(new RequestInput($this->getRequest()));
     if (is_numeric($exitCode)) {
         $model = new ConsoleModel();
         $model->setErrorLevel($exitCode);
         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);
 }
 /**
  * Inspect the result, and cast it to a ViewModel if a string is detected
  *
  * @param MvcEvent $e
  * @return void
  */
 public function createViewModelFromString(MvcEvent $e)
 {
     $result = $e->getResult();
     if (!is_string($result)) {
         return;
     }
     // create Console model
     $model = new ConsoleModel();
     // store the result in a model variable
     $model->setVariable(ConsoleModel::RESULT, $result);
     $e->setResult($model);
 }
 /**
  * @return ConsoleModel
  */
 public function decodeVariableAction()
 {
     $request = $this->getConsoleRequest();
     $variable = $request->getParam('variable');
     $decodedValue = $this->getEncryptor()->getVariable($variable);
     $response = new ConsoleModel();
     if ($decodedValue === null) {
         $this->writeConsoleLine('Variable does not exist', ConsoleColor::LIGHT_RED);
         $response->setErrorLevel(1);
     } else {
         $this->writeConsoleLine($decodedValue);
     }
     return $response;
 }
 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);
 }
Example #11
0
 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;
 }
Example #13
0
 /**
  * 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;
     }
 }
 /**
  * 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;
 }
 /**
  * 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);
 }
 private function processConsoleRequest(Collection $results)
 {
     // Return appropriate error code in console
     $model = new ConsoleModel(array('results' => $results));
     if ($results->getFailureCount() > 0) {
         $model->setErrorLevel(1);
     } else {
         $model->setErrorLevel(0);
     }
     return $model;
 }
 public function runAction()
 {
     $sm = $this->getServiceLocator();
     /* @var $console \Zend\Console\Adapter\AdapterInterface */
     /* @var $config array */
     /* @var $mm \Zend\ModuleManager\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();
     // 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;
 }
Example #18
0
 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;
     }
 }