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 requireLogin() {
$args = func_get_args();
$base = $this->loginOptions;
foreach ($args as $i => $arg) {
if (is_array($arg)) {
$this->loginOptions = $arg;
unset($args[$i]);
}
}
$this->loginOptions = array_merge($base, $this->loginOptions);
$this->_requireMethod('Login', $args);
if (isset($this->loginOptions['users'])) {
$this->loginUsers =& $this->loginOptions['users'];
}
} | Sets the actions that require an HTTP-authenticated request, or empty for all actions
@return void
@access public
@link http://book.cakephp.org/view/1302/requireLogin | requireLogin | php | Datawalke/Coordino | cake/libs/controller/components/security.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/security.php | MIT |
function loginCredentials($type = null) {
switch (strtolower($type)) {
case 'basic':
$login = array('username' => env('PHP_AUTH_USER'), 'password' => env('PHP_AUTH_PW'));
if (!empty($login['username'])) {
return $login;
}
break;
case 'digest':
default:
$digest = null;
if (version_compare(PHP_VERSION, '5.1') != -1) {
$digest = env('PHP_AUTH_DIGEST');
} elseif (function_exists('apache_request_headers')) {
$headers = apache_request_headers();
if (isset($headers['Authorization']) && !empty($headers['Authorization']) && substr($headers['Authorization'], 0, 7) == 'Digest ') {
$digest = substr($headers['Authorization'], 7);
}
} else {
// Server doesn't support digest-auth headers
trigger_error(__('SecurityComponent::loginCredentials() - Server does not support digest authentication', true), E_USER_WARNING);
}
if (!empty($digest)) {
return $this->parseDigestAuthData($digest);
}
break;
}
return null;
} | Attempts to validate the login credentials for an HTTP-authenticated request
@param string $type Either 'basic', 'digest', or null. If null/empty, will try both.
@return mixed If successful, returns an array with login name and password, otherwise null.
@access public
@link http://book.cakephp.org/view/1303/loginCredentials-string-type | loginCredentials | php | Datawalke/Coordino | cake/libs/controller/components/security.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/security.php | MIT |
function loginRequest($options = array()) {
$options = array_merge($this->loginOptions, $options);
$this->_setLoginDefaults($options);
$auth = 'WWW-Authenticate: ' . ucfirst($options['type']);
$out = array('realm="' . $options['realm'] . '"');
if (strtolower($options['type']) == 'digest') {
$out[] = 'qop="auth"';
$out[] = 'nonce="' . uniqid("") . '"';
$out[] = 'opaque="' . md5($options['realm']) . '"';
}
return $auth . ' ' . implode(',', $out);
} | Generates the text of an HTTP-authentication request header from an array of options.
@param array $options Set of options for header
@return string HTTP-authentication request header
@access public
@link http://book.cakephp.org/view/1304/loginRequest-array-options | loginRequest | php | Datawalke/Coordino | cake/libs/controller/components/security.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/security.php | MIT |
function parseDigestAuthData($digest) {
if (substr($digest, 0, 7) == 'Digest ') {
$digest = substr($digest, 7);
}
$keys = array();
$match = array();
$req = array('nonce' => 1, 'nc' => 1, 'cnonce' => 1, 'qop' => 1, 'username' => 1, 'uri' => 1, 'response' => 1);
preg_match_all('/(\w+)=([\'"]?)([a-zA-Z0-9@=.\/_-]+)\2/', $digest, $match, PREG_SET_ORDER);
foreach ($match as $i) {
$keys[$i[1]] = $i[3];
unset($req[$i[1]]);
}
if (empty($req)) {
return $keys;
}
return null;
} | Parses an HTTP digest authentication response, and returns an array of the data, or null on failure.
@param string $digest Digest authentication response
@return array Digest authentication parameters
@access public
@link http://book.cakephp.org/view/1305/parseDigestAuthData-string-digest | parseDigestAuthData | php | Datawalke/Coordino | cake/libs/controller/components/security.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/security.php | MIT |
function generateDigestResponseHash($data) {
return md5(
md5($data['username'] . ':' . $this->loginOptions['realm'] . ':' . $this->loginUsers[$data['username']]) .
':' . $data['nonce'] . ':' . $data['nc'] . ':' . $data['cnonce'] . ':' . $data['qop'] . ':' .
md5(env('REQUEST_METHOD') . ':' . $data['uri'])
);
} | Generates a hash to be compared with an HTTP digest-authenticated response
@param array $data HTTP digest response data, as parsed by SecurityComponent::parseDigestAuthData()
@return string Digest authentication hash
@access public
@see SecurityComponent::parseDigestAuthData()
@link http://book.cakephp.org/view/1306/generateDigestResponseHash-array-data | generateDigestResponseHash | php | Datawalke/Coordino | cake/libs/controller/components/security.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/security.php | MIT |
function blackHole(&$controller, $error = '') {
if ($this->blackHoleCallback == null) {
$code = 404;
if ($error == 'login') {
$code = 401;
$controller->header($this->loginRequest());
}
$controller->redirect(null, $code, true);
} else {
return $this->_callback($controller, $this->blackHoleCallback, array($error));
}
} | Black-hole an invalid request with a 404 error or custom callback. If SecurityComponent::$blackHoleCallback
is specified, it will use this callback by executing the method indicated in $error
@param object $controller Instantiating controller
@param string $error Error method
@return mixed If specified, controller blackHoleCallback's response, or no return otherwise
@access public
@see SecurityComponent::$blackHoleCallback
@link http://book.cakephp.org/view/1307/blackHole-object-controller-string-error | blackHole | php | Datawalke/Coordino | cake/libs/controller/components/security.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/security.php | MIT |
function _requireMethod($method, $actions = array()) {
if (isset($actions[0]) && is_array($actions[0])) {
$actions = $actions[0];
}
$this->{'require' . $method} = (empty($actions)) ? array('*'): $actions;
} | Sets the actions that require a $method HTTP request, or empty for all actions
@param string $method The HTTP method to assign controller actions to
@param array $actions Controller actions to set the required HTTP method to.
@return void
@access protected | _requireMethod | php | Datawalke/Coordino | cake/libs/controller/components/security.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/security.php | MIT |
function _methodsRequired(&$controller) {
foreach (array('Post', 'Get', 'Put', 'Delete') as $method) {
$property = 'require' . $method;
if (is_array($this->$property) && !empty($this->$property)) {
$require = array_map('strtolower', $this->$property);
if (in_array($this->_action, $require) || $this->$property == array('*')) {
if (!$this->RequestHandler->{'is' . $method}()) {
if (!$this->blackHole($controller, strtolower($method))) {
return null;
}
}
}
}
}
return true;
} | Check if HTTP methods are required
@param object $controller Instantiating controller
@return bool true if $method is required
@access protected | _methodsRequired | php | Datawalke/Coordino | cake/libs/controller/components/security.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/security.php | MIT |
function _secureRequired(&$controller) {
if (is_array($this->requireSecure) && !empty($this->requireSecure)) {
$requireSecure = array_map('strtolower', $this->requireSecure);
if (in_array($this->_action, $requireSecure) || $this->requireSecure == array('*')) {
if (!$this->RequestHandler->isSSL()) {
if (!$this->blackHole($controller, 'secure')) {
return null;
}
}
}
}
return true;
} | Check if access requires secure connection
@param object $controller Instantiating controller
@return bool true if secure connection required
@access protected | _secureRequired | php | Datawalke/Coordino | cake/libs/controller/components/security.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/security.php | MIT |
function _authRequired(&$controller) {
if (is_array($this->requireAuth) && !empty($this->requireAuth) && !empty($controller->data)) {
$requireAuth = array_map('strtolower', $this->requireAuth);
if (in_array($this->_action, $requireAuth) || $this->requireAuth == array('*')) {
if (!isset($controller->data['_Token'] )) {
if (!$this->blackHole($controller, 'auth')) {
return null;
}
}
if ($this->Session->check('_Token')) {
$tData = unserialize($this->Session->read('_Token'));
if (!empty($tData['allowedControllers']) && !in_array($controller->params['controller'], $tData['allowedControllers']) || !empty($tData['allowedActions']) && !in_array($controller->params['action'], $tData['allowedActions'])) {
if (!$this->blackHole($controller, 'auth')) {
return null;
}
}
} else {
if (!$this->blackHole($controller, 'auth')) {
return null;
}
}
}
}
return true;
} | Check if authentication is required
@param object $controller Instantiating controller
@return bool true if authentication required
@access protected | _authRequired | php | Datawalke/Coordino | cake/libs/controller/components/security.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/security.php | MIT |
function _loginRequired(&$controller) {
if (is_array($this->requireLogin) && !empty($this->requireLogin)) {
$requireLogin = array_map('strtolower', $this->requireLogin);
if (in_array($this->_action, $requireLogin) || $this->requireLogin == array('*')) {
$login = $this->loginCredentials($this->loginOptions['type']);
if ($login == null) {
$controller->header($this->loginRequest());
if (!empty($this->loginOptions['prompt'])) {
$this->_callback($controller, $this->loginOptions['prompt']);
} else {
$this->blackHole($controller, 'login');
}
} else {
if (isset($this->loginOptions['login'])) {
$this->_callback($controller, $this->loginOptions['login'], array($login));
} else {
if (strtolower($this->loginOptions['type']) == 'digest') {
if ($login && isset($this->loginUsers[$login['username']])) {
if ($login['response'] == $this->generateDigestResponseHash($login)) {
return true;
}
}
$this->blackHole($controller, 'login');
} else {
if (
!(in_array($login['username'], array_keys($this->loginUsers)) &&
$this->loginUsers[$login['username']] == $login['password'])
) {
$this->blackHole($controller, 'login');
}
}
}
}
}
}
return true;
} | Check if login is required
@param object $controller Instantiating controller
@return bool true if login is required
@access protected | _loginRequired | php | Datawalke/Coordino | cake/libs/controller/components/security.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/security.php | MIT |
function _generateToken(&$controller) {
if (isset($controller->params['requested']) && $controller->params['requested'] === 1) {
if ($this->Session->check('_Token')) {
$tokenData = unserialize($this->Session->read('_Token'));
$controller->params['_Token'] = $tokenData;
}
return false;
}
$authKey = Security::generateAuthKey();
$expires = strtotime('+' . Security::inactiveMins() . ' minutes');
$token = array(
'key' => $authKey,
'expires' => $expires,
'allowedControllers' => $this->allowedControllers,
'allowedActions' => $this->allowedActions,
'disabledFields' => $this->disabledFields
);
if (!isset($controller->data)) {
$controller->data = array();
}
if ($this->Session->check('_Token')) {
$tokenData = unserialize($this->Session->read('_Token'));
$valid = (
isset($tokenData['expires']) &&
$tokenData['expires'] > time() &&
isset($tokenData['key'])
);
if ($valid) {
$token['key'] = $tokenData['key'];
}
}
$controller->params['_Token'] = $token;
$this->Session->write('_Token', serialize($token));
return true;
} | Add authentication key for new form posts
@param object $controller Instantiating controller
@return bool Success
@access protected | _generateToken | php | Datawalke/Coordino | cake/libs/controller/components/security.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/security.php | MIT |
function _setLoginDefaults(&$options) {
$options = array_merge(array(
'type' => 'basic',
'realm' => env('SERVER_NAME'),
'qop' => 'auth',
'nonce' => String::uuid()
), array_filter($options));
$options = array_merge(array('opaque' => md5($options['realm'])), $options);
} | Sets the default login options for an HTTP-authenticated request
@param array $options Default login options
@return void
@access protected | _setLoginDefaults | php | Datawalke/Coordino | cake/libs/controller/components/security.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/security.php | MIT |
function _callback(&$controller, $method, $params = array()) {
if (is_callable(array($controller, $method))) {
return call_user_func_array(array(&$controller, $method), empty($params) ? null : $params);
} else {
return null;
}
} | Calls a controller callback method
@param object $controller Controller to run callback on
@param string $method Method to execute
@param array $params Parameters to send to method
@return mixed Controller callback method's response
@access protected | _callback | php | Datawalke/Coordino | cake/libs/controller/components/security.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/security.php | MIT |
function __construct($base = null) {
if (Configure::read('Session.start') === true) {
parent::__construct($base);
} else {
$this->__active = false;
}
} | Class constructor
@param string $base The base path for the Session | __construct | php | Datawalke/Coordino | cake/libs/controller/components/session.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/session.php | MIT |
function startup(&$controller) {
if ($this->started() === false && $this->__active === true) {
$this->__start();
}
} | Startup method.
@param object $controller Instantiating controller
@return void
@access public | startup | php | Datawalke/Coordino | cake/libs/controller/components/session.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/session.php | MIT |
function activate($base = null) {
if ($this->__active === true) {
return;
}
parent::__construct($base);
$this->__active = true;
} | Starts Session on if 'Session.start' is set to false in core.php
@param string $base The base path for the Session
@return void
@access public | activate | php | Datawalke/Coordino | cake/libs/controller/components/session.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/session.php | MIT |
function write($name, $value = null) {
if ($this->__active === true) {
$this->__start();
if (is_array($name)) {
foreach ($name as $key => $value) {
if (parent::write($key, $value) === false) {
return false;
}
}
return true;
}
if (parent::write($name, $value) === false) {
return false;
}
return true;
}
return false;
} | Used to write a value to a session key.
In your controller: $this->Session->write('Controller.sessKey', 'session value');
@param string $name The name of the key your are setting in the session.
This should be in a Controller.key format for better organizing
@param string $value The value you want to store in a session.
@return boolean Success
@access public
@link http://book.cakephp.org/view/1312/write | write | php | Datawalke/Coordino | cake/libs/controller/components/session.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/session.php | MIT |
function read($name = null) {
if ($this->__active === true) {
$this->__start();
return parent::read($name);
}
return false;
} | Used to read a session values for a key or return values for all keys.
In your controller: $this->Session->read('Controller.sessKey');
Calling the method without a param will return all session vars
@param string $name the name of the session key you want to read
@return mixed value from the session vars
@access public
@link http://book.cakephp.org/view/1314/read | read | php | Datawalke/Coordino | cake/libs/controller/components/session.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/session.php | MIT |
function delete($name) {
if ($this->__active === true) {
$this->__start();
return parent::delete($name);
}
return false;
} | Wrapper for SessionComponent::del();
In your controller: $this->Session->delete('Controller.sessKey');
@param string $name the name of the session key you want to delete
@return boolean true is session variable is set and can be deleted, false is variable was not set.
@access public
@link http://book.cakephp.org/view/1316/delete | delete | php | Datawalke/Coordino | cake/libs/controller/components/session.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/session.php | MIT |
function check($name) {
if ($this->__active === true) {
$this->__start();
return parent::check($name);
}
return false;
} | Used to check if a session variable is set
In your controller: $this->Session->check('Controller.sessKey');
@param string $name the name of the session key you want to check
@return boolean true is session variable is set, false if not
@access public
@link http://book.cakephp.org/view/1315/check | check | php | Datawalke/Coordino | cake/libs/controller/components/session.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/session.php | MIT |
function error() {
if ($this->__active === true) {
$this->__start();
return parent::error();
}
return false;
} | Used to determine the last error in a session.
In your controller: $this->Session->error();
@return string Last session error
@access public
@link http://book.cakephp.org/view/1318/error | error | php | Datawalke/Coordino | cake/libs/controller/components/session.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/session.php | MIT |
function setFlash($message, $element = 'default', $params = array(), $key = 'flash') {
if ($this->__active === true) {
$this->__start();
$this->write('Message.' . $key, compact('message', 'element', 'params'));
}
} | Used to set a session variable that can be used to output messages in the view.
In your controller: $this->Session->setFlash('This has been saved');
Additional params below can be passed to customize the output, or the Message.[key]
@param string $message Message to be flashed
@param string $element Element to wrap flash message in.
@param array $params Parameters to be sent to layout as view variables
@param string $key Message key, default is 'flash'
@access public
@link http://book.cakephp.org/view/1313/setFlash | setFlash | php | Datawalke/Coordino | cake/libs/controller/components/session.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/session.php | MIT |
function renew() {
if ($this->__active === true) {
$this->__start();
parent::renew();
}
} | Used to renew a session id
In your controller: $this->Session->renew();
@return void
@access public | renew | php | Datawalke/Coordino | cake/libs/controller/components/session.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/session.php | MIT |
function valid() {
if ($this->__active === true) {
$this->__start();
return parent::valid();
}
return false;
} | Used to check for a valid session.
In your controller: $this->Session->valid();
@return boolean true is session is valid, false is session is invalid
@access public | valid | php | Datawalke/Coordino | cake/libs/controller/components/session.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/session.php | MIT |
function destroy() {
if ($this->__active === true) {
$this->__start();
parent::destroy();
}
} | Used to destroy sessions
In your controller: $this->Session->destroy();
@return void
@access public
@link http://book.cakephp.org/view/1317/destroy | destroy | php | Datawalke/Coordino | cake/libs/controller/components/session.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/session.php | MIT |
function id($id = null) {
return parent::id($id);
} | Returns Session id
If $id is passed in a beforeFilter, the Session will be started
with the specified id
@param $id string
@return string
@access public | id | php | Datawalke/Coordino | cake/libs/controller/components/session.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/session.php | MIT |
function __start() {
if ($this->started() === false) {
if (!$this->id() && parent::start()) {
parent::_checkValid();
} else {
parent::start();
}
}
return $this->started();
} | Starts Session if SessionComponent is used in Controller::beforeFilter(),
or is called from
@return boolean
@access private | __start | php | Datawalke/Coordino | cake/libs/controller/components/session.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/controller/components/session.php | MIT |
function FileLog($options = array()) {
$options += array('path' => LOGS);
$this->_path = $options['path'];
} | Constructs a new File Logger.
Options
- `path` the path to save logs on.
@param array $options Options for the FileLog, see above.
@return void | FileLog | php | Datawalke/Coordino | cake/libs/log/file_log.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/log/file_log.php | MIT |
function write($type, $message) {
$debugTypes = array('notice', 'info', 'debug');
if ($type == 'error' || $type == 'warning') {
$filename = $this->_path . 'error.log';
} elseif (in_array($type, $debugTypes)) {
$filename = $this->_path . 'debug.log';
} else {
$filename = $this->_path . $type . '.log';
}
$output = date('Y-m-d H:i:s') . ' ' . ucfirst($type) . ': ' . $message . "\n";
$log = new File($filename, true);
if ($log->writable()) {
return $log->append($output);
}
} | Implements writing to log files.
@param string $type The type of log you are making.
@param string $message The message you want to log.
@return boolean success of write. | write | php | Datawalke/Coordino | cake/libs/log/file_log.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/log/file_log.php | MIT |
function __construct($options = array()) {
parent::__construct();
if (empty($options['name'])) {
$this->name = preg_replace('/schema$/i', '', get_class($this));
}
if (!empty($options['plugin'])) {
$this->plugin = $options['plugin'];
}
if (strtolower($this->name) === 'cake') {
$this->name = Inflector::camelize(Inflector::slug(Configure::read('App.dir')));
}
if (empty($options['path'])) {
if (is_dir(CONFIGS . 'schema')) {
$this->path = CONFIGS . 'schema';
} else {
$this->path = CONFIGS . 'sql';
}
}
$options = array_merge(get_object_vars($this), $options);
$this->_build($options);
} | Constructor
@param array $options optional load object properties | __construct | php | Datawalke/Coordino | cake/libs/model/cake_schema.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/cake_schema.php | MIT |
function _build($data) {
$file = null;
foreach ($data as $key => $val) {
if (!empty($val)) {
if (!in_array($key, array('plugin', 'name', 'path', 'file', 'connection', 'tables', '_log'))) {
$this->tables[$key] = $val;
unset($this->{$key});
} elseif ($key !== 'tables') {
if ($key === 'name' && $val !== $this->name && !isset($data['file'])) {
$file = Inflector::underscore($val) . '.php';
}
$this->{$key} = $val;
}
}
}
if (file_exists($this->path . DS . $file) && is_file($this->path . DS . $file)) {
$this->file = $file;
} elseif (!empty($this->plugin)) {
$this->path = App::pluginPath($this->plugin) . 'config' . DS . 'schema';
}
} | Builds schema object properties
@param array $data loaded object properties
@return void
@access protected | _build | php | Datawalke/Coordino | cake/libs/model/cake_schema.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/cake_schema.php | MIT |
function before($event = array()) {
return true;
} | Before callback to be implemented in subclasses
@param array $events schema object properties
@return boolean Should process continue
@access public | before | php | Datawalke/Coordino | cake/libs/model/cake_schema.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/cake_schema.php | MIT |
function &load($options = array()) {
if (is_string($options)) {
$options = array('path' => $options);
}
$this->_build($options);
extract(get_object_vars($this));
$class = $name .'Schema';
if (!class_exists($class)) {
if (file_exists($path . DS . $file) && is_file($path . DS . $file)) {
require_once($path . DS . $file);
} elseif (file_exists($path . DS . 'schema.php') && is_file($path . DS . 'schema.php')) {
require_once($path . DS . 'schema.php');
}
}
if (class_exists($class)) {
$Schema =& new $class($options);
return $Schema;
}
$false = false;
return $false;
} | Reads database and creates schema tables
@param array $options schema object properties
@return array Set of name and tables
@access public | load | php | Datawalke/Coordino | cake/libs/model/cake_schema.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/cake_schema.php | MIT |
function read($options = array()) {
extract(array_merge(
array(
'connection' => $this->connection,
'name' => $this->name,
'models' => true,
),
$options
));
$db =& ConnectionManager::getDataSource($connection);
App::import('Model', 'AppModel');
if (isset($this->plugin)) {
App::import('Model', Inflector::camelize($this->plugin) . 'AppModel');
}
$tables = array();
$currentTables = $db->listSources();
$prefix = null;
if (isset($db->config['prefix'])) {
$prefix = $db->config['prefix'];
}
if (!is_array($models) && $models !== false) {
if (isset($this->plugin)) {
$models = App::objects('model', App::pluginPath($this->plugin) . 'models' . DS, false);
} else {
$models = App::objects('model');
}
}
if (is_array($models)) {
foreach ($models as $model) {
$importModel = $model;
if (isset($this->plugin)) {
$importModel = $this->plugin . '.' . $model;
}
if (!App::import('Model', $importModel)) {
continue;
}
$vars = get_class_vars($model);
if (empty($vars['useDbConfig']) || $vars['useDbConfig'] != $connection) {
continue;
}
if (PHP5) {
$Object = ClassRegistry::init(array('class' => $model, 'ds' => $connection));
} else {
$Object =& ClassRegistry::init(array('class' => $model, 'ds' => $connection));
}
if (is_object($Object) && $Object->useTable !== false) {
$fulltable = $table = $db->fullTableName($Object, false);
if ($prefix && strpos($table, $prefix) !== 0) {
continue;
}
$table = $this->_noPrefixTable($prefix, $table);
if (in_array($fulltable, $currentTables)) {
$key = array_search($fulltable, $currentTables);
if (empty($tables[$table])) {
$tables[$table] = $this->__columns($Object);
$tables[$table]['indexes'] = $db->index($Object);
$tables[$table]['tableParameters'] = $db->readTableParameters($fulltable);
unset($currentTables[$key]);
}
if (!empty($Object->hasAndBelongsToMany)) {
foreach ($Object->hasAndBelongsToMany as $Assoc => $assocData) {
if (isset($assocData['with'])) {
$class = $assocData['with'];
}
if (is_object($Object->$class)) {
$withTable = $db->fullTableName($Object->$class, false);
if ($prefix && strpos($withTable, $prefix) !== 0) {
continue;
}
if (in_array($withTable, $currentTables)) {
$key = array_search($withTable, $currentTables);
$noPrefixWith = $this->_noPrefixTable($prefix, $withTable);
$tables[$noPrefixWith] = $this->__columns($Object->$class);
$tables[$noPrefixWith]['indexes'] = $db->index($Object->$class);
$tables[$noPrefixWith]['tableParameters'] = $db->readTableParameters($withTable);
unset($currentTables[$key]);
}
}
}
}
}
}
}
}
if (!empty($currentTables)) {
foreach ($currentTables as $table) {
if ($prefix) {
if (strpos($table, $prefix) !== 0) {
continue;
}
$table = $this->_noPrefixTable($prefix, $table);
}
$Object = new AppModel(array(
'name' => Inflector::classify($table), 'table' => $table, 'ds' => $connection
));
$systemTables = array(
'aros', 'acos', 'aros_acos', Configure::read('Session.table'), 'i18n'
);
$fulltable = $db->fullTableName($Object, false);
if (in_array($table, $systemTables)) {
$tables[$Object->table] = $this->__columns($Object);
$tables[$Object->table]['indexes'] = $db->index($Object);
$tables[$Object->table]['tableParameters'] = $db->readTableParameters($fulltable);
} elseif ($models === false) {
$tables[$table] = $this->__columns($Object);
$tables[$table]['indexes'] = $db->index($Object);
$tables[$table]['tableParameters'] = $db->readTableParameters($fulltable);
} else {
$tables['missing'][$table] = $this->__columns($Object);
$tables['missing'][$table]['indexes'] = $db->index($Object);
$tables['missing'][$table]['tableParameters'] = $db->readTableParameters($fulltable);
}
}
}
ksort($tables);
return compact('name', 'tables');
} | Reads database and creates schema tables
Options
- 'connection' - the db connection to use
- 'name' - name of the schema
- 'models' - a list of models to use, or false to ignore models
@param array $options schema object properties
@return array Array indexed by name and tables
@access public | read | php | Datawalke/Coordino | cake/libs/model/cake_schema.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/cake_schema.php | MIT |
function write($object, $options = array()) {
if (is_object($object)) {
$object = get_object_vars($object);
$this->_build($object);
}
if (is_array($object)) {
$options = $object;
unset($object);
}
extract(array_merge(
get_object_vars($this), $options
));
$out = "class {$name}Schema extends CakeSchema {\n";
$out .= "\tvar \$name = '{$name}';\n\n";
if ($path !== $this->path) {
$out .= "\tvar \$path = '{$path}';\n\n";
}
if ($file !== $this->file) {
$out .= "\tvar \$file = '{$file}';\n\n";
}
if ($connection !== 'default') {
$out .= "\tvar \$connection = '{$connection}';\n\n";
}
$out .= "\tfunction before(\$event = array()) {\n\t\treturn true;\n\t}\n\n\tfunction after(\$event = array()) {\n\t}\n\n";
if (empty($tables)) {
$this->read();
}
foreach ($tables as $table => $fields) {
if (!is_numeric($table) && $table !== 'missing') {
$out .= $this->generateTable($table, $fields);
}
}
$out .= "}\n";
$File =& new File($path . DS . $file, true);
$header = '$Id';
$content = "<?php \n/* {$name} schema generated on: " . date('Y-m-d H:i:s') . " : ". time() . "*/\n{$out}?>";
$content = $File->prepare($content);
if ($File->write($content)) {
return $content;
}
return false;
} | Writes schema file from object or options
@param mixed $object schema object or options array
@param array $options schema object properties to override object
@return mixed false or string written to file
@access public | write | php | Datawalke/Coordino | cake/libs/model/cake_schema.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/cake_schema.php | MIT |
function generateTable($table, $fields) {
$out = "\tvar \${$table} = array(\n";
if (is_array($fields)) {
$cols = array();
foreach ($fields as $field => $value) {
if ($field != 'indexes' && $field != 'tableParameters') {
if (is_string($value)) {
$type = $value;
$value = array('type'=> $type);
}
$col = "\t\t'{$field}' => array('type' => '" . $value['type'] . "', ";
unset($value['type']);
$col .= join(', ', $this->__values($value));
} elseif ($field == 'indexes') {
$col = "\t\t'indexes' => array(";
$props = array();
foreach ((array)$value as $key => $index) {
$props[] = "'{$key}' => array(" . join(', ', $this->__values($index)) . ")";
}
$col .= join(', ', $props);
} elseif ($field == 'tableParameters') {
//@todo add charset, collate and engine here
$col = "\t\t'tableParameters' => array(";
$props = array();
foreach ((array)$value as $key => $param) {
$props[] = "'{$key}' => '$param'";
}
$col .= join(', ', $props);
}
$col .= ")";
$cols[] = $col;
}
$out .= join(",\n", $cols);
}
$out .= "\n\t);\n";
return $out;
} | Generate the code for a table. Takes a table name and $fields array
Returns a completed variable declaration to be used in schema classes
@param string $table Table name you want returned.
@param array $fields Array of field information to generate the table with.
@return string Variable declaration for a schema class | generateTable | php | Datawalke/Coordino | cake/libs/model/cake_schema.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/cake_schema.php | MIT |
function compare($old, $new = null) {
if (empty($new)) {
$new =& $this;
}
if (is_array($new)) {
if (isset($new['tables'])) {
$new = $new['tables'];
}
} else {
$new = $new->tables;
}
if (is_array($old)) {
if (isset($old['tables'])) {
$old = $old['tables'];
}
} else {
$old = $old->tables;
}
$tables = array();
foreach ($new as $table => $fields) {
if ($table == 'missing') {
continue;
}
if (!array_key_exists($table, $old)) {
$tables[$table]['add'] = $fields;
} else {
$diff = $this->_arrayDiffAssoc($fields, $old[$table]);
if (!empty($diff)) {
$tables[$table]['add'] = $diff;
}
$diff = $this->_arrayDiffAssoc($old[$table], $fields);
if (!empty($diff)) {
$tables[$table]['drop'] = $diff;
}
}
foreach ($fields as $field => $value) {
if (isset($old[$table][$field])) {
$diff = $this->_arrayDiffAssoc($value, $old[$table][$field]);
if (!empty($diff) && $field !== 'indexes' && $field !== 'tableParameters') {
$tables[$table]['change'][$field] = array_merge($old[$table][$field], $diff);
}
}
if (isset($tables[$table]['add'][$field]) && $field !== 'indexes' && $field !== 'tableParameters') {
$wrapper = array_keys($fields);
if ($column = array_search($field, $wrapper)) {
if (isset($wrapper[$column - 1])) {
$tables[$table]['add'][$field]['after'] = $wrapper[$column - 1];
}
}
}
}
if (isset($old[$table]['indexes']) && isset($new[$table]['indexes'])) {
$diff = $this->_compareIndexes($new[$table]['indexes'], $old[$table]['indexes']);
if ($diff) {
if (!isset($tables[$table])) {
$tables[$table] = array();
}
if (isset($diff['drop'])) {
$tables[$table]['drop']['indexes'] = $diff['drop'];
}
if ($diff && isset($diff['add'])) {
$tables[$table]['add']['indexes'] = $diff['add'];
}
}
}
if (isset($old[$table]['tableParameters']) && isset($new[$table]['tableParameters'])) {
$diff = $this->_compareTableParameters($new[$table]['tableParameters'], $old[$table]['tableParameters']);
if ($diff) {
$tables[$table]['change']['tableParameters'] = $diff;
}
}
}
return $tables;
} | Compares two sets of schemas
@param mixed $old Schema object or array
@param mixed $new Schema object or array
@return array Tables (that are added, dropped, or changed)
@access public | compare | php | Datawalke/Coordino | cake/libs/model/cake_schema.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/cake_schema.php | MIT |
function _arrayDiffAssoc($array1, $array2) {
$difference = array();
foreach ($array1 as $key => $value) {
if (!array_key_exists($key, $array2)) {
$difference[$key] = $value;
continue;
}
$correspondingValue = $array2[$key];
if (is_null($value) !== is_null($correspondingValue)) {
$difference[$key] = $value;
continue;
}
if (is_bool($value) !== is_bool($correspondingValue)) {
$difference[$key] = $value;
continue;
}
if (is_array($value) && is_array($correspondingValue)) {
continue;
}
$compare = strval($value);
$correspondingValue = strval($correspondingValue);
if ($compare === $correspondingValue) {
continue;
}
$difference[$key] = $value;
}
return $difference;
} | Extended array_diff_assoc noticing change from/to NULL values
It behaves almost the same way as array_diff_assoc except for NULL values: if
one of the values is not NULL - change is detected. It is useful in situation
where one value is strval('') ant other is strval(null) - in string comparing
methods this results as EQUAL, while it is not.
@param array $array1 Base array
@param array $array2 Corresponding array checked for equality
@return array Difference as array with array(keys => values) from input array
where match was not found.
@access protected | _arrayDiffAssoc | php | Datawalke/Coordino | cake/libs/model/cake_schema.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/cake_schema.php | MIT |
function __values($values) {
$vals = array();
if (is_array($values)) {
foreach ($values as $key => $val) {
if (is_array($val)) {
$vals[] = "'{$key}' => array('" . implode("', '", $val) . "')";
} else if (!is_numeric($key)) {
$val = var_export($val, true);
$vals[] = "'{$key}' => {$val}";
}
}
}
return $vals;
} | Formats Schema columns from Model Object
@param array $values options keys(type, null, default, key, length, extra)
@return array Formatted values
@access public | __values | php | Datawalke/Coordino | cake/libs/model/cake_schema.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/cake_schema.php | MIT |
function __columns(&$Obj) {
$db =& ConnectionManager::getDataSource($Obj->useDbConfig);
$fields = $Obj->schema(true);
$columns = $props = array();
foreach ($fields as $name => $value) {
if ($Obj->primaryKey == $name) {
$value['key'] = 'primary';
}
if (!isset($db->columns[$value['type']])) {
trigger_error(sprintf(__('Schema generation error: invalid column type %s does not exist in DBO', true), $value['type']), E_USER_NOTICE);
continue;
} else {
$defaultCol = $db->columns[$value['type']];
if (isset($defaultCol['limit']) && $defaultCol['limit'] == $value['length']) {
unset($value['length']);
} elseif (isset($defaultCol['length']) && $defaultCol['length'] == $value['length']) {
unset($value['length']);
}
unset($value['limit']);
}
if (isset($value['default']) && ($value['default'] === '' || $value['default'] === false)) {
unset($value['default']);
}
if (empty($value['length'])) {
unset($value['length']);
}
if (empty($value['key'])) {
unset($value['key']);
}
$columns[$name] = $value;
}
return $columns;
} | Formats Schema columns from Model Object
@param array $Obj model object
@return array Formatted columns
@access public | __columns | php | Datawalke/Coordino | cake/libs/model/cake_schema.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/cake_schema.php | MIT |
function _compareTableParameters($new, $old) {
if (!is_array($new) || !is_array($old)) {
return false;
}
$change = $this->_arrayDiffAssoc($new, $old);
return $change;
} | Compare two schema files table Parameters
@param array $new New indexes
@param array $old Old indexes
@return mixed False on failure, or an array of parameters to add & drop. | _compareTableParameters | php | Datawalke/Coordino | cake/libs/model/cake_schema.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/cake_schema.php | MIT |
function _compareIndexes($new, $old) {
if (!is_array($new) || !is_array($old)) {
return false;
}
$add = $drop = array();
$diff = $this->_arrayDiffAssoc($new, $old);
if (!empty($diff)) {
$add = $diff;
}
$diff = $this->_arrayDiffAssoc($old, $new);
if (!empty($diff)) {
$drop = $diff;
}
foreach ($new as $name => $value) {
if (isset($old[$name])) {
$newUnique = isset($value['unique']) ? $value['unique'] : 0;
$oldUnique = isset($old[$name]['unique']) ? $old[$name]['unique'] : 0;
$newColumn = $value['column'];
$oldColumn = $old[$name]['column'];
$diff = false;
if ($newUnique != $oldUnique) {
$diff = true;
} elseif (is_array($newColumn) && is_array($oldColumn)) {
$diff = ($newColumn !== $oldColumn);
} elseif (is_string($newColumn) && is_string($oldColumn)) {
$diff = ($newColumn != $oldColumn);
} else {
$diff = true;
}
if ($diff) {
$drop[$name] = null;
$add[$name] = $value;
}
}
}
return array_filter(compact('add', 'drop'));
} | Compare two schema indexes
@param array $new New indexes
@param array $old Old indexes
@return mixed false on failure or array of indexes to add and drop | _compareIndexes | php | Datawalke/Coordino | cake/libs/model/cake_schema.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/cake_schema.php | MIT |
function _noPrefixTable($prefix, $table) {
return preg_replace('/^' . preg_quote($prefix) . '/', '', $table);
} | Trim the table prefix from the full table name, and return the prefix-less table
@param string $prefix Table prefix
@param string $table Full table name
@return string Prefix-less table name | _noPrefixTable | php | Datawalke/Coordino | cake/libs/model/cake_schema.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/cake_schema.php | MIT |
function &getInstance() {
static $instance = array();
if (!$instance) {
$instance[0] =& new ConnectionManager();
}
return $instance[0];
} | Gets a reference to the ConnectionManger object instance
@return object Instance
@access public
@static | getInstance | php | Datawalke/Coordino | cake/libs/model/connection_manager.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/connection_manager.php | MIT |
function &getDataSource($name) {
$_this =& ConnectionManager::getInstance();
if (!empty($_this->_dataSources[$name])) {
$return =& $_this->_dataSources[$name];
return $return;
}
if (empty($_this->_connectionsEnum[$name])) {
trigger_error(sprintf(__("ConnectionManager::getDataSource - Non-existent data source %s", true), $name), E_USER_ERROR);
$null = null;
return $null;
}
$conn = $_this->_connectionsEnum[$name];
$class = $conn['classname'];
if ($_this->loadDataSource($name) === null) {
trigger_error(sprintf(__("ConnectionManager::getDataSource - Could not load class %s", true), $class), E_USER_ERROR);
$null = null;
return $null;
}
$_this->_dataSources[$name] =& new $class($_this->config->{$name});
$_this->_dataSources[$name]->configKeyName = $name;
$return =& $_this->_dataSources[$name];
return $return;
} | Gets a reference to a DataSource object
@param string $name The name of the DataSource, as defined in app/config/database.php
@return object Instance
@access public
@static | getDataSource | php | Datawalke/Coordino | cake/libs/model/connection_manager.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/connection_manager.php | MIT |
function sourceList() {
$_this =& ConnectionManager::getInstance();
return array_keys($_this->_dataSources);
} | Gets the list of available DataSource connections
@return array List of available connections
@access public
@static | sourceList | php | Datawalke/Coordino | cake/libs/model/connection_manager.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/connection_manager.php | MIT |
function getSourceName(&$source) {
$_this =& ConnectionManager::getInstance();
foreach ($_this->_dataSources as $name => $ds) {
if ($ds == $source) {
return $name;
}
}
return '';
} | Gets a DataSource name from an object reference.
**Warning** this method may cause fatal errors in PHP4.
@param object $source DataSource object
@return string Datasource name, or null if source is not present
in the ConnectionManager.
@access public
@static | getSourceName | php | Datawalke/Coordino | cake/libs/model/connection_manager.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/connection_manager.php | MIT |
function loadDataSource($connName) {
$_this =& ConnectionManager::getInstance();
if (is_array($connName)) {
$conn = $connName;
} else {
$conn = $_this->_connectionsEnum[$connName];
}
if (class_exists($conn['classname'])) {
return false;
}
if (!empty($conn['parent'])) {
$_this->loadDataSource($conn['parent']);
}
$conn = array_merge(array('plugin' => null, 'classname' => null, 'parent' => null), $conn);
$class = "{$conn['plugin']}.{$conn['classname']}";
if (!App::import('Datasource', $class, !is_null($conn['plugin']))) {
trigger_error(sprintf(__('ConnectionManager::loadDataSource - Unable to import DataSource class %s', true), $class), E_USER_ERROR);
return null;
}
return true;
} | Loads the DataSource class for the given connection name
@param mixed $connName A string name of the connection, as defined in app/config/database.php,
or an array containing the filename (without extension) and class name of the object,
to be found in app/models/datasources/ or cake/libs/model/datasources/.
@return boolean True on success, null on failure or false if the class is already loaded
@access public
@static | loadDataSource | php | Datawalke/Coordino | cake/libs/model/connection_manager.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/connection_manager.php | MIT |
function enumConnectionObjects() {
$_this =& ConnectionManager::getInstance();
return $_this->_connectionsEnum;
} | Return a list of connections
@return array An associative array of elements where the key is the connection name
(as defined in Connections), and the value is an array with keys 'filename' and 'classname'.
@access public
@static | enumConnectionObjects | php | Datawalke/Coordino | cake/libs/model/connection_manager.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/connection_manager.php | MIT |
function &create($name = '', $config = array()) {
$_this =& ConnectionManager::getInstance();
if (empty($name) || empty($config) || array_key_exists($name, $_this->_connectionsEnum)) {
$null = null;
return $null;
}
$_this->config->{$name} = $config;
$_this->_connectionsEnum[$name] = $_this->__connectionData($config);
$return =& $_this->getDataSource($name);
return $return;
} | Dynamically creates a DataSource object at runtime, with the given name and settings
@param string $name The DataSource name
@param array $config The DataSource configuration settings
@return object A reference to the DataSource object, or null if creation failed
@access public
@static | create | php | Datawalke/Coordino | cake/libs/model/connection_manager.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/connection_manager.php | MIT |
function _getConnectionObjects() {
$connections = get_object_vars($this->config);
if ($connections != null) {
foreach ($connections as $name => $config) {
$this->_connectionsEnum[$name] = $this->__connectionData($config);
}
} else {
$this->cakeError('missingConnection', array(array('code' => 500, 'className' => 'ConnectionManager')));
}
} | Gets a list of class and file names associated with the user-defined DataSource connections
@return void
@access protected
@static | _getConnectionObjects | php | Datawalke/Coordino | cake/libs/model/connection_manager.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/connection_manager.php | MIT |
function __connectionData($config) {
if (!isset($config['datasource'])) {
$config['datasource'] = 'dbo';
}
$filename = $classname = $parent = $plugin = null;
if (!empty($config['driver'])) {
$parent = $this->__connectionData(array('datasource' => $config['datasource']));
$parentSource = preg_replace('/_source$/', '', $parent['filename']);
list($plugin, $classname) = pluginSplit($config['driver']);
if ($plugin) {
$source = Inflector::underscore($classname);
} else {
$source = $parentSource . '_' . $config['driver'];
$classname = Inflector::camelize(strtolower($source));
}
$filename = $parentSource . DS . $source;
} else {
list($plugin, $classname) = pluginSplit($config['datasource']);
if ($plugin) {
$filename = Inflector::underscore($classname);
} else {
$filename = Inflector::underscore($config['datasource']);
}
if (substr($filename, -7) != '_source') {
$filename .= '_source';
}
$classname = Inflector::camelize(strtolower($filename));
}
return compact('filename', 'classname', 'parent', 'plugin');
} | Returns the file, class name, and parent for the given driver.
@return array An indexed array with: filename, classname, plugin and parent
@access private | __connectionData | php | Datawalke/Coordino | cake/libs/model/connection_manager.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/connection_manager.php | MIT |
function node($ref = null) {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$type = $this->alias;
$result = null;
if (!empty($this->useTable)) {
$table = $this->useTable;
} else {
$table = Inflector::pluralize(Inflector::underscore($type));
}
if (empty($ref)) {
return null;
} elseif (is_string($ref)) {
$path = explode('/', $ref);
$start = $path[0];
unset($path[0]);
$queryData = array(
'conditions' => array(
$db->name("{$type}.lft") . ' <= ' . $db->name("{$type}0.lft"),
$db->name("{$type}.rght") . ' >= ' . $db->name("{$type}0.rght")),
'fields' => array('id', 'parent_id', 'model', 'foreign_key', 'alias'),
'joins' => array(array(
'table' => $table,
'alias' => "{$type}0",
'type' => 'LEFT',
'conditions' => array("{$type}0.alias" => $start)
)),
'order' => $db->name("{$type}.lft") . ' DESC'
);
foreach ($path as $i => $alias) {
$j = $i - 1;
$queryData['joins'][] = array(
'table' => $table,
'alias' => "{$type}{$i}",
'type' => 'LEFT',
'conditions' => array(
$db->name("{$type}{$i}.lft") . ' > ' . $db->name("{$type}{$j}.lft"),
$db->name("{$type}{$i}.rght") . ' < ' . $db->name("{$type}{$j}.rght"),
$db->name("{$type}{$i}.alias") . ' = ' . $db->value($alias, 'string'),
$db->name("{$type}{$j}.id") . ' = ' . $db->name("{$type}{$i}.parent_id")
)
);
$queryData['conditions'] = array('or' => array(
$db->name("{$type}.lft") . ' <= ' . $db->name("{$type}0.lft") . ' AND ' . $db->name("{$type}.rght") . ' >= ' . $db->name("{$type}0.rght"),
$db->name("{$type}.lft") . ' <= ' . $db->name("{$type}{$i}.lft") . ' AND ' . $db->name("{$type}.rght") . ' >= ' . $db->name("{$type}{$i}.rght"))
);
}
$result = $db->read($this, $queryData, -1);
$path = array_values($path);
if (
!isset($result[0][$type]) ||
(!empty($path) && $result[0][$type]['alias'] != $path[count($path) - 1]) ||
(empty($path) && $result[0][$type]['alias'] != $start)
) {
return false;
}
} elseif (is_object($ref) && is_a($ref, 'Model')) {
$ref = array('model' => $ref->alias, 'foreign_key' => $ref->id);
} elseif (is_array($ref) && !(isset($ref['model']) && isset($ref['foreign_key']))) {
$name = key($ref);
if (PHP5) {
$model = ClassRegistry::init(array('class' => $name, 'alias' => $name));
} else {
$model =& ClassRegistry::init(array('class' => $name, 'alias' => $name));
}
if (empty($model)) {
trigger_error(sprintf(__("Model class '%s' not found in AclNode::node() when trying to bind %s object", true), $type, $this->alias), E_USER_WARNING);
return null;
}
$tmpRef = null;
if (method_exists($model, 'bindNode')) {
$tmpRef = $model->bindNode($ref);
}
if (empty($tmpRef)) {
$ref = array('model' => $name, 'foreign_key' => $ref[$name][$model->primaryKey]);
} else {
if (is_string($tmpRef)) {
return $this->node($tmpRef);
}
$ref = $tmpRef;
}
}
if (is_array($ref)) {
if (is_array(current($ref)) && is_string(key($ref))) {
$name = key($ref);
$ref = current($ref);
}
foreach ($ref as $key => $val) {
if (strpos($key, $type) !== 0 && strpos($key, '.') === false) {
unset($ref[$key]);
$ref["{$type}0.{$key}"] = $val;
}
}
$queryData = array(
'conditions' => $ref,
'fields' => array('id', 'parent_id', 'model', 'foreign_key', 'alias'),
'joins' => array(array(
'table' => $table,
'alias' => "{$type}0",
'type' => 'LEFT',
'conditions' => array(
$db->name("{$type}.lft") . ' <= ' . $db->name("{$type}0.lft"),
$db->name("{$type}.rght") . ' >= ' . $db->name("{$type}0.rght")
)
)),
'order' => $db->name("{$type}.lft") . ' DESC'
);
$result = $db->read($this, $queryData, -1);
if (!$result) {
trigger_error(sprintf(__("AclNode::node() - Couldn't find %s node identified by \"%s\"", true), $type, print_r($ref, true)), E_USER_WARNING);
}
}
return $result;
} | Retrieves the Aro/Aco node for this model
@param mixed $ref Array with 'model' and 'foreign_key', model object, or string value
@return array Node found in database
@access public | node | php | Datawalke/Coordino | cake/libs/model/db_acl.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/db_acl.php | MIT |
function __construct() {
$config = Configure::read('Acl.database');
if (!empty($config)) {
$this->useDbConfig = $config;
}
parent::__construct();
} | Constructor, used to tell this model to use the
database configured for ACL | __construct | php | Datawalke/Coordino | cake/libs/model/db_acl.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/db_acl.php | MIT |
function __construct($id = false, $table = null, $ds = null) {
parent::__construct();
if (is_array($id)) {
extract(array_merge(
array(
'id' => $this->id, 'table' => $this->useTable, 'ds' => $this->useDbConfig,
'name' => $this->name, 'alias' => $this->alias
),
$id
));
}
if ($this->name === null) {
$this->name = (isset($name) ? $name : get_class($this));
}
if ($this->alias === null) {
$this->alias = (isset($alias) ? $alias : $this->name);
}
if ($this->primaryKey === null) {
$this->primaryKey = 'id';
}
ClassRegistry::addObject($this->alias, $this);
$this->id = $id;
unset($id);
if ($table === false) {
$this->useTable = false;
} elseif ($table) {
$this->useTable = $table;
}
if ($ds !== null) {
$this->useDbConfig = $ds;
}
if (is_subclass_of($this, 'AppModel')) {
$appVars = get_class_vars('AppModel');
$merge = array('_findMethods');
if ($this->actsAs !== null || $this->actsAs !== false) {
$merge[] = 'actsAs';
}
$parentClass = get_parent_class($this);
if (strtolower($parentClass) !== 'appmodel') {
$parentVars = get_class_vars($parentClass);
foreach ($merge as $var) {
if (isset($parentVars[$var]) && !empty($parentVars[$var])) {
$appVars[$var] = Set::merge($appVars[$var], $parentVars[$var]);
}
}
}
foreach ($merge as $var) {
if (isset($appVars[$var]) && !empty($appVars[$var]) && is_array($this->{$var})) {
$this->{$var} = Set::merge($appVars[$var], $this->{$var});
}
}
}
$this->Behaviors = new BehaviorCollection();
if ($this->useTable !== false) {
$this->setDataSource($ds);
if ($this->useTable === null) {
$this->useTable = Inflector::tableize($this->name);
}
$this->setSource($this->useTable);
if ($this->displayField == null) {
$this->displayField = $this->hasField(array('title', 'name', $this->primaryKey));
}
} elseif ($this->table === false) {
$this->table = Inflector::tableize($this->name);
}
$this->__createLinks();
$this->Behaviors->init($this->alias, $this->actsAs);
} | Constructor. Binds the model's database table to the object.
If `$id` is an array it can be used to pass several options into the model.
- id - The id to start the model on.
- table - The table to use for this model.
- ds - The connection name this model is connected to.
- name - The name of the model eg. Post.
- alias - The alias of the model, this is used for registering the instance in the `ClassRegistry`.
eg. `ParentThread`
### Overriding Model's __construct method.
When overriding Model::__construct() be careful to include and pass in all 3 of the
arguments to `parent::__construct($id, $table, $ds);`
### Dynamically creating models
You can dynamically create model instances using the $id array syntax.
{{{
$Post = new Model(array('table' => 'posts', 'name' => 'Post', 'ds' => 'connection2'));
}}}
Would create a model attached to the posts table on connection2. Dynamic model creation is useful
when you want a model object that contains no associations or attached behaviors.
@param mixed $id Set this ID for this model on startup, can also be an array of options, see above.
@param string $table Name of database table to use.
@param string $ds DataSource connection name. | __construct | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function call__($method, $params) {
$result = $this->Behaviors->dispatchMethod($this, $method, $params);
if ($result !== array('unhandled')) {
return $result;
}
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$return = $db->query($method, $params, $this);
if (!PHP5) {
$this->resetAssociations();
}
return $return;
} | Handles custom method calls, like findBy<field> for DB models,
and custom RPC calls for remote data sources.
@param string $method Name of method to call.
@param array $params Parameters for the method.
@return mixed Whatever is returned by called method
@access protected | call__ | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function bindModel($params, $reset = true) {
foreach ($params as $assoc => $model) {
if ($reset === true && !isset($this->__backAssociation[$assoc])) {
$this->__backAssociation[$assoc] = $this->{$assoc};
}
foreach ($model as $key => $value) {
$assocName = $key;
if (is_numeric($key)) {
$assocName = $value;
$value = array();
}
$modelName = $assocName;
$this->{$assoc}[$assocName] = $value;
if ($reset === false && isset($this->__backAssociation[$assoc])) {
$this->__backAssociation[$assoc][$assocName] = $value;
}
}
}
$this->__createLinks();
return true;
} | Bind model associations on the fly.
If `$reset` is false, association will not be reset
to the originals defined in the model
Example: Add a new hasOne binding to the Profile model not
defined in the model source code:
`$this->User->bindModel( array('hasOne' => array('Profile')) );`
Bindings that are not made permanent will be reset by the next Model::find() call on this
model.
@param array $params Set of bindings (indexed by binding type)
@param boolean $reset Set to false to make the binding permanent
@return boolean Success
@access public
@link http://book.cakephp.org/view/1045/Creating-and-Destroying-Associations-on-the-Fly | bindModel | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function unbindModel($params, $reset = true) {
foreach ($params as $assoc => $models) {
if ($reset === true && !isset($this->__backAssociation[$assoc])) {
$this->__backAssociation[$assoc] = $this->{$assoc};
}
foreach ($models as $model) {
if ($reset === false && isset($this->__backAssociation[$assoc][$model])) {
unset($this->__backAssociation[$assoc][$model]);
}
unset($this->{$assoc}[$model]);
}
}
return true;
} | Turn off associations on the fly.
If $reset is false, association will not be reset
to the originals defined in the model
Example: Turn off the associated Model Support request,
to temporarily lighten the User model:
`$this->User->unbindModel( array('hasMany' => array('Supportrequest')) );`
unbound models that are not made permanent will reset with the next call to Model::find()
@param array $params Set of bindings to unbind (indexed by binding type)
@param boolean $reset Set to false to make the unbinding permanent
@return boolean Success
@access public
@link http://book.cakephp.org/view/1045/Creating-and-Destroying-Associations-on-the-Fly | unbindModel | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function __createLinks() {
foreach ($this->__associations as $type) {
if (!is_array($this->{$type})) {
$this->{$type} = explode(',', $this->{$type});
foreach ($this->{$type} as $i => $className) {
$className = trim($className);
unset ($this->{$type}[$i]);
$this->{$type}[$className] = array();
}
}
if (!empty($this->{$type})) {
foreach ($this->{$type} as $assoc => $value) {
$plugin = null;
if (is_numeric($assoc)) {
unset ($this->{$type}[$assoc]);
$assoc = $value;
$value = array();
$this->{$type}[$assoc] = $value;
if (strpos($assoc, '.') !== false) {
$value = $this->{$type}[$assoc];
unset($this->{$type}[$assoc]);
list($plugin, $assoc) = pluginSplit($assoc, true);
$this->{$type}[$assoc] = $value;
}
}
$className = $assoc;
if (!empty($value['className'])) {
list($plugin, $className) = pluginSplit($value['className'], true);
$this->{$type}[$assoc]['className'] = $className;
}
$this->__constructLinkedModel($assoc, $plugin . $className);
}
$this->__generateAssociation($type);
}
}
} | Create a set of associations.
@return void
@access private | __createLinks | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function __constructLinkedModel($assoc, $className = null) {
if (empty($className)) {
$className = $assoc;
}
if (!isset($this->{$assoc}) || $this->{$assoc}->name !== $className) {
$model = array('class' => $className, 'alias' => $assoc);
if (PHP5) {
$this->{$assoc} = ClassRegistry::init($model);
} else {
$this->{$assoc} =& ClassRegistry::init($model);
}
if (strpos($className, '.') !== false) {
ClassRegistry::addObject($className, $this->{$assoc});
}
if ($assoc) {
$this->tableToModel[$this->{$assoc}->table] = $assoc;
}
}
} | Private helper method to create associated models of a given class.
@param string $assoc Association name
@param string $className Class name
@deprecated $this->$className use $this->$assoc instead. $assoc is the 'key' in the associations array;
examples: var $hasMany = array('Assoc' => array('className' => 'ModelName'));
usage: $this->Assoc->modelMethods();
var $hasMany = array('ModelName');
usage: $this->ModelName->modelMethods();
@return void
@access private | __constructLinkedModel | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function __generateAssociation($type) {
foreach ($this->{$type} as $assocKey => $assocData) {
$class = $assocKey;
$dynamicWith = false;
foreach ($this->__associationKeys[$type] as $key) {
if (!isset($this->{$type}[$assocKey][$key]) || $this->{$type}[$assocKey][$key] === null) {
$data = '';
switch ($key) {
case 'fields':
$data = '';
break;
case 'foreignKey':
$data = (($type == 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($this->table)) . '_id';
break;
case 'associationForeignKey':
$data = Inflector::singularize($this->{$class}->table) . '_id';
break;
case 'with':
$data = Inflector::camelize(Inflector::singularize($this->{$type}[$assocKey]['joinTable']));
$dynamicWith = true;
break;
case 'joinTable':
$tables = array($this->table, $this->{$class}->table);
sort ($tables);
$data = $tables[0] . '_' . $tables[1];
break;
case 'className':
$data = $class;
break;
case 'unique':
$data = true;
break;
}
$this->{$type}[$assocKey][$key] = $data;
}
}
if (!empty($this->{$type}[$assocKey]['with'])) {
$joinClass = $this->{$type}[$assocKey]['with'];
if (is_array($joinClass)) {
$joinClass = key($joinClass);
}
$plugin = null;
if (strpos($joinClass, '.') !== false) {
list($plugin, $joinClass) = explode('.', $joinClass);
$plugin .= '.';
$this->{$type}[$assocKey]['with'] = $joinClass;
}
if (!ClassRegistry::isKeySet($joinClass) && $dynamicWith === true) {
$this->{$joinClass} = new AppModel(array(
'name' => $joinClass,
'table' => $this->{$type}[$assocKey]['joinTable'],
'ds' => $this->useDbConfig
));
} else {
$this->__constructLinkedModel($joinClass, $plugin . $joinClass);
$this->{$type}[$assocKey]['joinTable'] = $this->{$joinClass}->table;
}
if (count($this->{$joinClass}->schema()) <= 2 && $this->{$joinClass}->primaryKey !== false) {
$this->{$joinClass}->primaryKey = $this->{$type}[$assocKey]['foreignKey'];
}
}
}
} | Build an array-based association from string.
@param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
@return void
@access private | __generateAssociation | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function setSource($tableName) {
$this->setDataSource($this->useDbConfig);
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$db->cacheSources = ($this->cacheSources && $db->cacheSources);
if ($db->isInterfaceSupported('listSources')) {
$sources = $db->listSources();
if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
return $this->cakeError('missingTable', array(array(
'className' => $this->alias,
'table' => $this->tablePrefix . $tableName,
'code' => 500
)));
}
$this->_schema = null;
}
$this->table = $this->useTable = $tableName;
$this->tableToModel[$this->table] = $this->alias;
$this->schema();
} | Sets a custom table for your controller class. Used by your controller to select a database table.
@param string $tableName Name of the custom table
@return void
@access public | setSource | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function set($one, $two = null) {
if (!$one) {
return;
}
if (is_object($one)) {
$one = Set::reverse($one);
}
if (is_array($one)) {
$data = $one;
if (empty($one[$this->alias])) {
if ($this->getAssociated(key($one)) === null) {
$data = array($this->alias => $one);
}
}
} else {
$data = array($this->alias => array($one => $two));
}
foreach ($data as $modelName => $fieldSet) {
if (is_array($fieldSet)) {
foreach ($fieldSet as $fieldName => $fieldValue) {
if (isset($this->validationErrors[$fieldName])) {
unset ($this->validationErrors[$fieldName]);
}
if ($modelName === $this->alias) {
if ($fieldName === $this->primaryKey) {
$this->id = $fieldValue;
}
}
if (is_array($fieldValue) || is_object($fieldValue)) {
$fieldValue = $this->deconstruct($fieldName, $fieldValue);
}
$this->data[$modelName][$fieldName] = $fieldValue;
}
}
}
return $data;
} | This function does two things:
1. it scans the array $one for the primary key,
and if that's found, it sets the current id to the value of $one[id].
For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
2. Returns an array with all of $one's keys and values.
(Alternative indata: two strings, which are mangled to
a one-item, two-dimensional array using $one for a key and $two as its value.)
@param mixed $one Array or string of data
@param string $two Value string for the alternative indata method
@return array Data with all of $one's keys and values
@access public
@link http://book.cakephp.org/view/1031/Saving-Your-Data | set | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function deconstruct($field, $data) {
if (!is_array($data)) {
return $data;
}
$copy = $data;
$type = $this->getColumnType($field);
if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
$useNewDate = (isset($data['year']) || isset($data['month']) ||
isset($data['day']) || isset($data['hour']) || isset($data['minute']));
$dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
$timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$format = $db->columns[$type]['format'];
$date = array();
if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] != 12 && 'pm' == $data['meridian']) {
$data['hour'] = $data['hour'] + 12;
}
if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
$data['hour'] = '00';
}
if ($type == 'time') {
foreach ($timeFields as $key => $val) {
if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
$data[$val] = '00';
} elseif ($data[$val] === '') {
$data[$val] = '';
} else {
$data[$val] = sprintf('%02d', $data[$val]);
}
if (!empty($data[$val])) {
$date[$key] = $data[$val];
} else {
return null;
}
}
}
if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
foreach ($dateFields as $key => $val) {
if ($val == 'hour' || $val == 'min' || $val == 'sec') {
if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
$data[$val] = '00';
} else {
$data[$val] = sprintf('%02d', $data[$val]);
}
}
if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
return null;
}
if (isset($data[$val]) && !empty($data[$val])) {
$date[$key] = $data[$val];
}
}
}
$date = str_replace(array_keys($date), array_values($date), $format);
if ($useNewDate && !empty($date)) {
return $date;
}
}
return $data;
} | Deconstructs a complex data type (array or object) into a single field value.
@param string $field The name of the field to be deconstructed
@param mixed $data An array or object to be deconstructed into a field
@return mixed The resulting data that should be assigned to a field
@access public | deconstruct | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function schema($field = false) {
if (!is_array($this->_schema) || $field === true) {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$db->cacheSources = ($this->cacheSources && $db->cacheSources);
if ($db->isInterfaceSupported('describe') && $this->useTable !== false) {
$this->_schema = $db->describe($this, $field);
} elseif ($this->useTable === false) {
$this->_schema = array();
}
}
if (is_string($field)) {
if (isset($this->_schema[$field])) {
return $this->_schema[$field];
} else {
return null;
}
}
return $this->_schema;
} | Returns an array of table metadata (column names and types) from the database.
$field => keys(type, null, default, key, length, extra)
@param mixed $field Set to true to reload schema, or a string to return a specific field
@return array Array of table metadata
@access public | schema | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function getColumnTypes() {
$columns = $this->schema();
if (empty($columns)) {
trigger_error(__('(Model::getColumnTypes) Unable to build model field data. If you are using a model without a database table, try implementing schema()', true), E_USER_WARNING);
}
$cols = array();
foreach ($columns as $field => $values) {
$cols[$field] = $values['type'];
}
return $cols;
} | Returns an associative array of field names and column types.
@return array Field types indexed by field name
@access public | getColumnTypes | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function getColumnType($column) {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$cols = $this->schema();
$model = null;
$column = str_replace(array($db->startQuote, $db->endQuote), '', $column);
if (strpos($column, '.')) {
list($model, $column) = explode('.', $column);
}
if ($model != $this->alias && isset($this->{$model})) {
return $this->{$model}->getColumnType($column);
}
if (isset($cols[$column]) && isset($cols[$column]['type'])) {
return $cols[$column]['type'];
}
return null;
} | Returns the column type of a column in the model.
@param string $column The name of the model column
@return string Column type
@access public | getColumnType | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function hasField($name, $checkVirtual = false) {
if (is_array($name)) {
foreach ($name as $n) {
if ($this->hasField($n, $checkVirtual)) {
return $n;
}
}
return false;
}
if ($checkVirtual && !empty($this->virtualFields)) {
if ($this->isVirtualField($name)) {
return true;
}
}
if (empty($this->_schema)) {
$this->schema();
}
if ($this->_schema != null) {
return isset($this->_schema[$name]);
}
return false;
} | Returns true if the supplied field exists in the model's database table.
@param mixed $name Name of field to look for, or an array of names
@param boolean $checkVirtual checks if the field is declared as virtual
@return mixed If $name is a string, returns a boolean indicating whether the field exists.
If $name is an array of field names, returns the first field that exists,
or false if none exist.
@access public | hasField | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function isVirtualField($field) {
if (empty($this->virtualFields) || !is_string($field)) {
return false;
}
if (isset($this->virtualFields[$field])) {
return true;
}
if (strpos($field, '.') !== false) {
list($model, $field) = explode('.', $field);
if ($model == $this->alias && isset($this->virtualFields[$field])) {
return true;
}
}
return false;
} | Returns true if the supplied field is a model Virtual Field
@param mixed $name Name of field to look for
@return boolean indicating whether the field exists as a model virtual field.
@access public | isVirtualField | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function getVirtualField($field = null) {
if ($field == null) {
return empty($this->virtualFields) ? false : $this->virtualFields;
}
if ($this->isVirtualField($field)) {
if (strpos($field, '.') !== false) {
list($model, $field) = explode('.', $field);
}
return $this->virtualFields[$field];
}
return false;
} | Returns the expression for a model virtual field
@param mixed $name Name of field to look for
@return mixed If $field is string expression bound to virtual field $field
If $field is null, returns an array of all model virtual fields
or false if none $field exist.
@access public | getVirtualField | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function create($data = array(), $filterKey = false) {
$defaults = array();
$this->id = false;
$this->data = array();
$this->validationErrors = array();
if ($data !== null && $data !== false) {
foreach ($this->schema() as $field => $properties) {
if ($this->primaryKey !== $field && isset($properties['default']) && $properties['default'] !== '') {
$defaults[$field] = $properties['default'];
}
}
$this->set($defaults);
$this->set($data);
}
if ($filterKey) {
$this->set($this->primaryKey, false);
}
return $this->data;
} | Initializes the model for writing a new record, loading the default values
for those fields that are not defined in $data, and clearing previous validation errors.
Especially helpful for saving data in loops.
@param mixed $data Optional data array to assign to the model after it is created. If null or false,
schema data defaults are not merged.
@param boolean $filterKey If true, overwrites any primary key input with an empty value
@return array The current Model::data; after merging $data and/or defaults from database
@access public
@link http://book.cakephp.org/view/1031/Saving-Your-Data | create | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function read($fields = null, $id = null) {
$this->validationErrors = array();
if ($id != null) {
$this->id = $id;
}
$id = $this->id;
if (is_array($this->id)) {
$id = $this->id[0];
}
if ($id !== null && $id !== false) {
$this->data = $this->find('first', array(
'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
'fields' => $fields
));
return $this->data;
} else {
return false;
}
} | Returns a list of fields from the database, and sets the current model
data (Model::$data) with the record found.
@param mixed $fields String of single fieldname, or an array of fieldnames.
@param mixed $id The ID of the record to read
@return array Array of database fields, or false if not found
@access public
@link http://book.cakephp.org/view/1017/Retrieving-Your-Data#read-1029 | read | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function field($name, $conditions = null, $order = null) {
if ($conditions === null && $this->id !== false) {
$conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
}
if ($this->recursive >= 1) {
$recursive = -1;
} else {
$recursive = $this->recursive;
}
$fields = $name;
if ($data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'))) {
if (strpos($name, '.') === false) {
if (isset($data[$this->alias][$name])) {
return $data[$this->alias][$name];
}
} else {
$name = explode('.', $name);
if (isset($data[$name[0]][$name[1]])) {
return $data[$name[0]][$name[1]];
}
}
if (isset($data[0]) && count($data[0]) > 0) {
return array_shift($data[0]);
}
} else {
return false;
}
} | Returns the contents of a single field given the supplied conditions, in the
supplied order.
@param string $name Name of field to get
@param array $conditions SQL conditions (defaults to NULL)
@param string $order SQL ORDER BY fragment
@return string field contents, or false if not found
@access public
@link http://book.cakephp.org/view/1017/Retrieving-Your-Data#field-1028 | field | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function saveField($name, $value, $validate = false) {
$id = $this->id;
$this->create(false);
if (is_array($validate)) {
$options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate);
} else {
$options = array('validate' => $validate, 'fieldList' => array($name));
}
return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
} | Saves the value of a single field to the database, based on the current
model ID.
@param string $name Name of the table field
@param mixed $value Value of the field
@param array $validate See $options param in Model::save(). Does not respect 'fieldList' key if passed
@return boolean See Model::save()
@access public
@see Model::save()
@link http://book.cakephp.org/view/1031/Saving-Your-Data | saveField | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function save($data = null, $validate = true, $fieldList = array()) {
$defaults = array('validate' => true, 'fieldList' => array(), 'callbacks' => true);
$_whitelist = $this->whitelist;
$fields = array();
if (!is_array($validate)) {
$options = array_merge($defaults, compact('validate', 'fieldList', 'callbacks'));
} else {
$options = array_merge($defaults, $validate);
}
if (!empty($options['fieldList'])) {
$this->whitelist = $options['fieldList'];
} elseif ($options['fieldList'] === null) {
$this->whitelist = array();
}
$this->set($data);
if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) {
return false;
}
foreach (array('created', 'updated', 'modified') as $field) {
$keyPresentAndEmpty = (
isset($this->data[$this->alias]) &&
array_key_exists($field, $this->data[$this->alias]) &&
$this->data[$this->alias][$field] === null
);
if ($keyPresentAndEmpty) {
unset($this->data[$this->alias][$field]);
}
}
$exists = $this->exists();
$dateFields = array('modified', 'updated');
if (!$exists) {
$dateFields[] = 'created';
}
if (isset($this->data[$this->alias])) {
$fields = array_keys($this->data[$this->alias]);
}
if ($options['validate'] && !$this->validates($options)) {
$this->whitelist = $_whitelist;
return false;
}
$db =& ConnectionManager::getDataSource($this->useDbConfig);
foreach ($dateFields as $updateCol) {
if ($this->hasField($updateCol) && !in_array($updateCol, $fields)) {
$default = array('formatter' => 'date');
$colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]);
if (!array_key_exists('format', $colType)) {
$time = strtotime('now');
} else {
$time = $colType['formatter']($colType['format']);
}
if (!empty($this->whitelist)) {
$this->whitelist[] = $updateCol;
}
$this->set($updateCol, $time);
}
}
if ($options['callbacks'] === true || $options['callbacks'] === 'before') {
$result = $this->Behaviors->trigger($this, 'beforeSave', array($options), array(
'break' => true, 'breakOn' => false
));
if (!$result || !$this->beforeSave($options)) {
$this->whitelist = $_whitelist;
return false;
}
}
if (empty($this->data[$this->alias][$this->primaryKey])) {
unset($this->data[$this->alias][$this->primaryKey]);
}
$fields = $values = array();
foreach ($this->data as $n => $v) {
if (isset($this->hasAndBelongsToMany[$n])) {
if (isset($v[$n])) {
$v = $v[$n];
}
$joined[$n] = $v;
} else {
if ($n === $this->alias) {
foreach (array('created', 'updated', 'modified') as $field) {
if (array_key_exists($field, $v) && empty($v[$field])) {
unset($v[$field]);
}
}
foreach ($v as $x => $y) {
if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) {
list($fields[], $values[]) = array($x, $y);
}
}
}
}
}
$count = count($fields);
if (!$exists && $count > 0) {
$this->id = false;
}
$success = true;
$created = false;
if ($count > 0) {
$cache = $this->_prepareUpdateFields(array_combine($fields, $values));
if (!empty($this->id)) {
$success = (bool)$db->update($this, $fields, $values);
} else {
$fInfo = $this->_schema[$this->primaryKey];
$isUUID = ($fInfo['length'] == 36 &&
($fInfo['type'] === 'string' || $fInfo['type'] === 'binary')
);
if (empty($this->data[$this->alias][$this->primaryKey]) && $isUUID) {
if (array_key_exists($this->primaryKey, $this->data[$this->alias])) {
$j = array_search($this->primaryKey, $fields);
$values[$j] = String::uuid();
} else {
list($fields[], $values[]) = array($this->primaryKey, String::uuid());
}
}
if (!$db->create($this, $fields, $values)) {
$success = $created = false;
} else {
$created = true;
}
}
if ($success && !empty($this->belongsTo)) {
$this->updateCounterCache($cache, $created);
}
}
if (!empty($joined) && $success === true) {
$this->__saveMulti($joined, $this->id, $db);
}
if ($success && $count > 0) {
if (!empty($this->data)) {
$success = $this->data;
}
if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
$this->Behaviors->trigger($this, 'afterSave', array($created, $options));
$this->afterSave($created);
}
if (!empty($this->data)) {
$success = Set::merge($success, $this->data);
}
$this->data = false;
$this->_clearCache();
$this->validationErrors = array();
}
$this->whitelist = $_whitelist;
return $success;
} | Saves model data (based on white-list, if supplied) to the database. By
default, validation occurs before save.
@param array $data Data to save.
@param mixed $validate Either a boolean, or an array.
If a boolean, indicates whether or not to validate before saving.
If an array, allows control of validate, callbacks, and fieldList
@param array $fieldList List of fields to allow to be written
@return mixed On success Model::$data if its not empty or true, false on failure
@access public
@link http://book.cakephp.org/view/1031/Saving-Your-Data | save | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function __saveMulti($joined, $id, &$db) {
foreach ($joined as $assoc => $data) {
if (isset($this->hasAndBelongsToMany[$assoc])) {
list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
$isUUID = !empty($this->{$join}->primaryKey) && (
$this->{$join}->_schema[$this->{$join}->primaryKey]['length'] == 36 && (
$this->{$join}->_schema[$this->{$join}->primaryKey]['type'] === 'string' ||
$this->{$join}->_schema[$this->{$join}->primaryKey]['type'] === 'binary'
)
);
$newData = $newValues = array();
$primaryAdded = false;
$fields = array(
$db->name($this->hasAndBelongsToMany[$assoc]['foreignKey']),
$db->name($this->hasAndBelongsToMany[$assoc]['associationForeignKey'])
);
$idField = $db->name($this->{$join}->primaryKey);
if ($isUUID && !in_array($idField, $fields)) {
$fields[] = $idField;
$primaryAdded = true;
}
foreach ((array)$data as $row) {
if ((is_string($row) && (strlen($row) == 36 || strlen($row) == 16)) || is_numeric($row)) {
$values = array(
$db->value($id, $this->getColumnType($this->primaryKey)),
$db->value($row)
);
if ($isUUID && $primaryAdded) {
$values[] = $db->value(String::uuid());
}
$values = implode(',', $values);
$newValues[] = "({$values})";
unset($values);
} elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
$newData[] = $row;
} elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
$newData[] = $row[$join];
}
}
if ($this->hasAndBelongsToMany[$assoc]['unique']) {
$conditions = array(
$join . '.' . $this->hasAndBelongsToMany[$assoc]['foreignKey'] => $id
);
if (!empty($this->hasAndBelongsToMany[$assoc]['conditions'])) {
$conditions = array_merge($conditions, (array)$this->hasAndBelongsToMany[$assoc]['conditions']);
}
$links = $this->{$join}->find('all', array(
'conditions' => $conditions,
'recursive' => empty($this->hasAndBelongsToMany[$assoc]['conditions']) ? -1 : 0,
'fields' => $this->hasAndBelongsToMany[$assoc]['associationForeignKey']
));
$associationForeignKey = "{$join}." . $this->hasAndBelongsToMany[$assoc]['associationForeignKey'];
$oldLinks = Set::extract($links, "{n}.{$associationForeignKey}");
if (!empty($oldLinks)) {
$conditions[$associationForeignKey] = $oldLinks;
$db->delete($this->{$join}, $conditions);
}
}
if (!empty($newData)) {
foreach ($newData as $data) {
$data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $id;
$this->{$join}->create($data);
$this->{$join}->save();
}
}
if (!empty($newValues)) {
$fields = implode(',', $fields);
$db->insertMulti($this->{$join}, $fields, $newValues);
}
}
}
} | Saves model hasAndBelongsToMany data to the database.
@param array $joined Data to save
@param mixed $id ID of record in this model
@access private | __saveMulti | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function updateCounterCache($keys = array(), $created = false) {
$keys = empty($keys) ? $this->data[$this->alias] : $keys;
$keys['old'] = isset($keys['old']) ? $keys['old'] : array();
foreach ($this->belongsTo as $parent => $assoc) {
$foreignKey = $assoc['foreignKey'];
$fkQuoted = $this->escapeField($assoc['foreignKey']);
if (!empty($assoc['counterCache'])) {
if ($assoc['counterCache'] === true) {
$assoc['counterCache'] = Inflector::underscore($this->alias) . '_count';
}
if (!$this->{$parent}->hasField($assoc['counterCache'])) {
continue;
}
if (!array_key_exists($foreignKey, $keys)) {
$keys[$foreignKey] = $this->field($foreignKey);
}
$recursive = (isset($assoc['counterScope']) ? 1 : -1);
$conditions = ($recursive == 1) ? (array)$assoc['counterScope'] : array();
if (isset($keys['old'][$foreignKey])) {
if ($keys['old'][$foreignKey] != $keys[$foreignKey]) {
$conditions[$fkQuoted] = $keys['old'][$foreignKey];
$count = intval($this->find('count', compact('conditions', 'recursive')));
$this->{$parent}->updateAll(
array($assoc['counterCache'] => $count),
array($this->{$parent}->escapeField() => $keys['old'][$foreignKey])
);
}
}
$conditions[$fkQuoted] = $keys[$foreignKey];
if ($recursive == 1) {
$conditions = array_merge($conditions, (array)$assoc['counterScope']);
}
$count = intval($this->find('count', compact('conditions', 'recursive')));
$this->{$parent}->updateAll(
array($assoc['counterCache'] => $count),
array($this->{$parent}->escapeField() => $keys[$foreignKey])
);
}
}
} | Updates the counter cache of belongsTo associations after a save or delete operation
@param array $keys Optional foreign key data, defaults to the information $this->data
@param boolean $created True if a new record was created, otherwise only associations with
'counterScope' defined get updated
@return void
@access public | updateCounterCache | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function _prepareUpdateFields($data) {
$foreignKeys = array();
foreach ($this->belongsTo as $assoc => $info) {
if ($info['counterCache']) {
$foreignKeys[$assoc] = $info['foreignKey'];
}
}
$included = array_intersect($foreignKeys, array_keys($data));
if (empty($included) || empty($this->id)) {
return array();
}
$old = $this->find('first', array(
'conditions' => array($this->primaryKey => $this->id),
'fields' => array_values($included),
'recursive' => -1
));
return array_merge($data, array('old' => $old[$this->alias]));
} | Helper method for Model::updateCounterCache(). Checks the fields to be updated for
@param array $data The fields of the record that will be updated
@return array Returns updated foreign key values, along with an 'old' key containing the old
values, or empty if no foreign keys are updated.
@access protected | _prepareUpdateFields | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function saveAll($data = null, $options = array()) {
if (empty($data)) {
$data = $this->data;
}
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$options = array_merge(array('validate' => 'first', 'atomic' => true), $options);
$this->validationErrors = $validationErrors = array();
$validates = true;
$return = array();
if (empty($data) && $options['validate'] !== false) {
$result = $this->save($data, $options);
return !empty($result);
}
if ($options['atomic'] && $options['validate'] !== 'only') {
$transactionBegun = $db->begin($this);
}
if (Set::numeric(array_keys($data))) {
while ($validates) {
$return = array();
foreach ($data as $key => $record) {
if (!$currentValidates = $this->__save($record, $options)) {
$validationErrors[$key] = $this->validationErrors;
}
if ($options['validate'] === 'only' || $options['validate'] === 'first') {
$validating = true;
if ($options['atomic']) {
$validates = $validates && $currentValidates;
} else {
$validates = $currentValidates;
}
} else {
$validating = false;
$validates = $currentValidates;
}
if (!$options['atomic']) {
$return[] = $validates;
} elseif (!$validates && !$validating) {
break;
}
}
$this->validationErrors = $validationErrors;
switch (true) {
case ($options['validate'] === 'only'):
return ($options['atomic'] ? $validates : $return);
break;
case ($options['validate'] === 'first'):
$options['validate'] = true;
break;
default:
if ($options['atomic']) {
if ($validates) {
if ($transactionBegun) {
return $db->commit($this) !== false;
} else {
return true;
}
}
$db->rollback($this);
return false;
}
return $return;
break;
}
}
if ($options['atomic'] && !$validates) {
$db->rollback($this);
return false;
}
return $return;
}
$associations = $this->getAssociated();
while ($validates) {
foreach ($data as $association => $values) {
if (isset($associations[$association])) {
switch ($associations[$association]) {
case 'belongsTo':
if ($this->{$association}->__save($values, $options)) {
$data[$this->alias][$this->belongsTo[$association]['foreignKey']] = $this->{$association}->id;
} else {
$validationErrors[$association] = $this->{$association}->validationErrors;
$validates = false;
}
if (!$options['atomic']) {
$return[$association][] = $validates;
}
break;
}
}
}
if (!$this->__save($data, $options)) {
$validationErrors[$this->alias] = $this->validationErrors;
$validates = false;
}
if (!$options['atomic']) {
$return[$this->alias] = $validates;
}
$validating = ($options['validate'] === 'only' || $options['validate'] === 'first');
foreach ($data as $association => $values) {
if (!$validates && !$validating) {
break;
}
if (isset($associations[$association])) {
$type = $associations[$association];
switch ($type) {
case 'hasOne':
if (!$validating) {
$values[$this->{$type}[$association]['foreignKey']] = $this->id;
}
if (!$this->{$association}->__save($values, $options)) {
$validationErrors[$association] = $this->{$association}->validationErrors;
$validates = false;
}
if (!$options['atomic']) {
$return[$association][] = $validates;
}
break;
case 'hasMany':
if (!$validating) {
foreach ($values as $i => $value) {
$values[$i][$this->{$type}[$association]['foreignKey']] = $this->id;
}
}
$_options = array_merge($options, array('atomic' => false));
if ($_options['validate'] === 'first') {
$_options['validate'] = 'only';
}
$_return = $this->{$association}->saveAll($values, $_options);
if ($_return === false || (is_array($_return) && in_array(false, $_return, true))) {
$validationErrors[$association] = $this->{$association}->validationErrors;
$validates = false;
}
if (is_array($_return)) {
foreach ($_return as $val) {
if (!isset($return[$association])) {
$return[$association] = array();
} elseif (!is_array($return[$association])) {
$return[$association] = array($return[$association]);
}
$return[$association][] = $val;
}
} else {
$return[$association] = $_return;
}
break;
}
}
}
$this->validationErrors = $validationErrors;
if (isset($validationErrors[$this->alias])) {
$this->validationErrors = $validationErrors[$this->alias];
}
switch (true) {
case ($options['validate'] === 'only'):
return ($options['atomic'] ? $validates : $return);
break;
case ($options['validate'] === 'first'):
$options['validate'] = true;
$return = array();
break;
default:
if ($options['atomic']) {
if ($validates) {
if ($transactionBegun) {
return $db->commit($this) !== false;
} else {
return true;
}
} else {
$db->rollback($this);
}
}
return $return;
break;
}
if ($options['atomic'] && !$validates) {
$db->rollback($this);
return false;
}
}
} | Saves multiple individual records for a single model; Also works with a single record, as well as
all its associated records.
#### Options
- validate: Set to false to disable validation, true to validate each record before saving,
'first' to validate *all* records before any are saved (default),
or 'only' to only validate the records, but not save them.
- atomic: If true (default), will attempt to save all records in a single transaction.
Should be set to false if database/table does not support transactions.
- fieldList: Equivalent to the $fieldList parameter in Model::save()
@param array $data Record data to save. This can be either a numerically-indexed array (for saving multiple
records of the same type), or an array indexed by association name.
@param array $options Options to use when saving record data, See $options above.
@return mixed If atomic: True on success, or false on failure.
Otherwise: array similar to the $data array passed, but values are set to true/false
depending on whether each record saved successfully.
@access public
@link http://book.cakephp.org/view/1032/Saving-Related-Model-Data-hasOne-hasMany-belongsTo
@link http://book.cakephp.org/view/1031/Saving-Your-Data | saveAll | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function __save($data, $options) {
if ($options['validate'] === 'first' || $options['validate'] === 'only') {
if (!($this->create($data) && $this->validates($options))) {
return false;
}
} elseif (!($this->create(null) !== null && $this->save($data, $options))) {
return false;
}
return true;
} | Private helper method used by saveAll.
@return boolean Success
@access private
@see Model::saveAll() | __save | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function updateAll($fields, $conditions = true) {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
return $db->update($this, $fields, null, $conditions);
} | Updates multiple model records based on a set of conditions.
@param array $fields Set of fields and values, indexed by fields.
Fields are treated as SQL snippets, to insert literal values manually escape your data.
@param mixed $conditions Conditions to match, true for all records
@return boolean True on success, false on failure
@access public
@link http://book.cakephp.org/view/1031/Saving-Your-Data | updateAll | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function delete($id = null, $cascade = true) {
if (!empty($id)) {
$this->id = $id;
}
$id = $this->id;
if ($this->beforeDelete($cascade)) {
$filters = $this->Behaviors->trigger($this, 'beforeDelete', array($cascade), array(
'break' => true, 'breakOn' => false
));
if (!$filters || !$this->exists()) {
return false;
}
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$this->_deleteDependent($id, $cascade);
$this->_deleteLinks($id);
$this->id = $id;
if (!empty($this->belongsTo)) {
$keys = $this->find('first', array(
'fields' => $this->__collectForeignKeys(),
'conditions' => array($this->alias . '.' . $this->primaryKey => $id)
));
}
if ($db->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) {
if (!empty($this->belongsTo)) {
$this->updateCounterCache($keys[$this->alias]);
}
$this->Behaviors->trigger($this, 'afterDelete');
$this->afterDelete();
$this->_clearCache();
$this->id = false;
return true;
}
}
return false;
} | Removes record for given ID. If no ID is given, the current ID is used. Returns true on success.
@param mixed $id ID of record to delete
@param boolean $cascade Set to true to delete records that depend on this record
@return boolean True on success
@access public
@link http://book.cakephp.org/view/1036/delete | delete | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function _deleteDependent($id, $cascade) {
if (!empty($this->__backAssociation)) {
$savedAssociatons = $this->__backAssociation;
$this->__backAssociation = array();
}
if ($cascade === true) {
foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) {
if ($data['dependent'] === true) {
$model =& $this->{$assoc};
if ($data['foreignKey'] === false && $data['conditions'] && in_array($this->name, $model->getAssociated('belongsTo'))) {
$model->recursive = 0;
$conditions = array($this->escapeField(null, $this->name) => $id);
} else {
$model->recursive = -1;
$conditions = array($model->escapeField($data['foreignKey']) => $id);
if ($data['conditions']) {
$conditions = array_merge((array)$data['conditions'], $conditions);
}
}
if (isset($data['exclusive']) && $data['exclusive']) {
$model->deleteAll($conditions);
} else {
$records = $model->find('all', array(
'conditions' => $conditions, 'fields' => $model->primaryKey
));
if (!empty($records)) {
foreach ($records as $record) {
$model->delete($record[$model->alias][$model->primaryKey]);
}
}
}
}
}
}
if (isset($savedAssociatons)) {
$this->__backAssociation = $savedAssociatons;
}
} | Cascades model deletes through associated hasMany and hasOne child records.
@param string $id ID of record that was deleted
@param boolean $cascade Set to true to delete records that depend on this record
@return void
@access protected | _deleteDependent | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function _deleteLinks($id) {
foreach ($this->hasAndBelongsToMany as $assoc => $data) {
$joinModel = $data['with'];
$records = $this->{$joinModel}->find('all', array(
'conditions' => array_merge(array($this->{$joinModel}->escapeField($data['foreignKey']) => $id)),
'fields' => $this->{$joinModel}->primaryKey,
'recursive' => -1
));
if (!empty($records)) {
foreach ($records as $record) {
$this->{$joinModel}->delete($record[$this->{$joinModel}->alias][$this->{$joinModel}->primaryKey]);
}
}
}
} | Cascades model deletes through HABTM join keys.
@param string $id ID of record that was deleted
@return void
@access protected | _deleteLinks | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function deleteAll($conditions, $cascade = true, $callbacks = false) {
if (empty($conditions)) {
return false;
}
$db =& ConnectionManager::getDataSource($this->useDbConfig);
if (!$cascade && !$callbacks) {
return $db->delete($this, $conditions);
} else {
$ids = $this->find('all', array_merge(array(
'fields' => "{$this->alias}.{$this->primaryKey}",
'recursive' => 0), compact('conditions'))
);
if ($ids === false) {
return false;
}
$ids = Set::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}");
if (empty($ids)) {
return true;
}
if ($callbacks) {
$_id = $this->id;
$result = true;
foreach ($ids as $id) {
$result = ($result && $this->delete($id, $cascade));
}
$this->id = $_id;
return $result;
} else {
foreach ($ids as $id) {
$this->_deleteLinks($id);
if ($cascade) {
$this->_deleteDependent($id, $cascade);
}
}
return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids));
}
}
} | Deletes multiple model records based on a set of conditions.
@param mixed $conditions Conditions to match
@param boolean $cascade Set to true to delete records that depend on this record
@param boolean $callbacks Run callbacks
@return boolean True on success, false on failure
@access public
@link http://book.cakephp.org/view/1038/deleteAll | deleteAll | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function __collectForeignKeys($type = 'belongsTo') {
$result = array();
foreach ($this->{$type} as $assoc => $data) {
if (isset($data['foreignKey']) && is_string($data['foreignKey'])) {
$result[$assoc] = $data['foreignKey'];
}
}
return $result;
} | Collects foreign keys from associations.
@return array
@access private | __collectForeignKeys | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function exists() {
if ($this->getID() === false) {
return false;
}
$conditions = array($this->alias . '.' . $this->primaryKey => $this->getID());
$query = array('conditions' => $conditions, 'recursive' => -1, 'callbacks' => false);
return ($this->find('count', $query) > 0);
} | Returns true if a record with the currently set ID exists.
Internally calls Model::getID() to obtain the current record ID to verify,
and then performs a Model::find('count') on the currently configured datasource
to ascertain the existence of the record in persistent storage.
@return boolean True if such a record exists
@access public | exists | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function hasAny($conditions = null) {
return ($this->find('count', array('conditions' => $conditions, 'recursive' => -1)) != false);
} | Returns true if a record that meets given conditions exists.
@param array $conditions SQL conditions array
@return boolean True if such a record exists
@access public | hasAny | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function _findFirst($state, $query, $results = array()) {
if ($state == 'before') {
$query['limit'] = 1;
return $query;
} elseif ($state == 'after') {
if (empty($results[0])) {
return false;
}
return $results[0];
}
} | Handles the before/after filter logic for find('first') operations. Only called by Model::find().
@param string $state Either "before" or "after"
@param array $query
@param array $data
@return array
@access protected
@see Model::find() | _findFirst | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function _findCount($state, $query, $results = array()) {
if ($state == 'before') {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
if (empty($query['fields'])) {
$query['fields'] = $db->calculate($this, 'count');
} elseif (is_string($query['fields']) && !preg_match('/count/i', $query['fields'])) {
$query['fields'] = $db->calculate($this, 'count', array(
$db->expression($query['fields']), 'count'
));
}
$query['order'] = false;
return $query;
} elseif ($state == 'after') {
if (isset($results[0][0]['count'])) {
return intval($results[0][0]['count']);
} elseif (isset($results[0][$this->alias]['count'])) {
return intval($results[0][$this->alias]['count']);
}
return false;
}
} | Handles the before/after filter logic for find('count') operations. Only called by Model::find().
@param string $state Either "before" or "after"
@param array $query
@param array $data
@return int The number of records found, or false
@access protected
@see Model::find() | _findCount | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function _findList($state, $query, $results = array()) {
if ($state == 'before') {
if (empty($query['fields'])) {
$query['fields'] = array("{$this->alias}.{$this->primaryKey}", "{$this->alias}.{$this->displayField}");
$list = array("{n}.{$this->alias}.{$this->primaryKey}", "{n}.{$this->alias}.{$this->displayField}", null);
} else {
if (!is_array($query['fields'])) {
$query['fields'] = String::tokenize($query['fields']);
}
if (count($query['fields']) == 1) {
if (strpos($query['fields'][0], '.') === false) {
$query['fields'][0] = $this->alias . '.' . $query['fields'][0];
}
$list = array("{n}.{$this->alias}.{$this->primaryKey}", '{n}.' . $query['fields'][0], null);
$query['fields'] = array("{$this->alias}.{$this->primaryKey}", $query['fields'][0]);
} elseif (count($query['fields']) == 3) {
for ($i = 0; $i < 3; $i++) {
if (strpos($query['fields'][$i], '.') === false) {
$query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
}
}
$list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], '{n}.' . $query['fields'][2]);
} else {
for ($i = 0; $i < 2; $i++) {
if (strpos($query['fields'][$i], '.') === false) {
$query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
}
}
$list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], null);
}
}
if (!isset($query['recursive']) || $query['recursive'] === null) {
$query['recursive'] = -1;
}
list($query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']) = $list;
return $query;
} elseif ($state == 'after') {
if (empty($results)) {
return array();
}
$lst = $query['list'];
return Set::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']);
}
} | Handles the before/after filter logic for find('list') operations. Only called by Model::find().
@param string $state Either "before" or "after"
@param array $query
@param array $data
@return array Key/value pairs of primary keys/display field values of all records found
@access protected
@see Model::find() | _findList | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function _findNeighbors($state, $query, $results = array()) {
if ($state == 'before') {
$query = array_merge(array('recursive' => 0), $query);
extract($query);
$conditions = (array)$conditions;
if (isset($field) && isset($value)) {
if (strpos($field, '.') === false) {
$field = $this->alias . '.' . $field;
}
} else {
$field = $this->alias . '.' . $this->primaryKey;
$value = $this->id;
}
$query['conditions'] = array_merge($conditions, array($field . ' <' => $value));
$query['order'] = $field . ' DESC';
$query['limit'] = 1;
$query['field'] = $field;
$query['value'] = $value;
return $query;
} elseif ($state == 'after') {
extract($query);
unset($query['conditions'][$field . ' <']);
$return = array();
if (isset($results[0])) {
$prevVal = Set::extract('/' . str_replace('.', '/', $field), $results[0]);
$query['conditions'][$field . ' >='] = $prevVal[0];
$query['conditions'][$field . ' !='] = $value;
$query['limit'] = 2;
} else {
$return['prev'] = null;
$query['conditions'][$field . ' >'] = $value;
$query['limit'] = 1;
}
$query['order'] = $field . ' ASC';
$return2 = $this->find('all', $query);
if (!array_key_exists('prev', $return)) {
$return['prev'] = $return2[0];
}
if (count($return2) == 2) {
$return['next'] = $return2[1];
} elseif (count($return2) == 1 && !$return['prev']) {
$return['next'] = $return2[0];
} else {
$return['next'] = null;
}
return $return;
}
} | Detects the previous field's value, then uses logic to find the 'wrapping'
rows and return them.
@param string $state Either "before" or "after"
@param mixed $query
@param array $results
@return array
@access protected | _findNeighbors | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function _findThreaded($state, $query, $results = array()) {
if ($state == 'before') {
return $query;
} elseif ($state == 'after') {
$return = $idMap = array();
$ids = Set::extract($results, '{n}.' . $this->alias . '.' . $this->primaryKey);
foreach ($results as $result) {
$result['children'] = array();
$id = $result[$this->alias][$this->primaryKey];
$parentId = $result[$this->alias]['parent_id'];
if (isset($idMap[$id]['children'])) {
$idMap[$id] = array_merge($result, (array)$idMap[$id]);
} else {
$idMap[$id] = array_merge($result, array('children' => array()));
}
if (!$parentId || !in_array($parentId, $ids)) {
$return[] =& $idMap[$id];
} else {
$idMap[$parentId]['children'][] =& $idMap[$id];
}
}
if (count($return) > 1) {
$ids = array_unique(Set::extract('/' . $this->alias . '/parent_id', $return));
if (count($ids) > 1) {
$root = $return[0][$this->alias]['parent_id'];
foreach ($return as $key => $value) {
if ($value[$this->alias]['parent_id'] != $root) {
unset($return[$key]);
}
}
}
}
return $return;
}
} | In the event of ambiguous results returned (multiple top level results, with different parent_ids)
top level results with different parent_ids to the first result will be dropped
@param mixed $state
@param mixed $query
@param array $results
@return array Threaded results
@access protected | _findThreaded | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function __filterResults($results, $primary = true) {
$return = $this->Behaviors->trigger($this, 'afterFind', array($results, $primary), array('modParams' => true));
if ($return !== true) {
$results = $return;
}
return $this->afterFind($results, $primary);
} | Passes query results through model and behavior afterFilter() methods.
@param array Results to filter
@param boolean $primary If this is the primary model results (results from model where the find operation was performed)
@return array Set of filtered results
@access private | __filterResults | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function resetAssociations() {
if (!empty($this->__backAssociation)) {
foreach ($this->__associations as $type) {
if (isset($this->__backAssociation[$type])) {
$this->{$type} = $this->__backAssociation[$type];
}
}
$this->__backAssociation = array();
}
foreach ($this->__associations as $type) {
foreach ($this->{$type} as $key => $name) {
if (!empty($this->{$key}->__backAssociation)) {
$this->{$key}->resetAssociations();
}
}
}
$this->__backAssociation = array();
return true;
} | This resets the association arrays for the model back
to those originally defined in the model. Normally called at the end
of each call to Model::find()
@return boolean Success
@access public | resetAssociations | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function isUnique($fields, $or = true) {
if (!is_array($fields)) {
$fields = func_get_args();
if (is_bool($fields[count($fields) - 1])) {
$or = $fields[count($fields) - 1];
unset($fields[count($fields) - 1]);
}
}
foreach ($fields as $field => $value) {
if (is_numeric($field)) {
unset($fields[$field]);
$field = $value;
if (isset($this->data[$this->alias][$field])) {
$value = $this->data[$this->alias][$field];
} else {
$value = null;
}
}
if (strpos($field, '.') === false) {
unset($fields[$field]);
$fields[$this->alias . '.' . $field] = $value;
}
}
if ($or) {
$fields = array('or' => $fields);
}
if (!empty($this->id)) {
$fields[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id;
}
return ($this->find('count', array('conditions' => $fields, 'recursive' => -1)) == 0);
} | Returns false if any fields passed match any (by default, all if $or = false) of their matching values.
@param array $fields Field/value pairs to search (if no values specified, they are pulled from $this->data)
@param boolean $or If false, all fields specified must match in order for a false return value
@return boolean False if any records matching any fields are found
@access public | isUnique | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function query() {
$params = func_get_args();
$db =& ConnectionManager::getDataSource($this->useDbConfig);
return call_user_func_array(array(&$db, 'query'), $params);
} | Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method.
@param string $sql SQL statement
@return array Resultset
@access public
@link http://book.cakephp.org/view/1027/query | query | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function validates($options = array()) {
$errors = $this->invalidFields($options);
if (empty($errors) && $errors !== false) {
$errors = $this->__validateWithModels($options);
}
if (is_array($errors)) {
return count($errors) === 0;
}
return $errors;
} | Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
that use the 'with' key as well. Since __saveMulti is incapable of exiting a save operation.
Will validate the currently set data. Use Model::set() or Model::create() to set the active data.
@param string $options An optional array of custom options to be made available in the beforeValidate callback
@return boolean True if there are no errors
@access public
@link http://book.cakephp.org/view/1182/Validating-Data-from-the-Controller | validates | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
function invalidFields($options = array()) {
if (
!$this->Behaviors->trigger(
$this,
'beforeValidate',
array($options),
array('break' => true, 'breakOn' => false)
) ||
$this->beforeValidate($options) === false
) {
return false;
}
if (!isset($this->validate) || empty($this->validate)) {
return $this->validationErrors;
}
$data = $this->data;
$methods = array_map('strtolower', get_class_methods($this));
$behaviorMethods = array_keys($this->Behaviors->methods());
if (isset($data[$this->alias])) {
$data = $data[$this->alias];
} elseif (!is_array($data)) {
$data = array();
}
$Validation =& Validation::getInstance();
$exists = null;
$_validate = $this->validate;
$whitelist = $this->whitelist;
if (!empty($options['fieldList'])) {
$whitelist = $options['fieldList'];
}
if (!empty($whitelist)) {
$validate = array();
foreach ((array)$whitelist as $f) {
if (!empty($this->validate[$f])) {
$validate[$f] = $this->validate[$f];
}
}
$this->validate = $validate;
}
foreach ($this->validate as $fieldName => $ruleSet) {
if (!is_array($ruleSet) || (is_array($ruleSet) && isset($ruleSet['rule']))) {
$ruleSet = array($ruleSet);
}
$default = array(
'allowEmpty' => null,
'required' => null,
'rule' => 'blank',
'last' => false,
'on' => null
);
foreach ($ruleSet as $index => $validator) {
if (!is_array($validator)) {
$validator = array('rule' => $validator);
}
$validator = array_merge($default, $validator);
if (isset($validator['message'])) {
$message = $validator['message'];
} else {
$message = __('This field cannot be left blank', true);
}
if (!empty($validator['on'])) {
if ($exists === null) {
$exists = $this->exists();
}
if (($validator['on'] == 'create' && $exists) || ($validator['on'] == 'update' && !$exists)) {
continue;
}
}
$required = (
(!isset($data[$fieldName]) && $validator['required'] === true) ||
(
isset($data[$fieldName]) && (empty($data[$fieldName]) &&
!is_numeric($data[$fieldName])) && $validator['allowEmpty'] === false
)
);
if ($required) {
$this->invalidate($fieldName, $message);
if ($validator['last']) {
break;
}
} elseif (array_key_exists($fieldName, $data)) {
if (empty($data[$fieldName]) && $data[$fieldName] != '0' && $validator['allowEmpty'] === true) {
break;
}
if (is_array($validator['rule'])) {
$rule = $validator['rule'][0];
unset($validator['rule'][0]);
$ruleParams = array_merge(array($data[$fieldName]), array_values($validator['rule']));
} else {
$rule = $validator['rule'];
$ruleParams = array($data[$fieldName]);
}
$valid = true;
if (in_array(strtolower($rule), $methods)) {
$ruleParams[] = $validator;
$ruleParams[0] = array($fieldName => $ruleParams[0]);
$valid = $this->dispatchMethod($rule, $ruleParams);
} elseif (in_array($rule, $behaviorMethods) || in_array(strtolower($rule), $behaviorMethods)) {
$ruleParams[] = $validator;
$ruleParams[0] = array($fieldName => $ruleParams[0]);
$valid = $this->Behaviors->dispatchMethod($this, $rule, $ruleParams);
} elseif (method_exists($Validation, $rule)) {
$valid = $Validation->dispatchMethod($rule, $ruleParams);
} elseif (!is_array($validator['rule'])) {
$valid = preg_match($rule, $data[$fieldName]);
} elseif (Configure::read('debug') > 0) {
trigger_error(sprintf(__('Could not find validation handler %s for %s', true), $rule, $fieldName), E_USER_WARNING);
}
if (!$valid || (is_string($valid) && strlen($valid) > 0)) {
if (is_string($valid) && strlen($valid) > 0) {
$validator['message'] = $valid;
} elseif (!isset($validator['message'])) {
if (is_string($index)) {
$validator['message'] = $index;
} elseif (is_numeric($index) && count($ruleSet) > 1) {
$validator['message'] = $index + 1;
} else {
$validator['message'] = $message;
}
}
$this->invalidate($fieldName, $validator['message']);
if ($validator['last']) {
break;
}
}
}
}
}
$this->validate = $_validate;
return $this->validationErrors;
} | Returns an array of fields that have failed validation. On the current model.
@param string $options An optional array of custom options to be made available in the beforeValidate callback
@return array Array of invalid fields
@see Model::validates()
@access public
@link http://book.cakephp.org/view/1182/Validating-Data-from-the-Controller | invalidFields | php | Datawalke/Coordino | cake/libs/model/model.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/model.php | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.