/** * Return console adapter to use when showing prompt. * * @return ConsoleAdapter */ public function getConsole() { if (!$this->console) { $this->console = Console::getInstance(); } return $this->console; }
/** * Initialize the application * * Creates a RouteCollection and populates it with the $routes provided. * * Sets the banner to call showVersion(). * * If no help command is defined, defines one. * * If no version command is defined, defines one. * * @param string $name Application name * @param string $version Application version * @param array|Traversable $routes Routes/route specifications to use for the application * @param Console $console Console adapter to use within the application * @param Dispatcher $dispatcher Configured dispatcher mapping routes to callables */ public function __construct($name, $version, $routes, Console $console = null, Dispatcher $dispatcher = null) { if (!is_array($routes) && !$routes instanceof Traversable) { throw new InvalidArgumentException('Routes must be provided as an array or Traversable object'); } $this->name = $name; $this->version = $version; if (null === $console) { $console = DefaultConsole::getInstance(); } $this->console = $console; if (null === $dispatcher) { $dispatcher = new Dispatcher(); } $this->dispatcher = $dispatcher; $this->routeCollection = $routeCollection = new RouteCollection(); $this->setRoutes($routes); $this->banner = [$this, 'showVersion']; if (!$routeCollection->hasRoute('help')) { $this->setupHelpCommand($routeCollection, $dispatcher); } if (!$routeCollection->hasRoute('version')) { $this->setupVersionCommand($routeCollection, $dispatcher); } if (!$routeCollection->hasRoute('autocomplete')) { $this->setupAutocompleteCommand($routeCollection, $dispatcher); } }
public function passwordAction() { $request = $this->getRequest(); // Make sure that we are running in a console and the user has not // tricked our // application into running this action from a public web server. if (!$request instanceof ConsoleRequest) { throw new \RuntimeException('You can only use this action from a console!'); } // Get user email from console and check if the user used --verbose or // -v flag $userEmail = $request->getParam('userEmail'); $verbose = $request->getParam('verbose'); // reset new password $newPassword = Rand::getString(16); $console = Console::getInstance(); if (Confirm::prompt('Is this the correct answer? [y/n]', 'y', 'n')) { $console->write("You chose YES\n"); } else { $console->write("You chose NO\n"); } if (!$verbose) { return "Done! {$userEmail} has received an email with his new password.\n"; } else { return "Done! New password for user {$userEmail} is '{$newPassword}'. It has also been emailed to him. \n"; } }
/** * * @return ConsoleAdapter */ public function getConsoleAdapter() { if (null === $this->consoleAdapter) { $this->consoleAdapter = Console::getInstance(); } return $this->consoleAdapter; }
/** * Creates all needed classes and fills them with random data */ public function installAction() { Time::check(); $this->createTables(); Console::getInstance()->writeLine('Tables created in ' . Time::check() . ' sec.'); $pupilService = $this->getPupilService(); $count = $this->generateItems($pupilService, $this->getRequest()->getParam('pupils', 100000), ['email', 'birthday'], function ($item) { return ['name' => $item['full'], 'email' => $item['email'], 'birthday' => $item['birthday'], 'level' => \Application\Entity\Pupil::$levels[rand(0, 5)]]; }); Console::getInstance()->writeLine($count . ' pupils generated in ' . Time::check() . ' sec.'); $teachersCount = $this->getRequest()->getParam('teachers', 10000); $teacherService = $this->getTeacherService(); $this->generateItems($teacherService, $teachersCount, ['phone'], function ($item) { $gender = $item['gender'] === \NameGenerator\Gender::GENDER_MALE ? TeacherEntity::GENDER_MALE : TeacherEntity::GENDER_FEMALE; return ['gender' => $gender, 'name' => $item['full'], 'phone' => $item['phone']]; }); Console::getInstance()->writeLine($teachersCount . ' teachers generated in ' . Time::check() . ' sec.'); $pupilMaxId = $pupilService->getMaxId(); $teacherMaxId = $teacherService->getMaxId(); $teacherPupilService = $this->getTeacherPupilService(); $linksCount = 0; for ($teacherId = 1; $teacherId < $teacherMaxId; $teacherId++) { $except = []; for ($j = 0; $j < rand(0, 3); $j++) { $pupil_id = rand(0, $pupilMaxId); if (in_array($pupil_id, $except)) { continue; } $except[] = $pupil_id; $teacherPupilService->insert(['teacher_id' => $teacherId, 'pupil_id' => $pupil_id]); $linksCount++; } } Console::getInstance()->writeLine($linksCount . ' links generated in ' . Time::check() . ' sec.'); }
public function __construct() { $routes = [['name' => '<config> <output_file> [--strip]', 'short_description' => "Generate class cache based on <config> file into <output_file>.", 'handler' => [$this, 'generateDump']]]; parent::__construct('Cache dumper', 1.0, $routes, Console::getInstance()); $this->removeRoute('autocomplete'); $this->removeRoute('help'); $this->removeRoute('version'); }
/** * Create console instance for color output of success/failure * messages. * * @param ConsoleAdapter $console */ public function __construct(ConsoleAdapter $console = null) { if (null === $console) { $this->console = Console::getInstance(); } else { $this->console = $console; } }
/** * setUp from PHPUnit */ public function setUp() { ob_start(); $this->console = Console::getInstance(); $this->routes = (include __DIR__ . '/../config/routes.php'); $this->deploy = new Deploy(); copy(__DIR__ . '/TestAsset/App/config/autoload/.gitignore.dist', __DIR__ . '/TestAsset/App/config/autoload/.gitignore'); }
/** * @coversNothing */ public function testDrawReal() { $console = Console::getInstance(); ob_start(); (new Logo())->draw($console); $this->assertNotEmpty(ob_get_contents()); ob_end_clean(); }
public function testCanForceInstance() { $console = Console::getInstance('Posix'); $this->assertTrue($console instanceof Adapter\AdapterInterface); $this->assertTrue($console instanceof Adapter\Posix); Console::overrideIsConsole(null); Console::resetInstance(); $console = Console::getInstance('Windows'); $this->assertTrue($console instanceof Adapter\AdapterInterface); $this->assertTrue($console instanceof Adapter\Windows); }
public function __construct(Options $options = null, Console $console = null) { if (null === $options) { $options = new Options(); } $this->options = $options; if (null === $console) { $console = Console::getInstance(); } $this->console = $console; }
/** * Dumps all available routes (including defined in modules) into cache file. * @see annotated_router.cache_file config key */ public function dumpCompleteAction() { $config = $this->serviceLocator->get('Config'); $console = Console::getInstance(); $console->writeLine('Dumping all routes into "' . $config['annotated_router']['cache_file'] . '"'); $annotatedRouterConfig = $this->serviceLocator->get('AnnotatedRouter\\ControllerParser')->getRouteConfig(); $annotatedRouterConfig = array_replace_recursive($annotatedRouterConfig, isset($config['router']['routes']) ? $config['router']['routes'] : array()); $generator = new ValueGenerator($annotatedRouterConfig); $content = "<?php\n\nreturn " . $generator . ';'; file_put_contents($config['annotated_router']['cache_file'], $content); }
protected function setUp() { $config = ['app' => "this is my app", "test" => "prova", "version" => "0.0.1", 'routes' => [['name' => 'hello', 'route' => "--name=", 'short_description' => "Good morning!! This is a beautiful day", "handler" => ['App\\Command\\Hello', 'run']]], "service_manager" => ["invokables" => [], "factories" => []]]; $builder = new ContainerBuilder(); $builder->useAnnotations(true); $builder->addDefinitions($config); $container = $builder->build(); $configServiceManager = new Config($config['service_manager']); $container->set("service_manager", new ServiceManager($configServiceManager)); $this->application = new Application($config['app'], $config['version'], $config['routes'], Console::getInstance(), new Dispatcher($container)); }
/** * Creates all needed classes and filles them with dummie data */ public function installAction() { Time::check(); $nameGenerator = new \NameGenerator\Generator(); $this->createTables(); $teachersCount = $this->getRequest()->getParam('teachers', 10000); $pupilsCount = $this->getRequest()->getParam('pupils', 100000); /** @var \Application\Model\Teacher $teacherTable */ $teacherTable = $this->getServiceLocator()->get('TeacherTable'); /** @var \Application\Model\Pupil $pupilTable */ $pupilTable = $this->getServiceLocator()->get('PupilTable'); /** @var \Application\Model\TeacherPupil $teacherPupilTable */ $teacherPupilTable = $this->getServiceLocator()->get('TeacherPupilTable'); Console::getInstance()->writeLine('Tables created in ' . Time::check() . ' sec.'); $pupils = $nameGenerator->get($pupilsCount, ['email', 'birthday']); foreach ($pupils as $randomPupil) { $level = \Application\Entity\Pupil::$levels[rand(0, count(\Application\Entity\Pupil::$levels) - 1)]; /** @var \Application\Entity\Pupil $pupil */ $pupil = $pupilTable->getEntity(); $pupil->setName($randomPupil['first'] . ' ' . $randomPupil['last'])->setEmail($randomPupil['email'])->setBirthday($randomPupil['birthday'])->setLevel($level); $pupilTable->insert($pupil); } Console::getInstance()->writeLine($pupilsCount . ' pupils generated in ' . Time::check() . ' sec.'); $teachers = $nameGenerator->get($teachersCount, ['phone']); foreach ($teachers as $randomTeacher) { $gender = $randomTeacher['gender'] == \NameGenerator\Gender::GENDER_MALE ? \Application\Entity\Teacher::GENDER_MALE : \Application\Entity\Teacher::GENDER_FEMALE; /** @var \Application\Entity\Teacher $teacher */ $teacher = $teacherTable->getEntity(); $teacher->setName($randomTeacher['first'] . ' ' . $randomTeacher['last'])->setGender($gender)->setPhone($randomTeacher['phone']); $teacherTable->insert($teacher); } Console::getInstance()->writeLine($teachersCount . ' teachers generated in ' . Time::check() . ' sec.'); $pupilMaxId = $pupilTable->getMaxId(); $teacherMaxId = $teacherTable->getMaxId(); $linksCount = 0; for ($teacherId = 1; $teacherId < $teacherMaxId; $teacherId++) { $except = []; for ($j = 0; $j < rand(0, 3); $j++) { $pupil_id = rand(0, $pupilMaxId); if (in_array($pupil_id, $except)) { continue; } $except[] = $pupil_id; $link = $teacherPupilTable->getEntity(); $link->teacher_id = $teacherId; $link->pupil_id = $pupil_id; $teacherPupilTable->insert($link); $linksCount++; } } Console::getInstance()->writeLine($linksCount . ' links generated in ' . Time::check() . ' sec.'); }
/** * Получить AccessToken из консоли * * @param EventInterface $e * * @return string|null * @throws \Zend\Console\Exception\RuntimeException * @throws \Zend\Console\Exception\InvalidArgumentException * @throws \Assert\AssertionFailedException */ public function getAccessToken(EventInterface $e) { if (!Console::isConsole()) { return null; } $authUrl = $e->getParam('authUrl', null); Assertion::url($authUrl); $console = Console::getInstance(); $console->writeLine(sprintf('Open the following link in your browser:')); $console->writeLine($authUrl); $console->writeLine(); $console->write('Enter verification code: '); return $console->readLine(); }
/** * @param Shortcode $shortcode * @return string */ public static function msg($shortcode) { $content = $shortcode->getContent(); $attributes = $shortcode->getParameters(); $fgColor = isset($attributes['fg']) ? self::getColorCode($attributes['fg']) : null; $bgColor = isset($attributes['bg']) ? self::getColorCode($attributes['bg']) : null; if (isset(self::$mapShortcodeToColor[$shortcode->getName()])) { $fgColor = self::$mapShortcodeToColor[$shortcode->getName()]; } if (isset($attributes['show']) && (bool) $attributes['show'] === false) { return '[hide]' . $content . '[/hide]'; } return Console::getInstance()->colorize($content, $fgColor, $bgColor); }
/** * (non-PHPdoc) * @see \Zend\Console\Getopt::getUsageMessage() * @param string $additional */ public function getUsageMessage($additional = '') { $console = Console::getInstance(); $usage = $console->colorize('Usage:', ColorInterface::YELLOW) . PHP_EOL; $usage .= ' ' . basename($this->progname, '.php') . ' [options] ' . $additional . PHP_EOL; $usage .= PHP_EOL; $usage .= $console->colorize('Options:', ColorInterface::YELLOW) . PHP_EOL; $maxLen = 40; $lines = array(); foreach ($this->rules as $rule) { if (isset($rule['isFreeformFlag'])) { continue; } $flags = array(); if (is_array($rule['alias'])) { foreach ($rule['alias'] as $flag) { if (strlen($flag) == 1) { $flags[] = '(-' . $flag . ')'; } else { $flags[] = $console->colorize('--' . $flag, ColorInterface::GREEN); } } } $linepart['name'] = implode(' ', $flags); if (isset($rule['param']) && $rule['param'] != 'none') { $linepart['name'] .= ' '; switch ($rule['param']) { case 'optional': $linepart['name'] .= "[ <{$rule['paramType']}> ]"; break; case 'required': $linepart['name'] .= "<{$rule['paramType']}>"; break; } } if (strlen($linepart['name']) > $maxLen) { $maxLen = strlen($linepart['name']); } $linepart['help'] = ''; if (isset($rule['help'])) { $linepart['help'] .= $rule['help']; } $lines[] = $linepart; } foreach ($lines as $linepart) { $usage .= sprintf(' %s %s' . PHP_EOL, str_pad($linepart['name'], $maxLen), $linepart['help']); } return $usage; }
/** * @param $param * @param $name * @param $description * * @return null */ public function showParam($param, $name, $description) { $console = Console::getInstance(); $shiftStr = str_repeat(" ", 8); $paramName = str_pad($param, 22, " ", STR_PAD_LEFT); $paramName = $console->colorize($paramName, ColorInterface::LIGHT_WHITE); $paramName = preg_replace("#<(dir|str|file)>#", $console->colorize("<\\1>", ColorInterface::WHITE), $paramName); $paramName = preg_replace("#(\\[\\-\\-.*?\\])#", $console->colorize("\\1", ColorInterface::WHITE), $paramName); $console->write($shiftStr . $paramName . " " . $console->colorize($name, ColorInterface::LIGHT_WHITE) . PHP_EOL); $descriptionArray = array_map('trim', explode("\n", $description)); foreach ($descriptionArray as $descriptionItem) { $console->write($shiftStr . str_repeat(" ", 24) . $descriptionItem . "\n"); } return null; }
private function recursiveDirectory($dir) { $stack[] = $dir; while ($stack) { $currentDir = array_pop($stack); if ($dh = opendir($currentDir)) { $count = 0; while (($file = readdir($dh)) !== false) { if ($file !== '.' and $file !== '..') { $count++; $currentFile = $currentDir . DIRECTORY_SEPARATOR . $file; if (is_dir($currentFile)) { $stack[] = $currentFile; } } } if ($count <= 0) { Console::getInstance()->writeLine($currentDir . ' - empty'); rmdir($currentDir); } } } }
<?php use Zend\Console\Console; use Zend\Console\ColorInterface; use DasRed\Zend\Console\Getopt; use DasRed\Translation\Version; use DasRed\Translation\Command\Factory; use DasRed\Translation\Command\Exception\InvalidArguments; set_error_handler(function ($errno, $errstr, $errfile, $errline, array $errcontext) { throw new Exception($errstr, $errno); }); require_once __DIR__ . '/../autoload.php'; // consoleoptions $console = Console::getInstance(); $opt = (new Getopt(['help|h' => 'Display this help message']))->setOptions([Getopt::CONFIG_CUMULATIVE_PARAMETERS => true]); $message = 'operation' . PHP_EOL; $message .= PHP_EOL; $message .= $console->colorize('translation Operations:', ColorInterface::YELLOW) . PHP_EOL; $message .= $console->colorize(' translation sort <path>', ColorInterface::GREEN) . ' sorts the translations keys in the files.' . PHP_EOL; $message .= $console->colorize(' translation duplicates <path>', ColorInterface::GREEN) . ' find keys with same content.' . PHP_EOL; $message .= PHP_EOL; $message .= $console->colorize('log Operations:', ColorInterface::YELLOW) . PHP_EOL; $message .= $console->colorize(' parse <logFile>', ColorInterface::GREEN) . ' parse a log file written with \\DasRed\\Translation\\Logger\\Formatter.' . PHP_EOL; $message .= $console->colorize(' toCsv <logFile> <csvFile>', ColorInterface::GREEN) . ' parse a log file written with \\DasRed\\Translation\\Logger\\Formatter and write to CSV.' . PHP_EOL; $message .= $console->colorize(' toExcel <logFile> <xlsFile>', ColorInterface::GREEN) . ' parse a log file written with \\DasRed\\Translation\\Logger\\Formatter and write to XLS.' . PHP_EOL; try { $opt->parse(); if ($opt->help) { throw new \Exception('wants help'); } if (!$opt->version && count($opt->getRemainingArgs()) < 2) {
/** * Constructor */ public function __construct() { $this->console = Console::getInstance(); }
public function deleteSpamAction() { $deleted = $this->getCommentTable()->deleteSpam(); $console = Console::getInstance(); $console->writeLine($deleted . ' spam comments removed'); }
/** * try to initiate console instance if not set * * @return self */ public function initConsole() { try { if ($console = Console::getInstance()) { $this->setConsole($console); } } catch (\Exception $e) { } return $this; }
#!/usr/bin/env php <?php /** * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com) */ use Zend\Console\Console; use ZF\Console\Application; use ZF\Deploy\SelfUpdate; switch (true) { case file_exists(__DIR__ . '/../vendor/autoload.php'): // Installed standalone require __DIR__ . '/../vendor/autoload.php'; break; case file_exists(__DIR__ . '/../../../autoload.php'): // Installed as a Composer dependency require __DIR__ . '/../../../autoload.php'; break; case file_exists('vendor/autoload.php'): // As a Composer dependency, relative to CWD require 'vendor/autoload.php'; break; default: throw new RuntimeException('Unable to locate Composer autoloader; please run "composer install".'); } define('VERSION', '1.0.3-dev'); $routes = (include __DIR__ . '/../config/routes.php'); $application = new Application('ZFDeploy', VERSION, $routes, Console::getInstance()); $application->getDispatcher()->map('self-update', new SelfUpdate(VERSION)); $exit = $application->run(); exit($exit);
} } else { if (!is_readable($sStandardAutoloaderPath = 'Zend/Loader/StandardAutoloader.php')) { throw new \InvalidArgumentException('StandardAutoloader file "' . $sStandardAutoloaderPath . '" is unreadable'); } if (false === (include $sStandardAutoloaderPath)) { throw new \RuntimeException('An error occurred while including file "' . $sStandardAutoloaderPath . '"'); } } if (!class_exists('Zend\\Loader\\StandardAutoloader')) { throw new \InvalidArgumentException('"' . $sStandardAutoloaderPath . '" does not provide "Zend\\Loader\\StandardAutoloader" class'); } //Setup autoloading $oAutoLoader = new \Zend\Loader\StandardAutoloader(array('autoregister_zf' => true)); $oAutoLoader->register(); $oConsole = \Zend\Console\Console::getInstance(); } catch (\Exception $oException) { echo 'An error occured' . PHP_EOL; if ($bVerbose) { echo $oException . PHP_EOL; } exit(2); } try { $oGetopt = new \Zend\Console\Getopt(array('help|h' => 'Get usage message', 'module|m-s' => 'Module path to deploy; if none provided, assumes current directory', 'dir|d-s' => 'Directory path where to deploy the module (ex: apache/www/my-module), the directory could be created if needed', 'modules|a-s' => '(optionnal) Additionnal module namespaces (comma separated) to be used in the application', 'zapp|z-s' => '(optionnal) ZendSkeletonApplication file path, allows locale or remote directory, allows archive (Phar, Rar, Zip) depending on PHP installed libraries', 'composer|c-s' => '(optionnal) Composer.phar file path, allows locale or remote directory', 'overwrite|w' => 'Whether or not to overwrite existing deployed ZendSkeletonApplication', 'verbose|v' => 'Whether or not to display execution trace')); $oGetopt->parse(); $bVerbose = !!$oGetopt->getOption('verbose'); } catch (\Zend\Console\Exception\RuntimeException $oException) { $oConsole->writeLine($oException->getUsageMessage()); exit(2); }
}], ['name' => 'create-asset-symlinks', 'description' => 'Symlink assets installed by npm into the public tree.', 'short_description' => 'Symlink assets.', 'handler' => function ($route, $console) use($container) { $handler = $container->get(MwopConsole\CreateAssetSymlinks::class); return $handler($route, $console); }], ['name' => 'feed-generator', 'route' => '[--outputDir=] [--baseUri=]', 'description' => 'Generate feeds (RSS and Atom) for the blog, including all tags.', 'short_description' => 'Generate blog feeds.', 'options_descriptions' => ['--outputDir' => 'Directory to which to write the feeds (defaults to data/feeds)', '--baseUri' => 'Base URI for the site (defaults to https://mwop.net)'], 'defaults' => ['outputDir' => 'data/feeds', 'baseUri' => 'https://mwop.net'], 'handler' => function ($route, $console) use($container) { $handler = $container->get(Blog\Console\FeedGenerator::class); return $handler($route, $console); }], ['name' => 'generate-search-data', 'route' => '[--path=]', 'description' => 'Generate site search data based on blog posts.', 'short_description' => 'Generate site search data.', 'options_descriptions' => ['--path' => 'Base path of the application; posts are expected at $path/data/blog/ ' . 'and search terms will be written to $path/public/js/search_terms.json'], 'defaults' => ['path' => realpath(getcwd())], 'handler' => function ($route, $console) use($container) { $handler = $container->get(Blog\Console\GenerateSearchData::class); return $handler($route, $console); }], ['name' => 'github-links', 'route' => '[--output=] [--template=]', 'description' => 'Fetch GitHub activity stream and generate links for the home page.', 'short_description' => 'Fetch GitHub activity stream.', 'options_descriptions' => ['--output' => 'Output file to which to write links', '--template' => 'Template string to use when generating link output'], 'defaults' => ['output' => 'data/github-links.mustache'], 'handler' => function ($route, $console) use($container) { $handler = $container->get(Github\Console\Fetch::class); return $handler($route, $console); }], ['name' => 'homepage-feeds', 'route' => '', 'description' => 'Fetch feed data for homepage activity stream.', 'short_description' => 'Fetch homepage feed data.', 'defaults' => ['path' => realpath(getcwd())], 'handler' => function ($route, $console) use($container) { $handler = $container->get(MwopConsole\FeedAggregator::class); return $handler($route, $console); }], ['name' => 'prep-offline-pages', 'route' => '[--serviceWorker=]', 'description' => 'Prepare the offline pages list for the service-worker.js file.', 'short_description' => 'Prep offline page cache list', 'options_descriptions' => ['--serviceWorker' => 'Path to the service-worker.js file'], 'defaults' => ['serviceWorker' => realpath(getcwd()) . '/public/service-worker.js'], 'handler' => function ($route, $console) use($container) { $handler = $container->get(MwopConsole\PrepOfflinePages::class); return $handler($route, $console); }], ['name' => 'seed-blog-db', 'route' => '[--path=] [--dbPath=] [--postsPath=] [--authorsPath=]', 'description' => 'Re-create the blog post database from the post entities.', 'short_description' => 'Generate and seed the blog post database.', 'options_descriptions' => ['--path' => 'Base path of the application; defaults to current working dir', '--dbPath' => 'Path to the database file, relative to the --path; defaults to data/posts.db', '--postsPath' => 'Path to the blog posts, relative to the --path; defaults to data/blog', '--authorsPath' => 'Path to the author metadata files, relative to the --path; ' . 'defaults to data/blog/authors'], 'defaults' => ['path' => realpath(getcwd()), 'postsPath' => 'data/blog/', 'authorsPath' => 'data/blog/authors', 'dbPath' => 'data/posts.db'], 'handler' => function ($route, $console) use($container) { $handler = $container->get(Blog\Console\SeedBlogDatabase::class); return $handler($route, $console); }], ['name' => 'tag-cloud', 'route' => '[--output=]', 'description' => 'Generate a Mustache template containing the tag cloud for the blog.', 'short_description' => 'Generate tag cloud.', 'options_descriptions' => ['--output' => 'Output file to which to write the tag cloud'], 'defaults' => ['output' => 'data/tag-cloud.mustache'], 'handler' => function ($route, $console) use($container) { $handler = $container->get(Blog\Console\TagCloud::class); return $handler($route, $console); }], ['name' => 'use-dist-templates', 'route' => '[--path=]', 'description' => 'Enable usage of distribution templates (optimizing CSS and JS).', 'short_description' => 'Use dist templates.', 'options_descriptions' => ['--path' => 'Base path of the application; templates are expected at $path/templates/'], 'defaults' => ['path' => realpath(getcwd())], 'handler' => function ($route, $console) use($container) { $handler = $container->get(MwopConsole\UseDistTemplates::class); return $handler($route, $console); }]]; $app = new Application('mwop.net', VERSION, $routes, Console::getInstance()); $exit = $app->run(); exit($exit);
<?php /** * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2015 Matthew Weier O'Phinney (https://mwop.net) */ require __DIR__ . '/../vendor/autoload.php'; use Zend\Console\Console; use ZF\Console\Application; use ZF\Console\Dispatcher; $version = '@package_version@'; // Reset version if not rewritten (which happens when using // a phar) $version = $version === '@' . 'package_version' . '@' ? 'dev-master' : $version; $application = new Application('Component Installer', $version, include __DIR__ . '/../config/routes.php', Console::getInstance(), new Dispatcher()); $exit = $application->run(); exit($exit);
#!/usr/bin/env php <?php $basePath = Phar::running(true); if ($basePath == '') { $basePath = __DIR__; chdir($basePath); } require_once $basePath . '/vendor/autoload.php'; $config = (require_once $basePath . '/config/config.php'); $container = new \Zend\ServiceManager\ServiceManager(); (new \Zend\ServiceManager\Config($config['dependencies'] ?? []))->configureServiceManager($container); $container->setService('config', $config); $dispatcher = new \ZF\Console\Dispatcher($container); $routes = $config['console']['routes'] ?? []; $application = new \ZF\Console\Application('Kharon', Kharon\Version::VERSION, $routes, \Zend\Console\Console::getInstance(), $dispatcher); $exit = $application->run(); exit($exit);
public function createAction() { $request = $this->getRequest(); if (!$request instanceof ConsoleRequest) { throw new \RuntimeException('This action can only be used from a console!'); } try { $console = Console::getInstance(); } catch (ConsoleException $e) { throw new \RuntimeException('This action can only be used from a console!'); } $this->setValidatorService($this->getServiceLocator()->get('loslicense.validator')); $outputFile = $request->getParam('outputFile', null); $writer = new \LosLicense\Config\Writer\PhpArray(); $writer->setUseBracketArraySyntax(true); $options = ['Trial', 'Personal', 'Standard']; $type = Select::prompt('License type?', $options, false, true); $valid_from = Line::prompt("\nValid from (Enter to not set one) YYYY-MM-DD HH:II:SS ? ", true, 20); $valid_until = Line::prompt("\nValid until (Enter to not set one) YYYY-MM-DD HH:II:SS ? ", true, 20); $customer = Line::prompt("\nCustomer? ", true, 100); $options = $this->getServiceLocator()->get('loslicense.options'); $features = $options->getFeatures(); $checked = Checkbox::prompt("\nFeatures? (Enter to finish) ", array_keys($features), true, true); $sign = false; if (Confirm::prompt("\nSign the license? [y/n] ", 'y', 'n')) { $sign = true; } if (Confirm::prompt("\nConfirm the license creation? [y/n] ", 'y', 'n')) { $config = new \Zend\Config\Config([], true); if ($type == 0) { $config->type = License::LICENSE_TRIAL; $license = new TrialLicense(); } elseif ($type == 1) { $config->type = License::LICENSE_PERSONAL; $license = new PersonalLicense(); } else { $config->type = License::LICENSE_STANDARD; $license = new StandardLicense(); } $license->setType($config->type); if (!empty($valid_from)) { $from = new \DateTime($valid_from); $config->valid_from = $from->format('Y-m-d H:i:s'); $license->setValidFrom($config->valid_from); } if (!empty($valid_until)) { $until = new \DateTime($valid_until); $config->valid_until = $until->format('Y-m-d H:i:s'); $license->setValidUntil($config->valid_until); } if (!empty($customer)) { $config->customer = $customer; $license->setCustomer($config->customer); } if (!empty($checked)) { $config->features = []; $licenseFeatures = []; foreach ($features as $feature => $value) { if (in_array($feature, $checked)) { if ($value === null) { $config->features->{$feature} = null; $licenseFeatures[$feature] = null; } else { $config->features->{$feature} = $value; $licenseFeatures[$feature] = $value; } } } $license->setFeatures($licenseFeatures); } if ($sign) { $signature = $this->getValidatorService()->signLicense($license); $config->signature = $signature; } if ($outputFile) { $writer->toFile($outputFile, $config); } else { echo $writer->toString($config); } $console->writeLine("License created", Color::GREEN); } }
/** * Get platform based console adapter */ function __construct() { $this->adapter = ZendConsole::getInstance(); }