code
stringlengths 31
1.39M
| docstring
stringlengths 23
16.8k
| func_name
stringlengths 1
126
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
166
| url
stringlengths 50
220
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
function generate() {
$this->out(__('Generating Schema...', true));
$options = array();
if (isset($this->params['f'])) {
$options = array('models' => false);
}
$snapshot = false;
if (isset($this->args[0]) && $this->args[0] === 'snapshot') {
$snapshot = true;
}
if (!$snapshot && file_exists($this->Schema->path . DS . $this->params['file'])) {
$snapshot = true;
$result = strtolower($this->in("Schema file exists.\n [O]verwrite\n [S]napshot\n [Q]uit\nWould you like to do?", array('o', 's', 'q'), 's'));
if ($result === 'q') {
return $this->_stop();
}
if ($result === 'o') {
$snapshot = false;
}
}
$cacheDisable = Configure::read('Cache.disable');
Configure::write('Cache.disable', true);
$content = $this->Schema->read($options);
$content['file'] = $this->params['file'];
Configure::write('Cache.disable', $cacheDisable);
if ($snapshot === true) {
$Folder =& new Folder($this->Schema->path);
$result = $Folder->read();
$numToUse = false;
if (isset($this->params['s'])) {
$numToUse = $this->params['s'];
}
$count = 1;
if (!empty($result[1])) {
foreach ($result[1] as $file) {
if (preg_match('/schema(?:[_\d]*)?\.php$/', $file)) {
$count++;
}
}
}
if ($numToUse !== false) {
if ($numToUse > $count) {
$count = $numToUse;
}
}
$fileName = rtrim($this->params['file'], '.php');
$content['file'] = $fileName . '_' . $count . '.php';
}
if ($this->Schema->write($content)) {
$this->out(sprintf(__('Schema file: %s generated', true), $content['file']));
$this->_stop();
} else {
$this->err(__('Schema file: %s generated', true));
$this->_stop();
}
}
|
Read database and Write schema object
accepts a connection as first arg or path to save as second arg
@access public
|
generate
|
php
|
Datawalke/Coordino
|
cake/console/libs/schema.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/schema.php
|
MIT
|
function dump() {
$write = false;
$Schema = $this->Schema->load();
if (!$Schema) {
$this->err(__('Schema could not be loaded', true));
$this->_stop();
}
if (isset($this->params['write'])) {
if ($this->params['write'] == 1) {
$write = Inflector::underscore($this->Schema->name);
} else {
$write = $this->params['write'];
}
}
$db =& ConnectionManager::getDataSource($this->Schema->connection);
$contents = "#" . $Schema->name . " sql generated on: " . date('Y-m-d H:i:s') . " : " . time() . "\n\n";
$contents .= $db->dropSchema($Schema) . "\n\n". $db->createSchema($Schema);
if ($write) {
if (strpos($write, '.sql') === false) {
$write .= '.sql';
}
if (strpos($write, DS) !== false) {
$File =& new File($write, true);
} else {
$File =& new File($this->Schema->path . DS . $write, true);
}
if ($File->write($contents)) {
$this->out(sprintf(__('SQL dump file created in %s', true), $File->pwd()));
$this->_stop();
} else {
$this->err(__('SQL dump could not be created', true));
$this->_stop();
}
}
$this->out($contents);
return $contents;
}
|
Dump Schema object to sql file
Use the `write` param to enable and control SQL file output location.
Simply using -write will write the sql file to the same dir as the schema file.
If -write contains a full path name the file will be saved there. If -write only
contains no DS, that will be used as the file name, in the same dir as the schema file.
@access public
|
dump
|
php
|
Datawalke/Coordino
|
cake/console/libs/schema.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/schema.php
|
MIT
|
function create() {
list($Schema, $table) = $this->_loadSchema();
$this->__create($Schema, $table);
}
|
Run database create commands. Alias for run create.
@return void
|
create
|
php
|
Datawalke/Coordino
|
cake/console/libs/schema.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/schema.php
|
MIT
|
function update() {
list($Schema, $table) = $this->_loadSchema();
$this->__update($Schema, $table);
}
|
Run database create commands. Alias for run create.
@return void
|
update
|
php
|
Datawalke/Coordino
|
cake/console/libs/schema.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/schema.php
|
MIT
|
function _loadSchema() {
$name = $plugin = null;
if (isset($this->params['name'])) {
$name = $this->params['name'];
}
if (isset($this->params['plugin'])) {
$plugin = $this->params['plugin'];
}
if (isset($this->params['dry'])) {
$this->__dry = true;
$this->out(__('Performing a dry run.', true));
}
$options = array('name' => $name, 'plugin' => $plugin);
if (isset($this->params['s'])) {
$fileName = rtrim($this->Schema->file, '.php');
$options['file'] = $fileName . '_' . $this->params['s'] . '.php';
}
$Schema =& $this->Schema->load($options);
if (!$Schema) {
$this->err(sprintf(__('%s could not be loaded', true), $this->Schema->path . DS . $this->Schema->file));
$this->_stop();
}
$table = null;
if (isset($this->args[1])) {
$table = $this->args[1];
}
return array(&$Schema, $table);
}
|
Prepares the Schema objects for database operations.
@return void
|
_loadSchema
|
php
|
Datawalke/Coordino
|
cake/console/libs/schema.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/schema.php
|
MIT
|
function __create(&$Schema, $table = null) {
$db =& ConnectionManager::getDataSource($this->Schema->connection);
$drop = $create = array();
if (!$table) {
foreach ($Schema->tables as $table => $fields) {
$drop[$table] = $db->dropSchema($Schema, $table);
$create[$table] = $db->createSchema($Schema, $table);
}
} elseif (isset($Schema->tables[$table])) {
$drop[$table] = $db->dropSchema($Schema, $table);
$create[$table] = $db->createSchema($Schema, $table);
}
if (empty($drop) || empty($create)) {
$this->out(__('Schema is up to date.', true));
$this->_stop();
}
$this->out("\n" . __('The following table(s) will be dropped.', true));
$this->out(array_keys($drop));
if ('y' == $this->in(__('Are you sure you want to drop the table(s)?', true), array('y', 'n'), 'n')) {
$this->out(__('Dropping table(s).', true));
$this->__run($drop, 'drop', $Schema);
}
$this->out("\n" . __('The following table(s) will be created.', true));
$this->out(array_keys($create));
if ('y' == $this->in(__('Are you sure you want to create the table(s)?', true), array('y', 'n'), 'y')) {
$this->out(__('Creating table(s).', true));
$this->__run($create, 'create', $Schema);
}
$this->out(__('End create.', true));
}
|
Create database from Schema object
Should be called via the run method
@access private
|
__create
|
php
|
Datawalke/Coordino
|
cake/console/libs/schema.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/schema.php
|
MIT
|
function __update(&$Schema, $table = null) {
$db =& ConnectionManager::getDataSource($this->Schema->connection);
$this->out(__('Comparing Database to Schema...', true));
$options = array();
if (isset($this->params['f'])) {
$options['models'] = false;
}
$Old = $this->Schema->read($options);
$compare = $this->Schema->compare($Old, $Schema);
$contents = array();
if (empty($table)) {
foreach ($compare as $table => $changes) {
$contents[$table] = $db->alterSchema(array($table => $changes), $table);
}
} elseif (isset($compare[$table])) {
$contents[$table] = $db->alterSchema(array($table => $compare[$table]), $table);
}
if (empty($contents)) {
$this->out(__('Schema is up to date.', true));
$this->_stop();
}
$this->out("\n" . __('The following statements will run.', true));
$this->out(array_map('trim', $contents));
if ('y' == $this->in(__('Are you sure you want to alter the tables?', true), array('y', 'n'), 'n')) {
$this->out();
$this->out(__('Updating Database...', true));
$this->__run($contents, 'update', $Schema);
}
$this->out(__('End update.', true));
}
|
Update database with Schema object
Should be called via the run method
@access private
|
__update
|
php
|
Datawalke/Coordino
|
cake/console/libs/schema.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/schema.php
|
MIT
|
function __run($contents, $event, &$Schema) {
if (empty($contents)) {
$this->err(__('Sql could not be run', true));
return;
}
Configure::write('debug', 2);
$db =& ConnectionManager::getDataSource($this->Schema->connection);
foreach ($contents as $table => $sql) {
if (empty($sql)) {
$this->out(sprintf(__('%s is up to date.', true), $table));
} else {
if ($this->__dry === true) {
$this->out(sprintf(__('Dry run for %s :', true), $table));
$this->out($sql);
} else {
if (!$Schema->before(array($event => $table))) {
return false;
}
$error = null;
if (!$db->execute($sql)) {
$error = $table . ': ' . $db->lastError();
}
$Schema->after(array($event => $table, 'errors' => $error));
if (!empty($error)) {
$this->out($error);
} else {
$this->out(sprintf(__('%s updated.', true), $table));
}
}
}
}
}
|
Runs sql from __create() or __update()
@access private
|
__run
|
php
|
Datawalke/Coordino
|
cake/console/libs/schema.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/schema.php
|
MIT
|
function _welcome() {
$this->Dispatch->clear();
$this->out();
$this->out('Welcome to CakePHP v' . Configure::version() . ' Console');
$this->hr();
$this->out('App : '. $this->params['app']);
$this->out('Path: '. $this->params['working']);
$this->hr();
}
|
Displays a header for the shell
@access protected
|
_welcome
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function _loadDbConfig() {
if (config('database') && class_exists('DATABASE_CONFIG')) {
$this->DbConfig =& new DATABASE_CONFIG();
return true;
}
$this->err('Database config could not be loaded.');
$this->out('Run `bake` to create the database configuration.');
return false;
}
|
Loads database file and constructs DATABASE_CONFIG class
makes $this->DbConfig available to subclasses
@return bool
@access protected
|
_loadDbConfig
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function _loadModels() {
if ($this->uses === null || $this->uses === false) {
return;
}
if ($this->uses === true && App::import('Model', 'AppModel')) {
$this->AppModel =& new AppModel(false, false, false);
return true;
}
if ($this->uses !== true && !empty($this->uses)) {
$uses = is_array($this->uses) ? $this->uses : array($this->uses);
$modelClassName = $uses[0];
if (strpos($uses[0], '.') !== false) {
list($plugin, $modelClassName) = explode('.', $uses[0]);
}
$this->modelClass = $modelClassName;
foreach ($uses as $modelClass) {
list($plugin, $modelClass) = pluginSplit($modelClass, true);
if (PHP5) {
$this->{$modelClass} = ClassRegistry::init($plugin . $modelClass);
} else {
$this->{$modelClass} =& ClassRegistry::init($plugin . $modelClass);
}
}
return true;
}
return false;
}
|
if var $uses = true
Loads AppModel file and constructs AppModel class
makes $this->AppModel available to subclasses
if var $uses is an array of models will load those models
@return bool
@access protected
|
_loadModels
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function loadTasks() {
if ($this->tasks === null || $this->tasks === false || $this->tasks === true || empty($this->tasks)) {
return true;
}
$tasks = $this->tasks;
if (!is_array($tasks)) {
$tasks = array($tasks);
}
foreach ($tasks as $taskName) {
$task = Inflector::underscore($taskName);
$taskClass = Inflector::camelize($taskName . 'Task');
if (!class_exists($taskClass)) {
foreach ($this->Dispatch->shellPaths as $path) {
$taskPath = $path . 'tasks' . DS . $task . '.php';
if (file_exists($taskPath)) {
require_once $taskPath;
break;
}
}
}
$taskClassCheck = $taskClass;
if (!PHP5) {
$taskClassCheck = strtolower($taskClass);
}
if (ClassRegistry::isKeySet($taskClassCheck)) {
$this->taskNames[] = $taskName;
if (!PHP5) {
$this->{$taskName} =& ClassRegistry::getObject($taskClassCheck);
} else {
$this->{$taskName} = ClassRegistry::getObject($taskClassCheck);
}
} else {
$this->taskNames[] = $taskName;
if (!PHP5) {
$this->{$taskName} =& new $taskClass($this->Dispatch);
} else {
$this->{$taskName} = new $taskClass($this->Dispatch);
}
}
if (!isset($this->{$taskName})) {
$this->err("Task `{$taskName}` could not be loaded");
$this->_stop();
}
}
return true;
}
|
Loads tasks defined in var $tasks
@return bool
@access public
|
loadTasks
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function in($prompt, $options = null, $default = null) {
if (!$this->interactive) {
return $default;
}
$in = $this->Dispatch->getInput($prompt, $options, $default);
if ($options && is_string($options)) {
if (strpos($options, ',')) {
$options = explode(',', $options);
} elseif (strpos($options, '/')) {
$options = explode('/', $options);
} else {
$options = array($options);
}
}
if (is_array($options)) {
while ($in === '' || ($in !== '' && (!in_array(strtolower($in), $options) && !in_array(strtoupper($in), $options)) && !in_array($in, $options))) {
$in = $this->Dispatch->getInput($prompt, $options, $default);
}
}
return $in;
}
|
Prompts the user for input, and returns it.
@param string $prompt Prompt text.
@param mixed $options Array or string of options.
@param string $default Default input value.
@return Either the default value, or the user-provided input.
@access public
|
in
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function out($message = null, $newlines = 1) {
if (is_array($message)) {
$message = implode($this->nl(), $message);
}
return $this->Dispatch->stdout($message . $this->nl($newlines), false);
}
|
Outputs a single or multiple messages to stdout. If no parameters
are passed outputs just a newline.
@param mixed $message A string or a an array of strings to output
@param integer $newlines Number of newlines to append
@return integer Returns the number of bytes returned from writing to stdout.
@access public
|
out
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function err($message = null, $newlines = 1) {
if (is_array($message)) {
$message = implode($this->nl(), $message);
}
$this->Dispatch->stderr($message . $this->nl($newlines));
}
|
Outputs a single or multiple error messages to stderr. If no parameters
are passed outputs just a newline.
@param mixed $message A string or a an array of strings to output
@param integer $newlines Number of newlines to append
@access public
|
err
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function nl($multiplier = 1) {
return str_repeat("\n", $multiplier);
}
|
Returns a single or multiple linefeeds sequences.
@param integer $multiplier Number of times the linefeed sequence should be repeated
@access public
@return string
|
nl
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function hr($newlines = 0) {
$this->out(null, $newlines);
$this->out('---------------------------------------------------------------');
$this->out(null, $newlines);
}
|
Outputs a series of minus characters to the standard output, acts as a visual separator.
@param integer $newlines Number of newlines to pre- and append
@access public
|
hr
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function error($title, $message = null) {
$this->err(sprintf(__('Error: %s', true), $title));
if (!empty($message)) {
$this->err($message);
}
$this->_stop(1);
}
|
Displays a formatted error message
and exits the application with status code 1
@param string $title Title of the error
@param string $message An optional error message
@access public
|
error
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function _checkArgs($expectedNum, $command = null) {
if (!$command) {
$command = $this->command;
}
if (count($this->args) < $expectedNum) {
$message[] = "Got: " . count($this->args);
$message[] = "Expected: {$expectedNum}";
$message[] = "Please type `cake {$this->shell} help` for help";
$message[] = "on usage of the {$this->name} {$command}.";
$this->error('Wrong number of parameters', $message);
}
}
|
Will check the number args matches otherwise throw an error
@param integer $expectedNum Expected number of paramters
@param string $command Command
@access protected
|
_checkArgs
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function createFile($path, $contents) {
$path = str_replace(DS . DS, DS, $path);
$this->out();
$this->out(sprintf(__("Creating file %s", true), $path));
if (is_file($path) && $this->interactive === true) {
$prompt = sprintf(__('File `%s` exists, overwrite?', true), $path);
$key = $this->in($prompt, array('y', 'n', 'q'), 'n');
if (strtolower($key) == 'q') {
$this->out(__('Quitting.', true), 2);
$this->_stop();
} elseif (strtolower($key) != 'y') {
$this->out(sprintf(__('Skip `%s`', true), $path), 2);
return false;
}
}
if (!class_exists('File')) {
require LIBS . 'file.php';
}
if ($File = new File($path, true)) {
$data = $File->prepare($contents);
$File->write($data);
$this->out(sprintf(__('Wrote `%s`', true), $path));
return true;
} else {
$this->err(sprintf(__('Could not write to `%s`.', true), $path), 2);
return false;
}
}
|
Creates a file at given path
@param string $path Where to put the file.
@param string $contents Content to put in the file.
@return boolean Success
@access public
|
createFile
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function help() {
if ($this->command != null) {
$this->err("Unknown {$this->name} command `{$this->command}`.");
$this->err("For usage, try `cake {$this->shell} help`.", 2);
} else {
$this->Dispatch->help();
}
}
|
Outputs usage text on the standard output. Implement it in subclasses.
@access public
|
help
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function _checkUnitTest() {
if (App::import('vendor', 'simpletest' . DS . 'simpletest')) {
return true;
}
$prompt = 'SimpleTest is not installed. Do you want to bake unit test files anyway?';
$unitTest = $this->in($prompt, array('y','n'), 'y');
$result = strtolower($unitTest) == 'y' || strtolower($unitTest) == 'yes';
if ($result) {
$this->out();
$this->out('You can download SimpleTest from http://simpletest.org');
}
return $result;
}
|
Action to create a Unit Test
@return boolean Success
@access protected
|
_checkUnitTest
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function shortPath($file) {
$shortPath = str_replace(ROOT, null, $file);
$shortPath = str_replace('..' . DS, '', $shortPath);
return str_replace(DS . DS, DS, $shortPath);
}
|
Makes absolute file path easier to read
@param string $file Absolute file path
@return sting short path
@access public
|
shortPath
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function _controllerPath($name) {
return strtolower(Inflector::underscore($name));
}
|
Creates the proper controller path for the specified controller class name
@param string $name Controller class name
@return string Path to controller
@access protected
|
_controllerPath
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function _controllerName($name) {
return Inflector::pluralize(Inflector::camelize($name));
}
|
Creates the proper controller plural name for the specified controller class name
@param string $name Controller class name
@return string Controller plural name
@access protected
|
_controllerName
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function _modelName($name) {
return Inflector::camelize(Inflector::singularize($name));
}
|
Creates the proper controller camelized name (singularized) for the specified name
@param string $name Name
@return string Camelized and singularized controller name
@access protected
|
_modelName
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function _modelKey($name) {
return Inflector::underscore($name) . '_id';
}
|
Creates the proper underscored model key for associations
@param string $name Model class name
@return string Singular model key
@access protected
|
_modelKey
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function _modelNameFromKey($key) {
return Inflector::camelize(str_replace('_id', '', $key));
}
|
Creates the proper model name from a foreign key
@param string $key Foreign key
@return string Model name
@access protected
|
_modelNameFromKey
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function _singularName($name) {
return Inflector::variable(Inflector::singularize($name));
}
|
creates the singular name for use in views.
@param string $name
@return string $name
@access protected
|
_singularName
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function _pluralName($name) {
return Inflector::variable(Inflector::pluralize($name));
}
|
Creates the plural name for views
@param string $name Name to use
@return string Plural name for views
@access protected
|
_pluralName
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function _singularHumanName($name) {
return Inflector::humanize(Inflector::underscore(Inflector::singularize($name)));
}
|
Creates the singular human name used in views
@param string $name Controller name
@return string Singular human name
@access protected
|
_singularHumanName
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function _pluralHumanName($name) {
return Inflector::humanize(Inflector::underscore($name));
}
|
Creates the plural human name used in views
@param string $name Controller name
@return string Plural human name
@access protected
|
_pluralHumanName
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function _pluginPath($pluginName) {
return App::pluginPath($pluginName);
}
|
Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
@param string $pluginName Name of the plugin you want ie. DebugKit
@return string $path path to the correct plugin.
|
_pluginPath
|
php
|
Datawalke/Coordino
|
cake/console/libs/shell.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/shell.php
|
MIT
|
function initialize() {
$corePath = App::core('cake');
if (isset($corePath[0])) {
define('TEST_CAKE_CORE_INCLUDE_PATH', rtrim($corePath[0], DS) . DS);
} else {
define('TEST_CAKE_CORE_INCLUDE_PATH', CAKE_CORE_INCLUDE_PATH);
}
$this->__installSimpleTest();
require_once CAKE . 'tests' . DS . 'lib' . DS . 'test_manager.php';
require_once CAKE . 'tests' . DS . 'lib' . DS . 'reporter' . DS . 'cake_cli_reporter.php';
$plugins = App::objects('plugin');
foreach ($plugins as $p) {
$this->plugins[] = Inflector::underscore($p);
}
$this->parseArgs();
$this->getManager();
}
|
Initialization method installs Simpletest and loads all plugins
@return void
@access public
|
initialize
|
php
|
Datawalke/Coordino
|
cake/console/libs/testsuite.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/testsuite.php
|
MIT
|
function parseArgs() {
if (empty($this->args)) {
return;
}
$this->category = $this->args[0];
if (!in_array($this->category, array('app', 'core'))) {
$this->isPluginTest = true;
}
if (isset($this->args[1])) {
$this->type = $this->args[1];
}
if (isset($this->args[2])) {
if ($this->args[2] == 'cov') {
$this->doCoverage = true;
} else {
$this->file = Inflector::underscore($this->args[2]);
}
}
if (isset($this->args[3]) && $this->args[3] == 'cov') {
$this->doCoverage = true;
}
}
|
Parse the arguments given into the Shell object properties.
@return void
@access public
|
parseArgs
|
php
|
Datawalke/Coordino
|
cake/console/libs/testsuite.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/testsuite.php
|
MIT
|
function getManager() {
$this->Manager = new TestManager();
$this->Manager->appTest = ($this->category === 'app');
if ($this->isPluginTest) {
$this->Manager->pluginTest = $this->category;
}
}
|
Gets a manager instance, and set the app/plugin properties.
@return void
|
getManager
|
php
|
Datawalke/Coordino
|
cake/console/libs/testsuite.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/testsuite.php
|
MIT
|
function main() {
$this->out(__('CakePHP Test Shell', true));
$this->hr();
if (count($this->args) == 0) {
$this->error(__('Sorry, you did not pass any arguments!', true));
}
if ($this->__canRun()) {
$message = sprintf(__('Running %s %s %s', true), $this->category, $this->type, $this->file);
$this->out($message);
$exitCode = 0;
if (!$this->__run()) {
$exitCode = 1;
}
$this->_stop($exitCode);
} else {
$this->error(__('Sorry, the tests could not be found.', true));
}
}
|
Main entry point to this shell
@return void
@access public
|
main
|
php
|
Datawalke/Coordino
|
cake/console/libs/testsuite.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/testsuite.php
|
MIT
|
function help() {
$this->out('Usage: ');
$this->out("\tcake testsuite category test_type file");
$this->out("\t\t- category - \"app\", \"core\" or name of a plugin");
$this->out("\t\t- test_type - \"case\", \"group\" or \"all\"");
$this->out("\t\t- test_file - file name with folder prefix and without the (test|group).php suffix");
$this->out();
$this->out('Examples: ');
$this->out("\t\tcake testsuite app all");
$this->out("\t\tcake testsuite core all");
$this->out();
$this->out("\t\tcake testsuite app case behaviors/debuggable");
$this->out("\t\tcake testsuite app case models/my_model");
$this->out("\t\tcake testsuite app case controllers/my_controller");
$this->out();
$this->out("\t\tcake testsuite core case file");
$this->out("\t\tcake testsuite core case router");
$this->out("\t\tcake testsuite core case set");
$this->out();
$this->out("\t\tcake testsuite app group mygroup");
$this->out("\t\tcake testsuite core group acl");
$this->out("\t\tcake testsuite core group socket");
$this->out();
$this->out("\t\tcake testsuite bugs case models/bug");
$this->out("\t\t // for the plugin 'bugs' and its test case 'models/bug'");
$this->out("\t\tcake testsuite bugs group bug");
$this->out("\t\t // for the plugin bugs and its test group 'bug'");
$this->out();
$this->out('Code Coverage Analysis: ');
$this->out("\n\nAppend 'cov' to any of the above in order to enable code coverage analysis");
}
|
Help screen
@return void
@access public
|
help
|
php
|
Datawalke/Coordino
|
cake/console/libs/testsuite.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/testsuite.php
|
MIT
|
function __canRun() {
$isNeitherAppNorCore = !in_array($this->category, array('app', 'core'));
$isPlugin = in_array(Inflector::underscore($this->category), $this->plugins);
if ($isNeitherAppNorCore && !$isPlugin) {
$message = sprintf(
__('%s is an invalid test category (either "app", "core" or name of a plugin)', true),
$this->category
);
$this->error($message);
return false;
}
$folder = $this->__findFolderByCategory($this->category);
if (!file_exists($folder)) {
$this->err(sprintf(__('%s not found', true), $folder));
return false;
}
if (!in_array($this->type, array('all', 'group', 'case'))) {
$this->err(sprintf(__('%s is invalid. Should be case, group or all', true), $this->type));
return false;
}
$fileName = $this->__getFileName($folder, $this->isPluginTest);
if ($fileName === true || file_exists($folder . $fileName)) {
return true;
}
$message = sprintf(
__('%s %s %s is an invalid test identifier', true),
$this->category, $this->type, $this->file
);
$this->err($message);
return false;
}
|
Checks if the arguments supplied point to a valid test file and thus the shell can be run.
@return bool true if it's a valid test file, false otherwise
@access private
|
__canRun
|
php
|
Datawalke/Coordino
|
cake/console/libs/testsuite.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/testsuite.php
|
MIT
|
function __run() {
$Reporter = new CakeCliReporter('utf-8', array(
'app' => $this->Manager->appTest,
'plugin' => $this->Manager->pluginTest,
'group' => ($this->type === 'group'),
'codeCoverage' => $this->doCoverage
));
if ($this->type == 'all') {
return $this->Manager->runAllTests($Reporter);
}
if ($this->doCoverage) {
if (!extension_loaded('xdebug')) {
$this->out(__('You must install Xdebug to use the CakePHP(tm) Code Coverage Analyzation. Download it from http://www.xdebug.org/docs/install', true));
$this->_stop(0);
}
}
if ($this->type == 'group') {
$ucFirstGroup = ucfirst($this->file);
if ($this->doCoverage) {
require_once CAKE . 'tests' . DS . 'lib' . DS . 'code_coverage_manager.php';
CodeCoverageManager::init($ucFirstGroup, $Reporter);
CodeCoverageManager::start();
}
$result = $this->Manager->runGroupTest($ucFirstGroup, $Reporter);
return $result;
}
$folder = $folder = $this->__findFolderByCategory($this->category);
$case = $this->__getFileName($folder, $this->isPluginTest);
if ($this->doCoverage) {
require_once CAKE . 'tests' . DS . 'lib' . DS . 'code_coverage_manager.php';
CodeCoverageManager::init($case, $Reporter);
CodeCoverageManager::start();
}
$result = $this->Manager->runTestCase($case, $Reporter);
return $result;
}
|
Executes the tests depending on our settings
@return void
@access private
|
__run
|
php
|
Datawalke/Coordino
|
cake/console/libs/testsuite.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/testsuite.php
|
MIT
|
function __getFileName($folder, $isPlugin) {
$ext = $this->Manager->getExtension($this->type);
switch ($this->type) {
case 'all':
return true;
case 'group':
return $this->file . $ext;
case 'case':
if ($this->category == 'app' || $isPlugin) {
return $this->file . $ext;
}
$coreCase = $this->file . $ext;
$coreLibCase = 'libs' . DS . $this->file . $ext;
if ($this->category == 'core' && file_exists($folder . DS . $coreCase)) {
return $coreCase;
} elseif ($this->category == 'core' && file_exists($folder . DS . $coreLibCase)) {
return $coreLibCase;
}
}
return false;
}
|
Gets the concrete filename for the inputted test name and category/type
@param string $folder Folder name to look for files in.
@param boolean $isPlugin If the test case is a plugin.
@return mixed Either string filename or boolean false on failure. Or true if the type is 'all'
@access private
|
__getFileName
|
php
|
Datawalke/Coordino
|
cake/console/libs/testsuite.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/testsuite.php
|
MIT
|
function __findFolderByCategory($category) {
$folder = '';
$paths = array(
'core' => CAKE,
'app' => APP
);
$typeDir = $this->type === 'group' ? 'groups' : 'cases';
if (array_key_exists($category, $paths)) {
$folder = $paths[$category] . 'tests' . DS . $typeDir . DS;
} else {
$pluginPath = App::pluginPath($category);
if (is_dir($pluginPath . 'tests')) {
$folder = $pluginPath . 'tests' . DS . $typeDir . DS;
}
}
return $folder;
}
|
Finds the correct folder to look for tests for based on the input category and type.
@param string $category The category of the test. Either 'app', 'core' or a plugin name.
@return string the folder path
@access private
|
__findFolderByCategory
|
php
|
Datawalke/Coordino
|
cake/console/libs/testsuite.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/testsuite.php
|
MIT
|
function __installSimpleTest() {
if (!App::import('Vendor', 'simpletest' . DS . 'reporter')) {
$this->err(__('Sorry, Simpletest could not be found. Download it from http://simpletest.org and install it to your vendors directory.', true));
exit;
}
}
|
tries to install simpletest and exits gracefully if it is not there
@return void
@access private
|
__installSimpleTest
|
php
|
Datawalke/Coordino
|
cake/console/libs/testsuite.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/testsuite.php
|
MIT
|
function startup() {
Configure::write('Cache.disable', 1);
parent::startup();
}
|
Disable caching for baking.
This forces the most current database schema to be used.
@return void
|
startup
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/bake.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/bake.php
|
MIT
|
function getPath() {
$path = $this->path;
if (isset($this->plugin)) {
$name = substr($this->name, 0, strlen($this->name) - 4);
$path = $this->_pluginPath($this->plugin) . Inflector::pluralize(Inflector::underscore($name)) . DS;
}
return $path;
}
|
Gets the path for output. Checks the plugin property
and returns the correct path.
@return string Path to output.
@access public
|
getPath
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/bake.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/bake.php
|
MIT
|
function execute() {
if (empty($this->args)) {
return $this->__interactive();
}
if (isset($this->args[0])) {
if (!isset($this->connection)) {
$this->connection = 'default';
}
if (strtolower($this->args[0]) == 'all') {
return $this->all();
}
$controller = $this->_controllerName($this->args[0]);
$actions = 'scaffold';
if (!empty($this->args[1]) && ($this->args[1] == 'public' || $this->args[1] == 'scaffold')) {
$this->out(__('Baking basic crud methods for ', true) . $controller);
$actions = $this->bakeActions($controller);
} elseif (!empty($this->args[1]) && $this->args[1] == 'admin') {
$admin = $this->Project->getPrefix();
if ($admin) {
$this->out(sprintf(__('Adding %s methods', true), $admin));
$actions = $this->bakeActions($controller, $admin);
}
}
if (!empty($this->args[2]) && $this->args[2] == 'admin') {
$admin = $this->Project->getPrefix();
if ($admin) {
$this->out(sprintf(__('Adding %s methods', true), $admin));
$actions .= "\n" . $this->bakeActions($controller, $admin);
}
}
if ($this->bake($controller, $actions)) {
if ($this->_checkUnitTest()) {
$this->bakeTest($controller);
}
}
}
}
|
Execution method always used for tasks
@access public
|
execute
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/controller.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/controller.php
|
MIT
|
function all() {
$this->interactive = false;
$this->listAll($this->connection, false);
ClassRegistry::config('Model', array('ds' => $this->connection));
$unitTestExists = $this->_checkUnitTest();
foreach ($this->__tables as $table) {
$model = $this->_modelName($table);
$controller = $this->_controllerName($model);
if (App::import('Model', $model)) {
$actions = $this->bakeActions($controller);
if ($this->bake($controller, $actions) && $unitTestExists) {
$this->bakeTest($controller);
}
}
}
}
|
Bake All the controllers at once. Will only bake controllers for models that exist.
@access public
@return void
|
all
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/controller.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/controller.php
|
MIT
|
function confirmController($controllerName, $useDynamicScaffold, $helpers, $components) {
$this->out();
$this->hr();
$this->out(__('The following controller will be created:', true));
$this->hr();
$this->out(sprintf(__("Controller Name:\n\t%s", true), $controllerName));
if (strtolower($useDynamicScaffold) == 'y') {
$this->out("var \$scaffold;");
}
$properties = array(
'helpers' => __("Helpers:", true),
'components' => __('Components:', true),
);
foreach ($properties as $var => $title) {
if (count($$var)) {
$output = '';
$length = count($$var);
foreach ($$var as $i => $propElement) {
if ($i != $length -1) {
$output .= ucfirst($propElement) . ', ';
} else {
$output .= ucfirst($propElement);
}
}
$this->out($title . "\n\t" . $output);
}
}
$this->hr();
}
|
Confirm a to be baked controller with the user
@return void
|
confirmController
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/controller.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/controller.php
|
MIT
|
function _askAboutMethods() {
$wannaBakeCrud = $this->in(
__("Would you like to create some basic class methods \n(index(), add(), view(), edit())?", true),
array('y','n'), 'n'
);
$wannaBakeAdminCrud = $this->in(
__("Would you like to create the basic class methods for admin routing?", true),
array('y','n'), 'n'
);
return array($wannaBakeCrud, $wannaBakeAdminCrud);
}
|
Interact with the user and ask about which methods (admin or regular they want to bake)
@return array Array containing (bakeRegular, bakeAdmin) answers
|
_askAboutMethods
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/controller.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/controller.php
|
MIT
|
function bakeActions($controllerName, $admin = null, $wannaUseSession = true) {
$currentModelName = $modelImport = $this->_modelName($controllerName);
$plugin = $this->plugin;
if ($plugin) {
$modelImport = $plugin . '.' . $modelImport;
}
if (!App::import('Model', $modelImport)) {
$this->err(__('You must have a model for this class to build basic methods. Please try again.', true));
$this->_stop();
}
$modelObj =& ClassRegistry::init($currentModelName);
$controllerPath = $this->_controllerPath($controllerName);
$pluralName = $this->_pluralName($currentModelName);
$singularName = Inflector::variable($currentModelName);
$singularHumanName = $this->_singularHumanName($controllerName);
$pluralHumanName = $this->_pluralName($controllerName);
$this->Template->set(compact('plugin', 'admin', 'controllerPath', 'pluralName', 'singularName', 'singularHumanName',
'pluralHumanName', 'modelObj', 'wannaUseSession', 'currentModelName'));
$actions = $this->Template->generate('actions', 'controller_actions');
return $actions;
}
|
Bake scaffold actions
@param string $controllerName Controller name
@param string $admin Admin route to use
@param boolean $wannaUseSession Set to true to use sessions, false otherwise
@return string Baked actions
@access private
|
bakeActions
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/controller.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/controller.php
|
MIT
|
function bake($controllerName, $actions = '', $helpers = null, $components = null) {
$isScaffold = ($actions === 'scaffold') ? true : false;
$this->Template->set('plugin', Inflector::camelize($this->plugin));
$this->Template->set(compact('controllerName', 'actions', 'helpers', 'components', 'isScaffold'));
$contents = $this->Template->generate('classes', 'controller');
$path = $this->getPath();
$filename = $path . $this->_controllerPath($controllerName) . '_controller.php';
if ($this->createFile($filename, $contents)) {
return $contents;
}
return false;
}
|
Assembles and writes a Controller file
@param string $controllerName Controller name
@param string $actions Actions to add, or set the whole controller to use $scaffold (set $actions to 'scaffold')
@param array $helpers Helpers to use in controller
@param array $components Components to use in controller
@param array $uses Models to use in controller
@return string Baked controller
@access private
|
bake
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/controller.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/controller.php
|
MIT
|
function bakeTest($className) {
$this->Test->plugin = $this->plugin;
$this->Test->connection = $this->connection;
$this->Test->interactive = $this->interactive;
return $this->Test->bake('Controller', $className);
}
|
Assembles and writes a unit test file
@param string $className Controller class name
@return string Baked test
@access private
|
bakeTest
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/controller.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/controller.php
|
MIT
|
function doHelpers() {
return $this->_doPropertyChoices(
__("Would you like this controller to use other helpers\nbesides HtmlHelper and FormHelper?", true),
__("Please provide a comma separated list of the other\nhelper names you'd like to use.\nExample: 'Ajax, Javascript, Time'", true)
);
}
|
Interact with the user and get a list of additional helpers
@return array Helpers that the user wants to use.
|
doHelpers
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/controller.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/controller.php
|
MIT
|
function doComponents() {
return $this->_doPropertyChoices(
__("Would you like this controller to use any components?", true),
__("Please provide a comma separated list of the component names you'd like to use.\nExample: 'Acl, Security, RequestHandler'", true)
);
}
|
Interact with the user and get a list of additional components
@return array Components the user wants to use.
|
doComponents
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/controller.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/controller.php
|
MIT
|
function _doPropertyChoices($prompt, $example) {
$proceed = $this->in($prompt, array('y','n'), 'n');
$property = array();
if (strtolower($proceed) == 'y') {
$propertyList = $this->in($example);
$propertyListTrimmed = str_replace(' ', '', $propertyList);
$property = explode(',', $propertyListTrimmed);
}
return array_filter($property);
}
|
Common code for property choice handling.
@param string $prompt A yes/no question to precede the list
@param sting $example A question for a comma separated list, with examples.
@return array Array of values for property.
|
_doPropertyChoices
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/controller.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/controller.php
|
MIT
|
function listAll($useDbConfig = null) {
if (is_null($useDbConfig)) {
$useDbConfig = $this->connection;
}
$this->__tables = $this->Model->getAllTables($useDbConfig);
if ($this->interactive == true) {
$this->out(__('Possible Controllers based on your current database:', true));
$this->_controllerNames = array();
$count = count($this->__tables);
for ($i = 0; $i < $count; $i++) {
$this->_controllerNames[] = $this->_controllerName($this->_modelName($this->__tables[$i]));
$this->out($i + 1 . ". " . $this->_controllerNames[$i]);
}
return $this->_controllerNames;
}
return $this->__tables;
}
|
Outputs and gets the list of possible controllers from database
@param string $useDbConfig Database configuration name
@param boolean $interactive Whether you are using listAll interactively and want options output.
@return array Set of controllers
@access public
|
listAll
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/controller.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/controller.php
|
MIT
|
function getName($useDbConfig = null) {
$controllers = $this->listAll($useDbConfig);
$enteredController = '';
while ($enteredController == '') {
$enteredController = $this->in(__("Enter a number from the list above,\ntype in the name of another controller, or 'q' to exit", true), null, 'q');
if ($enteredController === 'q') {
$this->out(__("Exit", true));
$this->_stop();
}
if ($enteredController == '' || intval($enteredController) > count($controllers)) {
$this->err(__("The Controller name you supplied was empty,\nor the number you selected was not an option. Please try again.", true));
$enteredController = '';
}
}
if (intval($enteredController) > 0 && intval($enteredController) <= count($controllers) ) {
$controllerName = $controllers[intval($enteredController) - 1];
} else {
$controllerName = Inflector::camelize($enteredController);
}
return $controllerName;
}
|
Forces the user to specify the controller he wants to bake, and returns the selected controller name.
@param string $useDbConfig Connection name to get a controller name for.
@return string Controller name
@access public
|
getName
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/controller.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/controller.php
|
MIT
|
function initialize() {
$this->path = $this->params['working'] . DS . 'config' . DS;
}
|
initialization callback
@var string
@access public
|
initialize
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/db_config.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/db_config.php
|
MIT
|
function execute() {
if (empty($this->args)) {
$this->__interactive();
$this->_stop();
}
}
|
Execution method always used for tasks
@access public
|
execute
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/db_config.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/db_config.php
|
MIT
|
function __verify($config) {
$config = array_merge($this->__defaultConfig, $config);
extract($config);
$this->out();
$this->hr();
$this->out('The following database configuration will be created:');
$this->hr();
$this->out("Name: $name");
$this->out("Driver: $driver");
$this->out("Persistent: $persistent");
$this->out("Host: $host");
if ($port) {
$this->out("Port: $port");
}
$this->out("User: $login");
$this->out("Pass: " . str_repeat('*', strlen($password)));
$this->out("Database: $database");
if ($prefix) {
$this->out("Table prefix: $prefix");
}
if ($schema) {
$this->out("Schema: $schema");
}
if ($encoding) {
$this->out("Encoding: $encoding");
}
$this->hr();
$looksGood = $this->in('Look okay?', array('y', 'n'), 'y');
if (strtolower($looksGood) == 'y') {
return $config;
}
return false;
}
|
Output verification message and bake if it looks good
@return boolean True if user says it looks good, false otherwise
@access private
|
__verify
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/db_config.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/db_config.php
|
MIT
|
function bake($configs) {
if (!is_dir($this->path)) {
$this->err($this->path . ' not found');
return false;
}
$filename = $this->path . 'database.php';
$oldConfigs = array();
if (file_exists($filename)) {
config('database');
$db = new $this->databaseClassName;
$temp = get_class_vars(get_class($db));
foreach ($temp as $configName => $info) {
$info = array_merge($this->__defaultConfig, $info);
if (!isset($info['schema'])) {
$info['schema'] = null;
}
if (!isset($info['encoding'])) {
$info['encoding'] = null;
}
if (!isset($info['port'])) {
$info['port'] = null;
}
if ($info['persistent'] === false) {
$info['persistent'] = 'false';
} else {
$info['persistent'] = ($info['persistent'] == true) ? 'true' : 'false';
}
$oldConfigs[] = array(
'name' => $configName,
'driver' => $info['driver'],
'persistent' => $info['persistent'],
'host' => $info['host'],
'port' => $info['port'],
'login' => $info['login'],
'password' => $info['password'],
'database' => $info['database'],
'prefix' => $info['prefix'],
'schema' => $info['schema'],
'encoding' => $info['encoding']
);
}
}
foreach ($oldConfigs as $key => $oldConfig) {
foreach ($configs as $key1 => $config) {
if ($oldConfig['name'] == $config['name']) {
unset($oldConfigs[$key]);
}
}
}
$configs = array_merge($oldConfigs, $configs);
$out = "<?php\n";
$out .= "class DATABASE_CONFIG {\n\n";
foreach ($configs as $config) {
$config = array_merge($this->__defaultConfig, $config);
extract($config);
$out .= "\tvar \${$name} = array(\n";
$out .= "\t\t'driver' => '{$driver}',\n";
$out .= "\t\t'persistent' => {$persistent},\n";
$out .= "\t\t'host' => '{$host}',\n";
if ($port) {
$out .= "\t\t'port' => {$port},\n";
}
$out .= "\t\t'login' => '{$login}',\n";
$out .= "\t\t'password' => '{$password}',\n";
$out .= "\t\t'database' => '{$database}',\n";
if ($schema) {
$out .= "\t\t'schema' => '{$schema}',\n";
}
if ($prefix) {
$out .= "\t\t'prefix' => '{$prefix}',\n";
}
if ($encoding) {
$out .= "\t\t'encoding' => '{$encoding}'\n";
}
$out .= "\t);\n";
}
$out .= "}\n";
$out .= "?>";
$filename = $this->path . 'database.php';
return $this->createFile($filename, $out);
}
|
Assembles and writes database.php
@param array $configs Configuration settings to use
@return boolean Success
@access public
|
bake
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/db_config.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/db_config.php
|
MIT
|
function getConfig() {
App::import('Model', 'ConnectionManager', false);
$useDbConfig = 'default';
$configs = get_class_vars($this->databaseClassName);
if (!is_array($configs)) {
return $this->execute();
}
$connections = array_keys($configs);
if (count($connections) > 1) {
$useDbConfig = $this->in(__('Use Database Config', true) .':', $connections, 'default');
}
return $useDbConfig;
}
|
Get a user specified Connection name
@return void
|
getConfig
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/db_config.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/db_config.php
|
MIT
|
function execute() {
if (isset($this->params['files']) && !is_array($this->params['files'])) {
$this->__files = explode(',', $this->params['files']);
}
if (isset($this->params['paths'])) {
$this->__paths = explode(',', $this->params['paths']);
} else {
$defaultPath = $this->params['working'];
$message = sprintf(__("What is the full path you would like to extract?\nExample: %s\n[Q]uit [D]one", true), $this->params['root'] . DS . 'myapp');
while (true) {
$response = $this->in($message, null, $defaultPath);
if (strtoupper($response) === 'Q') {
$this->out(__('Extract Aborted', true));
$this->_stop();
} elseif (strtoupper($response) === 'D') {
$this->out();
break;
} elseif (is_dir($response)) {
$this->__paths[] = $response;
$defaultPath = 'D';
} else {
$this->err(__('The directory path you supplied was not found. Please try again.', true));
}
$this->out();
}
}
if (isset($this->params['output'])) {
$this->__output = $this->params['output'];
} else {
$message = sprintf(__("What is the full path you would like to output?\nExample: %s\n[Q]uit", true), $this->__paths[0] . DS . 'locale');
while (true) {
$response = $this->in($message, null, $this->__paths[0] . DS . 'locale');
if (strtoupper($response) === 'Q') {
$this->out(__('Extract Aborted', true));
$this->_stop();
} elseif (is_dir($response)) {
$this->__output = $response . DS;
break;
} else {
$this->err(__('The directory path you supplied was not found. Please try again.', true));
}
$this->out();
}
}
if (isset($this->params['merge'])) {
$this->__merge = !(strtolower($this->params['merge']) === 'no');
} else {
$this->out();
$response = $this->in(sprintf(__('Would you like to merge all domains strings into the default.pot file?', true)), array('y', 'n'), 'n');
$this->__merge = strtolower($response) === 'y';
}
if (empty($this->__files)) {
$this->__searchFiles();
}
$this->__extract();
}
|
Execution method always used for tasks
@return void
@access private
|
execute
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/extract.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/extract.php
|
MIT
|
function __extract() {
$this->out();
$this->out();
$this->out(__('Extracting...', true));
$this->hr();
$this->out(__('Paths:', true));
foreach ($this->__paths as $path) {
$this->out(' ' . $path);
}
$this->out(__('Output Directory: ', true) . $this->__output);
$this->hr();
$this->__extractTokens();
$this->__buildFiles();
$this->__writeFiles();
$this->__paths = $this->__files = $this->__storage = array();
$this->__strings = $this->__tokens = array();
$this->out();
$this->out(__('Done.', true));
}
|
Extract text
@return void
@access private
|
__extract
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/extract.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/extract.php
|
MIT
|
function help() {
$this->out(__('CakePHP Language String Extraction:', true));
$this->hr();
$this->out(__('The Extract script generates .pot file(s) with translations', true));
$this->out(__('By default the .pot file(s) will be place in the locale directory of -app', true));
$this->out(__('By default -app is ROOT/app', true));
$this->hr();
$this->out(__('Usage: cake i18n extract <command> <param1> <param2>...', true));
$this->out();
$this->out(__('Params:', true));
$this->out(__(' -app [path...]: directory where your application is located', true));
$this->out(__(' -root [path...]: path to install', true));
$this->out(__(' -core [path...]: path to cake directory', true));
$this->out(__(' -paths [comma separated list of paths, full path is needed]', true));
$this->out(__(' -merge [yes|no]: Merge all domains strings into the default.pot file', true));
$this->out(__(' -output [path...]: Full path to output directory', true));
$this->out(__(' -files: [comma separated list of files, full path to file is needed]', true));
$this->out();
$this->out(__('Commands:', true));
$this->out(__(' cake i18n extract help: Shows this help message.', true));
$this->out();
}
|
Show help options
@return void
@access public
|
help
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/extract.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/extract.php
|
MIT
|
function __extractTokens() {
foreach ($this->__files as $file) {
$this->__file = $file;
$this->out(sprintf(__('Processing %s...', true), $file));
$code = file_get_contents($file);
$allTokens = token_get_all($code);
$this->__tokens = array();
$lineNumber = 1;
foreach ($allTokens as $token) {
if ((!is_array($token)) || (($token[0] != T_WHITESPACE) && ($token[0] != T_INLINE_HTML))) {
if (is_array($token)) {
$token[] = $lineNumber;
}
$this->__tokens[] = $token;
}
if (is_array($token)) {
$lineNumber += count(explode("\n", $token[1])) - 1;
} else {
$lineNumber += count(explode("\n", $token)) - 1;
}
}
unset($allTokens);
$this->__parse('__', array('singular'));
$this->__parse('__n', array('singular', 'plural'));
$this->__parse('__d', array('domain', 'singular'));
$this->__parse('__c', array('singular'));
$this->__parse('__dc', array('domain', 'singular'));
$this->__parse('__dn', array('domain', 'singular', 'plural'));
$this->__parse('__dcn', array('domain', 'singular', 'plural'));
}
}
|
Extract tokens out of all files to be processed
@return void
@access private
|
__extractTokens
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/extract.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/extract.php
|
MIT
|
function __parse($functionName, $map) {
$count = 0;
$tokenCount = count($this->__tokens);
while (($tokenCount - $count) > 1) {
list($countToken, $firstParenthesis) = array($this->__tokens[$count], $this->__tokens[$count + 1]);
if (!is_array($countToken)) {
$count++;
continue;
}
list($type, $string, $line) = $countToken;
if (($type == T_STRING) && ($string == $functionName) && ($firstParenthesis == '(')) {
$position = $count;
$depth = 0;
while ($depth == 0) {
if ($this->__tokens[$position] == '(') {
$depth++;
} elseif ($this->__tokens[$position] == ')') {
$depth--;
}
$position++;
}
$mapCount = count($map);
$strings = $this->__getStrings($position, $mapCount);
if ($mapCount == count($strings)) {
extract(array_combine($map, $strings));
$domain = isset($domain) ? $domain : 'default';
$string = isset($plural) ? $singular . "\0" . $plural : $singular;
$this->__strings[$domain][$string][$this->__file][] = $line;
} else {
$this->__markerError($this->__file, $line, $functionName, $count);
}
}
$count++;
}
}
|
Parse tokens
@param string $functionName Function name that indicates translatable string (e.g: '__')
@param array $map Array containing what variables it will find (e.g: domain, singular, plural)
@return void
@access private
|
__parse
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/extract.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/extract.php
|
MIT
|
function __getStrings($position, $target) {
$strings = array();
while (count($strings) < $target && ($this->__tokens[$position] == ',' || $this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING)) {
$condition1 = ($this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING && $this->__tokens[$position+1] == '.');
$condition2 = ($this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING && $this->__tokens[$position+1][0] == T_COMMENT);
if ($condition1 || $condition2) {
$string = '';
while ($this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING || $this->__tokens[$position][0] == T_COMMENT || $this->__tokens[$position] == '.') {
if ($this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
$string .= $this->__formatString($this->__tokens[$position][1]);
}
$position++;
}
if ($this->__tokens[$position][0] == T_COMMENT || $this->__tokens[$position] == ',' || $this->__tokens[$position] == ')') {
$strings[] = $string;
}
} else if ($this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
$strings[] = $this->__formatString($this->__tokens[$position][1]);
}
$position++;
}
return $strings;
}
|
Get the strings from the position forward
@param integer $position Actual position on tokens array
@param integer $target Number of strings to extract
@return array Strings extracted
|
__getStrings
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/extract.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/extract.php
|
MIT
|
function __buildFiles() {
foreach ($this->__strings as $domain => $strings) {
foreach ($strings as $string => $files) {
$occurrences = array();
foreach ($files as $file => $lines) {
$occurrences[] = $file . ':' . implode(';', $lines);
}
$occurrences = implode("\n#: ", $occurrences);
$header = '#: ' . str_replace($this->__paths, '', $occurrences) . "\n";
if (strpos($string, "\0") === false) {
$sentence = "msgid \"{$string}\"\n";
$sentence .= "msgstr \"\"\n\n";
} else {
list($singular, $plural) = explode("\0", $string);
$sentence = "msgid \"{$singular}\"\n";
$sentence .= "msgid_plural \"{$plural}\"\n";
$sentence .= "msgstr[0] \"\"\n";
$sentence .= "msgstr[1] \"\"\n\n";
}
$this->__store($domain, $header, $sentence);
if ($domain != 'default' && $this->__merge) {
$this->__store('default', $header, $sentence);
}
}
}
}
|
Build the translate template file contents out of obtained strings
@return void
@access private
|
__buildFiles
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/extract.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/extract.php
|
MIT
|
function __store($domain, $header, $sentence) {
if (!isset($this->__storage[$domain])) {
$this->__storage[$domain] = array();
}
if (!isset($this->__storage[$domain][$sentence])) {
$this->__storage[$domain][$sentence] = $header;
} else {
$this->__storage[$domain][$sentence] .= $header;
}
}
|
Prepare a file to be stored
@return void
@access private
|
__store
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/extract.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/extract.php
|
MIT
|
function __writeFiles() {
$overwriteAll = false;
foreach ($this->__storage as $domain => $sentences) {
$output = $this->__writeHeader();
foreach ($sentences as $sentence => $header) {
$output .= $header . $sentence;
}
$filename = $domain . '.pot';
$File = new File($this->__output . $filename);
$response = '';
while ($overwriteAll === false && $File->exists() && strtoupper($response) !== 'Y') {
$this->out();
$response = $this->in(sprintf(__('Error: %s already exists in this location. Overwrite? [Y]es, [N]o, [A]ll', true), $filename), array('y', 'n', 'a'), 'y');
if (strtoupper($response) === 'N') {
$response = '';
while ($response == '') {
$response = $this->in(sprintf(__("What would you like to name this file?\nExample: %s", true), 'new_' . $filename), null, 'new_' . $filename);
$File = new File($this->__output . $response);
$filename = $response;
}
} elseif (strtoupper($response) === 'A') {
$overwriteAll = true;
}
}
$File->write($output);
$File->close();
}
}
|
Write the files that need to be stored
@return void
@access private
|
__writeFiles
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/extract.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/extract.php
|
MIT
|
function __writeHeader() {
$output = "# LANGUAGE translation of CakePHP Application\n";
$output .= "# Copyright YEAR NAME <EMAIL@ADDRESS>\n";
$output .= "#\n";
$output .= "#, fuzzy\n";
$output .= "msgid \"\"\n";
$output .= "msgstr \"\"\n";
$output .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
$output .= "\"POT-Creation-Date: " . date("Y-m-d H:iO") . "\\n\"\n";
$output .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
$output .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
$output .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
$output .= "\"MIME-Version: 1.0\\n\"\n";
$output .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
$output .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
$output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";
return $output;
}
|
Build the translation template header
@return string Translation template header
@access private
|
__writeHeader
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/extract.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/extract.php
|
MIT
|
function __formatString($string) {
$quote = substr($string, 0, 1);
$string = substr($string, 1, -1);
if ($quote == '"') {
$string = stripcslashes($string);
} else {
$string = strtr($string, array("\\'" => "'", "\\\\" => "\\"));
}
$string = str_replace("\r\n", "\n", $string);
return addcslashes($string, "\0..\37\\\"");
}
|
Format a string to be added as a translateable string
@param string $string String to format
@return string Formatted string
@access private
|
__formatString
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/extract.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/extract.php
|
MIT
|
function __markerError($file, $line, $marker, $count) {
$this->out(sprintf(__("Invalid marker content in %s:%s\n* %s(", true), $file, $line, $marker), true);
$count += 2;
$tokenCount = count($this->__tokens);
$parenthesis = 1;
while ((($tokenCount - $count) > 0) && $parenthesis) {
if (is_array($this->__tokens[$count])) {
$this->out($this->__tokens[$count][1], false);
} else {
$this->out($this->__tokens[$count], false);
if ($this->__tokens[$count] == '(') {
$parenthesis++;
}
if ($this->__tokens[$count] == ')') {
$parenthesis--;
}
}
$count++;
}
$this->out("\n", true);
}
|
Indicate an invalid marker on a processed file
@param string $file File where invalid marker resides
@param integer $line Line number
@param string $marker Marker found
@param integer $count Count
@return void
@access private
|
__markerError
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/extract.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/extract.php
|
MIT
|
function __searchFiles() {
foreach ($this->__paths as $path) {
$Folder = new Folder($path);
$files = $Folder->findRecursive('.*\.(php|ctp|thtml|inc|tpl)', true);
$this->__files = array_merge($this->__files, $files);
}
}
|
Search files that may contain translateable strings
@return void
@access private
|
__searchFiles
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/extract.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/extract.php
|
MIT
|
function execute() {
if (empty($this->args)) {
$this->__interactive();
}
if (isset($this->args[0])) {
$this->interactive = false;
if (!isset($this->connection)) {
$this->connection = 'default';
}
if (strtolower($this->args[0]) == 'all') {
return $this->all();
}
$model = $this->_modelName($this->args[0]);
$this->bake($model);
}
}
|
Execution method always used for tasks
Handles dispatching to interactive, named, or all processess.
@access public
|
execute
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/fixture.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/fixture.php
|
MIT
|
function all() {
$this->interactive = false;
$this->Model->interactive = false;
$tables = $this->Model->listAll($this->connection, false);
foreach ($tables as $table) {
$model = $this->_modelName($table);
$this->bake($model);
}
}
|
Bake All the Fixtures at once. Will only bake fixtures for models that exist.
@access public
@return void
|
all
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/fixture.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/fixture.php
|
MIT
|
function importOptions($modelName) {
$options = array();
$doSchema = $this->in(__('Would you like to import schema for this fixture?', true), array('y', 'n'), 'n');
if ($doSchema == 'y') {
$options['schema'] = $modelName;
}
$doRecords = $this->in(__('Would you like to use record importing for this fixture?', true), array('y', 'n'), 'n');
if ($doRecords == 'y') {
$options['records'] = true;
}
if ($doRecords == 'n') {
$prompt = sprintf(__("Would you like to build this fixture with data from %s's table?", true), $modelName);
$fromTable = $this->in($prompt, array('y', 'n'), 'n');
if (strtolower($fromTable) == 'y') {
$options['fromTable'] = true;
}
}
return $options;
}
|
Interacts with the User to setup an array of import options. For a fixture.
@param string $modelName Name of model you are dealing with.
@return array Array of import options.
@access public
|
importOptions
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/fixture.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/fixture.php
|
MIT
|
function bake($model, $useTable = false, $importOptions = array()) {
if (!class_exists('CakeSchema')) {
App::import('Model', 'CakeSchema', false);
}
$table = $schema = $records = $import = $modelImport = null;
$importBits = array();
if (!$useTable) {
$useTable = Inflector::tableize($model);
} elseif ($useTable != Inflector::tableize($model)) {
$table = $useTable;
}
if (!empty($importOptions)) {
if (isset($importOptions['schema'])) {
$modelImport = true;
$importBits[] = "'model' => '{$importOptions['schema']}'";
}
if (isset($importOptions['records'])) {
$importBits[] = "'records' => true";
}
if ($this->connection != 'default') {
$importBits[] .= "'connection' => '{$this->connection}'";
}
if (!empty($importBits)) {
$import = sprintf("array(%s)", implode(', ', $importBits));
}
}
$this->_Schema = new CakeSchema();
$data = $this->_Schema->read(array('models' => false, 'connection' => $this->connection));
if (!isset($data['tables'][$useTable])) {
$this->err('Could not find your selected table ' . $useTable);
return false;
}
$tableInfo = $data['tables'][$useTable];
if (is_null($modelImport)) {
$schema = $this->_generateSchema($tableInfo);
}
if (!isset($importOptions['records']) && !isset($importOptions['fromTable'])) {
$recordCount = 1;
if (isset($this->params['count'])) {
$recordCount = $this->params['count'];
}
$records = $this->_makeRecordString($this->_generateRecords($tableInfo, $recordCount));
}
if (isset($this->params['records']) || isset($importOptions['fromTable'])) {
$records = $this->_makeRecordString($this->_getRecordsFromTable($model, $useTable));
}
$out = $this->generateFixtureFile($model, compact('records', 'table', 'schema', 'import', 'fields'));
return $out;
}
|
Assembles and writes a Fixture file
@param string $model Name of model to bake.
@param string $useTable Name of table to use.
@param array $importOptions Options for var $import
@return string Baked fixture content
@access public
|
bake
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/fixture.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/fixture.php
|
MIT
|
function generateFixtureFile($model, $otherVars) {
$defaults = array('table' => null, 'schema' => null, 'records' => null, 'import' => null, 'fields' => null);
$vars = array_merge($defaults, $otherVars);
$path = $this->getPath();
$filename = Inflector::underscore($model) . '_fixture.php';
$this->Template->set('model', $model);
$this->Template->set($vars);
$content = $this->Template->generate('classes', 'fixture');
$this->out("\nBaking test fixture for $model...");
$this->createFile($path . $filename, $content);
return $content;
}
|
Generate the fixture file, and write to disk
@param string $model name of the model being generated
@param string $fixture Contents of the fixture file.
@return string Content saved into fixture file.
@access public
|
generateFixtureFile
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/fixture.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/fixture.php
|
MIT
|
function getPath() {
$path = $this->path;
if (isset($this->plugin)) {
$path = $this->_pluginPath($this->plugin) . 'tests' . DS . 'fixtures' . DS;
}
return $path;
}
|
Get the path to the fixtures.
@return void
|
getPath
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/fixture.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/fixture.php
|
MIT
|
function _generateSchema($tableInfo) {
$schema = $this->_Schema->generateTable('f', $tableInfo);
return substr($schema, 10, -2);
}
|
Generates a string representation of a schema.
@param array $table Table schema array
@return string fields definitions
@access protected
|
_generateSchema
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/fixture.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/fixture.php
|
MIT
|
function _generateRecords($tableInfo, $recordCount = 1) {
$records = array();
for ($i = 0; $i < $recordCount; $i++) {
$record = array();
foreach ($tableInfo as $field => $fieldInfo) {
if (empty($fieldInfo['type'])) {
continue;
}
switch ($fieldInfo['type']) {
case 'integer':
case 'float':
$insert = $i + 1;
break;
case 'string':
case 'binary':
$isPrimaryUuid = (
isset($fieldInfo['key']) && strtolower($fieldInfo['key']) == 'primary' &&
isset($fieldInfo['length']) && $fieldInfo['length'] == 36
);
if ($isPrimaryUuid) {
$insert = String::uuid();
} else {
$insert = "Lorem ipsum dolor sit amet";
if (!empty($fieldInfo['length'])) {
$insert = substr($insert, 0, (int)$fieldInfo['length'] - 2);
}
}
break;
case 'timestamp':
$insert = time();
break;
case 'datetime':
$insert = date('Y-m-d H:i:s');
break;
case 'date':
$insert = date('Y-m-d');
break;
case 'time':
$insert = date('H:i:s');
break;
case 'boolean':
$insert = 1;
break;
case 'text':
$insert = "Lorem ipsum dolor sit amet, aliquet feugiat.";
$insert .= " Convallis morbi fringilla gravida,";
$insert .= " phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin";
$insert .= " venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla";
$insert .= " vestibulum massa neque ut et, id hendrerit sit,";
$insert .= " feugiat in taciti enim proin nibh, tempor dignissim, rhoncus";
$insert .= " duis vestibulum nunc mattis convallis.";
break;
}
$record[$field] = $insert;
}
$records[] = $record;
}
return $records;
}
|
Generate String representation of Records
@param array $table Table schema array
@return array Array of records to use in the fixture.
@access protected
|
_generateRecords
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/fixture.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/fixture.php
|
MIT
|
function _makeRecordString($records) {
$out = "array(\n";
foreach ($records as $record) {
$values = array();
foreach ($record as $field => $value) {
$val = var_export($value, true);
$values[] = "\t\t\t'$field' => $val";
}
$out .= "\t\tarray(\n";
$out .= implode(",\n", $values);
$out .= "\n\t\t),\n";
}
$out .= "\t)";
return $out;
}
|
Convert a $records array into a a string.
@param array $records Array of records to be converted to string
@return string A string value of the $records array.
@access protected
|
_makeRecordString
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/fixture.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/fixture.php
|
MIT
|
function _getRecordsFromTable($modelName, $useTable = null) {
if ($this->interactive) {
$condition = null;
$prompt = __("Please provide a SQL fragment to use as conditions\nExample: WHERE 1=1 LIMIT 10", true);
while (!$condition) {
$condition = $this->in($prompt, null, 'WHERE 1=1 LIMIT 10');
}
} else {
$condition = 'WHERE 1=1 LIMIT ' . (isset($this->params['count']) ? $this->params['count'] : 10);
}
App::import('Model', 'Model', false);
$modelObject =& new Model(array('name' => $modelName, 'table' => $useTable, 'ds' => $this->connection));
$records = $modelObject->find('all', array(
'conditions' => $condition,
'recursive' => -1
));
$db =& ConnectionManager::getDataSource($modelObject->useDbConfig);
$schema = $modelObject->schema(true);
$out = array();
foreach ($records as $record) {
$row = array();
foreach ($record[$modelObject->alias] as $field => $value) {
if ($schema[$field]['type'] === 'boolean') {
$value = (int)(bool)$value;
}
$row[$field] = $value;
}
$out[] = $row;
}
return $out;
}
|
Interact with the user to get a custom SQL condition and use that to extract data
to build a fixture.
@param string $modelName name of the model to take records from.
@param string $useTable Name of table to use.
@return array Array of records.
@access protected
|
_getRecordsFromTable
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/fixture.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/fixture.php
|
MIT
|
function execute() {
App::import('Model', 'Model', false);
if (empty($this->args)) {
$this->__interactive();
}
if (!empty($this->args[0])) {
$this->interactive = false;
if (!isset($this->connection)) {
$this->connection = 'default';
}
if (strtolower($this->args[0]) == 'all') {
return $this->all();
}
$model = $this->_modelName($this->args[0]);
$object = $this->_getModelObject($model);
if ($this->bake($object, false)) {
if ($this->_checkUnitTest()) {
$this->bakeFixture($model);
$this->bakeTest($model);
}
}
}
}
|
Execution method always used for tasks
@access public
|
execute
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/model.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/model.php
|
MIT
|
function all() {
$this->listAll($this->connection, false);
$unitTestExists = $this->_checkUnitTest();
foreach ($this->_tables as $table) {
if (in_array($table, $this->skipTables)) {
continue;
}
$modelClass = Inflector::classify($table);
$this->out(sprintf(__('Baking %s', true), $modelClass));
$object = $this->_getModelObject($modelClass);
if ($this->bake($object, false) && $unitTestExists) {
$this->bakeFixture($modelClass);
$this->bakeTest($modelClass);
}
}
}
|
Bake all models at once.
@return void
|
all
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/model.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/model.php
|
MIT
|
function &_getModelObject($className, $table = null) {
if (!$table) {
$table = Inflector::tableize($className);
}
$object =& new Model(array('name' => $className, 'table' => $table, 'ds' => $this->connection));
return $object;
}
|
Get a model object for a class name.
@param string $className Name of class you want model to be.
@return object Model instance
|
_getModelObject
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/model.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/model.php
|
MIT
|
function inOptions($options, $prompt = null, $default = null) {
$valid = false;
$max = count($options);
while (!$valid) {
foreach ($options as $i => $option) {
$this->out($i + 1 .'. ' . $option);
}
if (empty($prompt)) {
$prompt = __('Make a selection from the choices above', true);
}
$choice = $this->in($prompt, null, $default);
if (intval($choice) > 0 && intval($choice) <= $max) {
$valid = true;
}
}
return $choice - 1;
}
|
Generate a key value list of options and a prompt.
@param array $options Array of options to use for the selections. indexes must start at 0
@param string $prompt Prompt to use for options list.
@param integer $default The default option for the given prompt.
@return result of user choice.
|
inOptions
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/model.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/model.php
|
MIT
|
function _printAssociation($modelName, $type, $associations) {
if (!empty($associations[$type])) {
for ($i = 0; $i < count($associations[$type]); $i++) {
$out = "\t" . $modelName . ' ' . $type . ' ' . $associations[$type][$i]['alias'];
$this->out($out);
}
}
}
|
Print out all the associations of a particular type
@param string $modelName Name of the model relations belong to.
@param string $type Name of association you want to see. i.e. 'belongsTo'
@param string $associations Collection of associations.
@access protected
@return void
|
_printAssociation
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/model.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/model.php
|
MIT
|
function findPrimaryKey($fields) {
foreach ($fields as $name => $field) {
if (isset($field['key']) && $field['key'] == 'primary') {
break;
}
}
return $this->in(__('What is the primaryKey?', true), null, $name);
}
|
Finds a primary Key in a list of fields.
@param array $fields Array of fields that might have a primary key.
@return string Name of field that is a primary key.
@access public
|
findPrimaryKey
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/model.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/model.php
|
MIT
|
function findDisplayField($fields) {
$fieldNames = array_keys($fields);
$prompt = __("A displayField could not be automatically detected\nwould you like to choose one?", true);
$continue = $this->in($prompt, array('y', 'n'));
if (strtolower($continue) == 'n') {
return false;
}
$prompt = __('Choose a field from the options above:', true);
$choice = $this->inOptions($fieldNames, $prompt);
return $fieldNames[$choice];
}
|
interact with the user to find the displayField value for a model.
@param array $fields Array of fields to look for and choose as a displayField
@return mixed Name of field to use for displayField or false if the user declines to choose
|
findDisplayField
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/model.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/model.php
|
MIT
|
function doValidation(&$model) {
if (!is_object($model)) {
return false;
}
$fields = $model->schema();
if (empty($fields)) {
return false;
}
$validate = array();
$this->initValidations();
foreach ($fields as $fieldName => $field) {
$validation = $this->fieldValidation($fieldName, $field, $model->primaryKey);
if (!empty($validation)) {
$validate[$fieldName] = $validation;
}
}
return $validate;
}
|
Handles Generation and user interaction for creating validation.
@param object $model Model to have validations generated for.
@return array $validate Array of user selected validations.
@access public
|
doValidation
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/model.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/model.php
|
MIT
|
function fieldValidation($fieldName, $metaData, $primaryKey = 'id') {
$defaultChoice = count($this->_validations);
$validate = $alreadyChosen = array();
$anotherValidator = 'y';
while ($anotherValidator == 'y') {
if ($this->interactive) {
$this->out();
$this->out(sprintf(__('Field: %s', true), $fieldName));
$this->out(sprintf(__('Type: %s', true), $metaData['type']));
$this->hr();
$this->out(__('Please select one of the following validation options:', true));
$this->hr();
}
$prompt = '';
for ($i = 1; $i < $defaultChoice; $i++) {
$prompt .= $i . ' - ' . $this->_validations[$i] . "\n";
}
$prompt .= sprintf(__("%s - Do not do any validation on this field.\n", true), $defaultChoice);
$prompt .= __("... or enter in a valid regex validation string.\n", true);
$methods = array_flip($this->_validations);
$guess = $defaultChoice;
if ($metaData['null'] != 1 && !in_array($fieldName, array($primaryKey, 'created', 'modified', 'updated'))) {
if ($fieldName == 'email') {
$guess = $methods['email'];
} elseif ($metaData['type'] == 'string' && $metaData['length'] == 36) {
$guess = $methods['uuid'];
} elseif ($metaData['type'] == 'string') {
$guess = $methods['notempty'];
} elseif ($metaData['type'] == 'integer') {
$guess = $methods['numeric'];
} elseif ($metaData['type'] == 'boolean') {
$guess = $methods['boolean'];
} elseif ($metaData['type'] == 'date') {
$guess = $methods['date'];
} elseif ($metaData['type'] == 'time') {
$guess = $methods['time'];
}
}
if ($this->interactive === true) {
$choice = $this->in($prompt, null, $guess);
if (in_array($choice, $alreadyChosen)) {
$this->out(__("You have already chosen that validation rule,\nplease choose again", true));
continue;
}
if (!isset($this->_validations[$choice]) && is_numeric($choice)) {
$this->out(__('Please make a valid selection.', true));
continue;
}
$alreadyChosen[] = $choice;
} else {
$choice = $guess;
}
if (isset($this->_validations[$choice])) {
$validatorName = $this->_validations[$choice];
} else {
$validatorName = Inflector::slug($choice);
}
if ($choice != $defaultChoice) {
if (is_numeric($choice) && isset($this->_validations[$choice])) {
$validate[$validatorName] = $this->_validations[$choice];
} else {
$validate[$validatorName] = $choice;
}
}
if ($this->interactive == true && $choice != $defaultChoice) {
$anotherValidator = $this->in(__('Would you like to add another validation rule?', true), array('y', 'n'), 'n');
} else {
$anotherValidator = 'n';
}
}
return $validate;
}
|
Does individual field validation handling.
@param string $fieldName Name of field to be validated.
@param array $metaData metadata for field
@return array Array of validation for the field.
|
fieldValidation
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/model.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/model.php
|
MIT
|
function doAssociations(&$model) {
if (!is_object($model)) {
return false;
}
if ($this->interactive === true) {
$this->out(__('One moment while the associations are detected.', true));
}
$fields = $model->schema(true);
if (empty($fields)) {
return false;
}
if (empty($this->_tables)) {
$this->_tables = $this->getAllTables();
}
$associations = array(
'belongsTo' => array(), 'hasMany' => array(), 'hasOne'=> array(), 'hasAndBelongsToMany' => array()
);
$possibleKeys = array();
$associations = $this->findBelongsTo($model, $associations);
$associations = $this->findHasOneAndMany($model, $associations);
$associations = $this->findHasAndBelongsToMany($model, $associations);
if ($this->interactive !== true) {
unset($associations['hasOne']);
}
if ($this->interactive === true) {
$this->hr();
if (empty($associations)) {
$this->out(__('None found.', true));
} else {
$this->out(__('Please confirm the following associations:', true));
$this->hr();
$associations = $this->confirmAssociations($model, $associations);
}
$associations = $this->doMoreAssociations($model, $associations);
}
return $associations;
}
|
Handles associations
@param object $model
@return array $assocaitons
@access public
|
doAssociations
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/model.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/model.php
|
MIT
|
function findBelongsTo(&$model, $associations) {
$fields = $model->schema(true);
foreach ($fields as $fieldName => $field) {
$offset = strpos($fieldName, '_id');
if ($fieldName != $model->primaryKey && $fieldName != 'parent_id' && $offset !== false) {
$tmpModelName = $this->_modelNameFromKey($fieldName);
$associations['belongsTo'][] = array(
'alias' => $tmpModelName,
'className' => $tmpModelName,
'foreignKey' => $fieldName,
);
} elseif ($fieldName == 'parent_id') {
$associations['belongsTo'][] = array(
'alias' => 'Parent' . $model->name,
'className' => $model->name,
'foreignKey' => $fieldName,
);
}
}
return $associations;
}
|
Find belongsTo relations and add them to the associations list.
@param object $model Model instance of model being generated.
@param array $associations Array of inprogress associations
@return array $associations with belongsTo added in.
|
findBelongsTo
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/model.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/model.php
|
MIT
|
function findHasOneAndMany(&$model, $associations) {
$foreignKey = $this->_modelKey($model->name);
foreach ($this->_tables as $otherTable) {
$tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
$modelFieldsTemp = $tempOtherModel->schema(true);
$pattern = '/_' . preg_quote($model->table, '/') . '|' . preg_quote($model->table, '/') . '_/';
$possibleJoinTable = preg_match($pattern , $otherTable);
if ($possibleJoinTable == true) {
continue;
}
foreach ($modelFieldsTemp as $fieldName => $field) {
$assoc = false;
if ($fieldName != $model->primaryKey && $fieldName == $foreignKey) {
$assoc = array(
'alias' => $tempOtherModel->name,
'className' => $tempOtherModel->name,
'foreignKey' => $fieldName
);
} elseif ($otherTable == $model->table && $fieldName == 'parent_id') {
$assoc = array(
'alias' => 'Child' . $model->name,
'className' => $model->name,
'foreignKey' => $fieldName
);
}
if ($assoc) {
$associations['hasOne'][] = $assoc;
$associations['hasMany'][] = $assoc;
}
}
}
return $associations;
}
|
Find the hasOne and HasMany relations and add them to associations list
@param object $model Model instance being generated
@param array $associations Array of inprogress associations
@return array $associations with hasOne and hasMany added in.
|
findHasOneAndMany
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/model.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/model.php
|
MIT
|
function findHasAndBelongsToMany(&$model, $associations) {
$foreignKey = $this->_modelKey($model->name);
foreach ($this->_tables as $otherTable) {
$tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
$modelFieldsTemp = $tempOtherModel->schema(true);
$offset = strpos($otherTable, $model->table . '_');
$otherOffset = strpos($otherTable, '_' . $model->table);
if ($offset !== false) {
$offset = strlen($model->table . '_');
$habtmName = $this->_modelName(substr($otherTable, $offset));
$associations['hasAndBelongsToMany'][] = array(
'alias' => $habtmName,
'className' => $habtmName,
'foreignKey' => $foreignKey,
'associationForeignKey' => $this->_modelKey($habtmName),
'joinTable' => $otherTable
);
} elseif ($otherOffset !== false) {
$habtmName = $this->_modelName(substr($otherTable, 0, $otherOffset));
$associations['hasAndBelongsToMany'][] = array(
'alias' => $habtmName,
'className' => $habtmName,
'foreignKey' => $foreignKey,
'associationForeignKey' => $this->_modelKey($habtmName),
'joinTable' => $otherTable
);
}
}
return $associations;
}
|
Find the hasAndBelongsToMany relations and add them to associations list
@param object $model Model instance being generated
@param array $associations Array of inprogress associations
@return array $associations with hasAndBelongsToMany added in.
|
findHasAndBelongsToMany
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/model.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/model.php
|
MIT
|
function confirmAssociations(&$model, $associations) {
foreach ($associations as $type => $settings) {
if (!empty($associations[$type])) {
$count = count($associations[$type]);
$response = 'y';
foreach ($associations[$type] as $i => $assoc) {
$prompt = "{$model->name} {$type} {$assoc['alias']}?";
$response = $this->in($prompt, array('y','n'), 'y');
if ('n' == strtolower($response)) {
unset($associations[$type][$i]);
} elseif ($type == 'hasMany') {
unset($associations['hasOne'][$i]);
}
}
$associations[$type] = array_merge($associations[$type]);
}
}
return $associations;
}
|
Interact with the user and confirm associations.
@param array $model Temporary Model instance.
@param array $associations Array of associations to be confirmed.
@return array Array of confirmed associations
|
confirmAssociations
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/model.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/model.php
|
MIT
|
function doMoreAssociations($model, $associations) {
$prompt = __('Would you like to define some additional model associations?', true);
$wannaDoMoreAssoc = $this->in($prompt, array('y','n'), 'n');
$possibleKeys = $this->_generatePossibleKeys();
while (strtolower($wannaDoMoreAssoc) == 'y') {
$assocs = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
$this->out(__('What is the association type?', true));
$assocType = intval($this->inOptions($assocs, __('Enter a number',true)));
$this->out(__("For the following options be very careful to match your setup exactly.\nAny spelling mistakes will cause errors.", true));
$this->hr();
$alias = $this->in(__('What is the alias for this association?', true));
$className = $this->in(sprintf(__('What className will %s use?', true), $alias), null, $alias );
$suggestedForeignKey = null;
if ($assocType == 0) {
$showKeys = $possibleKeys[$model->table];
$suggestedForeignKey = $this->_modelKey($alias);
} else {
$otherTable = Inflector::tableize($className);
if (in_array($otherTable, $this->_tables)) {
if ($assocType < 3) {
$showKeys = $possibleKeys[$otherTable];
} else {
$showKeys = null;
}
} else {
$otherTable = $this->in(__('What is the table for this model?', true));
$showKeys = $possibleKeys[$otherTable];
}
$suggestedForeignKey = $this->_modelKey($model->name);
}
if (!empty($showKeys)) {
$this->out(__('A helpful List of possible keys', true));
$foreignKey = $this->inOptions($showKeys, __('What is the foreignKey?', true));
$foreignKey = $showKeys[intval($foreignKey)];
}
if (!isset($foreignKey)) {
$foreignKey = $this->in(__('What is the foreignKey? Specify your own.', true), null, $suggestedForeignKey);
}
if ($assocType == 3) {
$associationForeignKey = $this->in(__('What is the associationForeignKey?', true), null, $this->_modelKey($model->name));
$joinTable = $this->in(__('What is the joinTable?', true));
}
$associations[$assocs[$assocType]] = array_values((array)$associations[$assocs[$assocType]]);
$count = count($associations[$assocs[$assocType]]);
$i = ($count > 0) ? $count : 0;
$associations[$assocs[$assocType]][$i]['alias'] = $alias;
$associations[$assocs[$assocType]][$i]['className'] = $className;
$associations[$assocs[$assocType]][$i]['foreignKey'] = $foreignKey;
if ($assocType == 3) {
$associations[$assocs[$assocType]][$i]['associationForeignKey'] = $associationForeignKey;
$associations[$assocs[$assocType]][$i]['joinTable'] = $joinTable;
}
$wannaDoMoreAssoc = $this->in(__('Define another association?', true), array('y','n'), 'y');
}
return $associations;
}
|
Interact with the user and generate additional non-conventional associations
@param object $model Temporary model instance
@param array $associations Array of associations.
@return array Array of associations.
|
doMoreAssociations
|
php
|
Datawalke/Coordino
|
cake/console/libs/tasks/model.php
|
https://github.com/Datawalke/Coordino/blob/master/cake/console/libs/tasks/model.php
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.