/** * 创建控制器 * * @param array $args 参数 * @param array $options 选项 */ public function execute(array $args, array $options = []) { $template = isset($options['template']) ? $options['template'] : false; $template || ($template = __DIR__ . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'Controller.php.dist'); $name = $args[0]; $name = explode('-', $name); if (count($name) < 2) { throw new \InvalidArgumentException(sprintf('The arg name "%s" is invalid. eg: adminbase-Blog/Category', $name)); } $namespace = trim(trim($name[0], '\\/')); $path = Cml::getApplicationDir('apps_path') . DIRECTORY_SEPARATOR . $namespace . DIRECTORY_SEPARATOR . Cml::getApplicationDir('app_controller_path_name') . DIRECTORY_SEPARATOR; $component = explode('/', trim(trim($name[1], '/'))); if (count($component) > 1) { $className = ucfirst(array_pop($component)) . Config::get('controller_suffix'); $component = implode(DIRECTORY_SEPARATOR, $component); $path .= $component . DIRECTORY_SEPARATOR; $component = '\\' . $component; } else { $className = ucfirst($component[0]) . Config::get('controller_suffix'); $component = ''; } if (!is_dir($path) && false == mkdir($path, 0700, true)) { throw new \RuntimeException(sprintf('The path "%s" could not be create', $path)); } $contents = strtr(file_get_contents($template), ['$namespace' => $namespace, '$component' => $component, '$className' => $className]); if (false === file_put_contents($path . $className . '.php', $contents)) { throw new \RuntimeException(sprintf('The file "%s" could not be written to', $path)); } Output::writeln(Colour::colour('Controller created successfully. ', Colour::GREEN)); }
/** * 生成软链接 * * @param null $rootDir 站点静态文件根目录默认为项目目录下的public目录 */ public static function createSymbolicLink($rootDir = null) { $isCli = Request::isCli(); if ($isCli) { Output::writeln(Colour::colour('create link start!', [Colour::GREEN, Colour::HIGHLIGHT])); } else { echo "<br />**************************create link start!*********************<br />"; } is_null($rootDir) && ($rootDir = CML_PROJECT_PATH . DIRECTORY_SEPARATOR . 'public'); is_dir($rootDir) || mkdir($rootDir, true, 0700); //modules_static_path_name // 递归遍历目录 $dirIterator = new \DirectoryIterator(Cml::getApplicationDir('apps_path')); foreach ($dirIterator as $file) { if (!$file->isDot() && $file->isDir()) { $resourceDir = $file->getPathname() . DIRECTORY_SEPARATOR . Cml::getApplicationDir('app_static_path_name'); if (is_dir($resourceDir)) { $distDir = $rootDir . DIRECTORY_SEPARATOR . $file->getFilename(); $cmd = Request::operatingSystem() ? "mklink /d {$distDir} {$resourceDir}" : "ln -s {$resourceDir} {$distDir}"; is_dir($distDir) || exec($cmd, $result); $tip = " create link Application [{$file->getFilename()}] result : [" . (is_dir($distDir) ? 'true' : 'false') . "]"; if ($isCli) { Output::writeln(Colour::colour($tip, [Colour::WHITE, Colour::HIGHLIGHT])); } else { print_r('|<span style="color:blue">' . str_pad($tip, 64, ' ', STR_PAD_BOTH) . '</span>|'); } } } } if ($isCli) { Output::writeln(Colour::colour('create link end!', [Colour::GREEN, Colour::HIGHLIGHT])); } else { echo "<br />****************************create link end!**********************<br />"; } }
/** * 创建一个新的seeder * * @param array $args 参数 * @param array $options 选项 */ public function execute(array $args, array $options = []) { $this->bootstrap($args, $options); // get the seed path from the config $path = $this->getConfig()->getSeedPath(); if (!file_exists($path)) { $ask = new Dialog(); if ($ask->confirm(Colour::colour('Create seeds directory?', [Colour::RED, Colour::HIGHLIGHT]))) { mkdir($path, 0755, true); } } $this->verifySeedDirectory($path); $path = realpath($path); $className = $args[0]; if (!Util::isValidPhinxClassName($className)) { throw new \InvalidArgumentException(sprintf('The seed class name "%s" is invalid. Please use CamelCase format', $className)); } // Compute the file path $filePath = $path . DIRECTORY_SEPARATOR . $className . '.php'; if (is_file($filePath)) { throw new \InvalidArgumentException(sprintf('The file "%s" already exists', basename($filePath))); } // inject the class names appropriate to this seeder $contents = file_get_contents($this->getSeedTemplateFilename()); $classes = ['$useClassName' => 'Phinx\\Seed\\AbstractSeed', '$className' => $className, '$baseClassName' => 'AbstractSeed']; $contents = strtr($contents, $classes); if (false === file_put_contents($filePath, $contents)) { throw new \RuntimeException(sprintf('The file "%s" could not be written to', $path)); } Output::writeln('using seed base class ' . $classes['$useClassName']); Output::writeln('created ' . str_replace(Cml::getApplicationDir('secure_src'), '{secure_src}', $filePath)); }
/** * 自定义异常处理 * * @param mixed $e 异常对象 */ public function appException(&$e) { $error = []; $exceptionClass = new \ReflectionClass($e); $error['exception'] = '\\' . $exceptionClass->name; $error['message'] = $e->getMessage(); $trace = $e->getTrace(); foreach ($trace as $key => $val) { $error['files'][$key] = $val; } if (substr($e->getFile(), -20) !== '\\Tools\\functions.php' || $e->getLine() !== 90) { array_unshift($error['files'], ['file' => $e->getFile(), 'line' => $e->getLine(), 'type' => 'throw']); } if (!Cml::$debug) { //正式环境 只显示‘系统错误’并将错误信息记录到日志 Log::emergency($error['message'], [$error['files'][0]]); $error = []; $error['message'] = Lang::get('_CML_ERROR_'); } if (Request::isCli()) { Output::writeException(sprintf("%s\n[%s]\n%s", isset($error['files']) ? implode($error['files'][0], ':') : '', get_class($e), $error['message'])); } else { header('HTTP/1.1 500 Internal Server Error'); View::getEngine('html')->reset()->assign('error', $error); Cml::showSystemTemplate(Config::get('html_exception')); } }
/** * 获取迁移信息 * * @param array $args 参数 * @param array $options 选项 */ public function execute(array $args, array $options = []) { $this->bootstrap($args, $options); $format = isset($options['format']) ? $options['format'] : $options['f']; if (null !== $format) { Output::writeln('using format ' . $format); } $this->getManager()->printStatus($format); }
/** * 运行迁移 * * @param array $args 参数 * @param array $options 选项 * * @return int */ public function execute(array $args, array $options = []) { $this->bootstrap($args, $options); $version = isset($options['target']) ? $options['target'] : $options['t']; $date = isset($options['date']) ? $options['date'] : $options['d']; // run the migrations $start = microtime(true); if (null !== $date) { $this->getManager()->migrateToDateTime(new \DateTime($date)); } else { $this->getManager()->migrate($version); } $end = microtime(true); Output::writeln(''); Output::writeln(Colour::colour('All Done. Took ' . sprintf('%.4fs', $end - $start), Colour::CYAN)); return 0; }
/** * 回滚迁移 * * @param array $args 参数 * @param array $options 选项 */ public function execute(array $args, array $options = []) { $this->bootstrap($args, $options); $version = isset($options['target']) ? $options['target'] : $options['t']; $date = isset($options['date']) ? $options['date'] : $options['d']; $force = isset($options['force']) ? $options['force'] : $options['f']; // rollback the specified environment $start = microtime(true); if (null !== $date) { $this->getManager()->rollbackToDateTime(new \DateTime($date), $force); } else { $this->getManager()->rollback($version, $force); } $end = microtime(true); Output::writeln(''); Output::writeln(Colour::colour('All Done. Took ', Colour::GREEN) . sprintf('%.4fs', $end - $start)); }
/** * 执行 seeders. * * @param array $args 参数 * @param array $options 选项 */ public function execute(array $args, array $options = []) { $this->bootstrap($args, $options); $seedSet = isset($options['seed']) ? $options['seed'] : $options['s']; $start = microtime(true); if (empty($seedSet)) { // run all the seed(ers) $this->getManager()->seed(); } else { is_array($seedSet) || ($seedSet = [$seedSet]); // run seed(ers) specified in a comma-separated list of classes foreach ($seedSet as $seed) { $this->getManager()->seed(trim($seed)); } } $end = microtime(true); Output::writeln(''); Output::writeln(Colour::colour('All Done. Took ' . sprintf('%.4fs', $end - $start), Colour::GREEN)); }
/** * 致命错误捕获 * * @param array $error 错误信息 */ public function fatalError(&$error) { if (Cml::$debug) { $run = new Run(); $run->pushHandler(Request::isCli() ? new PlainTextHandler() : new PrettyPageHandler()); $run->handleException(new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line'])); } else { //正式环境 只显示‘系统错误’并将错误信息记录到日志 Log::emergency('fatal_error', [$error]); $error = []; $error['message'] = Lang::get('_CML_ERROR_'); if (Request::isCli()) { Output::writeException(sprintf("[%s]\n%s", 'Fatal Error', $error['message'])); } else { header('HTTP/1.1 500 Internal Server Error'); View::getEngine('html')->reset()->assign('error', $error); Cml::showSystemTemplate(Config::get('html_exception')); } } exit; }
/** * 向shell输出一条消息 * * @param string $message */ private static function message($message = '') { $message = sprintf("%s %d %d %s", date('Y-m-d H:i:s'), posix_getpid(), posix_getppid(), $message); Output::writeln(Colour::colour($message, Colour::GREEN)); }
/** * 确认对话框 * * <code> * if($dialog->confirm('Are you sure?')) { ... } * if($dialog->confirm('Your choice?', null, ['a', 'b', 'c'])) { ... } * </code> * * @param string $question 问题 * @param array $choices 选项 * @param string $answer 通过的答案 * @param string $default 默认选项 * @param string $errorMessage 错误信息 * * @return bool */ public function confirm($question, array $choices = ['Y', 'n'], $answer = 'y', $default = 'y', $errorMessage = 'Invalid choice') { $text = $question . ' [' . implode('/', $choices) . ']'; $choices = array_map('strtolower', $choices); $answer = strtolower($answer); $default = strtolower($default); do { $input = strtolower($this->ask($text)); if (in_array($input, $choices)) { return $input === $answer; } else { if (empty($input) && !empty($default)) { return $default === $answer; } } Output::writeln($errorMessage); return false; } while (true); }
/** * Parse the config file and load it into the config object * * @param array $options 选项 * * @throws \InvalidArgumentException * * @return void */ protected function loadConfig($options) { if (isset($options['env']) && !in_array($options['env'], ['cli', 'product', 'development'])) { throw new \InvalidArgumentException('option --env\'s value must be [cli, product, development]'); } $env = 'development'; isset($options['env']) && ($env = $options['env']); Output::writeln('using config -- ' . Colour::colour($env, Colour::GREEN)); $this->setConfig(new Config($env)); }
/** * 任务完成 * * @return $this */ public function success() { Output::writeln(); return $this; }
/** * 创建一个迁移 * * @param array $args 参数 * @param array $options 选项 */ public function execute(array $args, array $options = []) { $className = $args[0]; $this->bootstrap($args, $options); if (!Util::isValidPhinxClassName($className)) { throw new \InvalidArgumentException(sprintf('The migration class name "%s" is invalid. Please use CamelCase format.', $className)); } // get the migration path from the config $path = $this->getConfig()->getMigrationPath(); if (!is_dir($path)) { $ask = new Dialog(); if ($ask->confirm(Colour::colour('Create migrations directory?', [Colour::RED, Colour::HIGHLIGHT]))) { mkdir($path, 0755, true); } } $this->verifyMigrationDirectory($path); $path = realpath($path); if (!Util::isUniqueMigrationClassName($className, $path)) { throw new \InvalidArgumentException(sprintf('The migration class name "%s" already exists', $className)); } // Compute the file path $fileName = Util::mapClassNameToFileName($className); $filePath = $path . DIRECTORY_SEPARATOR . $fileName; if (is_file($filePath)) { throw new \InvalidArgumentException(sprintf('The file "%s" already exists', $filePath)); } // Get the alternative template and static class options from the command line, but only allow one of them. $altTemplate = $options['template']; $creationClassName = $options['class']; if ($altTemplate && $creationClassName) { throw new \InvalidArgumentException('Cannot use --template and --class at the same time'); } // Verify the alternative template file's existence. if ($altTemplate && !is_file($altTemplate)) { throw new \InvalidArgumentException(sprintf('The alternative template file "%s" does not exist', $altTemplate)); } if ($creationClassName) { // Supplied class does not exist, is it aliased? if (!class_exists($creationClassName)) { throw new \InvalidArgumentException(sprintf('The class "%s" does not exist', $creationClassName)); } // Does the class implement the required interface? if (!is_subclass_of($creationClassName, self::CREATION_INTERFACE)) { throw new \InvalidArgumentException(sprintf('The class "%s" does not implement the required interface "%s"', $creationClassName, self::CREATION_INTERFACE)); } } // Determine the appropriate mechanism to get the template if ($creationClassName) { // Get the template from the creation class $creationClass = new $creationClassName(); $contents = $creationClass->getMigrationTemplate(); } else { // Load the alternative template if it is defined. $contents = file_get_contents($altTemplate ?: $this->getMigrationTemplateFilename()); } // inject the class names appropriate to this migration $classes = ['$useClassName' => $this->getConfig()->getMigrationBaseClassName(false), '$className' => $className, '$version' => Util::getVersionFromFileName($fileName), '$baseClassName' => $this->getConfig()->getMigrationBaseClassName(true)]; $contents = strtr($contents, $classes); if (false === file_put_contents($filePath, $contents)) { throw new \RuntimeException(sprintf('The file "%s" could not be written to', $path)); } // Do we need to do the post creation call to the creation class? if ($creationClassName) { $creationClass->postMigrationCreation($filePath, $className, $this->getConfig()->getMigrationBaseClassName()); } Output::writeln('using migration base class ' . Colour::colour($classes['$useClassName'], Colour::GREEN)); if (!empty($altTemplate)) { Output::writeln('using alternative template ' . Colour::colour($altTemplate, Colour::GREEN)); } elseif (!empty($creationClassName)) { Output::writeln('using template creation class ' . Colour::colour($creationClassName, Colour::GREEN)); } else { Output::writeln('using default template'); } Output::writeln('created ' . str_replace(Cml::getApplicationDir('secure_src'), '{secure_src}', $filePath)); }
/** * 运行命令 * * @param array|null $argv * * @return mixed */ public function run(array $argv = null) { try { if ($argv === null) { $argv = isset($_SERVER['argv']) ? array_slice($_SERVER['argv'], 1) : []; } list($args, $options) = Input::parse($argv); $command = count($args) ? array_shift($args) : 'help'; if (!isset($this->commands[$command])) { throw new \InvalidArgumentException("Command '{$command}' does not exist"); } isset($options['no-ansi']) && Colour::setNoAnsi(); if (isset($options['h']) || isset($options['help'])) { $help = new Help($this); $help->execute([$command]); exit(0); } $command = explode('::', $this->commands[$command]); return call_user_func_array([new $command[0]($this), isset($command[1]) ? $command[1] : 'execute'], [$args, $options]); } catch (\Exception $e) { Output::writeException($e); exit(1); } }
/** * 格式化输出 * * @param string $text 要输出的内容 * @param array $option 格式化选项 @see Format * * @return $this */ public function writeln($text, $option = []) { Output::writeln($this->format($text, $option)); return $this; }