Task.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. <?php
  2. /**
  3. * Interface that all minion tasks must implement
  4. *
  5. * @package Kohana/Minion
  6. * @author Kohana Team
  7. * @copyright (c) Kohana Team
  8. * @license https://koseven.ga/LICENSE.md
  9. */
  10. abstract class Kohana_Minion_Task {
  11. /**
  12. * The separator used to separate different levels of tasks
  13. * @var string
  14. */
  15. public static $task_separator = ':';
  16. /**
  17. * Converts a task (e.g. db:migrate to a class name)
  18. *
  19. * @param string Task name
  20. * @return string Class name
  21. */
  22. public static function convert_task_to_class_name($task)
  23. {
  24. $task = trim($task);
  25. if (empty($task))
  26. return '';
  27. return 'Task_'.implode('_', array_map('ucfirst', explode(Minion_Task::$task_separator, $task)));
  28. }
  29. /**
  30. * Gets the task name of a task class / task object
  31. *
  32. * @param string|Minion_Task The task class / object
  33. * @return string The task name
  34. */
  35. public static function convert_class_to_task($class)
  36. {
  37. if (is_object($class))
  38. {
  39. $class = get_class($class);
  40. }
  41. return strtolower(str_replace('_', Minion_Task::$task_separator, substr($class, 5)));
  42. }
  43. /**
  44. * Factory for loading minion tasks
  45. *
  46. * @param array An array of command line options. It should contain the 'task' key
  47. * @throws Minion_Exception_InvalidTask
  48. * @return Minion_Task The Minion task
  49. */
  50. public static function factory($options)
  51. {
  52. if (($task = Arr::get($options, 'task')) !== NULL)
  53. {
  54. unset($options['task']);
  55. }
  56. else if (($task = Arr::get($options, 0)) !== NULL)
  57. {
  58. // The first positional argument (aka 0) may be the task name
  59. unset($options[0]);
  60. }
  61. else
  62. {
  63. // If we didn't get a valid task, generate the help
  64. $task = 'help';
  65. }
  66. $class = Minion_Task::convert_task_to_class_name($task);
  67. if ( ! class_exists($class))
  68. {
  69. throw new Minion_Exception_InvalidTask(
  70. "Task ':task' is not a valid minion task",
  71. [':task' => $class]
  72. );
  73. }
  74. $class = new $class;
  75. if ( ! $class instanceof Minion_Task)
  76. {
  77. throw new Minion_Exception_InvalidTask(
  78. "Task ':task' is not a valid minion task",
  79. [':task' => $class]
  80. );
  81. }
  82. $class->set_options($options);
  83. // Show the help page for this task if requested
  84. if (array_key_exists('help', $options))
  85. {
  86. $class->_method = '_help';
  87. }
  88. return $class;
  89. }
  90. /**
  91. * The list of options this task accepts and their default values.
  92. *
  93. * protected $_options = array(
  94. * 'limit' => 4,
  95. * 'table' => NULL,
  96. * );
  97. *
  98. * @var array
  99. */
  100. protected $_options = [];
  101. /**
  102. * Populated with the accepted options for this task.
  103. * This array is automatically populated based on $_options.
  104. *
  105. * @var array
  106. */
  107. protected $_accepted_options = [];
  108. protected $_method = '_execute';
  109. protected function __construct()
  110. {
  111. // Populate $_accepted_options based on keys from $_options
  112. $this->_accepted_options = array_keys($this->_options);
  113. }
  114. /**
  115. * The file that get's passes to Validation::errors() when validation fails
  116. * @var string|NULL
  117. */
  118. protected $_errors_file = 'validation';
  119. /**
  120. * Gets the task name for the task
  121. *
  122. * @return string
  123. */
  124. public function __toString()
  125. {
  126. static $task_name = NULL;
  127. if ($task_name === NULL)
  128. {
  129. $task_name = Minion_Task::convert_class_to_task($this);
  130. }
  131. return $task_name;
  132. }
  133. /**
  134. * Sets options for this task
  135. *
  136. * $param array the array of options to set
  137. * @return this
  138. */
  139. public function set_options(array $options)
  140. {
  141. foreach ($options as $key => $value)
  142. {
  143. $this->_options[$key] = $value;
  144. }
  145. return $this;
  146. }
  147. /**
  148. * Get the options that were passed into this task with their defaults
  149. *
  150. * @return array
  151. */
  152. public function get_options()
  153. {
  154. return (array) $this->_options;
  155. }
  156. /**
  157. * Get a set of options that this task can accept
  158. *
  159. * @return array
  160. */
  161. public function get_accepted_options()
  162. {
  163. return (array) $this->_accepted_options;
  164. }
  165. /**
  166. * Adds any validation rules/labels for validating _options
  167. *
  168. * public function build_validation(Validation $validation)
  169. * {
  170. * return parent::build_validation($validation)
  171. * ->rule('paramname', 'not_empty'); // Require this param
  172. * }
  173. *
  174. * @param Validation the validation object to add rules to
  175. *
  176. * @return Validation
  177. */
  178. public function build_validation(Validation $validation)
  179. {
  180. // Add a rule to each key making sure it's in the task
  181. foreach ($validation->data() as $key => $value)
  182. {
  183. $validation->rule($key, [$this, 'valid_option'], [':validation', ':field']);
  184. }
  185. return $validation;
  186. }
  187. /**
  188. * Returns $_errors_file
  189. *
  190. * @return string
  191. */
  192. public function get_errors_file()
  193. {
  194. return $this->_errors_file;
  195. }
  196. /**
  197. * Execute the task with the specified set of options
  198. *
  199. * @return null
  200. */
  201. public function execute()
  202. {
  203. $options = $this->get_options();
  204. // Validate $options
  205. $validation = Validation::factory($options);
  206. $validation = $this->build_validation($validation);
  207. if ( $this->_method != '_help' AND ! $validation->check())
  208. {
  209. echo View::factory('minion/error/validation')
  210. ->set('task', Minion_Task::convert_class_to_task($this))
  211. ->set('errors', $validation->errors($this->get_errors_file()));
  212. }
  213. else
  214. {
  215. // Finally, run the task
  216. $method = $this->_method;
  217. echo $this->{$method}($options);
  218. }
  219. }
  220. abstract protected function _execute(array $params);
  221. /**
  222. * Outputs help for this task
  223. *
  224. * @return null
  225. */
  226. protected function _help(array $params)
  227. {
  228. $tasks = $this->_compile_task_list(Kohana::list_files('classes/task'));
  229. $inspector = new ReflectionClass($this);
  230. list($description, $tags) = $this->_parse_doccomment($inspector->getDocComment());
  231. $view = View::factory('minion/help/task')
  232. ->set('description', $description)
  233. ->set('tags', (array) $tags)
  234. ->set('task', Minion_Task::convert_class_to_task($this));
  235. echo $view;
  236. }
  237. public function valid_option(Validation $validation, $option)
  238. {
  239. if ( ! in_array($option, $this->_accepted_options))
  240. {
  241. $validation->error($option, 'minion_option');
  242. }
  243. }
  244. /**
  245. * Parses a doccomment, extracting both the comment and any tags associated
  246. *
  247. * Based on the code in Kodoc::parse()
  248. *
  249. * @param string The comment to parse
  250. * @return array First element is the comment, second is an array of tags
  251. */
  252. protected function _parse_doccomment($comment)
  253. {
  254. // Normalize all new lines to \n
  255. $comment = str_replace(["\r\n", "\n"], "\n", $comment);
  256. // Remove the phpdoc open/close tags and split
  257. $comment = array_slice(explode("\n", $comment), 1, -1);
  258. // Tag content
  259. $tags = [];
  260. foreach ($comment as $i => $line)
  261. {
  262. // Remove all leading whitespace
  263. $line = preg_replace('/^\s*\* ?/m', '', $line);
  264. // Search this line for a tag
  265. if (preg_match('/^@(\S+)(?:\s*(.+))?$/', $line, $matches))
  266. {
  267. // This is a tag line
  268. unset($comment[$i]);
  269. $name = $matches[1];
  270. $text = isset($matches[2]) ? $matches[2] : '';
  271. $tags[$name] = $text;
  272. }
  273. else
  274. {
  275. $comment[$i] = (string) $line;
  276. }
  277. }
  278. $comment = trim(implode("\n", $comment));
  279. return [$comment, $tags];
  280. }
  281. /**
  282. * Compiles a list of available tasks from a directory structure
  283. *
  284. * @param array Directory structure of tasks
  285. * @param string prefix
  286. * @return array Compiled tasks
  287. */
  288. protected function _compile_task_list(array $files, $prefix = '')
  289. {
  290. $output = [];
  291. foreach ($files as $file => $path)
  292. {
  293. $file = substr($file, strrpos($file, DIRECTORY_SEPARATOR) + 1);
  294. if (is_array($path) AND count($path))
  295. {
  296. $task = $this->_compile_task_list($path, $prefix.$file.Minion_Task::$task_separator);
  297. if ($task)
  298. {
  299. $output = array_merge($output, $task);
  300. }
  301. }
  302. else
  303. {
  304. $output[] = strtolower($prefix.substr($file, 0, -strlen(EXT)));
  305. }
  306. }
  307. return $output;
  308. }
  309. }