GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — develop (#163)
by
unknown
09:22
created
myth/CIModules/database/controllers/Database.php 1 patch
Indentation   +224 added lines, -224 removed lines patch added patch discarded remove patch
@@ -35,207 +35,207 @@  discard block
 block discarded – undo
35 35
 class Database extends \Myth\Controllers\CLIController
36 36
 {
37 37
 
38
-    protected $descriptions = [
39
-        'migrate'       => ['migrate [$to]',        'Runs the migrations up or down until schema at version \$to'],
40
-        'quietMigrate'  => ['quiteMigrate [$to]',   'Same as migrate but without any feedback.'],
41
-        'refresh'       => ['refresh',              'Runs migrations back to version 0 (uninstall) and then back to the most recent migration.'],
42
-        'newMigration'  => ['newMigration [$name]', 'Creates a new migration file.'],
43
-        'seed'          => ['seed [$name]',         'Runs the named database seeder.']
44
-    ];
45
-
46
-    protected $long_descriptions = [
47
-        'migrate'       => '',
48
-        'quietMigrate'  => '',
49
-        'refresh'       => '',
50
-        'newMigration'  => '',
51
-        'seed'          => ''
52
-    ];
53
-
54
-    //-------------------------------------------------------------------
55
-
56
-    //--------------------------------------------------------------------
57
-    // Migration Methods
58
-    //--------------------------------------------------------------------
59
-
60
-    /**
61
-     * Provides a command-line interface to the migration scripts.
62
-     * If no $to is provided, will migrate to the latest version.
63
-     *
64
-     * Example:
65
-     *      > php index.php database migrate
66
-     *
67
-     * @param string $type 'app', 'myth', 'all' or {module_name}
68
-     * @param null $to
69
-     * @param bool $silent If TRUE, will NOT display any prompts for verification.
70
-     * @return bool|void
71
-     */
72
-    public function migrate($type=null, $to = null, $silent = false)
73
-    {
74
-        $this->load->library('migration');
75
-
76
-        if (empty($type))
77
-        {
78
-            $type = CLI::prompt("Migration group to refresh?", $this->migration->default_migration_path());
79
-
80
-            if (empty($type))
81
-            {
82
-                return $silent ? false : CLI::error("\tYou must supply a group to refresh.");
83
-            }
84
-        }
85
-
86
-        // We need to append 'mod:' to properly handle modules, if
87
-        // the $type is not one of the recognized migration groups.
88
-        $this->config->load('migration');
89
-        $groups = config_item('migration_paths');
90
-        $groups = array_keys($groups);
91
-
92
-        // If it's not in the groups list, then assume it's a module.
93
-        if (! in_array($type, $groups))
94
-        {
95
-            if (strpos($type, 'mod:') !== 0)
96
-            {
97
-                $type = 'mod:'. $type;
98
-            }
99
-        }
100
-
101
-        unset($groups);
102
-
103
-        // Get our stats on the migrations
104
-        $latest = $this->migration->get_latest($type);
105
-        $latest = empty($latest) ? 0 : substr($latest, 0, strpos($latest, '_'));
106
-
107
-        if (empty($latest)) {
108
-            return CLI::write("\tNo migrations found.", 'yellow');
109
-        }
110
-
111
-        $current = $this->migration->get_version($type);
112
-
113
-        // Already at the desired version?
114
-        if ((! is_null($to) && $current == $to) OR (is_null($to) && $current == $latest))
115
-        {
116
-            return $silent ? true : CLI::write("\tDatabase is already at the desired version ({$current})", 'yellow');
117
-        }
118
-
119
-        $target = is_null($to) ? $latest : $to;
120
-
121
-        // Just to be safe, verify with the user they want to migrate
122
-        // to the latest version.
123
-        if (is_null($to)) {
124
-            // If we're in silent mode, don't prompt, just go to the latest...
125
-            if (! $silent) {
126
-                $go_ahead = CLI::prompt('Migrate to the latest available version?', array('y', 'n'));
127
-
128
-                if ($go_ahead == 'n') {
129
-                    return CLI::write('Bailing...', 'yellow');
130
-                }
131
-            }
132
-
133
-            if (! $this->migration->latest($type)) {
134
-                return CLI::error("\n\tERROR: " . $this->migration->error_string() . "\n");
135
-            }
136
-        } else {
137
-            if ($this->migration->version($type, $to) === false) {
138
-                return CLI::error("\n\tERROR: " . $this->migration->error_string() . "\n");
139
-            }
140
-        }
141
-
142
-        return $silent ? true :
143
-            CLI::write("\n\tSuccessfully migrated database from version {$current} to {$target}.\n", 'green');
144
-    }
145
-
146
-    //--------------------------------------------------------------------
147
-
148
-    /**
149
-     * Performs a migration that does not prompt for any information.
150
-     * Suitable for use within automated scripts that can't be
151
-     * bothered with answering questions.
152
-     *
153
-     * @param string $type 'app', 'myth', 'all' or {module_name}
154
-     * @param null $to
155
-     * @return bool|void
156
-     */
157
-    public function quietMigrate($type='app', $to = null)
158
-    {
159
-        return $this->migrate($type, $to, true);
160
-    }
161
-
162
-    //--------------------------------------------------------------------
163
-
164
-
165
-    /**
166
-     * Migrates the database back to 0, then back up to the latest version.
167
-     *
168
-     * @param string $type  The group or module to refresh.
169
-     * @return mixed
170
-     */
171
-    public function refresh($type=null)
172
-    {
173
-        $this->load->library('migration');
174
-
175
-        if (empty($type))
176
-        {
177
-            $type = CLI::prompt("Migration group to refresh?", $this->migration->default_migration_path());
178
-
179
-            if (empty($type))
180
-            {
181
-                return CLI::error("\tYou must supply a group to refresh.");
182
-            }
183
-        }
184
-
185
-        if ($this->migration->version($type, 0) === false) {
186
-            return CLI::error("\tERROR: " . $this->migration->error_string());
187
-        }
188
-
189
-        CLI::write(CLI::color("\tCleared the database.", 'green'));
190
-
191
-        if ($this->migration->latest($type) === false) {
192
-            return CLI::error("\tERROR: " . $this->migration->error_string());
193
-        }
194
-
195
-        CLI::write("\tRe-installed the database to the latest migration.", 'green');
196
-    }
197
-
198
-    //--------------------------------------------------------------------
199
-
200
-    /**
201
-     * Creates a new migration file ready to be used.
202
-     *
203
-     * @param $name
204
-     */
205
-    public function newMigration($name = null, $type = 'app')
206
-    {
207
-        if (empty($name)) {
208
-            $name = CLI::prompt('Migration name? ');
209
-
210
-            if (empty($name)) {
211
-                return CLI::error("\tYou must provide a migration name.", 'red');
212
-            }
213
-        }
214
-
215
-        $this->load->library('migration');
216
-
217
-        $path = $this->migration->determine_migration_path($type);
218
-
219
-        // Does the alias path exist in our config?
220
-        if (! $path) {
221
-            return CLI::error("\tThe migration path for '{$type}' does not exist.'");
222
-        }
223
-
224
-        // Does the path really exist?
225
-        if (! is_dir($path)) {
226
-            return CLI::error("\tThe path for '{$type}' is not a directory.");
227
-        }
228
-
229
-        // Is the folder writeable?
230
-        if (! is_writeable($path)) {
231
-            return CLI::error("\tThe folder for '{$type}' migrations is not writeable.");
232
-        }
233
-
234
-        $file = $this->migration->make_name($name);
235
-
236
-        $path = rtrim($path, '/') .'/'. $file;
237
-
238
-        $contents = <<<EOT
38
+	protected $descriptions = [
39
+		'migrate'       => ['migrate [$to]',        'Runs the migrations up or down until schema at version \$to'],
40
+		'quietMigrate'  => ['quiteMigrate [$to]',   'Same as migrate but without any feedback.'],
41
+		'refresh'       => ['refresh',              'Runs migrations back to version 0 (uninstall) and then back to the most recent migration.'],
42
+		'newMigration'  => ['newMigration [$name]', 'Creates a new migration file.'],
43
+		'seed'          => ['seed [$name]',         'Runs the named database seeder.']
44
+	];
45
+
46
+	protected $long_descriptions = [
47
+		'migrate'       => '',
48
+		'quietMigrate'  => '',
49
+		'refresh'       => '',
50
+		'newMigration'  => '',
51
+		'seed'          => ''
52
+	];
53
+
54
+	//-------------------------------------------------------------------
55
+
56
+	//--------------------------------------------------------------------
57
+	// Migration Methods
58
+	//--------------------------------------------------------------------
59
+
60
+	/**
61
+	 * Provides a command-line interface to the migration scripts.
62
+	 * If no $to is provided, will migrate to the latest version.
63
+	 *
64
+	 * Example:
65
+	 *      > php index.php database migrate
66
+	 *
67
+	 * @param string $type 'app', 'myth', 'all' or {module_name}
68
+	 * @param null $to
69
+	 * @param bool $silent If TRUE, will NOT display any prompts for verification.
70
+	 * @return bool|void
71
+	 */
72
+	public function migrate($type=null, $to = null, $silent = false)
73
+	{
74
+		$this->load->library('migration');
75
+
76
+		if (empty($type))
77
+		{
78
+			$type = CLI::prompt("Migration group to refresh?", $this->migration->default_migration_path());
79
+
80
+			if (empty($type))
81
+			{
82
+				return $silent ? false : CLI::error("\tYou must supply a group to refresh.");
83
+			}
84
+		}
85
+
86
+		// We need to append 'mod:' to properly handle modules, if
87
+		// the $type is not one of the recognized migration groups.
88
+		$this->config->load('migration');
89
+		$groups = config_item('migration_paths');
90
+		$groups = array_keys($groups);
91
+
92
+		// If it's not in the groups list, then assume it's a module.
93
+		if (! in_array($type, $groups))
94
+		{
95
+			if (strpos($type, 'mod:') !== 0)
96
+			{
97
+				$type = 'mod:'. $type;
98
+			}
99
+		}
100
+
101
+		unset($groups);
102
+
103
+		// Get our stats on the migrations
104
+		$latest = $this->migration->get_latest($type);
105
+		$latest = empty($latest) ? 0 : substr($latest, 0, strpos($latest, '_'));
106
+
107
+		if (empty($latest)) {
108
+			return CLI::write("\tNo migrations found.", 'yellow');
109
+		}
110
+
111
+		$current = $this->migration->get_version($type);
112
+
113
+		// Already at the desired version?
114
+		if ((! is_null($to) && $current == $to) OR (is_null($to) && $current == $latest))
115
+		{
116
+			return $silent ? true : CLI::write("\tDatabase is already at the desired version ({$current})", 'yellow');
117
+		}
118
+
119
+		$target = is_null($to) ? $latest : $to;
120
+
121
+		// Just to be safe, verify with the user they want to migrate
122
+		// to the latest version.
123
+		if (is_null($to)) {
124
+			// If we're in silent mode, don't prompt, just go to the latest...
125
+			if (! $silent) {
126
+				$go_ahead = CLI::prompt('Migrate to the latest available version?', array('y', 'n'));
127
+
128
+				if ($go_ahead == 'n') {
129
+					return CLI::write('Bailing...', 'yellow');
130
+				}
131
+			}
132
+
133
+			if (! $this->migration->latest($type)) {
134
+				return CLI::error("\n\tERROR: " . $this->migration->error_string() . "\n");
135
+			}
136
+		} else {
137
+			if ($this->migration->version($type, $to) === false) {
138
+				return CLI::error("\n\tERROR: " . $this->migration->error_string() . "\n");
139
+			}
140
+		}
141
+
142
+		return $silent ? true :
143
+			CLI::write("\n\tSuccessfully migrated database from version {$current} to {$target}.\n", 'green');
144
+	}
145
+
146
+	//--------------------------------------------------------------------
147
+
148
+	/**
149
+	 * Performs a migration that does not prompt for any information.
150
+	 * Suitable for use within automated scripts that can't be
151
+	 * bothered with answering questions.
152
+	 *
153
+	 * @param string $type 'app', 'myth', 'all' or {module_name}
154
+	 * @param null $to
155
+	 * @return bool|void
156
+	 */
157
+	public function quietMigrate($type='app', $to = null)
158
+	{
159
+		return $this->migrate($type, $to, true);
160
+	}
161
+
162
+	//--------------------------------------------------------------------
163
+
164
+
165
+	/**
166
+	 * Migrates the database back to 0, then back up to the latest version.
167
+	 *
168
+	 * @param string $type  The group or module to refresh.
169
+	 * @return mixed
170
+	 */
171
+	public function refresh($type=null)
172
+	{
173
+		$this->load->library('migration');
174
+
175
+		if (empty($type))
176
+		{
177
+			$type = CLI::prompt("Migration group to refresh?", $this->migration->default_migration_path());
178
+
179
+			if (empty($type))
180
+			{
181
+				return CLI::error("\tYou must supply a group to refresh.");
182
+			}
183
+		}
184
+
185
+		if ($this->migration->version($type, 0) === false) {
186
+			return CLI::error("\tERROR: " . $this->migration->error_string());
187
+		}
188
+
189
+		CLI::write(CLI::color("\tCleared the database.", 'green'));
190
+
191
+		if ($this->migration->latest($type) === false) {
192
+			return CLI::error("\tERROR: " . $this->migration->error_string());
193
+		}
194
+
195
+		CLI::write("\tRe-installed the database to the latest migration.", 'green');
196
+	}
197
+
198
+	//--------------------------------------------------------------------
199
+
200
+	/**
201
+	 * Creates a new migration file ready to be used.
202
+	 *
203
+	 * @param $name
204
+	 */
205
+	public function newMigration($name = null, $type = 'app')
206
+	{
207
+		if (empty($name)) {
208
+			$name = CLI::prompt('Migration name? ');
209
+
210
+			if (empty($name)) {
211
+				return CLI::error("\tYou must provide a migration name.", 'red');
212
+			}
213
+		}
214
+
215
+		$this->load->library('migration');
216
+
217
+		$path = $this->migration->determine_migration_path($type);
218
+
219
+		// Does the alias path exist in our config?
220
+		if (! $path) {
221
+			return CLI::error("\tThe migration path for '{$type}' does not exist.'");
222
+		}
223
+
224
+		// Does the path really exist?
225
+		if (! is_dir($path)) {
226
+			return CLI::error("\tThe path for '{$type}' is not a directory.");
227
+		}
228
+
229
+		// Is the folder writeable?
230
+		if (! is_writeable($path)) {
231
+			return CLI::error("\tThe folder for '{$type}' migrations is not writeable.");
232
+		}
233
+
234
+		$file = $this->migration->make_name($name);
235
+
236
+		$path = rtrim($path, '/') .'/'. $file;
237
+
238
+		$contents = <<<EOT
239 239
 <?php
240 240
 
241 241
 /**
@@ -262,36 +262,36 @@  discard block
 block discarded – undo
262 262
 
263 263
 }
264 264
 EOT;
265
-        $contents = str_replace('{name}', $name, $contents);
266
-        $contents = str_replace('{date}', date('Y-m-d H:i:s a'), $contents);
267
-        $contents = str_replace('{clean_name}', ucwords(str_replace('_', ' ', $name)), $contents);
265
+		$contents = str_replace('{name}', $name, $contents);
266
+		$contents = str_replace('{date}', date('Y-m-d H:i:s a'), $contents);
267
+		$contents = str_replace('{clean_name}', ucwords(str_replace('_', ' ', $name)), $contents);
268 268
 
269
-        $this->load->helper('file');
269
+		$this->load->helper('file');
270 270
 
271
-        if (write_file($path, $contents)) {
272
-            return CLI::write("\tNew migration created: " . CLI::color($file, 'yellow'), 'green');
273
-        }
271
+		if (write_file($path, $contents)) {
272
+			return CLI::write("\tNew migration created: " . CLI::color($file, 'yellow'), 'green');
273
+		}
274 274
 
275
-        return CLI::error("\tUnkown error trying to create migration: {$file}", 'red');
276
-    }
275
+		return CLI::error("\tUnkown error trying to create migration: {$file}", 'red');
276
+	}
277 277
 
278
-    //--------------------------------------------------------------------
278
+	//--------------------------------------------------------------------
279 279
 
280
-    //--------------------------------------------------------------------
281
-    // Seeding Methods
282
-    //--------------------------------------------------------------------
280
+	//--------------------------------------------------------------------
281
+	// Seeding Methods
282
+	//--------------------------------------------------------------------
283 283
 
284
-    /**
285
-     * Installs any database seeds stored in database/seeds. Seeds just need to
286
-     * extend the Seeder class and have a method named run.
287
-     */
288
-    public function seed($name = null)
289
-    {
290
-        $this->load->library('seeder');
284
+	/**
285
+	 * Installs any database seeds stored in database/seeds. Seeds just need to
286
+	 * extend the Seeder class and have a method named run.
287
+	 */
288
+	public function seed($name = null)
289
+	{
290
+		$this->load->library('seeder');
291 291
 
292
-        $this->seeder->call($name);
293
-    }
292
+		$this->seeder->call($name);
293
+	}
294 294
 
295
-    //--------------------------------------------------------------------
295
+	//--------------------------------------------------------------------
296 296
 
297 297
 }
Please login to merge, or discard this patch.
myth/CIModules/database/libraries/Seeder.php 1 patch
Indentation   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -39,92 +39,92 @@
 block discarded – undo
39 39
  */
40 40
 class Seeder {
41 41
 
42
-    public $error_string    = '';
42
+	public $error_string    = '';
43 43
 
44
-    protected $ci;
44
+	protected $ci;
45 45
 
46
-    protected $is_cli = false;
46
+	protected $is_cli = false;
47 47
 
48
-    protected $db;
49
-    protected $dbforge;
48
+	protected $db;
49
+	protected $dbforge;
50 50
 
51
-    //--------------------------------------------------------------------
51
+	//--------------------------------------------------------------------
52 52
 
53
-    public function __construct ()
54
-    {
55
-        $this->ci =& get_instance();
53
+	public function __construct ()
54
+	{
55
+		$this->ci =& get_instance();
56 56
 
57
-        $this->is_cli = $this->ci->input->is_cli_request();
57
+		$this->is_cli = $this->ci->input->is_cli_request();
58 58
 
59
-        if ($this->is_cli)
60
-        {
61
-            $cli = new CLI();
62
-            $cli::_init();
63
-        }
59
+		if ($this->is_cli)
60
+		{
61
+			$cli = new CLI();
62
+			$cli::_init();
63
+		}
64 64
 
65
-        $this->ci->load->dbforge();
65
+		$this->ci->load->dbforge();
66 66
 
67
-        // Setup some convenience vars.
68
-        $this->db       =& $this->ci->db;
69
-        $this->dbforge  =& $this->ci->dbforge;
70
-    }
67
+		// Setup some convenience vars.
68
+		$this->db       =& $this->ci->db;
69
+		$this->dbforge  =& $this->ci->dbforge;
70
+	}
71 71
 
72
-    //--------------------------------------------------------------------
72
+	//--------------------------------------------------------------------
73 73
 
74 74
 
75
-    /**
76
-     * Run the database seeds. It's where the magic happens.
77
-     * This method MUST be overridden by child classes.
78
-     */
79
-    public function run ()
80
-    {
75
+	/**
76
+	 * Run the database seeds. It's where the magic happens.
77
+	 * This method MUST be overridden by child classes.
78
+	 */
79
+	public function run ()
80
+	{
81 81
 
82
-    }
82
+	}
83 83
 
84
-    //--------------------------------------------------------------------
84
+	//--------------------------------------------------------------------
85 85
 
86
-    /**
87
-     * Loads the class file and calls the run() method
88
-     * on the class.
89
-     *
90
-     * @param $class
91
-     */
92
-    public function call ($class)
93
-    {
94
-        if (empty($class))
95
-        {
96
-            // Ask the user...
97
-            $class = trim( CLI::prompt("Seeder name") );
86
+	/**
87
+	 * Loads the class file and calls the run() method
88
+	 * on the class.
89
+	 *
90
+	 * @param $class
91
+	 */
92
+	public function call ($class)
93
+	{
94
+		if (empty($class))
95
+		{
96
+			// Ask the user...
97
+			$class = trim( CLI::prompt("Seeder name") );
98 98
 
99
-            if (empty($class)) {
100
-                return CLI::error("\tNo Seeder was specified.");
101
-            }
102
-        }
99
+			if (empty($class)) {
100
+				return CLI::error("\tNo Seeder was specified.");
101
+			}
102
+		}
103 103
 
104
-        $path = APPPATH .'database/seeds/'. str_replace('.php', '', $class) .'.php';
104
+		$path = APPPATH .'database/seeds/'. str_replace('.php', '', $class) .'.php';
105 105
 
106
-        if ( ! is_file($path))
107
-        {
108
-            return CLI::error("\tUnable to find seed class: ". $class);
109
-        }
106
+		if ( ! is_file($path))
107
+		{
108
+			return CLI::error("\tUnable to find seed class: ". $class);
109
+		}
110 110
 
111
-        try {
112
-            require $path;
111
+		try {
112
+			require $path;
113 113
 
114
-            $seeder = new $class();
114
+			$seeder = new $class();
115 115
 
116
-            $seeder->run();
116
+			$seeder->run();
117 117
 
118
-            unset($seeder);
119
-        }
120
-        catch (\Exception $e)
121
-        {
122
-            show_error($e->getMessage(), $e->getCode());
123
-        }
118
+			unset($seeder);
119
+		}
120
+		catch (\Exception $e)
121
+		{
122
+			show_error($e->getMessage(), $e->getCode());
123
+		}
124 124
 
125
-        return Cli::write("\tSeeded: $class", 'green');
126
-    }
125
+		return Cli::write("\tSeeded: $class", 'green');
126
+	}
127 127
 
128
-    //--------------------------------------------------------------------
128
+	//--------------------------------------------------------------------
129 129
 
130 130
 }
Please login to merge, or discard this patch.
myth/CIModules/docs/config/docs.php 1 patch
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -57,8 +57,8 @@
 block discarded – undo
57 57
 | if realpath cannot find/read the folder.
58 58
 */
59 59
 $config['docs.folders'] = [
60
-    'application'   => APPPATH .'docs',
61
-    'developer'     => APPPATH .'../myth/_docs_src'
60
+	'application'   => APPPATH .'docs',
61
+	'developer'     => APPPATH .'../myth/_docs_src'
62 62
 ];
63 63
 
64 64
 /*
Please login to merge, or discard this patch.
myth/CIModules/forge/controllers/Forge.php 1 patch
Indentation   +168 added lines, -168 removed lines patch added patch discarded remove patch
@@ -34,133 +34,133 @@  discard block
 block discarded – undo
34 34
 
35 35
 class Forge extends \Myth\Controllers\CLIController {
36 36
 
37
-    public function __construct()
38
-    {
39
-        parent::__construct();
37
+	public function __construct()
38
+	{
39
+		parent::__construct();
40 40
 
41
-        $this->load->config('forge');
42
-    }
41
+		$this->load->config('forge');
42
+	}
43 43
 
44
-    //--------------------------------------------------------------------
44
+	//--------------------------------------------------------------------
45 45
 
46 46
 
47
-    public function _remap($method, $params)
48
-    {
49
-        if (method_exists($this, $method))
50
-        {
51
-            call_user_func_array( [$this, $method], $params);
52
-        }
53
-        else
54
-        {
55
-	        $params = array_merge([CLI::cli_string()], $params);
47
+	public function _remap($method, $params)
48
+	{
49
+		if (method_exists($this, $method))
50
+		{
51
+			call_user_func_array( [$this, $method], $params);
52
+		}
53
+		else
54
+		{
55
+			$params = array_merge([CLI::cli_string()], $params);
56 56
 
57
-            call_user_func_array( [$this, 'run'], $params);
58
-        }
59
-    }
57
+			call_user_func_array( [$this, 'run'], $params);
58
+		}
59
+	}
60 60
     
61
-    //--------------------------------------------------------------------
62
-
63
-    /**
64
-     * Overrides to implement dynamic description building based on
65
-     * scanning the collections and grabbing the information from
66
-     * 'forge.php' files.
67
-     */
68
-    public function index()
69
-    {
70
-        $collections = config_item('forge.collections');
71
-
72
-        if (! is_array($collections) || ! count($collections) )
73
-        {
74
-            return CLI::error('No generator collections found.');
75
-        }
76
-
77
-        // We loop through each collection scanning
78
-        // for any generator folders that have a
79
-        // 'forge.php' file. For each one found
80
-        // we build out another section in our help commands
81
-        foreach ($collections as $alias => $path)
82
-        {
83
-            $path = rtrim($path, '/ ') .'/';
84
-            $folders = scandir($path);
85
-
86
-            $_descriptions = [];
87
-
88
-            foreach ($folders as $dir)
89
-            {
90
-                if ($dir == '.' || $dir == '..' || ! is_file($path . $dir .'/forge.php'))
91
-                {
92
-                    continue;
93
-                }
94
-
95
-                include $path . $dir .'/forge.php';
96
-
97
-                // Don't have valid arrays to work with? Move along...
98
-                if (! isset($descriptions))
99
-                {
100
-                    log_message('debug', '[Forge] Invalid forge.php file at: '. $path . $dir .'/forge.php');
101
-                    continue;
102
-                }
103
-
104
-                $_descriptions = array_merge($descriptions, $_descriptions);
105
-            }
106
-
107
-	        ksort($_descriptions);
108
-
109
-            CLI::new_line();
110
-            CLI::write(ucwords( str_replace('_', ' ', $alias)) .' Collection');
111
-            $this->sayDescriptions($_descriptions);
112
-        }
113
-    }
114
-
115
-    //--------------------------------------------------------------------
116
-
117
-    /**
118
-     * The primary method that calls the correct generator and
119
-     * makes it run.
120
-     */
121
-    public function run($command)
122
-    {
123
-	    $quiet = false;
124
-
125
-	    $segments = explode(" ", $command);
126
-
127
-	    // Get rid of the 'forge' command
128
-	    if ($segments[0] == 'forge') {
129
-		    array_shift( $segments );
130
-	    }
131
-
132
-	    $command = trim(str_ireplace("forge", '', array_shift($segments)));
61
+	//--------------------------------------------------------------------
62
+
63
+	/**
64
+	 * Overrides to implement dynamic description building based on
65
+	 * scanning the collections and grabbing the information from
66
+	 * 'forge.php' files.
67
+	 */
68
+	public function index()
69
+	{
70
+		$collections = config_item('forge.collections');
71
+
72
+		if (! is_array($collections) || ! count($collections) )
73
+		{
74
+			return CLI::error('No generator collections found.');
75
+		}
76
+
77
+		// We loop through each collection scanning
78
+		// for any generator folders that have a
79
+		// 'forge.php' file. For each one found
80
+		// we build out another section in our help commands
81
+		foreach ($collections as $alias => $path)
82
+		{
83
+			$path = rtrim($path, '/ ') .'/';
84
+			$folders = scandir($path);
85
+
86
+			$_descriptions = [];
87
+
88
+			foreach ($folders as $dir)
89
+			{
90
+				if ($dir == '.' || $dir == '..' || ! is_file($path . $dir .'/forge.php'))
91
+				{
92
+					continue;
93
+				}
94
+
95
+				include $path . $dir .'/forge.php';
96
+
97
+				// Don't have valid arrays to work with? Move along...
98
+				if (! isset($descriptions))
99
+				{
100
+					log_message('debug', '[Forge] Invalid forge.php file at: '. $path . $dir .'/forge.php');
101
+					continue;
102
+				}
103
+
104
+				$_descriptions = array_merge($descriptions, $_descriptions);
105
+			}
106
+
107
+			ksort($_descriptions);
108
+
109
+			CLI::new_line();
110
+			CLI::write(ucwords( str_replace('_', ' ', $alias)) .' Collection');
111
+			$this->sayDescriptions($_descriptions);
112
+		}
113
+	}
114
+
115
+	//--------------------------------------------------------------------
116
+
117
+	/**
118
+	 * The primary method that calls the correct generator and
119
+	 * makes it run.
120
+	 */
121
+	public function run($command)
122
+	{
123
+		$quiet = false;
124
+
125
+		$segments = explode(" ", $command);
126
+
127
+		// Get rid of the 'forge' command
128
+		if ($segments[0] == 'forge') {
129
+			array_shift( $segments );
130
+		}
131
+
132
+		$command = trim(str_ireplace("forge", '', array_shift($segments)));
133 133
 
134 134
 		$dir = $this->locateGenerator($command);
135 135
 
136 136
 		$class_name = ucfirst($command) .'Generator';
137 137
 
138
-	    if (! file_exists($dir . $class_name .'.php'))
139
-	    {
140
-		    return CLI::error("Generator file not found for: {$class_name}");
141
-	    }
138
+		if (! file_exists($dir . $class_name .'.php'))
139
+		{
140
+			return CLI::error("Generator file not found for: {$class_name}");
141
+		}
142 142
 
143 143
 		require_once $dir . $class_name .'.php';
144 144
 
145
-	    if (! class_exists($class_name, false))
146
-	    {
147
-		    return CLI::error("No class `{$class_name}` found in generator file.");
148
-	    }
145
+		if (! class_exists($class_name, false))
146
+		{
147
+			return CLI::error("No class `{$class_name}` found in generator file.");
148
+		}
149 149
 
150
-	    // Should we run the process quietly?
151
-	    if ( (CLI::option('q') || CLI::option('quiet')))
152
-	    {
153
-		    $quiet = true;
154
-	    }
150
+		// Should we run the process quietly?
151
+		if ( (CLI::option('q') || CLI::option('quiet')))
152
+		{
153
+			$quiet = true;
154
+		}
155 155
 
156
-	    CLI::write('Invoked '. CLI::color($class_name, 'yellow'));
156
+		CLI::write('Invoked '. CLI::color($class_name, 'yellow'));
157 157
 
158 158
 		$class = new $class_name();
159 159
 
160
-	    $class->run( $segments, $quiet );
161
-    }
160
+		$class->run( $segments, $quiet );
161
+	}
162 162
 
163
-    //--------------------------------------------------------------------
163
+	//--------------------------------------------------------------------
164 164
 
165 165
 	/**
166 166
 	 * Displays the readme file for a generator if it exists.
@@ -205,67 +205,67 @@  discard block
 block discarded – undo
205 205
 	//--------------------------------------------------------------------
206 206
 
207 207
 
208
-    /**
209
-     * Overrides CLIController's version to support searching our
210
-     * collections for the help description.
211
-     *
212
-     * @param null $method
213
-     */
214
-    public function longDescribeMethod($method=null)
215
-    {
216
-	    $collections = config_item('forge.collections');
217
-
218
-	    if (! is_array($collections) || ! count($collections) )
219
-	    {
220
-		    return CLI::error('No generator collections found.');
221
-	    }
222
-
223
-	    // We loop through each collection scanning
224
-	    // for any generator folders that have a
225
-	    // 'forge.php' file. For each one found
226
-	    // we build out another section in our help commands
227
-	    foreach ($collections as $alias => $path)
228
-	    {
229
-
230
-		    $path = rtrim($path, '/ ') .'/';
231
-		    $folders = scandir($path);
232
-
233
-		    if (! $i = array_search(ucfirst($method), $folders))
234
-		    {
235
-			    continue;
236
-		    }
237
-
238
-		    $dir = $path . $folders[$i] .'/';
239
-
240
-		    if (! is_file($dir .'/forge.php'))
241
-		    {
242
-			    CLI::error("The {$method} command does not have any cli help available.");
243
-		    }
244
-
245
-		    include $dir .'/forge.php';
246
-
247
-		    // Don't have valid arrays to work with? Move along...
248
-		    if (! isset($long_description))
249
-		    {
250
-			    log_message('debug', '[Forge] Invalid forge.php file at: '. $dir .'/forge.php');
251
-			    continue;
252
-		    }
253
-
254
-		    if (empty($long_description))
255
-		    {
256
-			    return CLI::error("The {$method} command does not have an cli help available.");
257
-		    }
258
-
259
-		    CLI::new_line();
260
-		    CLI::write( CLI::color(ucfirst($method) .' Help', 'yellow') );
261
-		    return CLI::write( CLI::wrap($long_description, CLI::getWidth()) );
262
-	    }
263
-
264
-	    // Still here?
265
-	    CLI::error("No help found for command: {$method}");
266
-    }
267
-
268
-    //--------------------------------------------------------------------
208
+	/**
209
+	 * Overrides CLIController's version to support searching our
210
+	 * collections for the help description.
211
+	 *
212
+	 * @param null $method
213
+	 */
214
+	public function longDescribeMethod($method=null)
215
+	{
216
+		$collections = config_item('forge.collections');
217
+
218
+		if (! is_array($collections) || ! count($collections) )
219
+		{
220
+			return CLI::error('No generator collections found.');
221
+		}
222
+
223
+		// We loop through each collection scanning
224
+		// for any generator folders that have a
225
+		// 'forge.php' file. For each one found
226
+		// we build out another section in our help commands
227
+		foreach ($collections as $alias => $path)
228
+		{
229
+
230
+			$path = rtrim($path, '/ ') .'/';
231
+			$folders = scandir($path);
232
+
233
+			if (! $i = array_search(ucfirst($method), $folders))
234
+			{
235
+				continue;
236
+			}
237
+
238
+			$dir = $path . $folders[$i] .'/';
239
+
240
+			if (! is_file($dir .'/forge.php'))
241
+			{
242
+				CLI::error("The {$method} command does not have any cli help available.");
243
+			}
244
+
245
+			include $dir .'/forge.php';
246
+
247
+			// Don't have valid arrays to work with? Move along...
248
+			if (! isset($long_description))
249
+			{
250
+				log_message('debug', '[Forge] Invalid forge.php file at: '. $dir .'/forge.php');
251
+				continue;
252
+			}
253
+
254
+			if (empty($long_description))
255
+			{
256
+				return CLI::error("The {$method} command does not have an cli help available.");
257
+			}
258
+
259
+			CLI::new_line();
260
+			CLI::write( CLI::color(ucfirst($method) .' Help', 'yellow') );
261
+			return CLI::write( CLI::wrap($long_description, CLI::getWidth()) );
262
+		}
263
+
264
+		// Still here?
265
+		CLI::error("No help found for command: {$method}");
266
+	}
267
+
268
+	//--------------------------------------------------------------------
269 269
 
270 270
 	/**
271 271
 	 * Scans through the collections for the folder for this generator.
Please login to merge, or discard this patch.
myth/CLI.php 1 patch
Indentation   +511 added lines, -511 removed lines patch added patch discarded remove patch
@@ -1,14 +1,14 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 /**
3
- * Part of the Fuel framework.
4
- *
5
- * @package    Fuel
6
- * @version    1.7
7
- * @author     Fuel Development Team
8
- * @license    MIT License
9
- * @copyright  2010 - 2013 Fuel Development Team
10
- * @link       http://fuelphp.com
11
- */
3
+	 * Part of the Fuel framework.
4
+	 *
5
+	 * @package    Fuel
6
+	 * @version    1.7
7
+	 * @author     Fuel Development Team
8
+	 * @license    MIT License
9
+	 * @copyright  2010 - 2013 Fuel Development Team
10
+	 * @link       http://fuelphp.com
11
+	 */
12 12
 
13 13
 /**
14 14
  * Modified to work with CodeIgniter by Lonnie Ezell.
@@ -30,506 +30,506 @@  discard block
 block discarded – undo
30 30
  */
31 31
 class CLI {
32 32
 
33
-    public static $readline_support = false;
33
+	public static $readline_support = false;
34 34
 
35
-    public static $wait_msg = 'Press any key to continue...';
35
+	public static $wait_msg = 'Press any key to continue...';
36 36
 
37
-    public static $segments = [];
37
+	public static $segments = [];
38 38
 
39 39
 	protected static $options = [];
40 40
 
41 41
 	protected static $initialized = false;
42 42
 
43
-    // Used by progress bar
44
-    protected static $inProgress = false;
45
-
46
-    protected static $foreground_colors = array(
47
-        'black'			=> '0;30',
48
-        'dark_gray'		=> '1;30',
49
-        'blue'			=> '0;34',
50
-        'dark_blue'		=> '1;34',
51
-        'light_blue'	=> '1;34',
52
-        'green'			=> '0;32',
53
-        'light_green'	=> '1;32',
54
-        'cyan'			=> '0;36',
55
-        'light_cyan'	=> '1;36',
56
-        'red'			=> '0;31',
57
-        'light_red'		=> '1;31',
58
-        'purple'		=> '0;35',
59
-        'light_purple'	=> '1;35',
60
-        'light_yellow'	=> '0;33',
61
-        'yellow'		=> '1;33',
62
-        'light_gray'	=> '0;37',
63
-        'white'			=> '1;37',
64
-    );
65
-
66
-    protected static $background_colors = array(
67
-        'black'			=> '40',
68
-        'red'			=> '41',
69
-        'green'			=> '42',
70
-        'yellow'		=> '43',
71
-        'blue'			=> '44',
72
-        'magenta'		=> '45',
73
-        'cyan'			=> '46',
74
-        'light_gray'	=> '47',
75
-    );
76
-
77
-    //--------------------------------------------------------------------
78
-
79
-    /**
80
-     * Static constructor.	Parses all the CLI params.
81
-     */
82
-    public static function _init()
83
-    {
84
-	    if (static::$initialized === true)
85
-	    {
86
-		    return;
87
-	    }
88
-
89
-        if ( ! (PHP_SAPI === 'cli' || defined('STDIN')) )
90
-        {
91
-            throw new \Exception('Cli class cannot be used outside of the command line.');
92
-        }
93
-
94
-	    self::parseCommand();
95
-
96
-        // Readline is an extension for PHP that makes interactive with PHP much more bash-like
97
-        // http://www.php.net/manual/en/readline.installation.php
98
-        static::$readline_support = extension_loaded('readline');
99
-
100
-	    static::$initialized = true;
101
-    }
102
-
103
-    //--------------------------------------------------------------------
104
-
105
-    /**
106
-     * Grabs an individual
107
-     *
108
-     * @param $index
109
-     * @return null
110
-     */
111
-    public static function segment($index)
112
-    {
113
-        if (! isset(static::$segments[$index - 1]))
114
-        {
115
-            return null;
116
-        }
117
-
118
-        return static::$segments[$index - 1];
119
-    }
120
-
121
-    //--------------------------------------------------------------------
122
-
123
-    /**
124
-     * Returns the command string portion of the arguments. Used
125
-     * by the 'sprint' CLI script to grab the portion of the arguments
126
-     * that is used to call the CodeIgniter application.
127
-     *
128
-     * @return string
129
-     */
130
-    public static function cli_string()
131
-    {
132
-        return implode(' ', static::$segments);
133
-    }
134
-
135
-    //--------------------------------------------------------------------
136
-
137
-
138
-
139
-    /**
140
-     * Get input from the shell, using readline or the standard STDIN
141
-     *
142
-     * Named options must be in the following formats:
143
-     * php index.php user -v --v -name=John --name=John
144
-     *
145
-     * @param	string|int	$name	the name of the option (int if unnamed)
146
-     * @return	string
147
-     */
148
-    public static function input($prefix = '')
149
-    {
150
-        if (static::$readline_support)
151
-        {
152
-            return readline($prefix);
153
-        }
154
-
155
-        echo $prefix;
156
-        return fgets(STDIN);
157
-    }
158
-
159
-    //--------------------------------------------------------------------
160
-
161
-    /**
162
-     * Asks the user for input.  This can have either 1 or 2 arguments.
163
-     *
164
-     * Usage:
165
-     *
166
-     * // Waits for any key press
167
-     * CLI::prompt();
168
-     *
169
-     * // Takes any input
170
-     * $color = CLI::prompt('What is your favorite color?');
171
-     *
172
-     * // Takes any input, but offers default
173
-     * $color = CLI::prompt('What is your favourite color?', 'white');
174
-     *
175
-     * // Will only accept the options in the array
176
-     * $ready = CLI::prompt('Are you ready?', array('y','n'));
177
-     *
178
-     * @return	string	the user input
179
-     */
180
-    public static function prompt()
181
-    {
182
-        $args = func_get_args();
183
-
184
-        $options = array();
185
-        $output = '';
186
-        $default = null;
187
-
188
-        // How many we got
189
-        $arg_count = count($args);
190
-
191
-        // Is the last argument a boolean? True means required
192
-        $required = end($args) === true;
193
-
194
-        // Reduce the argument count if required was passed, we don't care about that anymore
195
-        $required === true and --$arg_count;
196
-
197
-        // This method can take a few crazy combinations of arguments, so lets work it out
198
-        switch ($arg_count)
199
-        {
200
-            case 2:
201
-
202
-                // E.g: $ready = CLI::prompt('Are you ready?', array('y','n'));
203
-                if (is_array($args[1]))
204
-                {
205
-                    list($output, $options)=$args;
206
-                }
207
-
208
-                // E.g: $color = CLI::prompt('What is your favourite color?', 'white');
209
-                elseif (is_string($args[1]))
210
-                {
211
-                    list($output, $default)=$args;
212
-                }
213
-
214
-                break;
215
-
216
-            case 1:
217
-
218
-                // No question (probably been asked already) so just show options
219
-                // E.g: $ready = CLI::prompt(array('y','n'));
220
-                if (is_array($args[0]))
221
-                {
222
-                    $options = $args[0];
223
-                }
224
-
225
-                // Question without options
226
-                // E.g: $ready = CLI::prompt('What did you do today?');
227
-                elseif (is_string($args[0]))
228
-                {
229
-                    $output = $args[0];
230
-                }
231
-
232
-                break;
233
-        }
234
-
235
-        // If a question has been asked with the read
236
-        if ($output !== '')
237
-        {
238
-            $extra_output = '';
239
-
240
-            if ($default !== null)
241
-            {
242
-                $extra_output = ' [ Default: "'.$default.'" ]';
243
-            }
244
-
245
-            elseif ($options !== array())
246
-            {
247
-                $extra_output = ' [ '.implode(', ', $options).' ]';
248
-            }
249
-
250
-            fwrite(STDOUT, $output.$extra_output.': ');
251
-        }
252
-
253
-        // Read the input from keyboard.
254
-        $input = trim(static::input()) ?: $default;
255
-
256
-        // No input provided and we require one (default will stop this being called)
257
-        if (empty($input) and $required === true)
258
-        {
259
-            static::write('This is required.');
260
-            static::new_line();
261
-
262
-            $input = forward_static_call_array(array(__CLASS__, 'prompt'), $args);
263
-        }
264
-
265
-        // If options are provided and the choice is not in the array, tell them to try again
266
-        if ( ! empty($options) and ! in_array($input, $options))
267
-        {
268
-            static::write('This is not a valid option. Please try again.');
269
-            static::new_line();
270
-
271
-            $input = forward_static_call_array(array(__CLASS__, 'prompt'), $args);
272
-        }
273
-
274
-        return $input;
275
-    }
276
-
277
-    //--------------------------------------------------------------------
278
-
279
-    /**
280
-     * Outputs a string to the cli.	 If you send an array it will implode them
281
-     * with a line break.
282
-     *
283
-     * @param	string|array	$text	the text to output, or array of lines
284
-     */
285
-    public static function write($text = '', $foreground = null, $background = null)
286
-    {
287
-        if (is_array($text))
288
-        {
289
-            $text = implode(PHP_EOL, $text);
290
-        }
291
-
292
-        if ($foreground or $background)
293
-        {
294
-            $text = static::color($text, $foreground, $background);
295
-        }
296
-
297
-        fwrite(STDOUT, $text.PHP_EOL);
298
-    }
299
-
300
-    //--------------------------------------------------------------------
301
-
302
-    /**
303
-     * Outputs an error to the CLI using STDERR instead of STDOUT
304
-     *
305
-     * @param	string|array	$text	the text to output, or array of errors
306
-     */
307
-    public static function error($text = '', $foreground = 'light_red', $background = null)
308
-    {
309
-        if (is_array($text))
310
-        {
311
-            $text = implode(PHP_EOL, $text);
312
-        }
313
-
314
-        if ($foreground OR $background)
315
-        {
316
-            $text = static::color($text, $foreground, $background);
317
-        }
318
-
319
-        fwrite(STDERR, $text.PHP_EOL);
320
-    }
321
-
322
-    //--------------------------------------------------------------------
323
-
324
-    /**
325
-     * Beeps a certain number of times.
326
-     *
327
-     * @param	int $num	the number of times to beep
328
-     */
329
-    public static function beep($num = 1)
330
-    {
331
-        echo str_repeat("\x07", $num);
332
-    }
333
-
334
-    //--------------------------------------------------------------------
335
-
336
-    /**
337
-     * Waits a certain number of seconds, optionally showing a wait message and
338
-     * waiting for a key press.
339
-     *
340
-     * @param	int		$seconds	number of seconds
341
-     * @param	bool	$countdown	show a countdown or not
342
-     */
343
-    public static function wait($seconds = 0, $countdown = false)
344
-    {
345
-        if ($countdown === true)
346
-        {
347
-            $time = $seconds;
348
-
349
-            while ($time > 0)
350
-            {
351
-                fwrite(STDOUT, $time.'... ');
352
-                sleep(1);
353
-                $time--;
354
-            }
355
-            static::write();
356
-        }
357
-
358
-        else
359
-        {
360
-            if ($seconds > 0)
361
-            {
362
-                sleep($seconds);
363
-            }
364
-            else
365
-            {
366
-                static::write(static::$wait_msg);
367
-                static::input();
368
-            }
369
-        }
370
-    }
371
-
372
-
373
-    //--------------------------------------------------------------------
374
-
375
-    /**
376
-     * if operating system === windows
377
-     */
378
-    public static function is_windows()
379
-    {
380
-        return 'win' === strtolower(substr(php_uname("s"), 0, 3));
381
-    }
382
-
383
-    //--------------------------------------------------------------------
384
-
385
-    /**
386
-     * Enter a number of empty lines
387
-     *
388
-     * @param	integer	Number of lines to output
389
-     * @return	void
390
-     */
391
-    public static function new_line($num = 1)
392
-    {
393
-        // Do it once or more, write with empty string gives us a new line
394
-        for($i = 0; $i < $num; $i++)
395
-        {
396
-            static::write();
397
-        }
398
-    }
399
-
400
-    //--------------------------------------------------------------------
401
-
402
-    /**
403
-     * Clears the screen of output
404
-     *
405
-     * @return	void
406
-     */
407
-    public static function clear_screen()
408
-    {
409
-        static::is_windows()
410
-
411
-            // Windows is a bit crap at this, but their terminal is tiny so shove this in
412
-            ? static::new_line(40)
413
-
414
-            // Anything with a flair of Unix will handle these magic characters
415
-            : fwrite(STDOUT, chr(27)."[H".chr(27)."[2J");
416
-    }
417
-
418
-    //--------------------------------------------------------------------
419
-
420
-    /**
421
-     * Returns the given text with the correct color codes for a foreground and
422
-     * optionally a background color.
423
-     *
424
-     * @param	string	$text		the text to color
425
-     * @param	string	$foreground the foreground color
426
-     * @param	string	$background the background color
427
-     * @param	string	$format		other formatting to apply. Currently only 'underline' is understood
428
-     * @return	string	the color coded string
429
-     */
430
-    public static function color($text, $foreground, $background = null, $format=null)
431
-    {
432
-        if (static::is_windows() and ! isset($_SERVER['ANSICON']))
433
-        {
434
-            return $text;
435
-        }
436
-
437
-        if ( ! array_key_exists($foreground, static::$foreground_colors))
438
-        {
439
-            throw new \RuntimeException('Invalid CLI foreground color: '.$foreground);
440
-        }
441
-
442
-        if ( $background !== null and ! array_key_exists($background, static::$background_colors))
443
-        {
444
-            throw new \RuntimeException('Invalid CLI background color: '.$background);
445
-        }
446
-
447
-        $string = "\033[".static::$foreground_colors[$foreground]."m";
448
-
449
-        if ($background !== null)
450
-        {
451
-            $string .= "\033[".static::$background_colors[$background]."m";
452
-        }
453
-
454
-        if ($format === 'underline')
455
-        {
456
-            $string .= "\033[4m";
457
-        }
458
-
459
-        $string .= $text."\033[0m";
460
-
461
-        return $string;
462
-    }
463
-
464
-    //--------------------------------------------------------------------
465
-
466
-    public static function getWidth($default=80)
467
-    {
468
-        if (static::is_windows())
469
-        {
470
-            return $default;
471
-        }
472
-
473
-        return (int)shell_exec('tput cols');
474
-    }
43
+	// Used by progress bar
44
+	protected static $inProgress = false;
45
+
46
+	protected static $foreground_colors = array(
47
+		'black'			=> '0;30',
48
+		'dark_gray'		=> '1;30',
49
+		'blue'			=> '0;34',
50
+		'dark_blue'		=> '1;34',
51
+		'light_blue'	=> '1;34',
52
+		'green'			=> '0;32',
53
+		'light_green'	=> '1;32',
54
+		'cyan'			=> '0;36',
55
+		'light_cyan'	=> '1;36',
56
+		'red'			=> '0;31',
57
+		'light_red'		=> '1;31',
58
+		'purple'		=> '0;35',
59
+		'light_purple'	=> '1;35',
60
+		'light_yellow'	=> '0;33',
61
+		'yellow'		=> '1;33',
62
+		'light_gray'	=> '0;37',
63
+		'white'			=> '1;37',
64
+	);
65
+
66
+	protected static $background_colors = array(
67
+		'black'			=> '40',
68
+		'red'			=> '41',
69
+		'green'			=> '42',
70
+		'yellow'		=> '43',
71
+		'blue'			=> '44',
72
+		'magenta'		=> '45',
73
+		'cyan'			=> '46',
74
+		'light_gray'	=> '47',
75
+	);
76
+
77
+	//--------------------------------------------------------------------
78
+
79
+	/**
80
+	 * Static constructor.	Parses all the CLI params.
81
+	 */
82
+	public static function _init()
83
+	{
84
+		if (static::$initialized === true)
85
+		{
86
+			return;
87
+		}
88
+
89
+		if ( ! (PHP_SAPI === 'cli' || defined('STDIN')) )
90
+		{
91
+			throw new \Exception('Cli class cannot be used outside of the command line.');
92
+		}
93
+
94
+		self::parseCommand();
95
+
96
+		// Readline is an extension for PHP that makes interactive with PHP much more bash-like
97
+		// http://www.php.net/manual/en/readline.installation.php
98
+		static::$readline_support = extension_loaded('readline');
99
+
100
+		static::$initialized = true;
101
+	}
102
+
103
+	//--------------------------------------------------------------------
104
+
105
+	/**
106
+	 * Grabs an individual
107
+	 *
108
+	 * @param $index
109
+	 * @return null
110
+	 */
111
+	public static function segment($index)
112
+	{
113
+		if (! isset(static::$segments[$index - 1]))
114
+		{
115
+			return null;
116
+		}
117
+
118
+		return static::$segments[$index - 1];
119
+	}
120
+
121
+	//--------------------------------------------------------------------
122
+
123
+	/**
124
+	 * Returns the command string portion of the arguments. Used
125
+	 * by the 'sprint' CLI script to grab the portion of the arguments
126
+	 * that is used to call the CodeIgniter application.
127
+	 *
128
+	 * @return string
129
+	 */
130
+	public static function cli_string()
131
+	{
132
+		return implode(' ', static::$segments);
133
+	}
134
+
135
+	//--------------------------------------------------------------------
136
+
137
+
138
+
139
+	/**
140
+	 * Get input from the shell, using readline or the standard STDIN
141
+	 *
142
+	 * Named options must be in the following formats:
143
+	 * php index.php user -v --v -name=John --name=John
144
+	 *
145
+	 * @param	string|int	$name	the name of the option (int if unnamed)
146
+	 * @return	string
147
+	 */
148
+	public static function input($prefix = '')
149
+	{
150
+		if (static::$readline_support)
151
+		{
152
+			return readline($prefix);
153
+		}
154
+
155
+		echo $prefix;
156
+		return fgets(STDIN);
157
+	}
158
+
159
+	//--------------------------------------------------------------------
160
+
161
+	/**
162
+	 * Asks the user for input.  This can have either 1 or 2 arguments.
163
+	 *
164
+	 * Usage:
165
+	 *
166
+	 * // Waits for any key press
167
+	 * CLI::prompt();
168
+	 *
169
+	 * // Takes any input
170
+	 * $color = CLI::prompt('What is your favorite color?');
171
+	 *
172
+	 * // Takes any input, but offers default
173
+	 * $color = CLI::prompt('What is your favourite color?', 'white');
174
+	 *
175
+	 * // Will only accept the options in the array
176
+	 * $ready = CLI::prompt('Are you ready?', array('y','n'));
177
+	 *
178
+	 * @return	string	the user input
179
+	 */
180
+	public static function prompt()
181
+	{
182
+		$args = func_get_args();
183
+
184
+		$options = array();
185
+		$output = '';
186
+		$default = null;
187
+
188
+		// How many we got
189
+		$arg_count = count($args);
190
+
191
+		// Is the last argument a boolean? True means required
192
+		$required = end($args) === true;
193
+
194
+		// Reduce the argument count if required was passed, we don't care about that anymore
195
+		$required === true and --$arg_count;
196
+
197
+		// This method can take a few crazy combinations of arguments, so lets work it out
198
+		switch ($arg_count)
199
+		{
200
+			case 2:
201
+
202
+				// E.g: $ready = CLI::prompt('Are you ready?', array('y','n'));
203
+				if (is_array($args[1]))
204
+				{
205
+					list($output, $options)=$args;
206
+				}
207
+
208
+				// E.g: $color = CLI::prompt('What is your favourite color?', 'white');
209
+				elseif (is_string($args[1]))
210
+				{
211
+					list($output, $default)=$args;
212
+				}
213
+
214
+				break;
215
+
216
+			case 1:
217
+
218
+				// No question (probably been asked already) so just show options
219
+				// E.g: $ready = CLI::prompt(array('y','n'));
220
+				if (is_array($args[0]))
221
+				{
222
+					$options = $args[0];
223
+				}
224
+
225
+				// Question without options
226
+				// E.g: $ready = CLI::prompt('What did you do today?');
227
+				elseif (is_string($args[0]))
228
+				{
229
+					$output = $args[0];
230
+				}
231
+
232
+				break;
233
+		}
234
+
235
+		// If a question has been asked with the read
236
+		if ($output !== '')
237
+		{
238
+			$extra_output = '';
239
+
240
+			if ($default !== null)
241
+			{
242
+				$extra_output = ' [ Default: "'.$default.'" ]';
243
+			}
244
+
245
+			elseif ($options !== array())
246
+			{
247
+				$extra_output = ' [ '.implode(', ', $options).' ]';
248
+			}
249
+
250
+			fwrite(STDOUT, $output.$extra_output.': ');
251
+		}
252
+
253
+		// Read the input from keyboard.
254
+		$input = trim(static::input()) ?: $default;
255
+
256
+		// No input provided and we require one (default will stop this being called)
257
+		if (empty($input) and $required === true)
258
+		{
259
+			static::write('This is required.');
260
+			static::new_line();
261
+
262
+			$input = forward_static_call_array(array(__CLASS__, 'prompt'), $args);
263
+		}
264
+
265
+		// If options are provided and the choice is not in the array, tell them to try again
266
+		if ( ! empty($options) and ! in_array($input, $options))
267
+		{
268
+			static::write('This is not a valid option. Please try again.');
269
+			static::new_line();
270
+
271
+			$input = forward_static_call_array(array(__CLASS__, 'prompt'), $args);
272
+		}
273
+
274
+		return $input;
275
+	}
276
+
277
+	//--------------------------------------------------------------------
278
+
279
+	/**
280
+	 * Outputs a string to the cli.	 If you send an array it will implode them
281
+	 * with a line break.
282
+	 *
283
+	 * @param	string|array	$text	the text to output, or array of lines
284
+	 */
285
+	public static function write($text = '', $foreground = null, $background = null)
286
+	{
287
+		if (is_array($text))
288
+		{
289
+			$text = implode(PHP_EOL, $text);
290
+		}
291
+
292
+		if ($foreground or $background)
293
+		{
294
+			$text = static::color($text, $foreground, $background);
295
+		}
296
+
297
+		fwrite(STDOUT, $text.PHP_EOL);
298
+	}
299
+
300
+	//--------------------------------------------------------------------
301
+
302
+	/**
303
+	 * Outputs an error to the CLI using STDERR instead of STDOUT
304
+	 *
305
+	 * @param	string|array	$text	the text to output, or array of errors
306
+	 */
307
+	public static function error($text = '', $foreground = 'light_red', $background = null)
308
+	{
309
+		if (is_array($text))
310
+		{
311
+			$text = implode(PHP_EOL, $text);
312
+		}
313
+
314
+		if ($foreground OR $background)
315
+		{
316
+			$text = static::color($text, $foreground, $background);
317
+		}
318
+
319
+		fwrite(STDERR, $text.PHP_EOL);
320
+	}
321
+
322
+	//--------------------------------------------------------------------
323
+
324
+	/**
325
+	 * Beeps a certain number of times.
326
+	 *
327
+	 * @param	int $num	the number of times to beep
328
+	 */
329
+	public static function beep($num = 1)
330
+	{
331
+		echo str_repeat("\x07", $num);
332
+	}
333
+
334
+	//--------------------------------------------------------------------
335
+
336
+	/**
337
+	 * Waits a certain number of seconds, optionally showing a wait message and
338
+	 * waiting for a key press.
339
+	 *
340
+	 * @param	int		$seconds	number of seconds
341
+	 * @param	bool	$countdown	show a countdown or not
342
+	 */
343
+	public static function wait($seconds = 0, $countdown = false)
344
+	{
345
+		if ($countdown === true)
346
+		{
347
+			$time = $seconds;
348
+
349
+			while ($time > 0)
350
+			{
351
+				fwrite(STDOUT, $time.'... ');
352
+				sleep(1);
353
+				$time--;
354
+			}
355
+			static::write();
356
+		}
357
+
358
+		else
359
+		{
360
+			if ($seconds > 0)
361
+			{
362
+				sleep($seconds);
363
+			}
364
+			else
365
+			{
366
+				static::write(static::$wait_msg);
367
+				static::input();
368
+			}
369
+		}
370
+	}
371
+
372
+
373
+	//--------------------------------------------------------------------
374
+
375
+	/**
376
+	 * if operating system === windows
377
+	 */
378
+	public static function is_windows()
379
+	{
380
+		return 'win' === strtolower(substr(php_uname("s"), 0, 3));
381
+	}
382
+
383
+	//--------------------------------------------------------------------
384
+
385
+	/**
386
+	 * Enter a number of empty lines
387
+	 *
388
+	 * @param	integer	Number of lines to output
389
+	 * @return	void
390
+	 */
391
+	public static function new_line($num = 1)
392
+	{
393
+		// Do it once or more, write with empty string gives us a new line
394
+		for($i = 0; $i < $num; $i++)
395
+		{
396
+			static::write();
397
+		}
398
+	}
399
+
400
+	//--------------------------------------------------------------------
401
+
402
+	/**
403
+	 * Clears the screen of output
404
+	 *
405
+	 * @return	void
406
+	 */
407
+	public static function clear_screen()
408
+	{
409
+		static::is_windows()
410
+
411
+			// Windows is a bit crap at this, but their terminal is tiny so shove this in
412
+			? static::new_line(40)
413
+
414
+			// Anything with a flair of Unix will handle these magic characters
415
+			: fwrite(STDOUT, chr(27)."[H".chr(27)."[2J");
416
+	}
417
+
418
+	//--------------------------------------------------------------------
419
+
420
+	/**
421
+	 * Returns the given text with the correct color codes for a foreground and
422
+	 * optionally a background color.
423
+	 *
424
+	 * @param	string	$text		the text to color
425
+	 * @param	string	$foreground the foreground color
426
+	 * @param	string	$background the background color
427
+	 * @param	string	$format		other formatting to apply. Currently only 'underline' is understood
428
+	 * @return	string	the color coded string
429
+	 */
430
+	public static function color($text, $foreground, $background = null, $format=null)
431
+	{
432
+		if (static::is_windows() and ! isset($_SERVER['ANSICON']))
433
+		{
434
+			return $text;
435
+		}
436
+
437
+		if ( ! array_key_exists($foreground, static::$foreground_colors))
438
+		{
439
+			throw new \RuntimeException('Invalid CLI foreground color: '.$foreground);
440
+		}
441
+
442
+		if ( $background !== null and ! array_key_exists($background, static::$background_colors))
443
+		{
444
+			throw new \RuntimeException('Invalid CLI background color: '.$background);
445
+		}
446
+
447
+		$string = "\033[".static::$foreground_colors[$foreground]."m";
448
+
449
+		if ($background !== null)
450
+		{
451
+			$string .= "\033[".static::$background_colors[$background]."m";
452
+		}
453
+
454
+		if ($format === 'underline')
455
+		{
456
+			$string .= "\033[4m";
457
+		}
458
+
459
+		$string .= $text."\033[0m";
460
+
461
+		return $string;
462
+	}
463
+
464
+	//--------------------------------------------------------------------
465
+
466
+	public static function getWidth($default=80)
467
+	{
468
+		if (static::is_windows())
469
+		{
470
+			return $default;
471
+		}
472
+
473
+		return (int)shell_exec('tput cols');
474
+	}
475 475
     
476
-    //--------------------------------------------------------------------
477
-
478
-    public static function getHeight($default=32)
479
-    {
480
-        if (static::is_windows())
481
-        {
482
-            return $default;
483
-        }
484
-
485
-        return (int)shell_exec('tput lines');
486
-    }
487
-
488
-    //--------------------------------------------------------------------
489
-
490
-    /**
491
-     * Displays a progress bar on the CLI. You must call it repeatedly
492
-     * to update it. Set $thisStep = false to erase the progress bar.
493
-     *
494
-     * @param int $thisStep
495
-     * @param int $totalSteps
496
-     */
497
-    public static function showProgress($thisStep=1, $totalSteps=10)
498
-    {
499
-        // The first time through, save
500
-        // our position so the script knows where to go
501
-        // back to when writing the bar, and
502
-        // at the end of the script.
503
-        if (! static::$inProgress) {
504
-            fwrite(STDOUT, "\0337");
505
-            static::$inProgress = true;
506
-        }
507
-
508
-        // Restore position
509
-        fwrite(STDERR, "\0338");
510
-
511
-        if ($thisStep !== false) {
512
-            // Don't allow div by zero or negative numbers....
513
-            $thisStep = abs($thisStep);
514
-            $totalSteps = $totalSteps < 1 ? 1 : $totalSteps;
515
-
516
-            $percent = intval( ($thisStep / $totalSteps) * 100 );
517
-            $step = (int)round($percent / 10);
518
-
519
-            // Write the progress bar
520
-            fwrite(STDOUT, "[\033[32m" . str_repeat('#', $step) . str_repeat('.', 10 - $step) . "\033[0m]");
521
-            // Textual representation...
522
-            fwrite(STDOUT, " {$percent}% Complete" . PHP_EOL);
523
-            // Move up, undo the PHP_EOL
524
-            fwrite(STDOUT, "\033[1A");
525
-        }
526
-        else
527
-        {
528
-            fwrite(STDERR, "\007");
529
-        }
530
-    }
531
-
532
-    //--------------------------------------------------------------------
476
+	//--------------------------------------------------------------------
477
+
478
+	public static function getHeight($default=32)
479
+	{
480
+		if (static::is_windows())
481
+		{
482
+			return $default;
483
+		}
484
+
485
+		return (int)shell_exec('tput lines');
486
+	}
487
+
488
+	//--------------------------------------------------------------------
489
+
490
+	/**
491
+	 * Displays a progress bar on the CLI. You must call it repeatedly
492
+	 * to update it. Set $thisStep = false to erase the progress bar.
493
+	 *
494
+	 * @param int $thisStep
495
+	 * @param int $totalSteps
496
+	 */
497
+	public static function showProgress($thisStep=1, $totalSteps=10)
498
+	{
499
+		// The first time through, save
500
+		// our position so the script knows where to go
501
+		// back to when writing the bar, and
502
+		// at the end of the script.
503
+		if (! static::$inProgress) {
504
+			fwrite(STDOUT, "\0337");
505
+			static::$inProgress = true;
506
+		}
507
+
508
+		// Restore position
509
+		fwrite(STDERR, "\0338");
510
+
511
+		if ($thisStep !== false) {
512
+			// Don't allow div by zero or negative numbers....
513
+			$thisStep = abs($thisStep);
514
+			$totalSteps = $totalSteps < 1 ? 1 : $totalSteps;
515
+
516
+			$percent = intval( ($thisStep / $totalSteps) * 100 );
517
+			$step = (int)round($percent / 10);
518
+
519
+			// Write the progress bar
520
+			fwrite(STDOUT, "[\033[32m" . str_repeat('#', $step) . str_repeat('.', 10 - $step) . "\033[0m]");
521
+			// Textual representation...
522
+			fwrite(STDOUT, " {$percent}% Complete" . PHP_EOL);
523
+			// Move up, undo the PHP_EOL
524
+			fwrite(STDOUT, "\033[1A");
525
+		}
526
+		else
527
+		{
528
+			fwrite(STDERR, "\007");
529
+		}
530
+	}
531
+
532
+	//--------------------------------------------------------------------
533 533
 
534 534
 	/**
535 535
 	 * Checks to see if an option was passed to us on the CLI and returns
@@ -541,11 +541,11 @@  discard block
 block discarded – undo
541 541
 	 */
542 542
 	public static function option($name)
543 543
 	{
544
-	    if (array_key_exists($name, self::$options))
545
-	    {
546
-		    $val = self::$options[$name] === null ? true : self::$options[$name];
547
-		    return $val;
548
-	    }
544
+		if (array_key_exists($name, self::$options))
545
+		{
546
+			$val = self::$options[$name] === null ? true : self::$options[$name];
547
+			return $val;
548
+		}
549 549
 
550 550
 		return null;
551 551
 	}
@@ -559,7 +559,7 @@  discard block
 block discarded – undo
559 559
 	 */
560 560
 	public static function getOptions()
561 561
 	{
562
-	    return self::$options;
562
+		return self::$options;
563 563
 	}
564 564
 
565 565
 	//--------------------------------------------------------------------
@@ -615,10 +615,10 @@  discard block
 block discarded – undo
615 615
 			return '';
616 616
 		}
617 617
 
618
-        if ($max == 0)
619
-        {
620
-            $max = CLI::getWidth();
621
-        }
618
+		if ($max == 0)
619
+		{
620
+			$max = CLI::getWidth();
621
+		}
622 622
 
623 623
 		if (CLI::getWidth() < $max)
624 624
 		{
Please login to merge, or discard this patch.
myth/Controllers/BaseController.php 1 patch
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 	{
101 101
 		parent::__construct();
102 102
 
103
-        $this->load->library('session');
103
+		$this->load->library('session');
104 104
 
105 105
 		$this->setupCache();
106 106
 
@@ -236,8 +236,8 @@  discard block
 block discarded – undo
236 236
 		}
237 237
 
238 238
 		$this->output->enable_profiler( FALSE )
239
-		             ->set_content_type( 'text/plain' )
240
-		             ->set_output( $text );
239
+					 ->set_content_type( 'text/plain' )
240
+					 ->set_output( $text );
241 241
 	}
242 242
 
243 243
 	//--------------------------------------------------------------------
@@ -267,8 +267,8 @@  discard block
 block discarded – undo
267 267
 		}
268 268
 
269 269
 		$this->output->enable_profiler( FALSE )
270
-		             ->set_content_type( 'application/json' )
271
-		             ->set_output( json_encode( $json ) );
270
+					 ->set_content_type( 'application/json' )
271
+					 ->set_output( json_encode( $json ) );
272 272
 	}
273 273
 
274 274
 	//--------------------------------------------------------------------
@@ -292,8 +292,8 @@  discard block
 block discarded – undo
292 292
 		}
293 293
 
294 294
 		$this->output->enable_profiler( FALSE )
295
-		             ->set_content_type( 'application/x-javascript' )
296
-		             ->set_output( $js );
295
+					 ->set_content_type( 'application/x-javascript' )
296
+					 ->set_output( $js );
297 297
 	}
298 298
 
299 299
 	//--------------------------------------------------------------------
Please login to merge, or discard this patch.
myth/Controllers/CLIController.php 1 patch
Indentation   +138 added lines, -138 removed lines patch added patch discarded remove patch
@@ -41,144 +41,144 @@
 block discarded – undo
41 41
  */
42 42
 class CLIController extends \CI_Controller {
43 43
 
44
-    /**
45
-     * Holds short descriptions for the public functions in this class.
46
-     * Each 'key' in the array should match the function name.
47
-     *
48
-     * @var array
49
-     */
50
-    protected $descriptions = [];
51
-
52
-    /**
53
-     * Holds long descriptions for the public functions in this class.
54
-     * Each 'key' in the array should match the function name.
55
-     * @var array
56
-     */
57
-    protected $long_descriptions = [];
58
-
59
-    //--------------------------------------------------------------------
60
-
61
-    /**
62
-     * Ensures that we are running on the CLI, and collects basic settings
63
-     * like collecting our command line arguments into a pretty array.
64
-     */
65
-    public function __construct()
66
-    {
67
-        parent::__construct();
68
-
69
-        // Restrict usage to the command line.
70
-        if (! is_cli() )
71
-        {
72
-            show_error( lang('cli_required') );
73
-        }
74
-
75
-        // Make sure the CLI library is loaded and ready.
44
+	/**
45
+	 * Holds short descriptions for the public functions in this class.
46
+	 * Each 'key' in the array should match the function name.
47
+	 *
48
+	 * @var array
49
+	 */
50
+	protected $descriptions = [];
51
+
52
+	/**
53
+	 * Holds long descriptions for the public functions in this class.
54
+	 * Each 'key' in the array should match the function name.
55
+	 * @var array
56
+	 */
57
+	protected $long_descriptions = [];
58
+
59
+	//--------------------------------------------------------------------
60
+
61
+	/**
62
+	 * Ensures that we are running on the CLI, and collects basic settings
63
+	 * like collecting our command line arguments into a pretty array.
64
+	 */
65
+	public function __construct()
66
+	{
67
+		parent::__construct();
68
+
69
+		// Restrict usage to the command line.
70
+		if (! is_cli() )
71
+		{
72
+			show_error( lang('cli_required') );
73
+		}
74
+
75
+		// Make sure the CLI library is loaded and ready.
76 76
 //        CLI::_init();
77
-    }
78
-
79
-    //--------------------------------------------------------------------
80
-
81
-    /**
82
-     * A default index method that all CLI Controllers can share. Will
83
-     * list all of the methods and their short descriptions, if available.
84
-     */
85
-    public function index()
86
-    {
87
-        CLI::new_line();
88
-        CLI::write( lang('cli.available_commands') );
89
-
90
-        $this->sayDescriptions($this->descriptions);
91
-
92
-        CLI::new_line();
93
-    }
94
-
95
-    //--------------------------------------------------------------------
96
-
97
-
98
-    /**
99
-     * Grabs the short description of a command, if it exists.
100
-     *
101
-     * @param null $method
102
-     */
103
-    public function describeMethod($method=null)
104
-    {
105
-        if (empty($this->descriptions[$method]))
106
-        {
107
-            return CLI::error( lang('cli.bad_description') );
108
-        }
109
-
110
-        CLI::write("\t{$this->descriptions[$method]}", 'yellow');
111
-    }
112
-
113
-    //--------------------------------------------------------------------
114
-
115
-    public function longDescribeMethod($method=null)
116
-    {
117
-        if (empty($this->long_descriptions[$method]))
118
-        {
119
-            return CLI::error( lang('cli.no_help') );
120
-        }
121
-
122
-        CLI::write("\t{$this->long_descriptions[$method]}", 'yellow');
123
-    }
124
-
125
-    //--------------------------------------------------------------------
126
-
127
-    //--------------------------------------------------------------------
128
-    // Private Methods
129
-    //--------------------------------------------------------------------
130
-
131
-    protected function sayDescriptions($descriptions)
132
-    {
133
-        $names      = array_keys($descriptions);
134
-        $syntaxes   = array_column($descriptions, 0);
135
-        $descs      = array_column($descriptions, 1);
136
-
137
-        // Pad each item to the same length
138
-        $names      = $this->padArray($names);
139
-        $syntaxes   = $this->padArray($syntaxes);
140
-
141
-        for ($i=0; $i < count($names); $i++)
142
-        {
143
-            $out = CLI::color($names[$i], 'yellow');
144
-
145
-            // The rest of the items stay default color.
146
-            if (isset($syntaxes[$i]))
147
-            {
148
-                $out .= $syntaxes[$i];
149
-            }
150
-
151
-            if (isset($descs[$i]))
152
-            {
153
-                $out .= CLI::wrap($descs[$i], 125, strlen($names[$i]) + strlen($syntaxes[$i]));
154
-            }
155
-
156
-            CLI::write($out);
157
-        }
158
-    }
159
-
160
-    //--------------------------------------------------------------------
161
-
162
-    /**
163
-     * Returns a new array where all of the string elements have
164
-     * been padding with trailling spaces to be the same length.
165
-     *
166
-     * @param array $array
167
-     * @param int $extra // How many extra spaces to add at the end
168
-     * @return array
169
-     */
170
-    protected function padArray($array, $extra=2)
171
-    {
172
-        $max = max(array_map('strlen', $array)) + $extra;
173
-
174
-        foreach ($array as &$item)
175
-        {
176
-            $item = str_pad($item, $max);
177
-        }
178
-
179
-        return $array;
180
-    }
181
-
182
-    //--------------------------------------------------------------------
77
+	}
78
+
79
+	//--------------------------------------------------------------------
80
+
81
+	/**
82
+	 * A default index method that all CLI Controllers can share. Will
83
+	 * list all of the methods and their short descriptions, if available.
84
+	 */
85
+	public function index()
86
+	{
87
+		CLI::new_line();
88
+		CLI::write( lang('cli.available_commands') );
89
+
90
+		$this->sayDescriptions($this->descriptions);
91
+
92
+		CLI::new_line();
93
+	}
94
+
95
+	//--------------------------------------------------------------------
96
+
97
+
98
+	/**
99
+	 * Grabs the short description of a command, if it exists.
100
+	 *
101
+	 * @param null $method
102
+	 */
103
+	public function describeMethod($method=null)
104
+	{
105
+		if (empty($this->descriptions[$method]))
106
+		{
107
+			return CLI::error( lang('cli.bad_description') );
108
+		}
109
+
110
+		CLI::write("\t{$this->descriptions[$method]}", 'yellow');
111
+	}
112
+
113
+	//--------------------------------------------------------------------
114
+
115
+	public function longDescribeMethod($method=null)
116
+	{
117
+		if (empty($this->long_descriptions[$method]))
118
+		{
119
+			return CLI::error( lang('cli.no_help') );
120
+		}
121
+
122
+		CLI::write("\t{$this->long_descriptions[$method]}", 'yellow');
123
+	}
124
+
125
+	//--------------------------------------------------------------------
126
+
127
+	//--------------------------------------------------------------------
128
+	// Private Methods
129
+	//--------------------------------------------------------------------
130
+
131
+	protected function sayDescriptions($descriptions)
132
+	{
133
+		$names      = array_keys($descriptions);
134
+		$syntaxes   = array_column($descriptions, 0);
135
+		$descs      = array_column($descriptions, 1);
136
+
137
+		// Pad each item to the same length
138
+		$names      = $this->padArray($names);
139
+		$syntaxes   = $this->padArray($syntaxes);
140
+
141
+		for ($i=0; $i < count($names); $i++)
142
+		{
143
+			$out = CLI::color($names[$i], 'yellow');
144
+
145
+			// The rest of the items stay default color.
146
+			if (isset($syntaxes[$i]))
147
+			{
148
+				$out .= $syntaxes[$i];
149
+			}
150
+
151
+			if (isset($descs[$i]))
152
+			{
153
+				$out .= CLI::wrap($descs[$i], 125, strlen($names[$i]) + strlen($syntaxes[$i]));
154
+			}
155
+
156
+			CLI::write($out);
157
+		}
158
+	}
159
+
160
+	//--------------------------------------------------------------------
161
+
162
+	/**
163
+	 * Returns a new array where all of the string elements have
164
+	 * been padding with trailling spaces to be the same length.
165
+	 *
166
+	 * @param array $array
167
+	 * @param int $extra // How many extra spaces to add at the end
168
+	 * @return array
169
+	 */
170
+	protected function padArray($array, $extra=2)
171
+	{
172
+		$max = max(array_map('strlen', $array)) + $extra;
173
+
174
+		foreach ($array as &$item)
175
+		{
176
+			$item = str_pad($item, $max);
177
+		}
178
+
179
+		return $array;
180
+	}
181
+
182
+	//--------------------------------------------------------------------
183 183
 
184 184
 }
Please login to merge, or discard this patch.
myth/Controllers/ThemedController.php 1 patch
Indentation   +353 added lines, -353 removed lines patch added patch discarded remove patch
@@ -41,358 +41,358 @@
 block discarded – undo
41 41
  */
42 42
 class ThemedController extends BaseController
43 43
 {
44
-    /**
45
-     * Stores data variables to be sent to the view.
46
-     * @var array
47
-     */
48
-    protected $vars = array();
49
-
50
-    /**
51
-     * Stores current status message.
52
-     * @var
53
-     */
54
-    protected $message;
55
-
56
-    /**
57
-     * The UIKit to make available to the template views.
58
-     * @var string
59
-     */
60
-    protected $uikit = '';
61
-
62
-    /**
63
-     * An instance of an active Themer to use.
64
-     * @var null
65
-     */
66
-    protected $themer = null;
67
-
68
-    /**
69
-     * Allows per-controller override of theme.
70
-     * @var null
71
-     */
72
-    protected $theme = null;
73
-
74
-    /**
75
-     * Per-controller override of the current layout file.
76
-     * @var null
77
-     */
78
-    protected $layout = null;
79
-
80
-    /**
81
-     * Stores an array of javascript files.
82
-     * @var array
83
-     */
84
-    protected $external_scripts = array();
85
-
86
-    /**
87
-     * Stores an array of CSS stylesheets.
88
-     * @var array
89
-     */
90
-    protected $stylesheets = array();
91
-
92
-    /**
93
-     * A MenuCollection instance
94
-     * @var
95
-     */
96
-    protected $meta;
97
-
98
-    /**
99
-     * Whether set() should escape the output...
100
-     * @var bool
101
-     */
102
-    protected $auto_escape = null;
103
-
104
-    /**
105
-     * An instance of ZendFrameworks Escaper
106
-     * @var null
107
-     */
108
-    protected $escaper = null;
109
-
110
-    //--------------------------------------------------------------------
111
-
112
-    /**
113
-     * Constructor takes care of getting the template engine up and running
114
-     * and bound to our DI object, as well as any other preliminary needs,
115
-     * like detecting the variant to use, etc.
116
-     */
117
-    public function __construct()
118
-    {
119
-        parent::__construct();
120
-
121
-        // Setup our Template Engine
122
-        $themer = config_item('active_themer');
123
-
124
-        if (empty($themer)) {
125
-            throw new \RuntimeException( lang('no_themer') );
126
-        }
127
-
128
-        $this->themer = new $themer( get_instance() );
129
-
130
-        // Register our paths with the themer
131
-        $paths = config_item('theme.paths');
132
-
133
-        foreach ($paths as $key => $path) {
134
-            $this->themer->addThemePath($key, $path);
135
-        }
136
-
137
-        // Set our default theme.
138
-        $this->themer->setDefaultTheme( config_item('theme.default_theme') );
139
-
140
-        // Register our variants with the engine.
141
-        $variants = config_item('theme.variants');
142
-
143
-        foreach ($variants as $key => $value) {
144
-            $this->themer->addVariant($key, $value);
145
-        }
146
-
147
-        $this->detectVariant();
148
-
149
-        // Ensure that our UIKit is loaded up if we're using one.
150
-        $uikit = config_item('theme.uikit');
151
-
152
-        if ($uikit)
153
-        {
154
-            $this->uikit = new $uikit();
155
-        }
156
-
157
-        // Load up our meta collection
158
-        $this->meta = new MetaCollection( get_instance() );
159
-
160
-        // Should we autoescape vars?
161
-        if (is_null($this->auto_escape))
162
-        {
163
-            $this->auto_escape = config_item( 'theme.auto_escape' );
164
-        }
165
-    }
166
-
167
-    //--------------------------------------------------------------------
168
-
169
-    /**
170
-     * Provides a common interface with the other rendering methods to
171
-     * set the output of the method. Uses the current instance of $this->template.
172
-     * Ensures that any data we've stored through $this->setVar() are present
173
-     * and includes the status messages into the data.
174
-     *
175
-     * @param array $data
176
-     * @param int   $cache_time
177
-     */
178
-    public function render($data = array(), $cache_time=0)
179
-    {
180
-	    if ($cache_time > 0)
181
-	    {
182
-		    $this->output->cache( (int)$cache_time );
183
-	    }
184
-
185
-        // Determine the correct theme to use
186
-        $theme = ! empty($this->theme) ? $this->theme : config_item('theme.default_theme');
187
-        $this->themer->setTheme($theme);
188
-
189
-        // Determine the correct layout to use
190
-        $layout = !empty($this->layout) ? $this->layout : null;
191
-        $this->themer->setLayout($layout);
192
-
193
-        // Merge any saved vars into the data
194
-        // But first, escape the data if needed
195
-        if ($this->auto_escape)
196
-        {
197
-            $data = esc($data, 'html');
198
-        }
199
-        $data = array_merge($data, $this->vars);
200
-
201
-        // Make sure the MetaCollection is available in the view.
202
-        $data['html_meta'] = $this->meta;
203
-
204
-        // Include our UIKit so views can use it
205
-        if (! empty($this->uikit)) {
206
-            $data['uikit'] = $this->uikit;
207
-        }
208
-
209
-        // Build our notices from the theme's view file.
210
-        $data['notice'] = $this->themer->display($this->themer->theme() . ':notice', ["notice" => $this->message()]);
211
-
212
-        // Make sure any scripts/stylesheets are available to the view
213
-        $data['external_scripts'] = $this->external_scripts;
214
-        $data['stylesheets'] = $this->stylesheets;
215
-
216
-        $this->themer->set($data);
217
-
218
-        $this->output->set_content_type('html')
219
-                     ->set_output($this->themer->render());
220
-    }
221
-
222
-    //--------------------------------------------------------------------
223
-
224
-    /**
225
-     * Sets a data variable to be sent to the view during the render() method.
226
-     * Will auto-escape data on the way in, unless specifically told not to.
227
-     *
228
-     * Uses ZendFramework's Escaper to handle the data escaping,
229
-     * based on context. Valid contexts are:
230
-     *      - html
231
-     *      - htmlAttr
232
-     *      - js
233
-     *      - css
234
-     *      - url
235
-     *
236
-     * @param string $name
237
-     * @param mixed $value
238
-     * @param string $context
239
-     * @param bool $do_escape
240
-     */
241
-    public function setVar($name, $value = null, $context='html', $do_escape=null)
242
-    {
243
-        $escape = $do_escape == true ? true : $this->auto_escape;
244
-
245
-        if (is_null($this->escaper))
246
-        {
247
-            $this->escaper = new Escaper(config_item('charset'));
248
-        }
249
-
250
-        if (is_array($name))
251
-        {
252
-            foreach ($name as $k => $v)
253
-            {
254
-                $this->vars[$k] = $escape ? esc($v, $context, $this->escaper) : $v;
255
-            }
256
-        }
257
-        else
258
-        {
259
-            $this->vars[$name] = $escape ? esc($value, $context, $this->escaper) : $value;
260
-        }
261
-    }
262
-
263
-    //--------------------------------------------------------------------
264
-
265
-    //--------------------------------------------------------------------
266
-    // Status Messages
267
-    //--------------------------------------------------------------------
268
-
269
-    /**
270
-     * Sets a status message (for displaying small success/error messages).
271
-     * This is used in place of the session->flashdata functions since you
272
-     * don't always want to have to refresh the page to show the message.
273
-     *
274
-     * @param string $message The message to save.
275
-     * @param string $type The string to be included as the CSS class of the containing div.
276
-     */
277
-    public function setMessage($message = '', $type = 'info')
278
-    {
279
-        if (! empty($message)) {
280
-            if (isset($this->session)) {
281
-                $this->session->set_flashdata('message', $type . '::' . $message);
282
-            }
283
-
284
-            $this->message = array(
285
-                'type' => $type,
286
-                'message' => $message
287
-            );
288
-        }
289
-    }
290
-
291
-    //--------------------------------------------------------------------
292
-
293
-    /**
294
-     * Retrieves the status message to display (if any).
295
-     *
296
-     * @param  string $message [description]
297
-     * @param  string $type [description]
298
-     * @return array
299
-     */
300
-    public function message($message = '', $type = 'info')
301
-    {
302
-        $return = array(
303
-            'message' => $message,
304
-            'type' => $type
305
-        );
306
-
307
-        // Does session data exist?
308
-        if (empty($message) && class_exists('CI_Session')) {
309
-            $message = $this->session->flashdata('message');
310
-
311
-            if (! empty($message)) {
312
-                // Split out our message parts
313
-                $temp_message = explode('::', $message);
314
-                $return['type'] = $temp_message[0];
315
-                $return['message'] = $temp_message[1];
316
-
317
-                unset($temp_message);
318
-            }
319
-        }
320
-
321
-        // If message is empty, we need to check our own storage.
322
-        if (empty($message)) {
323
-            if (empty($this->message['message'])) {
324
-                return '';
325
-            }
326
-
327
-            $return = $this->message;
328
-        }
329
-
330
-        // Clear our session data so we don't get extra messages on rare occasions.
331
-        if (class_exists('CI_Session')) {
332
-            $this->session->set_flashdata('message', '');
333
-        }
334
-
335
-        return $return;
336
-    }
337
-
338
-    //--------------------------------------------------------------------
339
-
340
-    //--------------------------------------------------------------------
341
-    // Utility Methods
342
-    //--------------------------------------------------------------------
343
-
344
-    /**
345
-     * Detects whether the item is being displayed on a desktop, phone,
346
-     * or tablet device.
347
-     */
348
-    protected function detectVariant()
349
-    {
350
-        // Variant Detection and setup
351
-        if (config_item('autodetect_variant') === true) {
352
-            $detect = new \Mobile_Detect();
353
-
354
-            if ($detect->isMobile()) {
355
-                $this->template->setVariant('phone');
356
-            } else if ($detect->isTablet()) {
357
-                $this->template->setVariant('tablet');
358
-            }
359
-        }
360
-    }
361
-
362
-    //--------------------------------------------------------------------
363
-
364
-    //--------------------------------------------------------------------
365
-    // 'Asset' functions
366
-    //--------------------------------------------------------------------
367
-
368
-    /**
369
-     * Adds an external javascript file to the 'external_scripts' array.
370
-     *
371
-     * @param [type] $filename [description]
372
-     */
373
-    public function addScript($filename)
374
-    {
375
-        if (strpos($filename, 'http') === FALSE) {
376
-            $filename = base_url() . 'assets/js/' . $filename;
377
-        }
378
-
379
-        $this->external_scripts[] = $filename;
380
-    }
381
-
382
-    //--------------------------------------------------------------------
383
-
384
-    /**
385
-     * Adds an external stylesheet file to the 'stylesheets' array.
386
-     */
387
-    public function addStyle($filename)
388
-    {
389
-        if (strpos($filename, 'http') === FALSE) {
390
-            $filename = base_url() . 'assets/css/' . $filename;
391
-        }
392
-
393
-        $this->stylesheets[] = $filename;
394
-    }
395
-
396
-    //--------------------------------------------------------------------
44
+	/**
45
+	 * Stores data variables to be sent to the view.
46
+	 * @var array
47
+	 */
48
+	protected $vars = array();
49
+
50
+	/**
51
+	 * Stores current status message.
52
+	 * @var
53
+	 */
54
+	protected $message;
55
+
56
+	/**
57
+	 * The UIKit to make available to the template views.
58
+	 * @var string
59
+	 */
60
+	protected $uikit = '';
61
+
62
+	/**
63
+	 * An instance of an active Themer to use.
64
+	 * @var null
65
+	 */
66
+	protected $themer = null;
67
+
68
+	/**
69
+	 * Allows per-controller override of theme.
70
+	 * @var null
71
+	 */
72
+	protected $theme = null;
73
+
74
+	/**
75
+	 * Per-controller override of the current layout file.
76
+	 * @var null
77
+	 */
78
+	protected $layout = null;
79
+
80
+	/**
81
+	 * Stores an array of javascript files.
82
+	 * @var array
83
+	 */
84
+	protected $external_scripts = array();
85
+
86
+	/**
87
+	 * Stores an array of CSS stylesheets.
88
+	 * @var array
89
+	 */
90
+	protected $stylesheets = array();
91
+
92
+	/**
93
+	 * A MenuCollection instance
94
+	 * @var
95
+	 */
96
+	protected $meta;
97
+
98
+	/**
99
+	 * Whether set() should escape the output...
100
+	 * @var bool
101
+	 */
102
+	protected $auto_escape = null;
103
+
104
+	/**
105
+	 * An instance of ZendFrameworks Escaper
106
+	 * @var null
107
+	 */
108
+	protected $escaper = null;
109
+
110
+	//--------------------------------------------------------------------
111
+
112
+	/**
113
+	 * Constructor takes care of getting the template engine up and running
114
+	 * and bound to our DI object, as well as any other preliminary needs,
115
+	 * like detecting the variant to use, etc.
116
+	 */
117
+	public function __construct()
118
+	{
119
+		parent::__construct();
120
+
121
+		// Setup our Template Engine
122
+		$themer = config_item('active_themer');
123
+
124
+		if (empty($themer)) {
125
+			throw new \RuntimeException( lang('no_themer') );
126
+		}
127
+
128
+		$this->themer = new $themer( get_instance() );
129
+
130
+		// Register our paths with the themer
131
+		$paths = config_item('theme.paths');
132
+
133
+		foreach ($paths as $key => $path) {
134
+			$this->themer->addThemePath($key, $path);
135
+		}
136
+
137
+		// Set our default theme.
138
+		$this->themer->setDefaultTheme( config_item('theme.default_theme') );
139
+
140
+		// Register our variants with the engine.
141
+		$variants = config_item('theme.variants');
142
+
143
+		foreach ($variants as $key => $value) {
144
+			$this->themer->addVariant($key, $value);
145
+		}
146
+
147
+		$this->detectVariant();
148
+
149
+		// Ensure that our UIKit is loaded up if we're using one.
150
+		$uikit = config_item('theme.uikit');
151
+
152
+		if ($uikit)
153
+		{
154
+			$this->uikit = new $uikit();
155
+		}
156
+
157
+		// Load up our meta collection
158
+		$this->meta = new MetaCollection( get_instance() );
159
+
160
+		// Should we autoescape vars?
161
+		if (is_null($this->auto_escape))
162
+		{
163
+			$this->auto_escape = config_item( 'theme.auto_escape' );
164
+		}
165
+	}
166
+
167
+	//--------------------------------------------------------------------
168
+
169
+	/**
170
+	 * Provides a common interface with the other rendering methods to
171
+	 * set the output of the method. Uses the current instance of $this->template.
172
+	 * Ensures that any data we've stored through $this->setVar() are present
173
+	 * and includes the status messages into the data.
174
+	 *
175
+	 * @param array $data
176
+	 * @param int   $cache_time
177
+	 */
178
+	public function render($data = array(), $cache_time=0)
179
+	{
180
+		if ($cache_time > 0)
181
+		{
182
+			$this->output->cache( (int)$cache_time );
183
+		}
184
+
185
+		// Determine the correct theme to use
186
+		$theme = ! empty($this->theme) ? $this->theme : config_item('theme.default_theme');
187
+		$this->themer->setTheme($theme);
188
+
189
+		// Determine the correct layout to use
190
+		$layout = !empty($this->layout) ? $this->layout : null;
191
+		$this->themer->setLayout($layout);
192
+
193
+		// Merge any saved vars into the data
194
+		// But first, escape the data if needed
195
+		if ($this->auto_escape)
196
+		{
197
+			$data = esc($data, 'html');
198
+		}
199
+		$data = array_merge($data, $this->vars);
200
+
201
+		// Make sure the MetaCollection is available in the view.
202
+		$data['html_meta'] = $this->meta;
203
+
204
+		// Include our UIKit so views can use it
205
+		if (! empty($this->uikit)) {
206
+			$data['uikit'] = $this->uikit;
207
+		}
208
+
209
+		// Build our notices from the theme's view file.
210
+		$data['notice'] = $this->themer->display($this->themer->theme() . ':notice', ["notice" => $this->message()]);
211
+
212
+		// Make sure any scripts/stylesheets are available to the view
213
+		$data['external_scripts'] = $this->external_scripts;
214
+		$data['stylesheets'] = $this->stylesheets;
215
+
216
+		$this->themer->set($data);
217
+
218
+		$this->output->set_content_type('html')
219
+					 ->set_output($this->themer->render());
220
+	}
221
+
222
+	//--------------------------------------------------------------------
223
+
224
+	/**
225
+	 * Sets a data variable to be sent to the view during the render() method.
226
+	 * Will auto-escape data on the way in, unless specifically told not to.
227
+	 *
228
+	 * Uses ZendFramework's Escaper to handle the data escaping,
229
+	 * based on context. Valid contexts are:
230
+	 *      - html
231
+	 *      - htmlAttr
232
+	 *      - js
233
+	 *      - css
234
+	 *      - url
235
+	 *
236
+	 * @param string $name
237
+	 * @param mixed $value
238
+	 * @param string $context
239
+	 * @param bool $do_escape
240
+	 */
241
+	public function setVar($name, $value = null, $context='html', $do_escape=null)
242
+	{
243
+		$escape = $do_escape == true ? true : $this->auto_escape;
244
+
245
+		if (is_null($this->escaper))
246
+		{
247
+			$this->escaper = new Escaper(config_item('charset'));
248
+		}
249
+
250
+		if (is_array($name))
251
+		{
252
+			foreach ($name as $k => $v)
253
+			{
254
+				$this->vars[$k] = $escape ? esc($v, $context, $this->escaper) : $v;
255
+			}
256
+		}
257
+		else
258
+		{
259
+			$this->vars[$name] = $escape ? esc($value, $context, $this->escaper) : $value;
260
+		}
261
+	}
262
+
263
+	//--------------------------------------------------------------------
264
+
265
+	//--------------------------------------------------------------------
266
+	// Status Messages
267
+	//--------------------------------------------------------------------
268
+
269
+	/**
270
+	 * Sets a status message (for displaying small success/error messages).
271
+	 * This is used in place of the session->flashdata functions since you
272
+	 * don't always want to have to refresh the page to show the message.
273
+	 *
274
+	 * @param string $message The message to save.
275
+	 * @param string $type The string to be included as the CSS class of the containing div.
276
+	 */
277
+	public function setMessage($message = '', $type = 'info')
278
+	{
279
+		if (! empty($message)) {
280
+			if (isset($this->session)) {
281
+				$this->session->set_flashdata('message', $type . '::' . $message);
282
+			}
283
+
284
+			$this->message = array(
285
+				'type' => $type,
286
+				'message' => $message
287
+			);
288
+		}
289
+	}
290
+
291
+	//--------------------------------------------------------------------
292
+
293
+	/**
294
+	 * Retrieves the status message to display (if any).
295
+	 *
296
+	 * @param  string $message [description]
297
+	 * @param  string $type [description]
298
+	 * @return array
299
+	 */
300
+	public function message($message = '', $type = 'info')
301
+	{
302
+		$return = array(
303
+			'message' => $message,
304
+			'type' => $type
305
+		);
306
+
307
+		// Does session data exist?
308
+		if (empty($message) && class_exists('CI_Session')) {
309
+			$message = $this->session->flashdata('message');
310
+
311
+			if (! empty($message)) {
312
+				// Split out our message parts
313
+				$temp_message = explode('::', $message);
314
+				$return['type'] = $temp_message[0];
315
+				$return['message'] = $temp_message[1];
316
+
317
+				unset($temp_message);
318
+			}
319
+		}
320
+
321
+		// If message is empty, we need to check our own storage.
322
+		if (empty($message)) {
323
+			if (empty($this->message['message'])) {
324
+				return '';
325
+			}
326
+
327
+			$return = $this->message;
328
+		}
329
+
330
+		// Clear our session data so we don't get extra messages on rare occasions.
331
+		if (class_exists('CI_Session')) {
332
+			$this->session->set_flashdata('message', '');
333
+		}
334
+
335
+		return $return;
336
+	}
337
+
338
+	//--------------------------------------------------------------------
339
+
340
+	//--------------------------------------------------------------------
341
+	// Utility Methods
342
+	//--------------------------------------------------------------------
343
+
344
+	/**
345
+	 * Detects whether the item is being displayed on a desktop, phone,
346
+	 * or tablet device.
347
+	 */
348
+	protected function detectVariant()
349
+	{
350
+		// Variant Detection and setup
351
+		if (config_item('autodetect_variant') === true) {
352
+			$detect = new \Mobile_Detect();
353
+
354
+			if ($detect->isMobile()) {
355
+				$this->template->setVariant('phone');
356
+			} else if ($detect->isTablet()) {
357
+				$this->template->setVariant('tablet');
358
+			}
359
+		}
360
+	}
361
+
362
+	//--------------------------------------------------------------------
363
+
364
+	//--------------------------------------------------------------------
365
+	// 'Asset' functions
366
+	//--------------------------------------------------------------------
367
+
368
+	/**
369
+	 * Adds an external javascript file to the 'external_scripts' array.
370
+	 *
371
+	 * @param [type] $filename [description]
372
+	 */
373
+	public function addScript($filename)
374
+	{
375
+		if (strpos($filename, 'http') === FALSE) {
376
+			$filename = base_url() . 'assets/js/' . $filename;
377
+		}
378
+
379
+		$this->external_scripts[] = $filename;
380
+	}
381
+
382
+	//--------------------------------------------------------------------
383
+
384
+	/**
385
+	 * Adds an external stylesheet file to the 'stylesheets' array.
386
+	 */
387
+	public function addStyle($filename)
388
+	{
389
+		if (strpos($filename, 'http') === FALSE) {
390
+			$filename = base_url() . 'assets/css/' . $filename;
391
+		}
392
+
393
+		$this->stylesheets[] = $filename;
394
+	}
395
+
396
+	//--------------------------------------------------------------------
397 397
 }
398 398
 
Please login to merge, or discard this patch.
myth/Cron/CronManager.php 1 patch
Indentation   +252 added lines, -252 removed lines patch added patch discarded remove patch
@@ -34,257 +34,257 @@
 block discarded – undo
34 34
 
35 35
 class CronManager {
36 36
 
37
-    protected static $tasks = [];
38
-
39
-    //--------------------------------------------------------------------
40
-
41
-    /**
42
-     * Schedules a new task in the system.
43
-     *
44
-     * @param $alias
45
-     * @param $time_string
46
-     * @param callable|string $task
47
-     */
48
-    public static function schedule($alias, $time_string, $task)
49
-    {
50
-        // Valid Alias?
51
-        if (! is_string($alias) || empty($alias))
52
-        {
53
-            throw new \RuntimeException( lang('cron.bad_alias') );
54
-        }
55
-
56
-        // Valid TimeString?
57
-        if (! is_string($time_string) || empty($time_string))
58
-        {
59
-            throw new \RuntimeException( lang('cron.bad_timestring') );
60
-        }
61
-
62
-        // Valid Task?
63
-        if (! is_callable($task) && ! is_string($task))
64
-        {
65
-            throw new \RuntimeException( lang('cron.bad_task') . $alias);
66
-        }
67
-
68
-        static::$tasks[$alias] = new CronTask($time_string, $task);
69
-    }
70
-
71
-    //--------------------------------------------------------------------
72
-
73
-    /**
74
-     * Removes a single task from the system.
75
-     *
76
-     * @param $alias
77
-     */
78
-    public static function remove($alias)
79
-    {
80
-        if (empty(static::$tasks[$alias]))
81
-        {
82
-            return null;
83
-        }
84
-
85
-        unset(static::$tasks[$alias]);
86
-
87
-        return true;
88
-    }
89
-
90
-    //--------------------------------------------------------------------
91
-
92
-
93
-    /**
94
-     * Provides an array of all tasks in the system. The format will be
95
-     * like:
96
-     *      [
97
-     *          'alias' => [
98
-     *              'next_run'  => '123456789',
99
-     *              'prev_run'  => '123456789',
100
-     *              'task'  => mixed
101
-     *          ],
102
-     *          ...
103
-     *      ]
104
-     */
105
-    public static function listAll($current_time='now')
106
-    {
107
-        if (! count(static::$tasks))
108
-        {
109
-            return null;
110
-        }
111
-
112
-        $output = array();
113
-
114
-        foreach (static::$tasks as $alias => $task)
115
-        {
116
-            $output[$alias] = [
117
-                'next_run'  => $task->nextRunDate($current_time),
118
-                'prev_run'  => $task->previousRunDate($current_time),
119
-                'task'      => $task->task()
120
-            ];
121
-        }
122
-
123
-        return $output;
124
-    }
125
-
126
-    //--------------------------------------------------------------------
127
-
128
-    /**
129
-     * Gets the task object assigned to an alias.
130
-     *
131
-     * @param $alias
132
-     * @return null|CronTask object
133
-     */
134
-    public static function task($alias)
135
-    {
136
-        if (empty(static::$tasks[$alias]) )
137
-        {
138
-            return null;
139
-        }
140
-
141
-        return static::$tasks[$alias];
142
-    }
143
-
144
-    //--------------------------------------------------------------------
145
-
146
-    /**
147
-     * Returns all tasks currently in the system.
148
-     *
149
-     * @return array
150
-     */
151
-    public static function tasks()
152
-    {
153
-        return count(static::$tasks) ? static::$tasks : null;
154
-    }
155
-
156
-    //--------------------------------------------------------------------
157
-
158
-    /**
159
-     * Runs all tasks scheduled to run right now.
160
-     *
161
-     * Can be limited to a single task by passing it's alias in the first param.
162
-     *
163
-     * Returns the output of all task runs as a single string. Perfect for
164
-     * emailing to users on completion
165
-     *
166
-     * @param null $alias
167
-     * @param bool $force_run
168
-     * @param string $current_time
169
-     * @return string
170
-     */
171
-    public static function run($alias=null, $force_run=false, $current_time='now')
172
-    {
173
-        $tasks = static::$tasks;
174
-
175
-        if (! empty($alias) && isset($tasks[$alias]))
176
-        {
177
-            $tasks = [$alias => $tasks[$alias] ];
178
-        }
179
-
180
-        $output = '';
181
-
182
-        $count = 0; // How many tasks have ran?
183
-
184
-        foreach ($tasks as $alias => $task)
185
-        {
186
-            if ($task->isDue($current_time) || $force_run === true)
187
-            {
188
-                $output .= sprintf( lang('cron.running_task'), $alias);
189
-
190
-                try {
191
-                    $result = self::runTask($alias);
192
-
193
-                    if (is_bool($result))
194
-                    {
195
-                        $output .= $result === true ? lang('done') ."\n" : lang('failed') ."\n";
196
-                    }
197
-                    else if (is_string($result))
198
-                    {
199
-                        $output .= sprintf( lang('cron.done_with_msg'), $result);
200
-                    }
201
-                }
202
-                catch (\Exception $e)
203
-                {
204
-                    $output .= "[Exception] ". $e->getMessage() ."\n";
205
-                }
206
-
207
-                $count++;
208
-            }
209
-            else
210
-            {
211
-                $output .= sprintf( lang('cron.not_scheduled_until'), $alias, $task->nextRunDate() );
212
-            }
213
-        }
214
-
215
-        if (! $count)
216
-        {
217
-            $output .= lang('cron.nothing_scheduled');
218
-        }
219
-
220
-        return $output;
221
-    }
222
-
223
-    //--------------------------------------------------------------------
224
-
225
-    /**
226
-     * Clears all tasks from the system
227
-     */
228
-    public static function reset()
229
-    {
230
-        static::$tasks = [];
231
-    }
232
-
233
-    //--------------------------------------------------------------------
234
-
235
-    //--------------------------------------------------------------------
236
-    // Protected Methods
237
-    //--------------------------------------------------------------------
238
-
239
-    /**
240
-     * Runs a single Task.
241
-     *
242
-     * NOTE: Tasks MUST return a true/false value only.
243
-     *
244
-     * @param $alias
245
-     * @return bool
246
-     */
247
-    protected static function runTask($alias)
248
-    {
249
-        $task = static::$tasks[$alias]->task();
250
-
251
-        $success = false;
252
-
253
-        // If it's a standard callable item,
254
-        // then run it.
255
-        if (is_callable($task))
256
-        {
257
-            $success = call_user_func($task);
258
-        }
259
-
260
-        // Otherwise, if it's a string it should be
261
-        // a library:method string so try to run it.
262
-        else if (is_string($task) && ! empty($task) && strpos($task, ':') !== false)
263
-        {
264
-            list($class, $method) = explode(':', $task);
265
-
266
-            // Let PHP try to autoload it through any available autoloaders
267
-            // (including Composer and user's custom autoloaders). If we
268
-            // don't find it, then assume it's a CI library that we can reach.
269
-            if (class_exists($class)) {
270
-                $class = new $class();
271
-            } else {
272
-                get_instance()->load->library($class);
273
-                $class =& get_instance()->$class;
274
-            }
275
-
276
-            if (! method_exists($class, $method)) {
277
-                log_message('error', "[CRON] Method not found: {$class}::{$method}");
278
-                return $success;
279
-            }
280
-
281
-            // Call the class with our parameters
282
-            $success = $class->{$method}();
283
-        }
284
-
285
-        return $success;
286
-    }
287
-
288
-    //--------------------------------------------------------------------
37
+	protected static $tasks = [];
38
+
39
+	//--------------------------------------------------------------------
40
+
41
+	/**
42
+	 * Schedules a new task in the system.
43
+	 *
44
+	 * @param $alias
45
+	 * @param $time_string
46
+	 * @param callable|string $task
47
+	 */
48
+	public static function schedule($alias, $time_string, $task)
49
+	{
50
+		// Valid Alias?
51
+		if (! is_string($alias) || empty($alias))
52
+		{
53
+			throw new \RuntimeException( lang('cron.bad_alias') );
54
+		}
55
+
56
+		// Valid TimeString?
57
+		if (! is_string($time_string) || empty($time_string))
58
+		{
59
+			throw new \RuntimeException( lang('cron.bad_timestring') );
60
+		}
61
+
62
+		// Valid Task?
63
+		if (! is_callable($task) && ! is_string($task))
64
+		{
65
+			throw new \RuntimeException( lang('cron.bad_task') . $alias);
66
+		}
67
+
68
+		static::$tasks[$alias] = new CronTask($time_string, $task);
69
+	}
70
+
71
+	//--------------------------------------------------------------------
72
+
73
+	/**
74
+	 * Removes a single task from the system.
75
+	 *
76
+	 * @param $alias
77
+	 */
78
+	public static function remove($alias)
79
+	{
80
+		if (empty(static::$tasks[$alias]))
81
+		{
82
+			return null;
83
+		}
84
+
85
+		unset(static::$tasks[$alias]);
86
+
87
+		return true;
88
+	}
89
+
90
+	//--------------------------------------------------------------------
91
+
92
+
93
+	/**
94
+	 * Provides an array of all tasks in the system. The format will be
95
+	 * like:
96
+	 *      [
97
+	 *          'alias' => [
98
+	 *              'next_run'  => '123456789',
99
+	 *              'prev_run'  => '123456789',
100
+	 *              'task'  => mixed
101
+	 *          ],
102
+	 *          ...
103
+	 *      ]
104
+	 */
105
+	public static function listAll($current_time='now')
106
+	{
107
+		if (! count(static::$tasks))
108
+		{
109
+			return null;
110
+		}
111
+
112
+		$output = array();
113
+
114
+		foreach (static::$tasks as $alias => $task)
115
+		{
116
+			$output[$alias] = [
117
+				'next_run'  => $task->nextRunDate($current_time),
118
+				'prev_run'  => $task->previousRunDate($current_time),
119
+				'task'      => $task->task()
120
+			];
121
+		}
122
+
123
+		return $output;
124
+	}
125
+
126
+	//--------------------------------------------------------------------
127
+
128
+	/**
129
+	 * Gets the task object assigned to an alias.
130
+	 *
131
+	 * @param $alias
132
+	 * @return null|CronTask object
133
+	 */
134
+	public static function task($alias)
135
+	{
136
+		if (empty(static::$tasks[$alias]) )
137
+		{
138
+			return null;
139
+		}
140
+
141
+		return static::$tasks[$alias];
142
+	}
143
+
144
+	//--------------------------------------------------------------------
145
+
146
+	/**
147
+	 * Returns all tasks currently in the system.
148
+	 *
149
+	 * @return array
150
+	 */
151
+	public static function tasks()
152
+	{
153
+		return count(static::$tasks) ? static::$tasks : null;
154
+	}
155
+
156
+	//--------------------------------------------------------------------
157
+
158
+	/**
159
+	 * Runs all tasks scheduled to run right now.
160
+	 *
161
+	 * Can be limited to a single task by passing it's alias in the first param.
162
+	 *
163
+	 * Returns the output of all task runs as a single string. Perfect for
164
+	 * emailing to users on completion
165
+	 *
166
+	 * @param null $alias
167
+	 * @param bool $force_run
168
+	 * @param string $current_time
169
+	 * @return string
170
+	 */
171
+	public static function run($alias=null, $force_run=false, $current_time='now')
172
+	{
173
+		$tasks = static::$tasks;
174
+
175
+		if (! empty($alias) && isset($tasks[$alias]))
176
+		{
177
+			$tasks = [$alias => $tasks[$alias] ];
178
+		}
179
+
180
+		$output = '';
181
+
182
+		$count = 0; // How many tasks have ran?
183
+
184
+		foreach ($tasks as $alias => $task)
185
+		{
186
+			if ($task->isDue($current_time) || $force_run === true)
187
+			{
188
+				$output .= sprintf( lang('cron.running_task'), $alias);
189
+
190
+				try {
191
+					$result = self::runTask($alias);
192
+
193
+					if (is_bool($result))
194
+					{
195
+						$output .= $result === true ? lang('done') ."\n" : lang('failed') ."\n";
196
+					}
197
+					else if (is_string($result))
198
+					{
199
+						$output .= sprintf( lang('cron.done_with_msg'), $result);
200
+					}
201
+				}
202
+				catch (\Exception $e)
203
+				{
204
+					$output .= "[Exception] ". $e->getMessage() ."\n";
205
+				}
206
+
207
+				$count++;
208
+			}
209
+			else
210
+			{
211
+				$output .= sprintf( lang('cron.not_scheduled_until'), $alias, $task->nextRunDate() );
212
+			}
213
+		}
214
+
215
+		if (! $count)
216
+		{
217
+			$output .= lang('cron.nothing_scheduled');
218
+		}
219
+
220
+		return $output;
221
+	}
222
+
223
+	//--------------------------------------------------------------------
224
+
225
+	/**
226
+	 * Clears all tasks from the system
227
+	 */
228
+	public static function reset()
229
+	{
230
+		static::$tasks = [];
231
+	}
232
+
233
+	//--------------------------------------------------------------------
234
+
235
+	//--------------------------------------------------------------------
236
+	// Protected Methods
237
+	//--------------------------------------------------------------------
238
+
239
+	/**
240
+	 * Runs a single Task.
241
+	 *
242
+	 * NOTE: Tasks MUST return a true/false value only.
243
+	 *
244
+	 * @param $alias
245
+	 * @return bool
246
+	 */
247
+	protected static function runTask($alias)
248
+	{
249
+		$task = static::$tasks[$alias]->task();
250
+
251
+		$success = false;
252
+
253
+		// If it's a standard callable item,
254
+		// then run it.
255
+		if (is_callable($task))
256
+		{
257
+			$success = call_user_func($task);
258
+		}
259
+
260
+		// Otherwise, if it's a string it should be
261
+		// a library:method string so try to run it.
262
+		else if (is_string($task) && ! empty($task) && strpos($task, ':') !== false)
263
+		{
264
+			list($class, $method) = explode(':', $task);
265
+
266
+			// Let PHP try to autoload it through any available autoloaders
267
+			// (including Composer and user's custom autoloaders). If we
268
+			// don't find it, then assume it's a CI library that we can reach.
269
+			if (class_exists($class)) {
270
+				$class = new $class();
271
+			} else {
272
+				get_instance()->load->library($class);
273
+				$class =& get_instance()->$class;
274
+			}
275
+
276
+			if (! method_exists($class, $method)) {
277
+				log_message('error', "[CRON] Method not found: {$class}::{$method}");
278
+				return $success;
279
+			}
280
+
281
+			// Call the class with our parameters
282
+			$success = $class->{$method}();
283
+		}
284
+
285
+		return $success;
286
+	}
287
+
288
+	//--------------------------------------------------------------------
289 289
 
290 290
 }
Please login to merge, or discard this patch.