id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
29,100
locomotivemtl/charcoal-core
src/Charcoal/Source/StorableTrait.php
StorableTrait.setKey
public function setKey($key) { if (!is_string($key)) { throw new InvalidArgumentException(sprintf( 'Key must be a string; received %s', (is_object($key) ? get_class($key) : gettype($key)) )); } if (!preg_match_all('/^[A-Za-z0-9_]+$/', $key)) { throw new InvalidArgumentException( sprintf('Key "%s" is invalid: must be alphanumeric / underscore.', $key) ); } $this->key = $key; return $this; }
php
public function setKey($key) { if (!is_string($key)) { throw new InvalidArgumentException(sprintf( 'Key must be a string; received %s', (is_object($key) ? get_class($key) : gettype($key)) )); } if (!preg_match_all('/^[A-Za-z0-9_]+$/', $key)) { throw new InvalidArgumentException( sprintf('Key "%s" is invalid: must be alphanumeric / underscore.', $key) ); } $this->key = $key; return $this; }
[ "public", "function", "setKey", "(", "$", "key", ")", "{", "if", "(", "!", "is_string", "(", "$", "key", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Key must be a string; received %s'", ",", "(", "is_object", "(", "$", "key", ")", "?", "get_class", "(", "$", "key", ")", ":", "gettype", "(", "$", "key", ")", ")", ")", ")", ";", "}", "if", "(", "!", "preg_match_all", "(", "'/^[A-Za-z0-9_]+$/'", ",", "$", "key", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Key \"%s\" is invalid: must be alphanumeric / underscore.'", ",", "$", "key", ")", ")", ";", "}", "$", "this", "->", "key", "=", "$", "key", ";", "return", "$", "this", ";", "}" ]
Set the primary property key. For uniquely identifying this object in storage. Note: For security reason, only alphanumeric characters (and underscores) are valid key names. Although SQL can support more, there's really no reason to. @param string $key The object's primary key. @throws InvalidArgumentException If the argument is not scalar. @return self
[ "Set", "the", "primary", "property", "key", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L106-L123
29,101
locomotivemtl/charcoal-core
src/Charcoal/Source/StorableTrait.php
StorableTrait.source
public function source() { if ($this->source === null) { $this->source = $this->createSource(); } return $this->source; }
php
public function source() { if ($this->source === null) { $this->source = $this->createSource(); } return $this->source; }
[ "public", "function", "source", "(", ")", "{", "if", "(", "$", "this", "->", "source", "===", "null", ")", "{", "$", "this", "->", "source", "=", "$", "this", "->", "createSource", "(", ")", ";", "}", "return", "$", "this", "->", "source", ";", "}" ]
Get the object's datasource repository. @return SourceInterface
[ "Get", "the", "object", "s", "datasource", "repository", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L153-L159
29,102
locomotivemtl/charcoal-core
src/Charcoal/Source/StorableTrait.php
StorableTrait.load
final public function load($id = null) { if ($id === null) { $id = $this->id(); } $this->source()->loadItem($id, $this); return $this; }
php
final public function load($id = null) { if ($id === null) { $id = $this->id(); } $this->source()->loadItem($id, $this); return $this; }
[ "final", "public", "function", "load", "(", "$", "id", "=", "null", ")", "{", "if", "(", "$", "id", "===", "null", ")", "{", "$", "id", "=", "$", "this", "->", "id", "(", ")", ";", "}", "$", "this", "->", "source", "(", ")", "->", "loadItem", "(", "$", "id", ",", "$", "this", ")", ";", "return", "$", "this", ";", "}" ]
Load an object from the database from its ID. @param mixed $id The identifier to load. @return self
[ "Load", "an", "object", "from", "the", "database", "from", "its", "ID", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L175-L182
29,103
locomotivemtl/charcoal-core
src/Charcoal/Source/StorableTrait.php
StorableTrait.loadFromQuery
final public function loadFromQuery($query, array $binds = []) { $this->source()->loadItemFromQuery($query, $binds, $this); return $this; }
php
final public function loadFromQuery($query, array $binds = []) { $this->source()->loadItemFromQuery($query, $binds, $this); return $this; }
[ "final", "public", "function", "loadFromQuery", "(", "$", "query", ",", "array", "$", "binds", "=", "[", "]", ")", "{", "$", "this", "->", "source", "(", ")", "->", "loadItemFromQuery", "(", "$", "query", ",", "$", "binds", ",", "$", "this", ")", ";", "return", "$", "this", ";", "}" ]
Load an object from the repository from a custom SQL query. @param string $query The SQL query. @param array $binds Optional. The SQL query parameters. @return self
[ "Load", "an", "object", "from", "the", "repository", "from", "a", "custom", "SQL", "query", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L204-L208
29,104
locomotivemtl/charcoal-core
src/Charcoal/Source/StorableTrait.php
StorableTrait.save
final public function save() { $pre = $this->preSave(); if ($pre === false) { $this->logger->error(sprintf( 'Can not save object "%s:%s"; cancelled by %s::preSave()', $this->objType(), $this->id(), get_called_class() )); return false; } $ret = $this->source()->saveItem($this); if ($ret === false) { $this->logger->error(sprintf( 'Can not save object "%s:%s"; repository failed for %s', $this->objType(), $this->id(), get_called_class() )); return false; } else { $this->setId($ret); } $post = $this->postSave(); if ($post === false) { $this->logger->error(sprintf( 'Saved object "%s:%s" but %s::postSave() failed', $this->objType(), $this->id(), get_called_class() )); return false; } return true; }
php
final public function save() { $pre = $this->preSave(); if ($pre === false) { $this->logger->error(sprintf( 'Can not save object "%s:%s"; cancelled by %s::preSave()', $this->objType(), $this->id(), get_called_class() )); return false; } $ret = $this->source()->saveItem($this); if ($ret === false) { $this->logger->error(sprintf( 'Can not save object "%s:%s"; repository failed for %s', $this->objType(), $this->id(), get_called_class() )); return false; } else { $this->setId($ret); } $post = $this->postSave(); if ($post === false) { $this->logger->error(sprintf( 'Saved object "%s:%s" but %s::postSave() failed', $this->objType(), $this->id(), get_called_class() )); return false; } return true; }
[ "final", "public", "function", "save", "(", ")", "{", "$", "pre", "=", "$", "this", "->", "preSave", "(", ")", ";", "if", "(", "$", "pre", "===", "false", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "sprintf", "(", "'Can not save object \"%s:%s\"; cancelled by %s::preSave()'", ",", "$", "this", "->", "objType", "(", ")", ",", "$", "this", "->", "id", "(", ")", ",", "get_called_class", "(", ")", ")", ")", ";", "return", "false", ";", "}", "$", "ret", "=", "$", "this", "->", "source", "(", ")", "->", "saveItem", "(", "$", "this", ")", ";", "if", "(", "$", "ret", "===", "false", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "sprintf", "(", "'Can not save object \"%s:%s\"; repository failed for %s'", ",", "$", "this", "->", "objType", "(", ")", ",", "$", "this", "->", "id", "(", ")", ",", "get_called_class", "(", ")", ")", ")", ";", "return", "false", ";", "}", "else", "{", "$", "this", "->", "setId", "(", "$", "ret", ")", ";", "}", "$", "post", "=", "$", "this", "->", "postSave", "(", ")", ";", "if", "(", "$", "post", "===", "false", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "sprintf", "(", "'Saved object \"%s:%s\" but %s::postSave() failed'", ",", "$", "this", "->", "objType", "(", ")", ",", "$", "this", "->", "id", "(", ")", ",", "get_called_class", "(", ")", ")", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Insert the object's current state in storage. @return boolean TRUE on success.
[ "Insert", "the", "object", "s", "current", "state", "in", "storage", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L215-L253
29,105
locomotivemtl/charcoal-core
src/Charcoal/Source/StorableTrait.php
StorableTrait.update
final public function update(array $keys = null) { $pre = $this->preUpdate($keys); if ($pre === false) { $this->logger->error(sprintf( 'Can not update object "%s:%s"; cancelled by %s::preUpdate()', $this->objType(), $this->id(), get_called_class() )); return false; } $ret = $this->source()->updateItem($this, $keys); if ($ret === false) { $this->logger->error(sprintf( 'Can not update object "%s:%s"; repository failed for %s', $this->objType(), $this->id(), get_called_class() )); return false; } $post = $this->postUpdate($keys); if ($post === false) { $this->logger->warning(sprintf( 'Updated object "%s:%s" but %s::postUpdate() failed', $this->objType(), $this->id(), get_called_class() )); return false; } return true; }
php
final public function update(array $keys = null) { $pre = $this->preUpdate($keys); if ($pre === false) { $this->logger->error(sprintf( 'Can not update object "%s:%s"; cancelled by %s::preUpdate()', $this->objType(), $this->id(), get_called_class() )); return false; } $ret = $this->source()->updateItem($this, $keys); if ($ret === false) { $this->logger->error(sprintf( 'Can not update object "%s:%s"; repository failed for %s', $this->objType(), $this->id(), get_called_class() )); return false; } $post = $this->postUpdate($keys); if ($post === false) { $this->logger->warning(sprintf( 'Updated object "%s:%s" but %s::postUpdate() failed', $this->objType(), $this->id(), get_called_class() )); return false; } return true; }
[ "final", "public", "function", "update", "(", "array", "$", "keys", "=", "null", ")", "{", "$", "pre", "=", "$", "this", "->", "preUpdate", "(", "$", "keys", ")", ";", "if", "(", "$", "pre", "===", "false", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "sprintf", "(", "'Can not update object \"%s:%s\"; cancelled by %s::preUpdate()'", ",", "$", "this", "->", "objType", "(", ")", ",", "$", "this", "->", "id", "(", ")", ",", "get_called_class", "(", ")", ")", ")", ";", "return", "false", ";", "}", "$", "ret", "=", "$", "this", "->", "source", "(", ")", "->", "updateItem", "(", "$", "this", ",", "$", "keys", ")", ";", "if", "(", "$", "ret", "===", "false", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "sprintf", "(", "'Can not update object \"%s:%s\"; repository failed for %s'", ",", "$", "this", "->", "objType", "(", ")", ",", "$", "this", "->", "id", "(", ")", ",", "get_called_class", "(", ")", ")", ")", ";", "return", "false", ";", "}", "$", "post", "=", "$", "this", "->", "postUpdate", "(", "$", "keys", ")", ";", "if", "(", "$", "post", "===", "false", ")", "{", "$", "this", "->", "logger", "->", "warning", "(", "sprintf", "(", "'Updated object \"%s:%s\" but %s::postUpdate() failed'", ",", "$", "this", "->", "objType", "(", ")", ",", "$", "this", "->", "id", "(", ")", ",", "get_called_class", "(", ")", ")", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Update the object in storage with the current state. @param string[] $keys If provided, only update the properties specified. @return boolean TRUE on success.
[ "Update", "the", "object", "in", "storage", "with", "the", "current", "state", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L261-L297
29,106
locomotivemtl/charcoal-core
src/Charcoal/Source/StorableTrait.php
StorableTrait.delete
final public function delete() { $pre = $this->preDelete(); if ($pre === false) { $this->logger->error(sprintf( 'Can not delete object "%s:%s"; cancelled by %s::preDelete()', $this->objType(), $this->id(), get_called_class() )); return false; } $ret = $this->source()->deleteItem($this); if ($ret === false) { $this->logger->error(sprintf( 'Can not delete object "%s:%s"; repository failed for %s', $this->objType(), $this->id(), get_called_class() )); return false; } $del = $this->postDelete(); if ($del === false) { $this->logger->warning(sprintf( 'Deleted object "%s:%s" but %s::postDelete() failed', $this->objType(), $this->id(), get_called_class() )); return false; } return true; }
php
final public function delete() { $pre = $this->preDelete(); if ($pre === false) { $this->logger->error(sprintf( 'Can not delete object "%s:%s"; cancelled by %s::preDelete()', $this->objType(), $this->id(), get_called_class() )); return false; } $ret = $this->source()->deleteItem($this); if ($ret === false) { $this->logger->error(sprintf( 'Can not delete object "%s:%s"; repository failed for %s', $this->objType(), $this->id(), get_called_class() )); return false; } $del = $this->postDelete(); if ($del === false) { $this->logger->warning(sprintf( 'Deleted object "%s:%s" but %s::postDelete() failed', $this->objType(), $this->id(), get_called_class() )); return false; } return true; }
[ "final", "public", "function", "delete", "(", ")", "{", "$", "pre", "=", "$", "this", "->", "preDelete", "(", ")", ";", "if", "(", "$", "pre", "===", "false", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "sprintf", "(", "'Can not delete object \"%s:%s\"; cancelled by %s::preDelete()'", ",", "$", "this", "->", "objType", "(", ")", ",", "$", "this", "->", "id", "(", ")", ",", "get_called_class", "(", ")", ")", ")", ";", "return", "false", ";", "}", "$", "ret", "=", "$", "this", "->", "source", "(", ")", "->", "deleteItem", "(", "$", "this", ")", ";", "if", "(", "$", "ret", "===", "false", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "sprintf", "(", "'Can not delete object \"%s:%s\"; repository failed for %s'", ",", "$", "this", "->", "objType", "(", ")", ",", "$", "this", "->", "id", "(", ")", ",", "get_called_class", "(", ")", ")", ")", ";", "return", "false", ";", "}", "$", "del", "=", "$", "this", "->", "postDelete", "(", ")", ";", "if", "(", "$", "del", "===", "false", ")", "{", "$", "this", "->", "logger", "->", "warning", "(", "sprintf", "(", "'Deleted object \"%s:%s\" but %s::postDelete() failed'", ",", "$", "this", "->", "objType", "(", ")", ",", "$", "this", "->", "id", "(", ")", ",", "get_called_class", "(", ")", ")", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Delete an object from storage. @return boolean TRUE on success.
[ "Delete", "an", "object", "from", "storage", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L304-L340
29,107
locomotivemtl/charcoal-core
src/Charcoal/Source/StorableTrait.php
StorableTrait.sourceFactory
protected function sourceFactory() { if (!isset($this->sourceFactory)) { throw new RuntimeException( sprintf('Source factory is not set for "%s"', get_class($this)) ); } return $this->sourceFactory; }
php
protected function sourceFactory() { if (!isset($this->sourceFactory)) { throw new RuntimeException( sprintf('Source factory is not set for "%s"', get_class($this)) ); } return $this->sourceFactory; }
[ "protected", "function", "sourceFactory", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "sourceFactory", ")", ")", "{", "throw", "new", "RuntimeException", "(", "sprintf", "(", "'Source factory is not set for \"%s\"'", ",", "get_class", "(", "$", "this", ")", ")", ")", ";", "}", "return", "$", "this", "->", "sourceFactory", ";", "}" ]
Get the datasource repository factory. @throws RuntimeException If the source factory was not previously set. @return FactoryInterface
[ "Get", "the", "datasource", "repository", "factory", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L360-L368
29,108
timble/kodekit
code/template/helper/listbox.php
TemplateHelperListbox.optionlist
public function optionlist($config = array()) { $translator = $this->getObject('translator'); $config = new ObjectConfigJson($config); $config->append(array( 'prompt' => '- '.$translator->translate('Select').' -', 'deselect' => false, 'options' => array(), 'select2' => true, 'attribs' => array(), )); if ($config->deselect && !$config->attribs->multiple) { $deselect = $this->option(array('value' => '', 'label' => $config->prompt)); $options = $config->options->toArray(); array_unshift($options, $deselect); $config->options = $options; } if ($config->attribs->multiple && $config->name && substr($config->name, -2) !== '[]') { $config->name .= '[]'; } $html = ''; if ($config->select2) { if (!$config->name) { $config->attribs->append(array( 'id' => 'select2-element-'.mt_rand(1000, 100000) )); } if ($config->deselect) { $config->attribs->append(array( 'data-placeholder' => $config->prompt )); } $config->append(array( 'select2_options' => array( 'element' => $config->attribs->id ? '#'.$config->attribs->id : 'select[name=\"'.$config->name.'\"]', 'options' => array( 'allowClear' => $config->deselect ) ) )); $html .= $this->createHelper('behavior')->select2($config->select2_options); } $html .= parent::optionlist($config); return $html; }
php
public function optionlist($config = array()) { $translator = $this->getObject('translator'); $config = new ObjectConfigJson($config); $config->append(array( 'prompt' => '- '.$translator->translate('Select').' -', 'deselect' => false, 'options' => array(), 'select2' => true, 'attribs' => array(), )); if ($config->deselect && !$config->attribs->multiple) { $deselect = $this->option(array('value' => '', 'label' => $config->prompt)); $options = $config->options->toArray(); array_unshift($options, $deselect); $config->options = $options; } if ($config->attribs->multiple && $config->name && substr($config->name, -2) !== '[]') { $config->name .= '[]'; } $html = ''; if ($config->select2) { if (!$config->name) { $config->attribs->append(array( 'id' => 'select2-element-'.mt_rand(1000, 100000) )); } if ($config->deselect) { $config->attribs->append(array( 'data-placeholder' => $config->prompt )); } $config->append(array( 'select2_options' => array( 'element' => $config->attribs->id ? '#'.$config->attribs->id : 'select[name=\"'.$config->name.'\"]', 'options' => array( 'allowClear' => $config->deselect ) ) )); $html .= $this->createHelper('behavior')->select2($config->select2_options); } $html .= parent::optionlist($config); return $html; }
[ "public", "function", "optionlist", "(", "$", "config", "=", "array", "(", ")", ")", "{", "$", "translator", "=", "$", "this", "->", "getObject", "(", "'translator'", ")", ";", "$", "config", "=", "new", "ObjectConfigJson", "(", "$", "config", ")", ";", "$", "config", "->", "append", "(", "array", "(", "'prompt'", "=>", "'- '", ".", "$", "translator", "->", "translate", "(", "'Select'", ")", ".", "' -'", ",", "'deselect'", "=>", "false", ",", "'options'", "=>", "array", "(", ")", ",", "'select2'", "=>", "true", ",", "'attribs'", "=>", "array", "(", ")", ",", ")", ")", ";", "if", "(", "$", "config", "->", "deselect", "&&", "!", "$", "config", "->", "attribs", "->", "multiple", ")", "{", "$", "deselect", "=", "$", "this", "->", "option", "(", "array", "(", "'value'", "=>", "''", ",", "'label'", "=>", "$", "config", "->", "prompt", ")", ")", ";", "$", "options", "=", "$", "config", "->", "options", "->", "toArray", "(", ")", ";", "array_unshift", "(", "$", "options", ",", "$", "deselect", ")", ";", "$", "config", "->", "options", "=", "$", "options", ";", "}", "if", "(", "$", "config", "->", "attribs", "->", "multiple", "&&", "$", "config", "->", "name", "&&", "substr", "(", "$", "config", "->", "name", ",", "-", "2", ")", "!==", "'[]'", ")", "{", "$", "config", "->", "name", ".=", "'[]'", ";", "}", "$", "html", "=", "''", ";", "if", "(", "$", "config", "->", "select2", ")", "{", "if", "(", "!", "$", "config", "->", "name", ")", "{", "$", "config", "->", "attribs", "->", "append", "(", "array", "(", "'id'", "=>", "'select2-element-'", ".", "mt_rand", "(", "1000", ",", "100000", ")", ")", ")", ";", "}", "if", "(", "$", "config", "->", "deselect", ")", "{", "$", "config", "->", "attribs", "->", "append", "(", "array", "(", "'data-placeholder'", "=>", "$", "config", "->", "prompt", ")", ")", ";", "}", "$", "config", "->", "append", "(", "array", "(", "'select2_options'", "=>", "array", "(", "'element'", "=>", "$", "config", "->", "attribs", "->", "id", "?", "'#'", ".", "$", "config", "->", "attribs", "->", "id", ":", "'select[name=\\\"'", ".", "$", "config", "->", "name", ".", "'\\\"]'", ",", "'options'", "=>", "array", "(", "'allowClear'", "=>", "$", "config", "->", "deselect", ")", ")", ")", ")", ";", "$", "html", ".=", "$", "this", "->", "createHelper", "(", "'behavior'", ")", "->", "select2", "(", "$", "config", "->", "select2_options", ")", ";", "}", "$", "html", ".=", "parent", "::", "optionlist", "(", "$", "config", ")", ";", "return", "$", "html", ";", "}" ]
Adds the option to enhance the select box using Select2 @param array|ObjectConfig $config @return string
[ "Adds", "the", "option", "to", "enhance", "the", "select", "box", "using", "Select2" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/template/helper/listbox.php#L79-L136
29,109
timble/kodekit
code/template/helper/listbox.php
TemplateHelperListbox.enabled
public function enabled( $config = array()) { $config = new ObjectConfigJson($config); $config->append(array( 'name' => 'enabled', 'attribs' => array(), 'deselect' => true, ))->append(array( 'selected' => $config->{$config->name} )); $translator = $this->getObject('translator'); $options = array(); $options[] = $this->option(array('label' => $translator->translate( 'Enabled' ) , 'value' => 1 )); $options[] = $this->option(array('label' => $translator->translate( 'Disabled' ), 'value' => 0 )); //Add the options to the config object $config->options = $options; return $this->optionlist($config); }
php
public function enabled( $config = array()) { $config = new ObjectConfigJson($config); $config->append(array( 'name' => 'enabled', 'attribs' => array(), 'deselect' => true, ))->append(array( 'selected' => $config->{$config->name} )); $translator = $this->getObject('translator'); $options = array(); $options[] = $this->option(array('label' => $translator->translate( 'Enabled' ) , 'value' => 1 )); $options[] = $this->option(array('label' => $translator->translate( 'Disabled' ), 'value' => 0 )); //Add the options to the config object $config->options = $options; return $this->optionlist($config); }
[ "public", "function", "enabled", "(", "$", "config", "=", "array", "(", ")", ")", "{", "$", "config", "=", "new", "ObjectConfigJson", "(", "$", "config", ")", ";", "$", "config", "->", "append", "(", "array", "(", "'name'", "=>", "'enabled'", ",", "'attribs'", "=>", "array", "(", ")", ",", "'deselect'", "=>", "true", ",", ")", ")", "->", "append", "(", "array", "(", "'selected'", "=>", "$", "config", "->", "{", "$", "config", "->", "name", "}", ")", ")", ";", "$", "translator", "=", "$", "this", "->", "getObject", "(", "'translator'", ")", ";", "$", "options", "=", "array", "(", ")", ";", "$", "options", "[", "]", "=", "$", "this", "->", "option", "(", "array", "(", "'label'", "=>", "$", "translator", "->", "translate", "(", "'Enabled'", ")", ",", "'value'", "=>", "1", ")", ")", ";", "$", "options", "[", "]", "=", "$", "this", "->", "option", "(", "array", "(", "'label'", "=>", "$", "translator", "->", "translate", "(", "'Disabled'", ")", ",", "'value'", "=>", "0", ")", ")", ";", "//Add the options to the config object", "$", "config", "->", "options", "=", "$", "options", ";", "return", "$", "this", "->", "optionlist", "(", "$", "config", ")", ";", "}" ]
Generates an HTML enabled listbox @param array $config An optional array with configuration options @return string Html
[ "Generates", "an", "HTML", "enabled", "listbox" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/template/helper/listbox.php#L144-L165
29,110
timble/kodekit
code/template/helper/listbox.php
TemplateHelperListbox.timezones
public function timezones($config = array()) { $config = new ObjectConfig($config); $config->append(array( 'name' => 'timezone', 'attribs' => array(), 'deselect' => true, 'prompt' => '- '.$this->getObject('translator')->translate('Select Time Zone').' -', )); if ($config->deselect) { $options[] = $this->option(array('label' => $config->prompt, 'value' => '')); } foreach (\DateTimeZone::listIdentifiers() as $identifier) { if (strpos($identifier, '/')) { list($group, $locale) = explode('/', $identifier, 2); $groups[$group][] = str_replace('_', ' ', $locale); } } $options[] = $this->option(array('label' => 'Coordinated Universal Time', 'value' => 'UTC')); foreach ($groups as $group => $locales) { foreach ($locales as $locale) { $options[$group][] = $this->option(array('label' => $locale, 'value' => str_replace(' ', '_', $group.'/'.$locale))); } } $list = $this->optionlist(array( 'options' => $options, 'name' => $config->name, 'selected' => $config->selected, 'attribs' => $config->attribs )); return $list; }
php
public function timezones($config = array()) { $config = new ObjectConfig($config); $config->append(array( 'name' => 'timezone', 'attribs' => array(), 'deselect' => true, 'prompt' => '- '.$this->getObject('translator')->translate('Select Time Zone').' -', )); if ($config->deselect) { $options[] = $this->option(array('label' => $config->prompt, 'value' => '')); } foreach (\DateTimeZone::listIdentifiers() as $identifier) { if (strpos($identifier, '/')) { list($group, $locale) = explode('/', $identifier, 2); $groups[$group][] = str_replace('_', ' ', $locale); } } $options[] = $this->option(array('label' => 'Coordinated Universal Time', 'value' => 'UTC')); foreach ($groups as $group => $locales) { foreach ($locales as $locale) { $options[$group][] = $this->option(array('label' => $locale, 'value' => str_replace(' ', '_', $group.'/'.$locale))); } } $list = $this->optionlist(array( 'options' => $options, 'name' => $config->name, 'selected' => $config->selected, 'attribs' => $config->attribs )); return $list; }
[ "public", "function", "timezones", "(", "$", "config", "=", "array", "(", ")", ")", "{", "$", "config", "=", "new", "ObjectConfig", "(", "$", "config", ")", ";", "$", "config", "->", "append", "(", "array", "(", "'name'", "=>", "'timezone'", ",", "'attribs'", "=>", "array", "(", ")", ",", "'deselect'", "=>", "true", ",", "'prompt'", "=>", "'- '", ".", "$", "this", "->", "getObject", "(", "'translator'", ")", "->", "translate", "(", "'Select Time Zone'", ")", ".", "' -'", ",", ")", ")", ";", "if", "(", "$", "config", "->", "deselect", ")", "{", "$", "options", "[", "]", "=", "$", "this", "->", "option", "(", "array", "(", "'label'", "=>", "$", "config", "->", "prompt", ",", "'value'", "=>", "''", ")", ")", ";", "}", "foreach", "(", "\\", "DateTimeZone", "::", "listIdentifiers", "(", ")", "as", "$", "identifier", ")", "{", "if", "(", "strpos", "(", "$", "identifier", ",", "'/'", ")", ")", "{", "list", "(", "$", "group", ",", "$", "locale", ")", "=", "explode", "(", "'/'", ",", "$", "identifier", ",", "2", ")", ";", "$", "groups", "[", "$", "group", "]", "[", "]", "=", "str_replace", "(", "'_'", ",", "' '", ",", "$", "locale", ")", ";", "}", "}", "$", "options", "[", "]", "=", "$", "this", "->", "option", "(", "array", "(", "'label'", "=>", "'Coordinated Universal Time'", ",", "'value'", "=>", "'UTC'", ")", ")", ";", "foreach", "(", "$", "groups", "as", "$", "group", "=>", "$", "locales", ")", "{", "foreach", "(", "$", "locales", "as", "$", "locale", ")", "{", "$", "options", "[", "$", "group", "]", "[", "]", "=", "$", "this", "->", "option", "(", "array", "(", "'label'", "=>", "$", "locale", ",", "'value'", "=>", "str_replace", "(", "' '", ",", "'_'", ",", "$", "group", ".", "'/'", ".", "$", "locale", ")", ")", ")", ";", "}", "}", "$", "list", "=", "$", "this", "->", "optionlist", "(", "array", "(", "'options'", "=>", "$", "options", ",", "'name'", "=>", "$", "config", "->", "name", ",", "'selected'", "=>", "$", "config", "->", "selected", ",", "'attribs'", "=>", "$", "config", "->", "attribs", ")", ")", ";", "return", "$", "list", ";", "}" ]
Generates an HTML timezones listbox @param array $config An optional array with configuration options @return string Html
[ "Generates", "an", "HTML", "timezones", "listbox" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/template/helper/listbox.php#L202-L241
29,111
rosasurfer/ministruts
src/loader/ClassLoader.php
ClassLoader.register
public function register() { if (!$this->registered) { spl_autoload_register([$this, 'autoLoad'], $throw=true, $prepend=false); $this->registered = true; } return $this; }
php
public function register() { if (!$this->registered) { spl_autoload_register([$this, 'autoLoad'], $throw=true, $prepend=false); $this->registered = true; } return $this; }
[ "public", "function", "register", "(", ")", "{", "if", "(", "!", "$", "this", "->", "registered", ")", "{", "spl_autoload_register", "(", "[", "$", "this", ",", "'autoLoad'", "]", ",", "$", "throw", "=", "true", ",", "$", "prepend", "=", "false", ")", ";", "$", "this", "->", "registered", "=", "true", ";", "}", "return", "$", "this", ";", "}" ]
Register this instance. @return $this
[ "Register", "this", "instance", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/loader/ClassLoader.php#L37-L43
29,112
rosasurfer/ministruts
src/loader/ClassLoader.php
ClassLoader.autoLoad
public function autoLoad($class) { $lowerClass = strtolower($class); if (isset($this->classMap[$lowerClass])) { include($this->classMap[$lowerClass]); } }
php
public function autoLoad($class) { $lowerClass = strtolower($class); if (isset($this->classMap[$lowerClass])) { include($this->classMap[$lowerClass]); } }
[ "public", "function", "autoLoad", "(", "$", "class", ")", "{", "$", "lowerClass", "=", "strtolower", "(", "$", "class", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "classMap", "[", "$", "lowerClass", "]", ")", ")", "{", "include", "(", "$", "this", "->", "classMap", "[", "$", "lowerClass", "]", ")", ";", "}", "}" ]
Load the specified class. @param string $class
[ "Load", "the", "specified", "class", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/loader/ClassLoader.php#L65-L71
29,113
locomotivemtl/charcoal-core
src/Charcoal/Source/AbstractExpression.php
AbstractExpression.quoteValue
public static function quoteValue($value) { $value = static::parseValue($value); if (!is_scalar($value)) { return $value; } if (is_bool($value)) { return (int)$value; } if (!is_numeric($value)) { $value = htmlspecialchars($value, ENT_QUOTES); $value = sprintf('"%s"', $value); } return $value; }
php
public static function quoteValue($value) { $value = static::parseValue($value); if (!is_scalar($value)) { return $value; } if (is_bool($value)) { return (int)$value; } if (!is_numeric($value)) { $value = htmlspecialchars($value, ENT_QUOTES); $value = sprintf('"%s"', $value); } return $value; }
[ "public", "static", "function", "quoteValue", "(", "$", "value", ")", "{", "$", "value", "=", "static", "::", "parseValue", "(", "$", "value", ")", ";", "if", "(", "!", "is_scalar", "(", "$", "value", ")", ")", "{", "return", "$", "value", ";", "}", "if", "(", "is_bool", "(", "$", "value", ")", ")", "{", "return", "(", "int", ")", "$", "value", ";", "}", "if", "(", "!", "is_numeric", "(", "$", "value", ")", ")", "{", "$", "value", "=", "htmlspecialchars", "(", "$", "value", ",", "ENT_QUOTES", ")", ";", "$", "value", "=", "sprintf", "(", "'\"%s\"'", ",", "$", "value", ")", ";", "}", "return", "$", "value", ";", "}" ]
Quote the given scalar value. @param mixed $value The value to be quoted. @return mixed Returns: - If $value is not a scalar value, the value is returned intact. - if $value is a boolean, the value is cast to an integer. - If $value is not a number, the value is stringified and wrapped in double quotes.
[ "Quote", "the", "given", "scalar", "value", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/AbstractExpression.php#L151-L169
29,114
locomotivemtl/charcoal-core
src/Charcoal/Source/AbstractExpression.php
AbstractExpression.quoteIdentifier
public static function quoteIdentifier($identifier, $tableName = null) { if ($identifier === null || $identifier === '') { return ''; } if (!is_string($identifier)) { throw new InvalidArgumentException(sprintf( 'Field Name must be a string, received %s', is_object($identifier) ? get_class($identifier) : gettype($identifier) )); } if ($tableName !== null) { if (!is_string($tableName)) { throw new InvalidArgumentException(sprintf( 'Table Name must be a string, received %s', is_object($tableName) ? get_class($tableName) : gettype($tableName) )); } if ($tableName === '') { throw new InvalidArgumentException( 'Table Name can not be empty.' ); } if ($identifier === '*') { $template = '%1$s.*'; } else { $template = '%1$s.`%2$s`'; } return sprintf($template, $tableName, $identifier); } if ($identifier === '*') { return $identifier; } else { return sprintf('`%1$s`', $identifier); } }
php
public static function quoteIdentifier($identifier, $tableName = null) { if ($identifier === null || $identifier === '') { return ''; } if (!is_string($identifier)) { throw new InvalidArgumentException(sprintf( 'Field Name must be a string, received %s', is_object($identifier) ? get_class($identifier) : gettype($identifier) )); } if ($tableName !== null) { if (!is_string($tableName)) { throw new InvalidArgumentException(sprintf( 'Table Name must be a string, received %s', is_object($tableName) ? get_class($tableName) : gettype($tableName) )); } if ($tableName === '') { throw new InvalidArgumentException( 'Table Name can not be empty.' ); } if ($identifier === '*') { $template = '%1$s.*'; } else { $template = '%1$s.`%2$s`'; } return sprintf($template, $tableName, $identifier); } if ($identifier === '*') { return $identifier; } else { return sprintf('`%1$s`', $identifier); } }
[ "public", "static", "function", "quoteIdentifier", "(", "$", "identifier", ",", "$", "tableName", "=", "null", ")", "{", "if", "(", "$", "identifier", "===", "null", "||", "$", "identifier", "===", "''", ")", "{", "return", "''", ";", "}", "if", "(", "!", "is_string", "(", "$", "identifier", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Field Name must be a string, received %s'", ",", "is_object", "(", "$", "identifier", ")", "?", "get_class", "(", "$", "identifier", ")", ":", "gettype", "(", "$", "identifier", ")", ")", ")", ";", "}", "if", "(", "$", "tableName", "!==", "null", ")", "{", "if", "(", "!", "is_string", "(", "$", "tableName", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Table Name must be a string, received %s'", ",", "is_object", "(", "$", "tableName", ")", "?", "get_class", "(", "$", "tableName", ")", ":", "gettype", "(", "$", "tableName", ")", ")", ")", ";", "}", "if", "(", "$", "tableName", "===", "''", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Table Name can not be empty.'", ")", ";", "}", "if", "(", "$", "identifier", "===", "'*'", ")", "{", "$", "template", "=", "'%1$s.*'", ";", "}", "else", "{", "$", "template", "=", "'%1$s.`%2$s`'", ";", "}", "return", "sprintf", "(", "$", "template", ",", "$", "tableName", ",", "$", "identifier", ")", ";", "}", "if", "(", "$", "identifier", "===", "'*'", ")", "{", "return", "$", "identifier", ";", "}", "else", "{", "return", "sprintf", "(", "'`%1$s`'", ",", "$", "identifier", ")", ";", "}", "}" ]
Quote the given field name. @param string $identifier The field name. @param string|null $tableName If provided, the table name is prepended to the $identifier. @throws InvalidArgumentException If the parameters are not string. @return string
[ "Quote", "the", "given", "field", "name", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/AbstractExpression.php#L179-L220
29,115
sroze/ChainOfResponsibility
ChainBuilder.php
ChainBuilder.getOrderedProcesses
public function getOrderedProcesses() { $graph = new DependencyGraph(); $root = new DependencyGraphNode(self::ROOT_NODE_NAME); $graph->addRoot($root); $processes = $this->getProcesses(); $nodes = []; foreach ($processes as $process) { $processName = $this->getProcessName($process); $node = new DependencyGraphNode($processName); $graph->addDependency($root, $node); $nodes[$processName] = [$process, $node]; } foreach ($nodes as $processName => $nodeDescription) { list($process, $node) = $nodeDescription; if (!$process instanceof DependentChainProcessInterface) { $graph->addDependency($root, $node); continue; } foreach ($process->dependsOn() as $dependencyName) { if (!array_key_exists($dependencyName, $nodes)) { throw new UnresolvedDependencyException(sprintf( 'Process "%s" is dependent of "%s" which is not found', $processName, $dependencyName )); } if ($graph->addDependency($node, $nodes[$dependencyName][1]) instanceof Left) { throw new CircularDependencyException(sprintf( 'Circular dependency found: %s already depends on %s', $dependencyName, $processName )); } } } return array_map(function ($nodeName) use ($nodes) { return $nodes[$nodeName][0]; }, array_filter($graph->flatten(), function ($nodeName) { return $nodeName !== self::ROOT_NODE_NAME; })); }
php
public function getOrderedProcesses() { $graph = new DependencyGraph(); $root = new DependencyGraphNode(self::ROOT_NODE_NAME); $graph->addRoot($root); $processes = $this->getProcesses(); $nodes = []; foreach ($processes as $process) { $processName = $this->getProcessName($process); $node = new DependencyGraphNode($processName); $graph->addDependency($root, $node); $nodes[$processName] = [$process, $node]; } foreach ($nodes as $processName => $nodeDescription) { list($process, $node) = $nodeDescription; if (!$process instanceof DependentChainProcessInterface) { $graph->addDependency($root, $node); continue; } foreach ($process->dependsOn() as $dependencyName) { if (!array_key_exists($dependencyName, $nodes)) { throw new UnresolvedDependencyException(sprintf( 'Process "%s" is dependent of "%s" which is not found', $processName, $dependencyName )); } if ($graph->addDependency($node, $nodes[$dependencyName][1]) instanceof Left) { throw new CircularDependencyException(sprintf( 'Circular dependency found: %s already depends on %s', $dependencyName, $processName )); } } } return array_map(function ($nodeName) use ($nodes) { return $nodes[$nodeName][0]; }, array_filter($graph->flatten(), function ($nodeName) { return $nodeName !== self::ROOT_NODE_NAME; })); }
[ "public", "function", "getOrderedProcesses", "(", ")", "{", "$", "graph", "=", "new", "DependencyGraph", "(", ")", ";", "$", "root", "=", "new", "DependencyGraphNode", "(", "self", "::", "ROOT_NODE_NAME", ")", ";", "$", "graph", "->", "addRoot", "(", "$", "root", ")", ";", "$", "processes", "=", "$", "this", "->", "getProcesses", "(", ")", ";", "$", "nodes", "=", "[", "]", ";", "foreach", "(", "$", "processes", "as", "$", "process", ")", "{", "$", "processName", "=", "$", "this", "->", "getProcessName", "(", "$", "process", ")", ";", "$", "node", "=", "new", "DependencyGraphNode", "(", "$", "processName", ")", ";", "$", "graph", "->", "addDependency", "(", "$", "root", ",", "$", "node", ")", ";", "$", "nodes", "[", "$", "processName", "]", "=", "[", "$", "process", ",", "$", "node", "]", ";", "}", "foreach", "(", "$", "nodes", "as", "$", "processName", "=>", "$", "nodeDescription", ")", "{", "list", "(", "$", "process", ",", "$", "node", ")", "=", "$", "nodeDescription", ";", "if", "(", "!", "$", "process", "instanceof", "DependentChainProcessInterface", ")", "{", "$", "graph", "->", "addDependency", "(", "$", "root", ",", "$", "node", ")", ";", "continue", ";", "}", "foreach", "(", "$", "process", "->", "dependsOn", "(", ")", "as", "$", "dependencyName", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "dependencyName", ",", "$", "nodes", ")", ")", "{", "throw", "new", "UnresolvedDependencyException", "(", "sprintf", "(", "'Process \"%s\" is dependent of \"%s\" which is not found'", ",", "$", "processName", ",", "$", "dependencyName", ")", ")", ";", "}", "if", "(", "$", "graph", "->", "addDependency", "(", "$", "node", ",", "$", "nodes", "[", "$", "dependencyName", "]", "[", "1", "]", ")", "instanceof", "Left", ")", "{", "throw", "new", "CircularDependencyException", "(", "sprintf", "(", "'Circular dependency found: %s already depends on %s'", ",", "$", "dependencyName", ",", "$", "processName", ")", ")", ";", "}", "}", "}", "return", "array_map", "(", "function", "(", "$", "nodeName", ")", "use", "(", "$", "nodes", ")", "{", "return", "$", "nodes", "[", "$", "nodeName", "]", "[", "0", "]", ";", "}", ",", "array_filter", "(", "$", "graph", "->", "flatten", "(", ")", ",", "function", "(", "$", "nodeName", ")", "{", "return", "$", "nodeName", "!==", "self", "::", "ROOT_NODE_NAME", ";", "}", ")", ")", ";", "}" ]
Get processes ordered based on their dependencies. @return array @throws CircularDependencyException @throws UnresolvedDependencyException
[ "Get", "processes", "ordered", "based", "on", "their", "dependencies", "." ]
d1c9743a4a7e5e63004be41d89175a05b3ea81b0
https://github.com/sroze/ChainOfResponsibility/blob/d1c9743a4a7e5e63004be41d89175a05b3ea81b0/ChainBuilder.php#L48-L93
29,116
timble/kodekit
code/database/query/insert.php
DatabaseQueryInsert.type
public function type($type) { $type = strtoupper($type); if (!in_array($type, ['INSERT', 'INSERT IGNORE', 'REPLACE'])) { throw new \UnexpectedValueException('Invalid insert type'); } $this->type = $type; return $this; }
php
public function type($type) { $type = strtoupper($type); if (!in_array($type, ['INSERT', 'INSERT IGNORE', 'REPLACE'])) { throw new \UnexpectedValueException('Invalid insert type'); } $this->type = $type; return $this; }
[ "public", "function", "type", "(", "$", "type", ")", "{", "$", "type", "=", "strtoupper", "(", "$", "type", ")", ";", "if", "(", "!", "in_array", "(", "$", "type", ",", "[", "'INSERT'", ",", "'INSERT IGNORE'", ",", "'REPLACE'", "]", ")", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "'Invalid insert type'", ")", ";", "}", "$", "this", "->", "type", "=", "$", "type", ";", "return", "$", "this", ";", "}" ]
Sets insert operation type Possible values are INSERT|REPLACE|INSERT IGNORE @param string $type @return $this
[ "Sets", "insert", "operation", "type" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/database/query/insert.php#L65-L76
29,117
timble/kodekit
code/string/escaper/escaper.php
StringEscaper.escape
public static function escape($string, $context = 'html') { $method = 'escape'.ucfirst($context); if(!method_exists(__CLASS__, $method)) { throw new \InvalidArgumentException(sprintf('Cannot escape to: %s. Unknow context.', $context)); } return static::$method($string); }
php
public static function escape($string, $context = 'html') { $method = 'escape'.ucfirst($context); if(!method_exists(__CLASS__, $method)) { throw new \InvalidArgumentException(sprintf('Cannot escape to: %s. Unknow context.', $context)); } return static::$method($string); }
[ "public", "static", "function", "escape", "(", "$", "string", ",", "$", "context", "=", "'html'", ")", "{", "$", "method", "=", "'escape'", ".", "ucfirst", "(", "$", "context", ")", ";", "if", "(", "!", "method_exists", "(", "__CLASS__", ",", "$", "method", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Cannot escape to: %s. Unknow context.'", ",", "$", "context", ")", ")", ";", "}", "return", "static", "::", "$", "method", "(", "$", "string", ")", ";", "}" ]
Escapde a string for a specific context @param string $string The string to escape @param string $context The context. Default HTML @throws \InvalidArgumentException If the context is not recognised @return string
[ "Escapde", "a", "string", "for", "a", "specific", "context" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/string/escaper/escaper.php#L47-L56
29,118
timble/kodekit
code/string/escaper/escaper.php
StringEscaper.escapeAttr
public static function escapeAttr($string) { if ($string !== '' && !ctype_digit($string)) { $matcher = function($matches) { $chr = $matches[0]; $ord = ord($chr); /** * Replace undefined characters * * Replace characters undefined in HTML with the hex entity for the Unicode * replacement character. */ if (($ord <= 0x1f && $chr != "\t" && $chr != "\n" && $chr != "\r") || ($ord >= 0x7f && $ord <= 0x9f) ) { return '&#xFFFD;'; } /** * Replace name entities * * If the current character to escape has a name entity replace it with while * grabbing the integer value of the character. */ if (strlen($chr) > 1) { $chr = static::convertEncoding($chr, 'UTF-16BE', 'UTF-8'); } $hex = bin2hex($chr); $ord = hexdec($hex); if (isset(static::$_entity_map[$ord])) { return '&' . static::$_entity_map[$ord] . ';'; } /** * Per OWASP recommendation * * Use upper hex entities for any other characters where a named entity does * not exist. */ if ($ord > 255) { return sprintf('&#x%04X;', $ord); } return sprintf('&#x%02X;', $ord); }; $string = preg_replace_callback('/[^a-z0-9,\.\-_]/iSu', $matcher, $string); } return $string; }
php
public static function escapeAttr($string) { if ($string !== '' && !ctype_digit($string)) { $matcher = function($matches) { $chr = $matches[0]; $ord = ord($chr); /** * Replace undefined characters * * Replace characters undefined in HTML with the hex entity for the Unicode * replacement character. */ if (($ord <= 0x1f && $chr != "\t" && $chr != "\n" && $chr != "\r") || ($ord >= 0x7f && $ord <= 0x9f) ) { return '&#xFFFD;'; } /** * Replace name entities * * If the current character to escape has a name entity replace it with while * grabbing the integer value of the character. */ if (strlen($chr) > 1) { $chr = static::convertEncoding($chr, 'UTF-16BE', 'UTF-8'); } $hex = bin2hex($chr); $ord = hexdec($hex); if (isset(static::$_entity_map[$ord])) { return '&' . static::$_entity_map[$ord] . ';'; } /** * Per OWASP recommendation * * Use upper hex entities for any other characters where a named entity does * not exist. */ if ($ord > 255) { return sprintf('&#x%04X;', $ord); } return sprintf('&#x%02X;', $ord); }; $string = preg_replace_callback('/[^a-z0-9,\.\-_]/iSu', $matcher, $string); } return $string; }
[ "public", "static", "function", "escapeAttr", "(", "$", "string", ")", "{", "if", "(", "$", "string", "!==", "''", "&&", "!", "ctype_digit", "(", "$", "string", ")", ")", "{", "$", "matcher", "=", "function", "(", "$", "matches", ")", "{", "$", "chr", "=", "$", "matches", "[", "0", "]", ";", "$", "ord", "=", "ord", "(", "$", "chr", ")", ";", "/**\n * Replace undefined characters\n *\n * Replace characters undefined in HTML with the hex entity for the Unicode\n * replacement character.\n */", "if", "(", "(", "$", "ord", "<=", "0x1f", "&&", "$", "chr", "!=", "\"\\t\"", "&&", "$", "chr", "!=", "\"\\n\"", "&&", "$", "chr", "!=", "\"\\r\"", ")", "||", "(", "$", "ord", ">=", "0x7f", "&&", "$", "ord", "<=", "0x9f", ")", ")", "{", "return", "'&#xFFFD;'", ";", "}", "/**\n * Replace name entities\n *\n * If the current character to escape has a name entity replace it with while\n * grabbing the integer value of the character.\n */", "if", "(", "strlen", "(", "$", "chr", ")", ">", "1", ")", "{", "$", "chr", "=", "static", "::", "convertEncoding", "(", "$", "chr", ",", "'UTF-16BE'", ",", "'UTF-8'", ")", ";", "}", "$", "hex", "=", "bin2hex", "(", "$", "chr", ")", ";", "$", "ord", "=", "hexdec", "(", "$", "hex", ")", ";", "if", "(", "isset", "(", "static", "::", "$", "_entity_map", "[", "$", "ord", "]", ")", ")", "{", "return", "'&'", ".", "static", "::", "$", "_entity_map", "[", "$", "ord", "]", ".", "';'", ";", "}", "/**\n * Per OWASP recommendation\n *\n * Use upper hex entities for any other characters where a named entity does\n * not exist.\n */", "if", "(", "$", "ord", ">", "255", ")", "{", "return", "sprintf", "(", "'&#x%04X;'", ",", "$", "ord", ")", ";", "}", "return", "sprintf", "(", "'&#x%02X;'", ",", "$", "ord", ")", ";", "}", ";", "$", "string", "=", "preg_replace_callback", "(", "'/[^a-z0-9,\\.\\-_]/iSu'", ",", "$", "matcher", ",", "$", "string", ")", ";", "}", "return", "$", "string", ";", "}" ]
Escape Html Attribute This method uses an extended set of characters o escape that are not covered by htmlspecialchars() to cover cases where an attribute might be unquoted or quoted illegally (e.g. backticks are valid quotes for IE). @param string $string @return string
[ "Escape", "Html", "Attribute" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/string/escaper/escaper.php#L81-L135
29,119
timble/kodekit
code/controller/behavior/permissible.php
ControllerBehaviorPermissible.canExecute
public function canExecute($action) { $method = 'can'.ucfirst($action); $methods = $this->getMixer()->getMethods(); if (!isset($methods[$method])) { $actions = $this->getActions(); $actions = array_flip($actions); $result = isset($actions[$action]); } else $result = $this->$method(); return $result; }
php
public function canExecute($action) { $method = 'can'.ucfirst($action); $methods = $this->getMixer()->getMethods(); if (!isset($methods[$method])) { $actions = $this->getActions(); $actions = array_flip($actions); $result = isset($actions[$action]); } else $result = $this->$method(); return $result; }
[ "public", "function", "canExecute", "(", "$", "action", ")", "{", "$", "method", "=", "'can'", ".", "ucfirst", "(", "$", "action", ")", ";", "$", "methods", "=", "$", "this", "->", "getMixer", "(", ")", "->", "getMethods", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "methods", "[", "$", "method", "]", ")", ")", "{", "$", "actions", "=", "$", "this", "->", "getActions", "(", ")", ";", "$", "actions", "=", "array_flip", "(", "$", "actions", ")", ";", "$", "result", "=", "isset", "(", "$", "actions", "[", "$", "action", "]", ")", ";", "}", "else", "$", "result", "=", "$", "this", "->", "$", "method", "(", ")", ";", "return", "$", "result", ";", "}" ]
Check if an action can be executed @param string $action Action name @return boolean True if the action can be executed, otherwise FALSE.
[ "Check", "if", "an", "action", "can", "be", "executed" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/controller/behavior/permissible.php#L122-L137
29,120
timble/kodekit
code/database/behavior/orderable.php
DatabaseBehaviorOrderable.order
public function order($change) { //force to integer settype($change, 'int'); if($change !== 0) { $old = (int) $this->ordering; $new = $this->ordering + $change; $new = $new <= 0 ? 1 : $new; $table = $this->getTable(); $query = $this->getObject('lib:database.query.update') ->table($table->getBase()); //Build the where query $this->_buildQueryWhere($query); if($change < 0) { $query->values('ordering = ordering + 1') ->where('ordering >= :new') ->where('ordering < :old') ->bind(array('new' => $new, 'old' => $old)); } else { $query->values('ordering = ordering - 1') ->where('ordering <= :new') ->where('ordering > :old') ->bind(array('new' => $new, 'old' => $old)); } $table->getDriver()->update($query); $this->ordering = $new; $this->save(); $this->reorder(); } return $this->getMixer(); }
php
public function order($change) { //force to integer settype($change, 'int'); if($change !== 0) { $old = (int) $this->ordering; $new = $this->ordering + $change; $new = $new <= 0 ? 1 : $new; $table = $this->getTable(); $query = $this->getObject('lib:database.query.update') ->table($table->getBase()); //Build the where query $this->_buildQueryWhere($query); if($change < 0) { $query->values('ordering = ordering + 1') ->where('ordering >= :new') ->where('ordering < :old') ->bind(array('new' => $new, 'old' => $old)); } else { $query->values('ordering = ordering - 1') ->where('ordering <= :new') ->where('ordering > :old') ->bind(array('new' => $new, 'old' => $old)); } $table->getDriver()->update($query); $this->ordering = $new; $this->save(); $this->reorder(); } return $this->getMixer(); }
[ "public", "function", "order", "(", "$", "change", ")", "{", "//force to integer", "settype", "(", "$", "change", ",", "'int'", ")", ";", "if", "(", "$", "change", "!==", "0", ")", "{", "$", "old", "=", "(", "int", ")", "$", "this", "->", "ordering", ";", "$", "new", "=", "$", "this", "->", "ordering", "+", "$", "change", ";", "$", "new", "=", "$", "new", "<=", "0", "?", "1", ":", "$", "new", ";", "$", "table", "=", "$", "this", "->", "getTable", "(", ")", ";", "$", "query", "=", "$", "this", "->", "getObject", "(", "'lib:database.query.update'", ")", "->", "table", "(", "$", "table", "->", "getBase", "(", ")", ")", ";", "//Build the where query", "$", "this", "->", "_buildQueryWhere", "(", "$", "query", ")", ";", "if", "(", "$", "change", "<", "0", ")", "{", "$", "query", "->", "values", "(", "'ordering = ordering + 1'", ")", "->", "where", "(", "'ordering >= :new'", ")", "->", "where", "(", "'ordering < :old'", ")", "->", "bind", "(", "array", "(", "'new'", "=>", "$", "new", ",", "'old'", "=>", "$", "old", ")", ")", ";", "}", "else", "{", "$", "query", "->", "values", "(", "'ordering = ordering - 1'", ")", "->", "where", "(", "'ordering <= :new'", ")", "->", "where", "(", "'ordering > :old'", ")", "->", "bind", "(", "array", "(", "'new'", "=>", "$", "new", ",", "'old'", "=>", "$", "old", ")", ")", ";", "}", "$", "table", "->", "getDriver", "(", ")", "->", "update", "(", "$", "query", ")", ";", "$", "this", "->", "ordering", "=", "$", "new", ";", "$", "this", "->", "save", "(", ")", ";", "$", "this", "->", "reorder", "(", ")", ";", "}", "return", "$", "this", "->", "getMixer", "(", ")", ";", "}" ]
Move the row up or down in the ordering Requires an 'ordering' column @param integer $change Amount to move up or down @return DatabaseRowAbstract
[ "Move", "the", "row", "up", "or", "down", "in", "the", "ordering" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/database/behavior/orderable.php#L72-L113
29,121
timble/kodekit
code/database/behavior/orderable.php
DatabaseBehaviorOrderable.reorder
public function reorder($base = 0) { //force to integer settype($base, 'int'); $table = $this->getTable(); $db = $table->getDriver(); $db->execute('SET @order = '.$base); $query = $this->getObject('lib:database.query.update') ->table($table->getBase()) ->values('ordering = (@order := @order + 1)') ->order('ordering', 'ASC'); //Build the where query $this->_buildQueryWhere($query); if ($base) { $query->where('ordering >= :ordering')->bind(array(':ordering' => $base)); } $db->update($query); return $this; }
php
public function reorder($base = 0) { //force to integer settype($base, 'int'); $table = $this->getTable(); $db = $table->getDriver(); $db->execute('SET @order = '.$base); $query = $this->getObject('lib:database.query.update') ->table($table->getBase()) ->values('ordering = (@order := @order + 1)') ->order('ordering', 'ASC'); //Build the where query $this->_buildQueryWhere($query); if ($base) { $query->where('ordering >= :ordering')->bind(array(':ordering' => $base)); } $db->update($query); return $this; }
[ "public", "function", "reorder", "(", "$", "base", "=", "0", ")", "{", "//force to integer", "settype", "(", "$", "base", ",", "'int'", ")", ";", "$", "table", "=", "$", "this", "->", "getTable", "(", ")", ";", "$", "db", "=", "$", "table", "->", "getDriver", "(", ")", ";", "$", "db", "->", "execute", "(", "'SET @order = '", ".", "$", "base", ")", ";", "$", "query", "=", "$", "this", "->", "getObject", "(", "'lib:database.query.update'", ")", "->", "table", "(", "$", "table", "->", "getBase", "(", ")", ")", "->", "values", "(", "'ordering = (@order := @order + 1)'", ")", "->", "order", "(", "'ordering'", ",", "'ASC'", ")", ";", "//Build the where query", "$", "this", "->", "_buildQueryWhere", "(", "$", "query", ")", ";", "if", "(", "$", "base", ")", "{", "$", "query", "->", "where", "(", "'ordering >= :ordering'", ")", "->", "bind", "(", "array", "(", "':ordering'", "=>", "$", "base", ")", ")", ";", "}", "$", "db", "->", "update", "(", "$", "query", ")", ";", "return", "$", "this", ";", "}" ]
Resets the order of all rows Resetting starts at $base to allow creating space in sequence for later record insertion. @param integer $base Order at which to start resetting. @return DatabaseBehaviorOrderable
[ "Resets", "the", "order", "of", "all", "rows" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/database/behavior/orderable.php#L123-L147
29,122
timble/kodekit
code/view/template.php
ViewTemplate.qualifyLayout
public function qualifyLayout($layout, $type = 'com') { $layout = (string) $layout; //Handle partial layout paths if(!parse_url($layout, PHP_URL_SCHEME)) { $package = $this->getIdentifier()->package; $domain = $this->getIdentifier()->domain; $format = $this->getFormat(); $path = $this->getIdentifier()->getPath(); array_shift($path); //remove 'view' $path[] = basename($layout); $path = implode('/', $path); if($domain) { $layout = $type.'://'.$domain .'/' . $package . '/' .$path; } else { $layout = $type.':' . $package . '/' .$path; } $layout = $layout.'.'.$format; } return $layout; }
php
public function qualifyLayout($layout, $type = 'com') { $layout = (string) $layout; //Handle partial layout paths if(!parse_url($layout, PHP_URL_SCHEME)) { $package = $this->getIdentifier()->package; $domain = $this->getIdentifier()->domain; $format = $this->getFormat(); $path = $this->getIdentifier()->getPath(); array_shift($path); //remove 'view' $path[] = basename($layout); $path = implode('/', $path); if($domain) { $layout = $type.'://'.$domain .'/' . $package . '/' .$path; } else { $layout = $type.':' . $package . '/' .$path; } $layout = $layout.'.'.$format; } return $layout; }
[ "public", "function", "qualifyLayout", "(", "$", "layout", ",", "$", "type", "=", "'com'", ")", "{", "$", "layout", "=", "(", "string", ")", "$", "layout", ";", "//Handle partial layout paths", "if", "(", "!", "parse_url", "(", "$", "layout", ",", "PHP_URL_SCHEME", ")", ")", "{", "$", "package", "=", "$", "this", "->", "getIdentifier", "(", ")", "->", "package", ";", "$", "domain", "=", "$", "this", "->", "getIdentifier", "(", ")", "->", "domain", ";", "$", "format", "=", "$", "this", "->", "getFormat", "(", ")", ";", "$", "path", "=", "$", "this", "->", "getIdentifier", "(", ")", "->", "getPath", "(", ")", ";", "array_shift", "(", "$", "path", ")", ";", "//remove 'view'", "$", "path", "[", "]", "=", "basename", "(", "$", "layout", ")", ";", "$", "path", "=", "implode", "(", "'/'", ",", "$", "path", ")", ";", "if", "(", "$", "domain", ")", "{", "$", "layout", "=", "$", "type", ".", "'://'", ".", "$", "domain", ".", "'/'", ".", "$", "package", ".", "'/'", ".", "$", "path", ";", "}", "else", "{", "$", "layout", "=", "$", "type", ".", "':'", ".", "$", "package", ".", "'/'", ".", "$", "path", ";", "}", "$", "layout", "=", "$", "layout", ".", "'.'", ".", "$", "format", ";", "}", "return", "$", "layout", ";", "}" ]
Qualify the layout Convert a relative layout URL into an absolute layout URL @param string $layout The view layout name @param string $type The filesystem locator type @return string The fully qualified template url
[ "Qualify", "the", "layout" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/view/template.php#L225-L252
29,123
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.setTable
public function setTable($table) { if (!is_string($table)) { throw new InvalidArgumentException(sprintf( 'DatabaseSource::setTable() expects a string as table. (%s given). [%s]', gettype($table), get_class($this->model()) )); } /** * For security reason, only alphanumeric characters (+ underscores) * are valid table names; Although SQL can support more, * there's really no reason to. */ if (!preg_match('/[A-Za-z0-9_]/', $table)) { throw new InvalidArgumentException(sprintf( 'Table name "%s" is invalid: must be alphanumeric / underscore.', $table )); } $this->table = $table; return $this; }
php
public function setTable($table) { if (!is_string($table)) { throw new InvalidArgumentException(sprintf( 'DatabaseSource::setTable() expects a string as table. (%s given). [%s]', gettype($table), get_class($this->model()) )); } /** * For security reason, only alphanumeric characters (+ underscores) * are valid table names; Although SQL can support more, * there's really no reason to. */ if (!preg_match('/[A-Za-z0-9_]/', $table)) { throw new InvalidArgumentException(sprintf( 'Table name "%s" is invalid: must be alphanumeric / underscore.', $table )); } $this->table = $table; return $this; }
[ "public", "function", "setTable", "(", "$", "table", ")", "{", "if", "(", "!", "is_string", "(", "$", "table", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'DatabaseSource::setTable() expects a string as table. (%s given). [%s]'", ",", "gettype", "(", "$", "table", ")", ",", "get_class", "(", "$", "this", "->", "model", "(", ")", ")", ")", ")", ";", "}", "/**\n * For security reason, only alphanumeric characters (+ underscores)\n * are valid table names; Although SQL can support more,\n * there's really no reason to.\n */", "if", "(", "!", "preg_match", "(", "'/[A-Za-z0-9_]/'", ",", "$", "table", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Table name \"%s\" is invalid: must be alphanumeric / underscore.'", ",", "$", "table", ")", ")", ";", "}", "$", "this", "->", "table", "=", "$", "table", ";", "return", "$", "this", ";", "}" ]
Set the database's table to use. @param string $table The source table. @throws InvalidArgumentException If argument is not a string or alphanumeric/underscore. @return self
[ "Set", "the", "database", "s", "table", "to", "use", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L86-L110
29,124
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.createTable
public function createTable() { if ($this->tableExists() === true) { return true; } $dbh = $this->db(); $driver = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME); $model = $this->model(); $metadata = $model->metadata(); $table = $this->table(); $fields = $this->getModelFields($model); $columns = []; foreach ($fields as $field) { $columns[] = $field->sql(); } $query = 'CREATE TABLE `'.$table.'` ('."\n"; $query .= implode(',', $columns); $key = $model->key(); if ($key) { $query .= ', PRIMARY KEY (`'.$key.'`) '."\n"; } /** @todo Add indexes for all defined list constraints (yea... tough job...) */ if ($driver === self::MYSQL_DRIVER_NAME) { $engine = 'InnoDB'; $query .= ') ENGINE='.$engine.' DEFAULT CHARSET=utf8 COMMENT="'.addslashes($metadata['name']).'";'; } else { $query .= ');'; } $this->logger->debug($query); $dbh->query($query); return true; }
php
public function createTable() { if ($this->tableExists() === true) { return true; } $dbh = $this->db(); $driver = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME); $model = $this->model(); $metadata = $model->metadata(); $table = $this->table(); $fields = $this->getModelFields($model); $columns = []; foreach ($fields as $field) { $columns[] = $field->sql(); } $query = 'CREATE TABLE `'.$table.'` ('."\n"; $query .= implode(',', $columns); $key = $model->key(); if ($key) { $query .= ', PRIMARY KEY (`'.$key.'`) '."\n"; } /** @todo Add indexes for all defined list constraints (yea... tough job...) */ if ($driver === self::MYSQL_DRIVER_NAME) { $engine = 'InnoDB'; $query .= ') ENGINE='.$engine.' DEFAULT CHARSET=utf8 COMMENT="'.addslashes($metadata['name']).'";'; } else { $query .= ');'; } $this->logger->debug($query); $dbh->query($query); return true; }
[ "public", "function", "createTable", "(", ")", "{", "if", "(", "$", "this", "->", "tableExists", "(", ")", "===", "true", ")", "{", "return", "true", ";", "}", "$", "dbh", "=", "$", "this", "->", "db", "(", ")", ";", "$", "driver", "=", "$", "dbh", "->", "getAttribute", "(", "PDO", "::", "ATTR_DRIVER_NAME", ")", ";", "$", "model", "=", "$", "this", "->", "model", "(", ")", ";", "$", "metadata", "=", "$", "model", "->", "metadata", "(", ")", ";", "$", "table", "=", "$", "this", "->", "table", "(", ")", ";", "$", "fields", "=", "$", "this", "->", "getModelFields", "(", "$", "model", ")", ";", "$", "columns", "=", "[", "]", ";", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "$", "columns", "[", "]", "=", "$", "field", "->", "sql", "(", ")", ";", "}", "$", "query", "=", "'CREATE TABLE `'", ".", "$", "table", ".", "'` ('", ".", "\"\\n\"", ";", "$", "query", ".=", "implode", "(", "','", ",", "$", "columns", ")", ";", "$", "key", "=", "$", "model", "->", "key", "(", ")", ";", "if", "(", "$", "key", ")", "{", "$", "query", ".=", "', PRIMARY KEY (`'", ".", "$", "key", ".", "'`) '", ".", "\"\\n\"", ";", "}", "/** @todo Add indexes for all defined list constraints (yea... tough job...) */", "if", "(", "$", "driver", "===", "self", "::", "MYSQL_DRIVER_NAME", ")", "{", "$", "engine", "=", "'InnoDB'", ";", "$", "query", ".=", "') ENGINE='", ".", "$", "engine", ".", "' DEFAULT CHARSET=utf8 COMMENT=\"'", ".", "addslashes", "(", "$", "metadata", "[", "'name'", "]", ")", ".", "'\";'", ";", "}", "else", "{", "$", "query", ".=", "');'", ";", "}", "$", "this", "->", "logger", "->", "debug", "(", "$", "query", ")", ";", "$", "dbh", "->", "query", "(", "$", "query", ")", ";", "return", "true", ";", "}" ]
Create a table from a model's metadata. @return boolean TRUE if the table was created, otherwise FALSE.
[ "Create", "a", "table", "from", "a", "model", "s", "metadata", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L143-L181
29,125
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.alterTable
public function alterTable() { if ($this->tableExists() === false) { return false; } $dbh = $this->db(); $table = $this->table(); $fields = $this->getModelFields($this->model()); $cols = $this->tableStructure(); foreach ($fields as $field) { $ident = $field->ident(); if (!array_key_exists($ident, $cols)) { // The key does not exist at all. $query = 'ALTER TABLE `'.$table.'` ADD '.$field->sql(); $this->logger->debug($query); $dbh->query($query); } else { // The key exists. Validate. $col = $cols[$ident]; $alter = true; if (strtolower($col['Type']) !== strtolower($field->sqlType())) { $alter = true; } if ((strtolower($col['Null']) === 'no') && !$field->allowNull()) { $alter = true; } if ((strtolower($col['Null']) !== 'no') && $field->allowNull()) { $alter = true; } if ($col['Default'] !== $field->defaultVal()) { $alter = true; } if ($alter === true) { $query = 'ALTER TABLE `'.$table.'` CHANGE `'.$ident.'` '.$field->sql(); $this->logger->debug($query); $dbh->query($query); } } } return true; }
php
public function alterTable() { if ($this->tableExists() === false) { return false; } $dbh = $this->db(); $table = $this->table(); $fields = $this->getModelFields($this->model()); $cols = $this->tableStructure(); foreach ($fields as $field) { $ident = $field->ident(); if (!array_key_exists($ident, $cols)) { // The key does not exist at all. $query = 'ALTER TABLE `'.$table.'` ADD '.$field->sql(); $this->logger->debug($query); $dbh->query($query); } else { // The key exists. Validate. $col = $cols[$ident]; $alter = true; if (strtolower($col['Type']) !== strtolower($field->sqlType())) { $alter = true; } if ((strtolower($col['Null']) === 'no') && !$field->allowNull()) { $alter = true; } if ((strtolower($col['Null']) !== 'no') && $field->allowNull()) { $alter = true; } if ($col['Default'] !== $field->defaultVal()) { $alter = true; } if ($alter === true) { $query = 'ALTER TABLE `'.$table.'` CHANGE `'.$ident.'` '.$field->sql(); $this->logger->debug($query); $dbh->query($query); } } } return true; }
[ "public", "function", "alterTable", "(", ")", "{", "if", "(", "$", "this", "->", "tableExists", "(", ")", "===", "false", ")", "{", "return", "false", ";", "}", "$", "dbh", "=", "$", "this", "->", "db", "(", ")", ";", "$", "table", "=", "$", "this", "->", "table", "(", ")", ";", "$", "fields", "=", "$", "this", "->", "getModelFields", "(", "$", "this", "->", "model", "(", ")", ")", ";", "$", "cols", "=", "$", "this", "->", "tableStructure", "(", ")", ";", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "$", "ident", "=", "$", "field", "->", "ident", "(", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "ident", ",", "$", "cols", ")", ")", "{", "// The key does not exist at all.", "$", "query", "=", "'ALTER TABLE `'", ".", "$", "table", ".", "'` ADD '", ".", "$", "field", "->", "sql", "(", ")", ";", "$", "this", "->", "logger", "->", "debug", "(", "$", "query", ")", ";", "$", "dbh", "->", "query", "(", "$", "query", ")", ";", "}", "else", "{", "// The key exists. Validate.", "$", "col", "=", "$", "cols", "[", "$", "ident", "]", ";", "$", "alter", "=", "true", ";", "if", "(", "strtolower", "(", "$", "col", "[", "'Type'", "]", ")", "!==", "strtolower", "(", "$", "field", "->", "sqlType", "(", ")", ")", ")", "{", "$", "alter", "=", "true", ";", "}", "if", "(", "(", "strtolower", "(", "$", "col", "[", "'Null'", "]", ")", "===", "'no'", ")", "&&", "!", "$", "field", "->", "allowNull", "(", ")", ")", "{", "$", "alter", "=", "true", ";", "}", "if", "(", "(", "strtolower", "(", "$", "col", "[", "'Null'", "]", ")", "!==", "'no'", ")", "&&", "$", "field", "->", "allowNull", "(", ")", ")", "{", "$", "alter", "=", "true", ";", "}", "if", "(", "$", "col", "[", "'Default'", "]", "!==", "$", "field", "->", "defaultVal", "(", ")", ")", "{", "$", "alter", "=", "true", ";", "}", "if", "(", "$", "alter", "===", "true", ")", "{", "$", "query", "=", "'ALTER TABLE `'", ".", "$", "table", ".", "'` CHANGE `'", ".", "$", "ident", ".", "'` '", ".", "$", "field", "->", "sql", "(", ")", ";", "$", "this", "->", "logger", "->", "debug", "(", "$", "query", ")", ";", "$", "dbh", "->", "query", "(", "$", "query", ")", ";", "}", "}", "}", "return", "true", ";", "}" ]
Alter an existing table to match the model's metadata. @return boolean TRUE if the table was altered, otherwise FALSE.
[ "Alter", "an", "existing", "table", "to", "match", "the", "model", "s", "metadata", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L188-L235
29,126
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.tableExists
public function tableExists() { $dbh = $this->db(); $table = $this->table(); $driver = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME); if ($driver === self::SQLITE_DRIVER_NAME) { $query = sprintf('SELECT name FROM sqlite_master WHERE type = "table" AND name = "%s";', $table); } else { $query = sprintf('SHOW TABLES LIKE "%s"', $table); } $this->logger->debug($query); $sth = $dbh->query($query); $exists = $sth->fetchColumn(0); return !!$exists; }
php
public function tableExists() { $dbh = $this->db(); $table = $this->table(); $driver = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME); if ($driver === self::SQLITE_DRIVER_NAME) { $query = sprintf('SELECT name FROM sqlite_master WHERE type = "table" AND name = "%s";', $table); } else { $query = sprintf('SHOW TABLES LIKE "%s"', $table); } $this->logger->debug($query); $sth = $dbh->query($query); $exists = $sth->fetchColumn(0); return !!$exists; }
[ "public", "function", "tableExists", "(", ")", "{", "$", "dbh", "=", "$", "this", "->", "db", "(", ")", ";", "$", "table", "=", "$", "this", "->", "table", "(", ")", ";", "$", "driver", "=", "$", "dbh", "->", "getAttribute", "(", "PDO", "::", "ATTR_DRIVER_NAME", ")", ";", "if", "(", "$", "driver", "===", "self", "::", "SQLITE_DRIVER_NAME", ")", "{", "$", "query", "=", "sprintf", "(", "'SELECT name FROM sqlite_master WHERE type = \"table\" AND name = \"%s\";'", ",", "$", "table", ")", ";", "}", "else", "{", "$", "query", "=", "sprintf", "(", "'SHOW TABLES LIKE \"%s\"'", ",", "$", "table", ")", ";", "}", "$", "this", "->", "logger", "->", "debug", "(", "$", "query", ")", ";", "$", "sth", "=", "$", "dbh", "->", "query", "(", "$", "query", ")", ";", "$", "exists", "=", "$", "sth", "->", "fetchColumn", "(", "0", ")", ";", "return", "!", "!", "$", "exists", ";", "}" ]
Determine if the source table exists. @return boolean TRUE if the table exists, otherwise FALSE.
[ "Determine", "if", "the", "source", "table", "exists", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L242-L258
29,127
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.tableStructure
public function tableStructure() { $dbh = $this->db(); $table = $this->table(); $driver = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME); if ($driver === self::SQLITE_DRIVER_NAME) { $query = sprintf('PRAGMA table_info("%s") ', $table); } else { $query = sprintf('SHOW COLUMNS FROM `%s`', $table); } $this->logger->debug($query); $sth = $dbh->query($query); $cols = $sth->fetchAll((PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC)); if ($driver === self::SQLITE_DRIVER_NAME) { $struct = []; foreach ($cols as $col) { // Normalize SQLite's result (PRAGMA) with mysql's (SHOW COLUMNS) $struct[$col['name']] = [ 'Type' => $col['type'], 'Null' => !!$col['notnull'] ? 'NO' : 'YES', 'Default' => $col['dflt_value'], 'Key' => !!$col['pk'] ? 'PRI' : '', 'Extra' => '' ]; } return $struct; } else { return $cols; } }
php
public function tableStructure() { $dbh = $this->db(); $table = $this->table(); $driver = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME); if ($driver === self::SQLITE_DRIVER_NAME) { $query = sprintf('PRAGMA table_info("%s") ', $table); } else { $query = sprintf('SHOW COLUMNS FROM `%s`', $table); } $this->logger->debug($query); $sth = $dbh->query($query); $cols = $sth->fetchAll((PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC)); if ($driver === self::SQLITE_DRIVER_NAME) { $struct = []; foreach ($cols as $col) { // Normalize SQLite's result (PRAGMA) with mysql's (SHOW COLUMNS) $struct[$col['name']] = [ 'Type' => $col['type'], 'Null' => !!$col['notnull'] ? 'NO' : 'YES', 'Default' => $col['dflt_value'], 'Key' => !!$col['pk'] ? 'PRI' : '', 'Extra' => '' ]; } return $struct; } else { return $cols; } }
[ "public", "function", "tableStructure", "(", ")", "{", "$", "dbh", "=", "$", "this", "->", "db", "(", ")", ";", "$", "table", "=", "$", "this", "->", "table", "(", ")", ";", "$", "driver", "=", "$", "dbh", "->", "getAttribute", "(", "PDO", "::", "ATTR_DRIVER_NAME", ")", ";", "if", "(", "$", "driver", "===", "self", "::", "SQLITE_DRIVER_NAME", ")", "{", "$", "query", "=", "sprintf", "(", "'PRAGMA table_info(\"%s\") '", ",", "$", "table", ")", ";", "}", "else", "{", "$", "query", "=", "sprintf", "(", "'SHOW COLUMNS FROM `%s`'", ",", "$", "table", ")", ";", "}", "$", "this", "->", "logger", "->", "debug", "(", "$", "query", ")", ";", "$", "sth", "=", "$", "dbh", "->", "query", "(", "$", "query", ")", ";", "$", "cols", "=", "$", "sth", "->", "fetchAll", "(", "(", "PDO", "::", "FETCH_GROUP", "|", "PDO", "::", "FETCH_UNIQUE", "|", "PDO", "::", "FETCH_ASSOC", ")", ")", ";", "if", "(", "$", "driver", "===", "self", "::", "SQLITE_DRIVER_NAME", ")", "{", "$", "struct", "=", "[", "]", ";", "foreach", "(", "$", "cols", "as", "$", "col", ")", "{", "// Normalize SQLite's result (PRAGMA) with mysql's (SHOW COLUMNS)", "$", "struct", "[", "$", "col", "[", "'name'", "]", "]", "=", "[", "'Type'", "=>", "$", "col", "[", "'type'", "]", ",", "'Null'", "=>", "!", "!", "$", "col", "[", "'notnull'", "]", "?", "'NO'", ":", "'YES'", ",", "'Default'", "=>", "$", "col", "[", "'dflt_value'", "]", ",", "'Key'", "=>", "!", "!", "$", "col", "[", "'pk'", "]", "?", "'PRI'", ":", "''", ",", "'Extra'", "=>", "''", "]", ";", "}", "return", "$", "struct", ";", "}", "else", "{", "return", "$", "cols", ";", "}", "}" ]
Get the table columns information. @return array An associative array.
[ "Get", "the", "table", "columns", "information", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L265-L296
29,128
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.tableIsEmpty
public function tableIsEmpty() { $table = $this->table(); $query = sprintf('SELECT NULL FROM `%s` LIMIT 1', $table); $this->logger->debug($query); $sth = $this->db()->query($query); return ($sth->rowCount() === 0); }
php
public function tableIsEmpty() { $table = $this->table(); $query = sprintf('SELECT NULL FROM `%s` LIMIT 1', $table); $this->logger->debug($query); $sth = $this->db()->query($query); return ($sth->rowCount() === 0); }
[ "public", "function", "tableIsEmpty", "(", ")", "{", "$", "table", "=", "$", "this", "->", "table", "(", ")", ";", "$", "query", "=", "sprintf", "(", "'SELECT NULL FROM `%s` LIMIT 1'", ",", "$", "table", ")", ";", "$", "this", "->", "logger", "->", "debug", "(", "$", "query", ")", ";", "$", "sth", "=", "$", "this", "->", "db", "(", ")", "->", "query", "(", "$", "query", ")", ";", "return", "(", "$", "sth", "->", "rowCount", "(", ")", "===", "0", ")", ";", "}" ]
Determine if the source table is empty or not. @return boolean TRUE if the table has no data, otherwise FALSE.
[ "Determine", "if", "the", "source", "table", "is", "empty", "or", "not", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L303-L310
29,129
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.getModelFields
private function getModelFields(ModelInterface $model, $properties = null) { if ($properties === null) { // No custom properties; use all (from model metadata) $properties = array_keys($model->metadata()->properties()); } else { // Ensure the key is always in the required fields. $properties = array_unique(array_merge([ $model->key() ], $properties)); } $fields = []; foreach ($properties as $propertyIdent) { $prop = $model->property($propertyIdent); if (!$prop || !$prop->active() || !$prop->storable()) { continue; } $val = $model->propertyValue($propertyIdent); foreach ($prop->fields($val) as $fieldIdent => $field) { $fields[$field->ident()] = $field; } } return $fields; }
php
private function getModelFields(ModelInterface $model, $properties = null) { if ($properties === null) { // No custom properties; use all (from model metadata) $properties = array_keys($model->metadata()->properties()); } else { // Ensure the key is always in the required fields. $properties = array_unique(array_merge([ $model->key() ], $properties)); } $fields = []; foreach ($properties as $propertyIdent) { $prop = $model->property($propertyIdent); if (!$prop || !$prop->active() || !$prop->storable()) { continue; } $val = $model->propertyValue($propertyIdent); foreach ($prop->fields($val) as $fieldIdent => $field) { $fields[$field->ident()] = $field; } } return $fields; }
[ "private", "function", "getModelFields", "(", "ModelInterface", "$", "model", ",", "$", "properties", "=", "null", ")", "{", "if", "(", "$", "properties", "===", "null", ")", "{", "// No custom properties; use all (from model metadata)", "$", "properties", "=", "array_keys", "(", "$", "model", "->", "metadata", "(", ")", "->", "properties", "(", ")", ")", ";", "}", "else", "{", "// Ensure the key is always in the required fields.", "$", "properties", "=", "array_unique", "(", "array_merge", "(", "[", "$", "model", "->", "key", "(", ")", "]", ",", "$", "properties", ")", ")", ";", "}", "$", "fields", "=", "[", "]", ";", "foreach", "(", "$", "properties", "as", "$", "propertyIdent", ")", "{", "$", "prop", "=", "$", "model", "->", "property", "(", "$", "propertyIdent", ")", ";", "if", "(", "!", "$", "prop", "||", "!", "$", "prop", "->", "active", "(", ")", "||", "!", "$", "prop", "->", "storable", "(", ")", ")", "{", "continue", ";", "}", "$", "val", "=", "$", "model", "->", "propertyValue", "(", "$", "propertyIdent", ")", ";", "foreach", "(", "$", "prop", "->", "fields", "(", "$", "val", ")", "as", "$", "fieldIdent", "=>", "$", "field", ")", "{", "$", "fields", "[", "$", "field", "->", "ident", "(", ")", "]", "=", "$", "field", ";", "}", "}", "return", "$", "fields", ";", "}" ]
Retrieve all fields from a model. @todo Move this method in StorableTrait or AbstractModel @param ModelInterface $model The model to get fields from. @param array|null $properties Optional list of properties to get. If NULL, retrieve all (from metadata). @return PropertyField[]
[ "Retrieve", "all", "fields", "from", "a", "model", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L321-L345
29,130
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.loadItem
public function loadItem($ident, StorableInterface $item = null) { $key = $this->model()->key(); return $this->loadItemFromKey($key, $ident, $item); }
php
public function loadItem($ident, StorableInterface $item = null) { $key = $this->model()->key(); return $this->loadItemFromKey($key, $ident, $item); }
[ "public", "function", "loadItem", "(", "$", "ident", ",", "StorableInterface", "$", "item", "=", "null", ")", "{", "$", "key", "=", "$", "this", "->", "model", "(", ")", "->", "key", "(", ")", ";", "return", "$", "this", "->", "loadItemFromKey", "(", "$", "key", ",", "$", "ident", ",", "$", "item", ")", ";", "}" ]
Load item by the primary column. @param mixed $ident Ident can be any scalar value. @param StorableInterface $item Optional item to load into. @return StorableInterface
[ "Load", "item", "by", "the", "primary", "column", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L354-L359
29,131
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.loadItemFromKey
public function loadItemFromKey($key, $ident, StorableInterface $item = null) { if ($item !== null) { $this->setModel($item); } else { $class = get_class($this->model()); $item = new $class; } $key = preg_replace('/[^\w-]+/', '', $key); // Missing parameters if (!$key || !$ident) { return $item; } $table = $this->table(); $query = sprintf(' SELECT * FROM `%s` WHERE `%s` = :ident LIMIT 1', $table, $key); $binds = [ 'ident' => $ident ]; return $this->loadItemFromQuery($query, $binds, $item); }
php
public function loadItemFromKey($key, $ident, StorableInterface $item = null) { if ($item !== null) { $this->setModel($item); } else { $class = get_class($this->model()); $item = new $class; } $key = preg_replace('/[^\w-]+/', '', $key); // Missing parameters if (!$key || !$ident) { return $item; } $table = $this->table(); $query = sprintf(' SELECT * FROM `%s` WHERE `%s` = :ident LIMIT 1', $table, $key); $binds = [ 'ident' => $ident ]; return $this->loadItemFromQuery($query, $binds, $item); }
[ "public", "function", "loadItemFromKey", "(", "$", "key", ",", "$", "ident", ",", "StorableInterface", "$", "item", "=", "null", ")", "{", "if", "(", "$", "item", "!==", "null", ")", "{", "$", "this", "->", "setModel", "(", "$", "item", ")", ";", "}", "else", "{", "$", "class", "=", "get_class", "(", "$", "this", "->", "model", "(", ")", ")", ";", "$", "item", "=", "new", "$", "class", ";", "}", "$", "key", "=", "preg_replace", "(", "'/[^\\w-]+/'", ",", "''", ",", "$", "key", ")", ";", "// Missing parameters", "if", "(", "!", "$", "key", "||", "!", "$", "ident", ")", "{", "return", "$", "item", ";", "}", "$", "table", "=", "$", "this", "->", "table", "(", ")", ";", "$", "query", "=", "sprintf", "(", "'\n SELECT\n *\n FROM\n `%s`\n WHERE\n `%s` = :ident\n LIMIT\n 1'", ",", "$", "table", ",", "$", "key", ")", ";", "$", "binds", "=", "[", "'ident'", "=>", "$", "ident", "]", ";", "return", "$", "this", "->", "loadItemFromQuery", "(", "$", "query", ",", "$", "binds", ",", "$", "item", ")", ";", "}" ]
Load item by the given column. @param string $key Column name. @param mixed $ident Value of said column. @param StorableInterface|null $item Optional. Item (storable object) to load into. @throws \Exception If the query fails. @return StorableInterface
[ "Load", "item", "by", "the", "given", "column", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L370-L401
29,132
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.loadItemFromQuery
public function loadItemFromQuery($query, array $binds = [], StorableInterface $item = null) { if ($item !== null) { $this->setModel($item); } else { $class = get_class($this->model()); $item = new $class; } // Missing parameters if (!$query) { return $item; } $sth = $this->dbQuery($query, $binds); if ($sth === false) { throw new PDOException('Could not load item.'); } $data = $sth->fetch(PDO::FETCH_ASSOC); if ($data) { $item->setFlatData($data); } return $item; }
php
public function loadItemFromQuery($query, array $binds = [], StorableInterface $item = null) { if ($item !== null) { $this->setModel($item); } else { $class = get_class($this->model()); $item = new $class; } // Missing parameters if (!$query) { return $item; } $sth = $this->dbQuery($query, $binds); if ($sth === false) { throw new PDOException('Could not load item.'); } $data = $sth->fetch(PDO::FETCH_ASSOC); if ($data) { $item->setFlatData($data); } return $item; }
[ "public", "function", "loadItemFromQuery", "(", "$", "query", ",", "array", "$", "binds", "=", "[", "]", ",", "StorableInterface", "$", "item", "=", "null", ")", "{", "if", "(", "$", "item", "!==", "null", ")", "{", "$", "this", "->", "setModel", "(", "$", "item", ")", ";", "}", "else", "{", "$", "class", "=", "get_class", "(", "$", "this", "->", "model", "(", ")", ")", ";", "$", "item", "=", "new", "$", "class", ";", "}", "// Missing parameters", "if", "(", "!", "$", "query", ")", "{", "return", "$", "item", ";", "}", "$", "sth", "=", "$", "this", "->", "dbQuery", "(", "$", "query", ",", "$", "binds", ")", ";", "if", "(", "$", "sth", "===", "false", ")", "{", "throw", "new", "PDOException", "(", "'Could not load item.'", ")", ";", "}", "$", "data", "=", "$", "sth", "->", "fetch", "(", "PDO", "::", "FETCH_ASSOC", ")", ";", "if", "(", "$", "data", ")", "{", "$", "item", "->", "setFlatData", "(", "$", "data", ")", ";", "}", "return", "$", "item", ";", "}" ]
Load item by the given query statement. @param string $query The SQL SELECT statement. @param array $binds Optional. The query parameters. @param StorableInterface $item Optional. Item (storable object) to load into. @throws PDOException If there is a query error. @return StorableInterface
[ "Load", "item", "by", "the", "given", "query", "statement", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L412-L437
29,133
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.loadItems
public function loadItems(StorableInterface $item = null) { if ($item !== null) { $this->setModel($item); } $query = $this->sqlLoad(); return $this->loadItemsFromQuery($query, [], $item); }
php
public function loadItems(StorableInterface $item = null) { if ($item !== null) { $this->setModel($item); } $query = $this->sqlLoad(); return $this->loadItemsFromQuery($query, [], $item); }
[ "public", "function", "loadItems", "(", "StorableInterface", "$", "item", "=", "null", ")", "{", "if", "(", "$", "item", "!==", "null", ")", "{", "$", "this", "->", "setModel", "(", "$", "item", ")", ";", "}", "$", "query", "=", "$", "this", "->", "sqlLoad", "(", ")", ";", "return", "$", "this", "->", "loadItemsFromQuery", "(", "$", "query", ",", "[", "]", ",", "$", "item", ")", ";", "}" ]
Load items for the given model. @param StorableInterface|null $item Optional model. @return StorableInterface[]
[ "Load", "items", "for", "the", "given", "model", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L445-L453
29,134
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.loadItemsFromQuery
public function loadItemsFromQuery($query, array $binds = [], StorableInterface $item = null) { if ($item !== null) { $this->setModel($item); } $items = []; $model = $this->model(); $dbh = $this->db(); $this->logger->debug($query); $sth = $dbh->prepare($query); // @todo Binds if (!empty($binds)) { unset($binds); } $sth->execute(); $sth->setFetchMode(PDO::FETCH_ASSOC); $className = get_class($model); while ($objData = $sth->fetch()) { $obj = new $className; $obj->setFlatData($objData); $items[] = $obj; } return $items; }
php
public function loadItemsFromQuery($query, array $binds = [], StorableInterface $item = null) { if ($item !== null) { $this->setModel($item); } $items = []; $model = $this->model(); $dbh = $this->db(); $this->logger->debug($query); $sth = $dbh->prepare($query); // @todo Binds if (!empty($binds)) { unset($binds); } $sth->execute(); $sth->setFetchMode(PDO::FETCH_ASSOC); $className = get_class($model); while ($objData = $sth->fetch()) { $obj = new $className; $obj->setFlatData($objData); $items[] = $obj; } return $items; }
[ "public", "function", "loadItemsFromQuery", "(", "$", "query", ",", "array", "$", "binds", "=", "[", "]", ",", "StorableInterface", "$", "item", "=", "null", ")", "{", "if", "(", "$", "item", "!==", "null", ")", "{", "$", "this", "->", "setModel", "(", "$", "item", ")", ";", "}", "$", "items", "=", "[", "]", ";", "$", "model", "=", "$", "this", "->", "model", "(", ")", ";", "$", "dbh", "=", "$", "this", "->", "db", "(", ")", ";", "$", "this", "->", "logger", "->", "debug", "(", "$", "query", ")", ";", "$", "sth", "=", "$", "dbh", "->", "prepare", "(", "$", "query", ")", ";", "// @todo Binds", "if", "(", "!", "empty", "(", "$", "binds", ")", ")", "{", "unset", "(", "$", "binds", ")", ";", "}", "$", "sth", "->", "execute", "(", ")", ";", "$", "sth", "->", "setFetchMode", "(", "PDO", "::", "FETCH_ASSOC", ")", ";", "$", "className", "=", "get_class", "(", "$", "model", ")", ";", "while", "(", "$", "objData", "=", "$", "sth", "->", "fetch", "(", ")", ")", "{", "$", "obj", "=", "new", "$", "className", ";", "$", "obj", "->", "setFlatData", "(", "$", "objData", ")", ";", "$", "items", "[", "]", "=", "$", "obj", ";", "}", "return", "$", "items", ";", "}" ]
Load items for the given query statement. @param string $query The SQL SELECT statement. @param array $binds This has to be done. @param StorableInterface|null $item Model Item. @return StorableInterface[]
[ "Load", "items", "for", "the", "given", "query", "statement", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L463-L493
29,135
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.updateItem
public function updateItem(StorableInterface $item, array $properties = null) { if ($item !== null) { $this->setModel($item); } $model = $this->model(); $table = $this->table(); $struct = array_keys($this->tableStructure()); $fields = $this->getModelFields($model, $properties); $updates = []; $binds = []; $types = []; foreach ($fields as $field) { $key = $field->ident(); if (in_array($key, $struct)) { if ($key !== $model->key()) { $param = ':'.$key; $updates[] = '`'.$key.'` = '.$param; } $binds[$key] = $field->val(); $types[$key] = $field->sqlPdoType(); } else { $this->logger->debug( sprintf('Field "%s" not in table structure', $key) ); } } if (empty($updates)) { $this->logger->warning( 'Could not update items. No valid fields were set / available in database table.', [ 'properties' => $properties, 'structure' => $struct ] ); return false; } $binds[$model->key()] = $model->id(); $types[$model->key()] = PDO::PARAM_STR; $query = ' UPDATE `'.$table.'` SET '.implode(", \n\t", $updates).' WHERE `'.$model->key().'`=:'.$model->key().''; $driver = $this->db()->getAttribute(PDO::ATTR_DRIVER_NAME); if ($driver == self::MYSQL_DRIVER_NAME) { $query .= "\n".'LIMIT 1'; } $result = $this->dbQuery($query, $binds, $types); if ($result === false) { return false; } else { return true; } }
php
public function updateItem(StorableInterface $item, array $properties = null) { if ($item !== null) { $this->setModel($item); } $model = $this->model(); $table = $this->table(); $struct = array_keys($this->tableStructure()); $fields = $this->getModelFields($model, $properties); $updates = []; $binds = []; $types = []; foreach ($fields as $field) { $key = $field->ident(); if (in_array($key, $struct)) { if ($key !== $model->key()) { $param = ':'.$key; $updates[] = '`'.$key.'` = '.$param; } $binds[$key] = $field->val(); $types[$key] = $field->sqlPdoType(); } else { $this->logger->debug( sprintf('Field "%s" not in table structure', $key) ); } } if (empty($updates)) { $this->logger->warning( 'Could not update items. No valid fields were set / available in database table.', [ 'properties' => $properties, 'structure' => $struct ] ); return false; } $binds[$model->key()] = $model->id(); $types[$model->key()] = PDO::PARAM_STR; $query = ' UPDATE `'.$table.'` SET '.implode(", \n\t", $updates).' WHERE `'.$model->key().'`=:'.$model->key().''; $driver = $this->db()->getAttribute(PDO::ATTR_DRIVER_NAME); if ($driver == self::MYSQL_DRIVER_NAME) { $query .= "\n".'LIMIT 1'; } $result = $this->dbQuery($query, $binds, $types); if ($result === false) { return false; } else { return true; } }
[ "public", "function", "updateItem", "(", "StorableInterface", "$", "item", ",", "array", "$", "properties", "=", "null", ")", "{", "if", "(", "$", "item", "!==", "null", ")", "{", "$", "this", "->", "setModel", "(", "$", "item", ")", ";", "}", "$", "model", "=", "$", "this", "->", "model", "(", ")", ";", "$", "table", "=", "$", "this", "->", "table", "(", ")", ";", "$", "struct", "=", "array_keys", "(", "$", "this", "->", "tableStructure", "(", ")", ")", ";", "$", "fields", "=", "$", "this", "->", "getModelFields", "(", "$", "model", ",", "$", "properties", ")", ";", "$", "updates", "=", "[", "]", ";", "$", "binds", "=", "[", "]", ";", "$", "types", "=", "[", "]", ";", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "$", "key", "=", "$", "field", "->", "ident", "(", ")", ";", "if", "(", "in_array", "(", "$", "key", ",", "$", "struct", ")", ")", "{", "if", "(", "$", "key", "!==", "$", "model", "->", "key", "(", ")", ")", "{", "$", "param", "=", "':'", ".", "$", "key", ";", "$", "updates", "[", "]", "=", "'`'", ".", "$", "key", ".", "'` = '", ".", "$", "param", ";", "}", "$", "binds", "[", "$", "key", "]", "=", "$", "field", "->", "val", "(", ")", ";", "$", "types", "[", "$", "key", "]", "=", "$", "field", "->", "sqlPdoType", "(", ")", ";", "}", "else", "{", "$", "this", "->", "logger", "->", "debug", "(", "sprintf", "(", "'Field \"%s\" not in table structure'", ",", "$", "key", ")", ")", ";", "}", "}", "if", "(", "empty", "(", "$", "updates", ")", ")", "{", "$", "this", "->", "logger", "->", "warning", "(", "'Could not update items. No valid fields were set / available in database table.'", ",", "[", "'properties'", "=>", "$", "properties", ",", "'structure'", "=>", "$", "struct", "]", ")", ";", "return", "false", ";", "}", "$", "binds", "[", "$", "model", "->", "key", "(", ")", "]", "=", "$", "model", "->", "id", "(", ")", ";", "$", "types", "[", "$", "model", "->", "key", "(", ")", "]", "=", "PDO", "::", "PARAM_STR", ";", "$", "query", "=", "'\n UPDATE\n `'", ".", "$", "table", ".", "'`\n SET\n '", ".", "implode", "(", "\", \\n\\t\"", ",", "$", "updates", ")", ".", "'\n WHERE\n `'", ".", "$", "model", "->", "key", "(", ")", ".", "'`=:'", ".", "$", "model", "->", "key", "(", ")", ".", "''", ";", "$", "driver", "=", "$", "this", "->", "db", "(", ")", "->", "getAttribute", "(", "PDO", "::", "ATTR_DRIVER_NAME", ")", ";", "if", "(", "$", "driver", "==", "self", "::", "MYSQL_DRIVER_NAME", ")", "{", "$", "query", ".=", "\"\\n\"", ".", "'LIMIT 1'", ";", "}", "$", "result", "=", "$", "this", "->", "dbQuery", "(", "$", "query", ",", "$", "binds", ",", "$", "types", ")", ";", "if", "(", "$", "result", "===", "false", ")", "{", "return", "false", ";", "}", "else", "{", "return", "true", ";", "}", "}" ]
Update an item in storage. @param StorableInterface $item The object to update. @param array $properties The list of properties to update, if not all. @return boolean TRUE if the item was updated, otherwise FALSE.
[ "Update", "an", "item", "in", "storage", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L559-L621
29,136
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.deleteItem
public function deleteItem(StorableInterface $item = null) { if ($item !== null) { $this->setModel($item); } $model = $this->model(); if (!$model->id()) { throw new UnexpectedValueException( sprintf('Can not delete "%s" item. No ID.', get_class($this)) ); } $key = $model->key(); $table = $this->table(); $query = ' DELETE FROM `'.$table.'` WHERE `'.$key.'` = :id'; $driver = $this->db()->getAttribute(PDO::ATTR_DRIVER_NAME); if ($driver == self::MYSQL_DRIVER_NAME) { $query .= "\n".'LIMIT 1'; } $binds = [ 'id' => $model->id() ]; $result = $this->dbQuery($query, $binds); if ($result === false) { return false; } else { return true; } }
php
public function deleteItem(StorableInterface $item = null) { if ($item !== null) { $this->setModel($item); } $model = $this->model(); if (!$model->id()) { throw new UnexpectedValueException( sprintf('Can not delete "%s" item. No ID.', get_class($this)) ); } $key = $model->key(); $table = $this->table(); $query = ' DELETE FROM `'.$table.'` WHERE `'.$key.'` = :id'; $driver = $this->db()->getAttribute(PDO::ATTR_DRIVER_NAME); if ($driver == self::MYSQL_DRIVER_NAME) { $query .= "\n".'LIMIT 1'; } $binds = [ 'id' => $model->id() ]; $result = $this->dbQuery($query, $binds); if ($result === false) { return false; } else { return true; } }
[ "public", "function", "deleteItem", "(", "StorableInterface", "$", "item", "=", "null", ")", "{", "if", "(", "$", "item", "!==", "null", ")", "{", "$", "this", "->", "setModel", "(", "$", "item", ")", ";", "}", "$", "model", "=", "$", "this", "->", "model", "(", ")", ";", "if", "(", "!", "$", "model", "->", "id", "(", ")", ")", "{", "throw", "new", "UnexpectedValueException", "(", "sprintf", "(", "'Can not delete \"%s\" item. No ID.'", ",", "get_class", "(", "$", "this", ")", ")", ")", ";", "}", "$", "key", "=", "$", "model", "->", "key", "(", ")", ";", "$", "table", "=", "$", "this", "->", "table", "(", ")", ";", "$", "query", "=", "'\n DELETE FROM\n `'", ".", "$", "table", ".", "'`\n WHERE\n `'", ".", "$", "key", ".", "'` = :id'", ";", "$", "driver", "=", "$", "this", "->", "db", "(", ")", "->", "getAttribute", "(", "PDO", "::", "ATTR_DRIVER_NAME", ")", ";", "if", "(", "$", "driver", "==", "self", "::", "MYSQL_DRIVER_NAME", ")", "{", "$", "query", ".=", "\"\\n\"", ".", "'LIMIT 1'", ";", "}", "$", "binds", "=", "[", "'id'", "=>", "$", "model", "->", "id", "(", ")", "]", ";", "$", "result", "=", "$", "this", "->", "dbQuery", "(", "$", "query", ",", "$", "binds", ")", ";", "if", "(", "$", "result", "===", "false", ")", "{", "return", "false", ";", "}", "else", "{", "return", "true", ";", "}", "}" ]
Delete an item from storage. @param StorableInterface $item Optional item to delete. If none, the current model object will be used. @throws UnexpectedValueException If the item does not have an ID. @return boolean TRUE if the item was deleted, otherwise FALSE.
[ "Delete", "an", "item", "from", "storage", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L630-L668
29,137
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.dbQuery
public function dbQuery($query, array $binds = [], array $types = []) { $this->logger->debug($query, $binds); $sth = $this->db()->prepare($query); if (!$sth) { return false; } if (!empty($binds)) { foreach ($binds as $key => $val) { if ($binds[$key] === null) { $types[$key] = PDO::PARAM_NULL; } elseif (!is_scalar($binds[$key])) { $binds[$key] = json_encode($binds[$key]); } $type = (isset($types[$key]) ? $types[$key] : PDO::PARAM_STR); $param = ':'.$key; $sth->bindParam($param, $binds[$key], $type); } } $result = $sth->execute(); if ($result === false) { return false; } return $sth; }
php
public function dbQuery($query, array $binds = [], array $types = []) { $this->logger->debug($query, $binds); $sth = $this->db()->prepare($query); if (!$sth) { return false; } if (!empty($binds)) { foreach ($binds as $key => $val) { if ($binds[$key] === null) { $types[$key] = PDO::PARAM_NULL; } elseif (!is_scalar($binds[$key])) { $binds[$key] = json_encode($binds[$key]); } $type = (isset($types[$key]) ? $types[$key] : PDO::PARAM_STR); $param = ':'.$key; $sth->bindParam($param, $binds[$key], $type); } } $result = $sth->execute(); if ($result === false) { return false; } return $sth; }
[ "public", "function", "dbQuery", "(", "$", "query", ",", "array", "$", "binds", "=", "[", "]", ",", "array", "$", "types", "=", "[", "]", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "$", "query", ",", "$", "binds", ")", ";", "$", "sth", "=", "$", "this", "->", "db", "(", ")", "->", "prepare", "(", "$", "query", ")", ";", "if", "(", "!", "$", "sth", ")", "{", "return", "false", ";", "}", "if", "(", "!", "empty", "(", "$", "binds", ")", ")", "{", "foreach", "(", "$", "binds", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "$", "binds", "[", "$", "key", "]", "===", "null", ")", "{", "$", "types", "[", "$", "key", "]", "=", "PDO", "::", "PARAM_NULL", ";", "}", "elseif", "(", "!", "is_scalar", "(", "$", "binds", "[", "$", "key", "]", ")", ")", "{", "$", "binds", "[", "$", "key", "]", "=", "json_encode", "(", "$", "binds", "[", "$", "key", "]", ")", ";", "}", "$", "type", "=", "(", "isset", "(", "$", "types", "[", "$", "key", "]", ")", "?", "$", "types", "[", "$", "key", "]", ":", "PDO", "::", "PARAM_STR", ")", ";", "$", "param", "=", "':'", ".", "$", "key", ";", "$", "sth", "->", "bindParam", "(", "$", "param", ",", "$", "binds", "[", "$", "key", "]", ",", "$", "type", ")", ";", "}", "}", "$", "result", "=", "$", "sth", "->", "execute", "(", ")", ";", "if", "(", "$", "result", "===", "false", ")", "{", "return", "false", ";", "}", "return", "$", "sth", ";", "}" ]
Execute a SQL query, with PDO, and returns the PDOStatement. If the query fails, this method will return false. @param string $query The SQL query to executed. @param array $binds Optional. Query parameter binds. @param array $types Optional. Types of parameter bindings. @return \PDOStatement|false The PDOStatement, otherwise FALSE.
[ "Execute", "a", "SQL", "query", "with", "PDO", "and", "returns", "the", "PDOStatement", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L680-L707
29,138
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.sqlLoad
public function sqlLoad() { if (!$this->hasTable()) { throw new UnexpectedValueException( 'Can not get SQL SELECT clause. No table defined.' ); } $selects = $this->sqlSelect(); $tables = $this->sqlFrom(); $filters = $this->sqlFilters(); $orders = $this->sqlOrders(); $limits = $this->sqlPagination(); $query = 'SELECT '.$selects.' FROM '.$tables.$filters.$orders.$limits; return $query; }
php
public function sqlLoad() { if (!$this->hasTable()) { throw new UnexpectedValueException( 'Can not get SQL SELECT clause. No table defined.' ); } $selects = $this->sqlSelect(); $tables = $this->sqlFrom(); $filters = $this->sqlFilters(); $orders = $this->sqlOrders(); $limits = $this->sqlPagination(); $query = 'SELECT '.$selects.' FROM '.$tables.$filters.$orders.$limits; return $query; }
[ "public", "function", "sqlLoad", "(", ")", "{", "if", "(", "!", "$", "this", "->", "hasTable", "(", ")", ")", "{", "throw", "new", "UnexpectedValueException", "(", "'Can not get SQL SELECT clause. No table defined.'", ")", ";", "}", "$", "selects", "=", "$", "this", "->", "sqlSelect", "(", ")", ";", "$", "tables", "=", "$", "this", "->", "sqlFrom", "(", ")", ";", "$", "filters", "=", "$", "this", "->", "sqlFilters", "(", ")", ";", "$", "orders", "=", "$", "this", "->", "sqlOrders", "(", ")", ";", "$", "limits", "=", "$", "this", "->", "sqlPagination", "(", ")", ";", "$", "query", "=", "'SELECT '", ".", "$", "selects", ".", "' FROM '", ".", "$", "tables", ".", "$", "filters", ".", "$", "orders", ".", "$", "limits", ";", "return", "$", "query", ";", "}" ]
Compile the SELECT statement for fetching one or more objects. @throws UnexpectedValueException If the source does not have a table defined. @return string
[ "Compile", "the", "SELECT", "statement", "for", "fetching", "one", "or", "more", "objects", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L715-L731
29,139
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.sqlLoadCount
public function sqlLoadCount() { if (!$this->hasTable()) { throw new UnexpectedValueException( 'Can not get SQL count. No table defined.' ); } $tables = $this->sqlFrom(); $filters = $this->sqlFilters(); $query = 'SELECT COUNT(*) FROM '.$tables.$filters; return $query; }
php
public function sqlLoadCount() { if (!$this->hasTable()) { throw new UnexpectedValueException( 'Can not get SQL count. No table defined.' ); } $tables = $this->sqlFrom(); $filters = $this->sqlFilters(); $query = 'SELECT COUNT(*) FROM '.$tables.$filters; return $query; }
[ "public", "function", "sqlLoadCount", "(", ")", "{", "if", "(", "!", "$", "this", "->", "hasTable", "(", ")", ")", "{", "throw", "new", "UnexpectedValueException", "(", "'Can not get SQL count. No table defined.'", ")", ";", "}", "$", "tables", "=", "$", "this", "->", "sqlFrom", "(", ")", ";", "$", "filters", "=", "$", "this", "->", "sqlFilters", "(", ")", ";", "$", "query", "=", "'SELECT COUNT(*) FROM '", ".", "$", "tables", ".", "$", "filters", ";", "return", "$", "query", ";", "}" ]
Compile the SELECT statement for fetching the number of objects. @throws UnexpectedValueException If the source does not have a table defined. @return string
[ "Compile", "the", "SELECT", "statement", "for", "fetching", "the", "number", "of", "objects", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L739-L752
29,140
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.sqlSelect
public function sqlSelect() { $properties = $this->properties(); if (empty($properties)) { return self::DEFAULT_TABLE_ALIAS.'.*'; } $parts = []; foreach ($properties as $key) { $parts[] = Expression::quoteIdentifier($key, self::DEFAULT_TABLE_ALIAS); } if (empty($parts)) { throw new UnexpectedValueException( 'Can not get SQL SELECT clause. No valid properties.' ); } $clause = implode(', ', $parts); return $clause; }
php
public function sqlSelect() { $properties = $this->properties(); if (empty($properties)) { return self::DEFAULT_TABLE_ALIAS.'.*'; } $parts = []; foreach ($properties as $key) { $parts[] = Expression::quoteIdentifier($key, self::DEFAULT_TABLE_ALIAS); } if (empty($parts)) { throw new UnexpectedValueException( 'Can not get SQL SELECT clause. No valid properties.' ); } $clause = implode(', ', $parts); return $clause; }
[ "public", "function", "sqlSelect", "(", ")", "{", "$", "properties", "=", "$", "this", "->", "properties", "(", ")", ";", "if", "(", "empty", "(", "$", "properties", ")", ")", "{", "return", "self", "::", "DEFAULT_TABLE_ALIAS", ".", "'.*'", ";", "}", "$", "parts", "=", "[", "]", ";", "foreach", "(", "$", "properties", "as", "$", "key", ")", "{", "$", "parts", "[", "]", "=", "Expression", "::", "quoteIdentifier", "(", "$", "key", ",", "self", "::", "DEFAULT_TABLE_ALIAS", ")", ";", "}", "if", "(", "empty", "(", "$", "parts", ")", ")", "{", "throw", "new", "UnexpectedValueException", "(", "'Can not get SQL SELECT clause. No valid properties.'", ")", ";", "}", "$", "clause", "=", "implode", "(", "', '", ",", "$", "parts", ")", ";", "return", "$", "clause", ";", "}" ]
Compile the SELECT clause. @throws UnexpectedValueException If the clause has no selectable fields. @return string
[ "Compile", "the", "SELECT", "clause", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L760-L781
29,141
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.sqlFrom
public function sqlFrom() { if (!$this->hasTable()) { throw new UnexpectedValueException( 'Can not get SQL FROM clause. No table defined.' ); } $table = $this->table(); return '`'.$table.'` AS `'.self::DEFAULT_TABLE_ALIAS.'`'; }
php
public function sqlFrom() { if (!$this->hasTable()) { throw new UnexpectedValueException( 'Can not get SQL FROM clause. No table defined.' ); } $table = $this->table(); return '`'.$table.'` AS `'.self::DEFAULT_TABLE_ALIAS.'`'; }
[ "public", "function", "sqlFrom", "(", ")", "{", "if", "(", "!", "$", "this", "->", "hasTable", "(", ")", ")", "{", "throw", "new", "UnexpectedValueException", "(", "'Can not get SQL FROM clause. No table defined.'", ")", ";", "}", "$", "table", "=", "$", "this", "->", "table", "(", ")", ";", "return", "'`'", ".", "$", "table", ".", "'` AS `'", ".", "self", "::", "DEFAULT_TABLE_ALIAS", ".", "'`'", ";", "}" ]
Compile the FROM clause. @throws UnexpectedValueException If the source does not have a table defined. @return string
[ "Compile", "the", "FROM", "clause", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L789-L799
29,142
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.sqlFilters
public function sqlFilters() { if (!$this->hasFilters()) { return ''; } $criteria = $this->createFilter([ 'filters' => $this->filters() ]); $sql = $criteria->sql(); if (strlen($sql) > 0) { $sql = ' WHERE '.$sql; } return $sql; }
php
public function sqlFilters() { if (!$this->hasFilters()) { return ''; } $criteria = $this->createFilter([ 'filters' => $this->filters() ]); $sql = $criteria->sql(); if (strlen($sql) > 0) { $sql = ' WHERE '.$sql; } return $sql; }
[ "public", "function", "sqlFilters", "(", ")", "{", "if", "(", "!", "$", "this", "->", "hasFilters", "(", ")", ")", "{", "return", "''", ";", "}", "$", "criteria", "=", "$", "this", "->", "createFilter", "(", "[", "'filters'", "=>", "$", "this", "->", "filters", "(", ")", "]", ")", ";", "$", "sql", "=", "$", "criteria", "->", "sql", "(", ")", ";", "if", "(", "strlen", "(", "$", "sql", ")", ">", "0", ")", "{", "$", "sql", "=", "' WHERE '", ".", "$", "sql", ";", "}", "return", "$", "sql", ";", "}" ]
Compile the WHERE clause. @todo [2016-02-19] Use bindings for filters value @return string
[ "Compile", "the", "WHERE", "clause", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L807-L823
29,143
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.sqlOrders
public function sqlOrders() { if (!$this->hasOrders()) { return ''; } $parts = []; foreach ($this->orders() as $order) { if (!$order instanceof DatabaseOrder) { $order = $this->createOrder($order->data()); } $sql = $order->sql(); if (strlen($sql) > 0) { $parts[] = $sql; } } if (empty($parts)) { return ''; } return ' ORDER BY '.implode(', ', $parts); }
php
public function sqlOrders() { if (!$this->hasOrders()) { return ''; } $parts = []; foreach ($this->orders() as $order) { if (!$order instanceof DatabaseOrder) { $order = $this->createOrder($order->data()); } $sql = $order->sql(); if (strlen($sql) > 0) { $parts[] = $sql; } } if (empty($parts)) { return ''; } return ' ORDER BY '.implode(', ', $parts); }
[ "public", "function", "sqlOrders", "(", ")", "{", "if", "(", "!", "$", "this", "->", "hasOrders", "(", ")", ")", "{", "return", "''", ";", "}", "$", "parts", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "orders", "(", ")", "as", "$", "order", ")", "{", "if", "(", "!", "$", "order", "instanceof", "DatabaseOrder", ")", "{", "$", "order", "=", "$", "this", "->", "createOrder", "(", "$", "order", "->", "data", "(", ")", ")", ";", "}", "$", "sql", "=", "$", "order", "->", "sql", "(", ")", ";", "if", "(", "strlen", "(", "$", "sql", ")", ">", "0", ")", "{", "$", "parts", "[", "]", "=", "$", "sql", ";", "}", "}", "if", "(", "empty", "(", "$", "parts", ")", ")", "{", "return", "''", ";", "}", "return", "' ORDER BY '", ".", "implode", "(", "', '", ",", "$", "parts", ")", ";", "}" ]
Compile the ORDER BY clause. @return string
[ "Compile", "the", "ORDER", "BY", "clause", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L830-L853
29,144
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.sqlPagination
public function sqlPagination() { $pager = $this->pagination(); if (!$pager instanceof DatabasePagination) { $pager = $this->createPagination($pager->data()); } $sql = $pager->sql(); if (strlen($sql) > 0) { $sql = ' '.$sql; } return $sql; }
php
public function sqlPagination() { $pager = $this->pagination(); if (!$pager instanceof DatabasePagination) { $pager = $this->createPagination($pager->data()); } $sql = $pager->sql(); if (strlen($sql) > 0) { $sql = ' '.$sql; } return $sql; }
[ "public", "function", "sqlPagination", "(", ")", "{", "$", "pager", "=", "$", "this", "->", "pagination", "(", ")", ";", "if", "(", "!", "$", "pager", "instanceof", "DatabasePagination", ")", "{", "$", "pager", "=", "$", "this", "->", "createPagination", "(", "$", "pager", "->", "data", "(", ")", ")", ";", "}", "$", "sql", "=", "$", "pager", "->", "sql", "(", ")", ";", "if", "(", "strlen", "(", "$", "sql", ")", ">", "0", ")", "{", "$", "sql", "=", "' '", ".", "$", "sql", ";", "}", "return", "$", "sql", ";", "}" ]
Compile the LIMIT clause. @return string
[ "Compile", "the", "LIMIT", "clause", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L860-L873
29,145
locomotivemtl/charcoal-core
src/Charcoal/Source/DatabaseSource.php
DatabaseSource.createOrder
protected function createOrder(array $data = null) { $order = new DatabaseOrder(); if ($data !== null) { $order->setData($data); } return $order; }
php
protected function createOrder(array $data = null) { $order = new DatabaseOrder(); if ($data !== null) { $order->setData($data); } return $order; }
[ "protected", "function", "createOrder", "(", "array", "$", "data", "=", "null", ")", "{", "$", "order", "=", "new", "DatabaseOrder", "(", ")", ";", "if", "(", "$", "data", "!==", "null", ")", "{", "$", "order", "->", "setData", "(", "$", "data", ")", ";", "}", "return", "$", "order", ";", "}" ]
Create a new order expression. @param array $data Optional expression data. @return DatabaseOrder
[ "Create", "a", "new", "order", "expression", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L896-L903
29,146
timble/kodekit
code/filesystem/mimetype/extension.php
FilesystemMimetypeExtension._getMimetype
protected function _getMimetype($extension) { $mimetypes = $this->_getMimetypes(); return isset($mimetypes[$extension]) ? $mimetypes[$extension] : null; }
php
protected function _getMimetype($extension) { $mimetypes = $this->_getMimetypes(); return isset($mimetypes[$extension]) ? $mimetypes[$extension] : null; }
[ "protected", "function", "_getMimetype", "(", "$", "extension", ")", "{", "$", "mimetypes", "=", "$", "this", "->", "_getMimetypes", "(", ")", ";", "return", "isset", "(", "$", "mimetypes", "[", "$", "extension", "]", ")", "?", "$", "mimetypes", "[", "$", "extension", "]", ":", "null", ";", "}" ]
Return a mimetype for the given extension @param string $extension @return string|null
[ "Return", "a", "mimetype", "for", "the", "given", "extension" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/filesystem/mimetype/extension.php#L98-L103
29,147
timble/kodekit
code/filesystem/mimetype/extension.php
FilesystemMimetypeExtension._getMimetypes
protected function _getMimetypes() { if(!isset($this->_mimetypes)) { $file = $this->getConfig()->file; if (is_readable($file)) { $this->_mimetypes = json_decode(file_get_contents($file), true); } } return $this->_mimetypes; }
php
protected function _getMimetypes() { if(!isset($this->_mimetypes)) { $file = $this->getConfig()->file; if (is_readable($file)) { $this->_mimetypes = json_decode(file_get_contents($file), true); } } return $this->_mimetypes; }
[ "protected", "function", "_getMimetypes", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_mimetypes", ")", ")", "{", "$", "file", "=", "$", "this", "->", "getConfig", "(", ")", "->", "file", ";", "if", "(", "is_readable", "(", "$", "file", ")", ")", "{", "$", "this", "->", "_mimetypes", "=", "json_decode", "(", "file_get_contents", "(", "$", "file", ")", ",", "true", ")", ";", "}", "}", "return", "$", "this", "->", "_mimetypes", ";", "}" ]
Returns mimetypes list @return array
[ "Returns", "mimetypes", "list" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/filesystem/mimetype/extension.php#L110-L122
29,148
timble/kodekit
code/controller/model.php
ControllerModel._actionBrowse
protected function _actionBrowse(ControllerContext $context) { $entity = $this->getModel()->fetch(); //Set the entity in the context $context->setEntity($entity); return $entity; }
php
protected function _actionBrowse(ControllerContext $context) { $entity = $this->getModel()->fetch(); //Set the entity in the context $context->setEntity($entity); return $entity; }
[ "protected", "function", "_actionBrowse", "(", "ControllerContext", "$", "context", ")", "{", "$", "entity", "=", "$", "this", "->", "getModel", "(", ")", "->", "fetch", "(", ")", ";", "//Set the entity in the context", "$", "context", "->", "setEntity", "(", "$", "entity", ")", ";", "return", "$", "entity", ";", "}" ]
Generic browse action, fetches an entity collection @param ControllerContextModel $context A controller context object @return ModelEntityInterface An entity object containing the selected entities
[ "Generic", "browse", "action", "fetches", "an", "entity", "collection" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/controller/model.php#L216-L224
29,149
timble/kodekit
code/controller/model.php
ControllerModel._fetchEntity
protected function _fetchEntity(ControllerContext $context) { if(!$context->result instanceof ModelEntityInterface) { switch($context->action) { case 'add' : $context->setEntity($this->getModel()->create($context->request->data->toArray())); break; case 'edit' : case 'delete': $context->setEntity($this->getModel()->fetch()); break; } } else $context->setEntity($context->result); }
php
protected function _fetchEntity(ControllerContext $context) { if(!$context->result instanceof ModelEntityInterface) { switch($context->action) { case 'add' : $context->setEntity($this->getModel()->create($context->request->data->toArray())); break; case 'edit' : case 'delete': $context->setEntity($this->getModel()->fetch()); break; } } else $context->setEntity($context->result); }
[ "protected", "function", "_fetchEntity", "(", "ControllerContext", "$", "context", ")", "{", "if", "(", "!", "$", "context", "->", "result", "instanceof", "ModelEntityInterface", ")", "{", "switch", "(", "$", "context", "->", "action", ")", "{", "case", "'add'", ":", "$", "context", "->", "setEntity", "(", "$", "this", "->", "getModel", "(", ")", "->", "create", "(", "$", "context", "->", "request", "->", "data", "->", "toArray", "(", ")", ")", ")", ";", "break", ";", "case", "'edit'", ":", "case", "'delete'", ":", "$", "context", "->", "setEntity", "(", "$", "this", "->", "getModel", "(", ")", "->", "fetch", "(", ")", ")", ";", "break", ";", "}", "}", "else", "$", "context", "->", "setEntity", "(", "$", "context", "->", "result", ")", ";", "}" ]
Fetch the model entity @param ControllerContextModel $context A controller context object @return void
[ "Fetch", "the", "model", "entity" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/controller/model.php#L362-L381
29,150
dereuromark/cakephp-feedback
src/Model/Table/FeedbackstoreTable.php
FeedbackstoreTable.mail
public function mail(array $feedbackObject, $copyreporter = false) { $returnobject = []; $returnobject['result'] = false; $returnobject['msg'] = ''; if (empty($feedbackObject)) { return $returnobject; } //Read settings from config if not in copy mode $to = Configure::read('Feedback.methods.mail.to'); $from = Configure::read('Feedback.methods.mail.from'); // Change recipient if sending a copy if ($copyreporter) { $to = $feedbackObject['email']; } //Change the sender if any given if (!empty($feedbackObject['email']) && !empty($feedbackObject['name'])) { $from = [$feedbackObject['email'] => $feedbackObject['name']]; } //Tmp store the screenshot: $tmpfile = APP . 'tmp' . DS . time() . '_' . rand(1000, 9999) . '.png'; if (!file_put_contents($tmpfile, base64_decode($feedbackObject['screenshot']))) { //Need to save tmp file throw new NotFoundException('Could not save tmp file for attachment in mail'); } $email = new Email(); $email->from($from); $email->to($to); $email->subject($feedbackObject['subject']); $email->emailFormat('html'); $email->attachments([ 'screenshot.png' => [ 'file' => $tmpfile, 'mimetype' => 'image/png', 'contentId' => 'id-screenshot' ] ]); //Mail specific: append browser, browser version, URL, etc to feedback : if ($copyreporter) { $feedbackObject['feedback'] = '<p>' . __d('feedback', 'A copy of your submitted feedback:') . '</p>' . $feedbackObject['feedback']; } $feedbackObject['feedback'] .= '<p>'; $feedbackObject['feedback'] .= sprintf('Browser: %s %s<br/>', $feedbackObject['browser'], $feedbackObject['browser_version']); $feedbackObject['feedback'] .= sprintf('Url: %s<br/>', $feedbackObject['url']); $feedbackObject['feedback'] .= sprintf('OS: %s<br/>', $feedbackObject['os']); $feedbackObject['feedback'] .= sprintf('By: %s<br/>', $feedbackObject['name']); $feedbackObject['feedback'] .= 'Screenshot: <br/>'; $feedbackObject['feedback'] .= '</p>'; $feedbackObject['feedback'] .= '<img src="cid:id-screenshot">'; //Add inline screenshot if ($email->send($feedbackObject['feedback'])) { $returnobject['result'] = true; $returnobject['msg'] = __d('feedback', 'Thank you. Your feedback was saved.'); return $returnobject; } unlink($tmpfile); return $returnobject; }
php
public function mail(array $feedbackObject, $copyreporter = false) { $returnobject = []; $returnobject['result'] = false; $returnobject['msg'] = ''; if (empty($feedbackObject)) { return $returnobject; } //Read settings from config if not in copy mode $to = Configure::read('Feedback.methods.mail.to'); $from = Configure::read('Feedback.methods.mail.from'); // Change recipient if sending a copy if ($copyreporter) { $to = $feedbackObject['email']; } //Change the sender if any given if (!empty($feedbackObject['email']) && !empty($feedbackObject['name'])) { $from = [$feedbackObject['email'] => $feedbackObject['name']]; } //Tmp store the screenshot: $tmpfile = APP . 'tmp' . DS . time() . '_' . rand(1000, 9999) . '.png'; if (!file_put_contents($tmpfile, base64_decode($feedbackObject['screenshot']))) { //Need to save tmp file throw new NotFoundException('Could not save tmp file for attachment in mail'); } $email = new Email(); $email->from($from); $email->to($to); $email->subject($feedbackObject['subject']); $email->emailFormat('html'); $email->attachments([ 'screenshot.png' => [ 'file' => $tmpfile, 'mimetype' => 'image/png', 'contentId' => 'id-screenshot' ] ]); //Mail specific: append browser, browser version, URL, etc to feedback : if ($copyreporter) { $feedbackObject['feedback'] = '<p>' . __d('feedback', 'A copy of your submitted feedback:') . '</p>' . $feedbackObject['feedback']; } $feedbackObject['feedback'] .= '<p>'; $feedbackObject['feedback'] .= sprintf('Browser: %s %s<br/>', $feedbackObject['browser'], $feedbackObject['browser_version']); $feedbackObject['feedback'] .= sprintf('Url: %s<br/>', $feedbackObject['url']); $feedbackObject['feedback'] .= sprintf('OS: %s<br/>', $feedbackObject['os']); $feedbackObject['feedback'] .= sprintf('By: %s<br/>', $feedbackObject['name']); $feedbackObject['feedback'] .= 'Screenshot: <br/>'; $feedbackObject['feedback'] .= '</p>'; $feedbackObject['feedback'] .= '<img src="cid:id-screenshot">'; //Add inline screenshot if ($email->send($feedbackObject['feedback'])) { $returnobject['result'] = true; $returnobject['msg'] = __d('feedback', 'Thank you. Your feedback was saved.'); return $returnobject; } unlink($tmpfile); return $returnobject; }
[ "public", "function", "mail", "(", "array", "$", "feedbackObject", ",", "$", "copyreporter", "=", "false", ")", "{", "$", "returnobject", "=", "[", "]", ";", "$", "returnobject", "[", "'result'", "]", "=", "false", ";", "$", "returnobject", "[", "'msg'", "]", "=", "''", ";", "if", "(", "empty", "(", "$", "feedbackObject", ")", ")", "{", "return", "$", "returnobject", ";", "}", "//Read settings from config if not in copy mode", "$", "to", "=", "Configure", "::", "read", "(", "'Feedback.methods.mail.to'", ")", ";", "$", "from", "=", "Configure", "::", "read", "(", "'Feedback.methods.mail.from'", ")", ";", "// Change recipient if sending a copy", "if", "(", "$", "copyreporter", ")", "{", "$", "to", "=", "$", "feedbackObject", "[", "'email'", "]", ";", "}", "//Change the sender if any given", "if", "(", "!", "empty", "(", "$", "feedbackObject", "[", "'email'", "]", ")", "&&", "!", "empty", "(", "$", "feedbackObject", "[", "'name'", "]", ")", ")", "{", "$", "from", "=", "[", "$", "feedbackObject", "[", "'email'", "]", "=>", "$", "feedbackObject", "[", "'name'", "]", "]", ";", "}", "//Tmp store the screenshot:", "$", "tmpfile", "=", "APP", ".", "'tmp'", ".", "DS", ".", "time", "(", ")", ".", "'_'", ".", "rand", "(", "1000", ",", "9999", ")", ".", "'.png'", ";", "if", "(", "!", "file_put_contents", "(", "$", "tmpfile", ",", "base64_decode", "(", "$", "feedbackObject", "[", "'screenshot'", "]", ")", ")", ")", "{", "//Need to save tmp file", "throw", "new", "NotFoundException", "(", "'Could not save tmp file for attachment in mail'", ")", ";", "}", "$", "email", "=", "new", "Email", "(", ")", ";", "$", "email", "->", "from", "(", "$", "from", ")", ";", "$", "email", "->", "to", "(", "$", "to", ")", ";", "$", "email", "->", "subject", "(", "$", "feedbackObject", "[", "'subject'", "]", ")", ";", "$", "email", "->", "emailFormat", "(", "'html'", ")", ";", "$", "email", "->", "attachments", "(", "[", "'screenshot.png'", "=>", "[", "'file'", "=>", "$", "tmpfile", ",", "'mimetype'", "=>", "'image/png'", ",", "'contentId'", "=>", "'id-screenshot'", "]", "]", ")", ";", "//Mail specific: append browser, browser version, URL, etc to feedback :", "if", "(", "$", "copyreporter", ")", "{", "$", "feedbackObject", "[", "'feedback'", "]", "=", "'<p>'", ".", "__d", "(", "'feedback'", ",", "'A copy of your submitted feedback:'", ")", ".", "'</p>'", ".", "$", "feedbackObject", "[", "'feedback'", "]", ";", "}", "$", "feedbackObject", "[", "'feedback'", "]", ".=", "'<p>'", ";", "$", "feedbackObject", "[", "'feedback'", "]", ".=", "sprintf", "(", "'Browser: %s %s<br/>'", ",", "$", "feedbackObject", "[", "'browser'", "]", ",", "$", "feedbackObject", "[", "'browser_version'", "]", ")", ";", "$", "feedbackObject", "[", "'feedback'", "]", ".=", "sprintf", "(", "'Url: %s<br/>'", ",", "$", "feedbackObject", "[", "'url'", "]", ")", ";", "$", "feedbackObject", "[", "'feedback'", "]", ".=", "sprintf", "(", "'OS: %s<br/>'", ",", "$", "feedbackObject", "[", "'os'", "]", ")", ";", "$", "feedbackObject", "[", "'feedback'", "]", ".=", "sprintf", "(", "'By: %s<br/>'", ",", "$", "feedbackObject", "[", "'name'", "]", ")", ";", "$", "feedbackObject", "[", "'feedback'", "]", ".=", "'Screenshot: <br/>'", ";", "$", "feedbackObject", "[", "'feedback'", "]", ".=", "'</p>'", ";", "$", "feedbackObject", "[", "'feedback'", "]", ".=", "'<img src=\"cid:id-screenshot\">'", ";", "//Add inline screenshot", "if", "(", "$", "email", "->", "send", "(", "$", "feedbackObject", "[", "'feedback'", "]", ")", ")", "{", "$", "returnobject", "[", "'result'", "]", "=", "true", ";", "$", "returnobject", "[", "'msg'", "]", "=", "__d", "(", "'feedback'", ",", "'Thank you. Your feedback was saved.'", ")", ";", "return", "$", "returnobject", ";", "}", "unlink", "(", "$", "tmpfile", ")", ";", "return", "$", "returnobject", ";", "}" ]
Mail function - Function has possibility to mail submitting user instead of target adress @deprecated Make a Store class @param array $feedbackObject @param bool $copyreporter @return array
[ "Mail", "function", "-", "Function", "has", "possibility", "to", "mail", "submitting", "user", "instead", "of", "target", "adress" ]
0bd774fda38b3cdd05db8c07a06a526d3ba81879
https://github.com/dereuromark/cakephp-feedback/blob/0bd774fda38b3cdd05db8c07a06a526d3ba81879/src/Model/Table/FeedbackstoreTable.php#L131-L197
29,151
dereuromark/cakephp-feedback
src/Model/Table/FeedbackstoreTable.php
FeedbackstoreTable.saveScreenshot
private function saveScreenshot(array $feedbackObject) { //Get save path from config $savepath = ROOT . DS . 'files' . DS . 'img' . DS . 'screenshots' . DS; //Serialize and save the object to a store in the Cake's tmp dir. if (!file_exists($savepath)) { if (!mkdir($savepath)) { //Throw error, directory is requird throw new NotFoundException('Could not create directory to save screenshots in. Please provide write rights to webserver user on directory: ' . $savepath); } } $screenshotname = $this->generateScreenshotName(); if (file_put_contents($savepath . $screenshotname, base64_decode($feedbackObject['screenshot']))) { //Return the screenshotname return $screenshotname; } return null; }
php
private function saveScreenshot(array $feedbackObject) { //Get save path from config $savepath = ROOT . DS . 'files' . DS . 'img' . DS . 'screenshots' . DS; //Serialize and save the object to a store in the Cake's tmp dir. if (!file_exists($savepath)) { if (!mkdir($savepath)) { //Throw error, directory is requird throw new NotFoundException('Could not create directory to save screenshots in. Please provide write rights to webserver user on directory: ' . $savepath); } } $screenshotname = $this->generateScreenshotName(); if (file_put_contents($savepath . $screenshotname, base64_decode($feedbackObject['screenshot']))) { //Return the screenshotname return $screenshotname; } return null; }
[ "private", "function", "saveScreenshot", "(", "array", "$", "feedbackObject", ")", "{", "//Get save path from config", "$", "savepath", "=", "ROOT", ".", "DS", ".", "'files'", ".", "DS", ".", "'img'", ".", "DS", ".", "'screenshots'", ".", "DS", ";", "//Serialize and save the object to a store in the Cake's tmp dir.", "if", "(", "!", "file_exists", "(", "$", "savepath", ")", ")", "{", "if", "(", "!", "mkdir", "(", "$", "savepath", ")", ")", "{", "//Throw error, directory is requird", "throw", "new", "NotFoundException", "(", "'Could not create directory to save screenshots in. Please provide write rights to webserver user on directory: '", ".", "$", "savepath", ")", ";", "}", "}", "$", "screenshotname", "=", "$", "this", "->", "generateScreenshotName", "(", ")", ";", "if", "(", "file_put_contents", "(", "$", "savepath", ".", "$", "screenshotname", ",", "base64_decode", "(", "$", "feedbackObject", "[", "'screenshot'", "]", ")", ")", ")", "{", "//Return the screenshotname", "return", "$", "screenshotname", ";", "}", "return", "null", ";", "}" ]
Auxiliary function that save screenshot as image in webroot @deprecated Make part of a Store class @param array $feedbackObject @return string|null
[ "Auxiliary", "function", "that", "save", "screenshot", "as", "image", "in", "webroot" ]
0bd774fda38b3cdd05db8c07a06a526d3ba81879
https://github.com/dereuromark/cakephp-feedback/blob/0bd774fda38b3cdd05db8c07a06a526d3ba81879/src/Model/Table/FeedbackstoreTable.php#L573-L593
29,152
deArcane/framework
src/Request/Container/Wrapper.php
Wrapper.parseValue
protected function parseValue($value){ switch( true ){ case ($value === 'false' || $value === 'true'): return ( $value === 'true' ) ? true : false ; case ctype_digit($value): return (int) $value; case is_float($value): return (float) $value; default: return $value; } }
php
protected function parseValue($value){ switch( true ){ case ($value === 'false' || $value === 'true'): return ( $value === 'true' ) ? true : false ; case ctype_digit($value): return (int) $value; case is_float($value): return (float) $value; default: return $value; } }
[ "protected", "function", "parseValue", "(", "$", "value", ")", "{", "switch", "(", "true", ")", "{", "case", "(", "$", "value", "===", "'false'", "||", "$", "value", "===", "'true'", ")", ":", "return", "(", "$", "value", "===", "'true'", ")", "?", "true", ":", "false", ";", "case", "ctype_digit", "(", "$", "value", ")", ":", "return", "(", "int", ")", "$", "value", ";", "case", "is_float", "(", "$", "value", ")", ":", "return", "(", "float", ")", "$", "value", ";", "default", ":", "return", "$", "value", ";", "}", "}" ]
Change variables to proper types.
[ "Change", "variables", "to", "proper", "types", "." ]
468da43678119f8c9e3f67183b5bec727c436404
https://github.com/deArcane/framework/blob/468da43678119f8c9e3f67183b5bec727c436404/src/Request/Container/Wrapper.php#L20-L34
29,153
rosasurfer/ministruts
src/console/docopt/pattern/Pattern.php
Pattern.fixIdentities
public function fixIdentities($unique = null) { if ($this->children) { if (!isset($unique)) $unique = array_unique($this->flat()); foreach ($this->children as $i => $child) { if (!$child instanceof BranchPattern) { if (!in_array($child, $unique)) // Not sure if this is a true substitute for 'assert c in uniq' throw new \UnexpectedValueException(); $this->children[$i] = $unique[array_search($child, $unique)]; } else { $child->fixIdentities($unique); } } } return $this; }
php
public function fixIdentities($unique = null) { if ($this->children) { if (!isset($unique)) $unique = array_unique($this->flat()); foreach ($this->children as $i => $child) { if (!$child instanceof BranchPattern) { if (!in_array($child, $unique)) // Not sure if this is a true substitute for 'assert c in uniq' throw new \UnexpectedValueException(); $this->children[$i] = $unique[array_search($child, $unique)]; } else { $child->fixIdentities($unique); } } } return $this; }
[ "public", "function", "fixIdentities", "(", "$", "unique", "=", "null", ")", "{", "if", "(", "$", "this", "->", "children", ")", "{", "if", "(", "!", "isset", "(", "$", "unique", ")", ")", "$", "unique", "=", "array_unique", "(", "$", "this", "->", "flat", "(", ")", ")", ";", "foreach", "(", "$", "this", "->", "children", "as", "$", "i", "=>", "$", "child", ")", "{", "if", "(", "!", "$", "child", "instanceof", "BranchPattern", ")", "{", "if", "(", "!", "in_array", "(", "$", "child", ",", "$", "unique", ")", ")", "// Not sure if this is a true substitute for 'assert c in uniq'", "throw", "new", "\\", "UnexpectedValueException", "(", ")", ";", "$", "this", "->", "children", "[", "$", "i", "]", "=", "$", "unique", "[", "array_search", "(", "$", "child", ",", "$", "unique", ")", "]", ";", "}", "else", "{", "$", "child", "->", "fixIdentities", "(", "$", "unique", ")", ";", "}", "}", "}", "return", "$", "this", ";", "}" ]
Make pattern-tree tips point to same object if they are equal. @param Pattern[]|null $unique [optional] @return $this
[ "Make", "pattern", "-", "tree", "tips", "point", "to", "same", "object", "if", "they", "are", "equal", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/console/docopt/pattern/Pattern.php#L67-L84
29,154
locomotivemtl/charcoal-core
src/Charcoal/Source/AbstractSource.php
AbstractSource.setData
public function setData(array $data) { foreach ($data as $key => $val) { $setter = $this->setter($key); if (is_callable([ $this, $setter ])) { $this->{$setter}($val); } else { $this->{$key} = $val; } } return $this; }
php
public function setData(array $data) { foreach ($data as $key => $val) { $setter = $this->setter($key); if (is_callable([ $this, $setter ])) { $this->{$setter}($val); } else { $this->{$key} = $val; } } return $this; }
[ "public", "function", "setData", "(", "array", "$", "data", ")", "{", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "val", ")", "{", "$", "setter", "=", "$", "this", "->", "setter", "(", "$", "key", ")", ";", "if", "(", "is_callable", "(", "[", "$", "this", ",", "$", "setter", "]", ")", ")", "{", "$", "this", "->", "{", "$", "setter", "}", "(", "$", "val", ")", ";", "}", "else", "{", "$", "this", "->", "{", "$", "key", "}", "=", "$", "val", ";", "}", "}", "return", "$", "this", ";", "}" ]
Set the source's settings. @param array $data Data to assign to the source. @return self
[ "Set", "the", "source", "s", "settings", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/AbstractSource.php#L98-L110
29,155
locomotivemtl/charcoal-core
src/Charcoal/Source/AbstractSource.php
AbstractSource.addProperty
public function addProperty($property) { $property = $this->resolvePropertyName($property); $this->properties[$property] = true; return $this; }
php
public function addProperty($property) { $property = $this->resolvePropertyName($property); $this->properties[$property] = true; return $this; }
[ "public", "function", "addProperty", "(", "$", "property", ")", "{", "$", "property", "=", "$", "this", "->", "resolvePropertyName", "(", "$", "property", ")", ";", "$", "this", "->", "properties", "[", "$", "property", "]", "=", "true", ";", "return", "$", "this", ";", "}" ]
Add a property of the source to fetch. @param string|PropertyInterface $property A property key to append. @return self
[ "Add", "a", "property", "of", "the", "source", "to", "fetch", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/AbstractSource.php#L173-L178
29,156
locomotivemtl/charcoal-core
src/Charcoal/Source/AbstractSource.php
AbstractSource.removeProperty
public function removeProperty($property) { $property = $this->resolvePropertyName($property); unset($this->properties[$property]); return $this; }
php
public function removeProperty($property) { $property = $this->resolvePropertyName($property); unset($this->properties[$property]); return $this; }
[ "public", "function", "removeProperty", "(", "$", "property", ")", "{", "$", "property", "=", "$", "this", "->", "resolvePropertyName", "(", "$", "property", ")", ";", "unset", "(", "$", "this", "->", "properties", "[", "$", "property", "]", ")", ";", "return", "$", "this", ";", "}" ]
Remove a property of the source to fetch. @param string|PropertyInterface $property A property key. @return self
[ "Remove", "a", "property", "of", "the", "source", "to", "fetch", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/AbstractSource.php#L186-L191
29,157
locomotivemtl/charcoal-core
src/Charcoal/Source/AbstractSource.php
AbstractSource.resolvePropertyName
protected function resolvePropertyName($property) { if ($property instanceof PropertyInterface) { $property = $property->ident(); } if (!is_string($property)) { throw new InvalidArgumentException( 'Property must be a string.' ); } if ($property === '') { throw new InvalidArgumentException( 'Property can not be empty.' ); } return $property; }
php
protected function resolvePropertyName($property) { if ($property instanceof PropertyInterface) { $property = $property->ident(); } if (!is_string($property)) { throw new InvalidArgumentException( 'Property must be a string.' ); } if ($property === '') { throw new InvalidArgumentException( 'Property can not be empty.' ); } return $property; }
[ "protected", "function", "resolvePropertyName", "(", "$", "property", ")", "{", "if", "(", "$", "property", "instanceof", "PropertyInterface", ")", "{", "$", "property", "=", "$", "property", "->", "ident", "(", ")", ";", "}", "if", "(", "!", "is_string", "(", "$", "property", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Property must be a string.'", ")", ";", "}", "if", "(", "$", "property", "===", "''", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Property can not be empty.'", ")", ";", "}", "return", "$", "property", ";", "}" ]
Resolve the name for the given property, throws an Exception if not. @param mixed $property Property to resolve. @throws InvalidArgumentException If property is not a string, empty, or invalid. @return string The property name.
[ "Resolve", "the", "name", "for", "the", "given", "property", "throws", "an", "Exception", "if", "not", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/AbstractSource.php#L200-L219
29,158
locomotivemtl/charcoal-core
src/Charcoal/Source/AbstractSource.php
AbstractSource.addFilter
public function addFilter($param, $value = null, array $options = null) { if (is_string($param) && $value !== null) { $expr = $this->createFilter(); $expr->setProperty($param); $expr->setValue($value); } else { $expr = $param; } $expr = $this->processFilter($expr); /** @deprecated 0.3 */ if (is_array($param) && isset($param['options'])) { $expr->setData($param['options']); } if (is_array($options)) { $expr->setData($options); } $this->filters[] = $this->parseFilterWithModel($expr); return $this; }
php
public function addFilter($param, $value = null, array $options = null) { if (is_string($param) && $value !== null) { $expr = $this->createFilter(); $expr->setProperty($param); $expr->setValue($value); } else { $expr = $param; } $expr = $this->processFilter($expr); /** @deprecated 0.3 */ if (is_array($param) && isset($param['options'])) { $expr->setData($param['options']); } if (is_array($options)) { $expr->setData($options); } $this->filters[] = $this->parseFilterWithModel($expr); return $this; }
[ "public", "function", "addFilter", "(", "$", "param", ",", "$", "value", "=", "null", ",", "array", "$", "options", "=", "null", ")", "{", "if", "(", "is_string", "(", "$", "param", ")", "&&", "$", "value", "!==", "null", ")", "{", "$", "expr", "=", "$", "this", "->", "createFilter", "(", ")", ";", "$", "expr", "->", "setProperty", "(", "$", "param", ")", ";", "$", "expr", "->", "setValue", "(", "$", "value", ")", ";", "}", "else", "{", "$", "expr", "=", "$", "param", ";", "}", "$", "expr", "=", "$", "this", "->", "processFilter", "(", "$", "expr", ")", ";", "/** @deprecated 0.3 */", "if", "(", "is_array", "(", "$", "param", ")", "&&", "isset", "(", "$", "param", "[", "'options'", "]", ")", ")", "{", "$", "expr", "->", "setData", "(", "$", "param", "[", "'options'", "]", ")", ";", "}", "if", "(", "is_array", "(", "$", "options", ")", ")", "{", "$", "expr", "->", "setData", "(", "$", "options", ")", ";", "}", "$", "this", "->", "filters", "[", "]", "=", "$", "this", "->", "parseFilterWithModel", "(", "$", "expr", ")", ";", "return", "$", "this", ";", "}" ]
Append a query filter on the source. There are 3 different ways of adding a filter: - as a `Filter` object, in which case it will be added directly. - `addFilter($obj);` - as an array of options, which will be used to build the `Filter` object - `addFilter(['property' => 'foo', 'value' => 42, 'operator' => '<=']);` - as 3 parameters: `property`, `value` and `options` - `addFilter('foo', 42, ['operator' => '<=']);` @deprecated 0.3 To be replaced with FilterCollectionTrait::addFilter() @uses self::parseFilterWithModel() @uses FilterCollectionTrait::processFilter() @param mixed $param The property to filter by, a {@see FilterInterface} object, or a filter array structure. @param mixed $value Optional value for the property to compare against. Only used if the first argument is a string. @param array $options Optional extra settings to apply on the filter. @throws InvalidArgumentException If the $param argument is invalid. @return self
[ "Append", "a", "query", "filter", "on", "the", "source", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/AbstractSource.php#L245-L268
29,159
locomotivemtl/charcoal-core
src/Charcoal/Source/AbstractSource.php
AbstractSource.parseFilterWithModel
protected function parseFilterWithModel(FilterInterface $filter) { if ($this->hasModel()) { if ($filter->hasProperty()) { $model = $this->model(); $property = $filter->property(); if (is_string($property) && $model->hasProperty($property)) { $property = $model->property($property); if ($property->l10n()) { $filter->setProperty($property->l10nIdent()); } if ($property->multiple()) { $filter->setOperator('FIND_IN_SET'); } } } if ($filter instanceof FilterCollectionInterface) { $filter->traverseFilters(function (FilterInterface $expr) { $this->parseFilterWithModel($expr); }); } } return $filter; }
php
protected function parseFilterWithModel(FilterInterface $filter) { if ($this->hasModel()) { if ($filter->hasProperty()) { $model = $this->model(); $property = $filter->property(); if (is_string($property) && $model->hasProperty($property)) { $property = $model->property($property); if ($property->l10n()) { $filter->setProperty($property->l10nIdent()); } if ($property->multiple()) { $filter->setOperator('FIND_IN_SET'); } } } if ($filter instanceof FilterCollectionInterface) { $filter->traverseFilters(function (FilterInterface $expr) { $this->parseFilterWithModel($expr); }); } } return $filter; }
[ "protected", "function", "parseFilterWithModel", "(", "FilterInterface", "$", "filter", ")", "{", "if", "(", "$", "this", "->", "hasModel", "(", ")", ")", "{", "if", "(", "$", "filter", "->", "hasProperty", "(", ")", ")", "{", "$", "model", "=", "$", "this", "->", "model", "(", ")", ";", "$", "property", "=", "$", "filter", "->", "property", "(", ")", ";", "if", "(", "is_string", "(", "$", "property", ")", "&&", "$", "model", "->", "hasProperty", "(", "$", "property", ")", ")", "{", "$", "property", "=", "$", "model", "->", "property", "(", "$", "property", ")", ";", "if", "(", "$", "property", "->", "l10n", "(", ")", ")", "{", "$", "filter", "->", "setProperty", "(", "$", "property", "->", "l10nIdent", "(", ")", ")", ";", "}", "if", "(", "$", "property", "->", "multiple", "(", ")", ")", "{", "$", "filter", "->", "setOperator", "(", "'FIND_IN_SET'", ")", ";", "}", "}", "}", "if", "(", "$", "filter", "instanceof", "FilterCollectionInterface", ")", "{", "$", "filter", "->", "traverseFilters", "(", "function", "(", "FilterInterface", "$", "expr", ")", "{", "$", "this", "->", "parseFilterWithModel", "(", "$", "expr", ")", ";", "}", ")", ";", "}", "}", "return", "$", "filter", ";", "}" ]
Process a query filter with the current model. @param FilterInterface $filter The expression object. @return FilterInterface The parsed expression object.
[ "Process", "a", "query", "filter", "with", "the", "current", "model", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/AbstractSource.php#L276-L303
29,160
locomotivemtl/charcoal-core
src/Charcoal/Source/AbstractSource.php
AbstractSource.addOrder
public function addOrder($param, $mode = 'asc', array $options = null) { if (is_string($param) && $mode !== null) { $expr = $this->createOrder(); $expr->setProperty($param); $expr->setMode($mode); } else { $expr = $param; } $expr = $this->processOrder($expr); /** @deprecated 0.3 */ if (is_array($param) && isset($param['options'])) { $expr->setData($param['options']); } if (is_array($options)) { $expr->setData($options); } $this->orders[] = $this->parseOrderWithModel($expr); return $this; }
php
public function addOrder($param, $mode = 'asc', array $options = null) { if (is_string($param) && $mode !== null) { $expr = $this->createOrder(); $expr->setProperty($param); $expr->setMode($mode); } else { $expr = $param; } $expr = $this->processOrder($expr); /** @deprecated 0.3 */ if (is_array($param) && isset($param['options'])) { $expr->setData($param['options']); } if (is_array($options)) { $expr->setData($options); } $this->orders[] = $this->parseOrderWithModel($expr); return $this; }
[ "public", "function", "addOrder", "(", "$", "param", ",", "$", "mode", "=", "'asc'", ",", "array", "$", "options", "=", "null", ")", "{", "if", "(", "is_string", "(", "$", "param", ")", "&&", "$", "mode", "!==", "null", ")", "{", "$", "expr", "=", "$", "this", "->", "createOrder", "(", ")", ";", "$", "expr", "->", "setProperty", "(", "$", "param", ")", ";", "$", "expr", "->", "setMode", "(", "$", "mode", ")", ";", "}", "else", "{", "$", "expr", "=", "$", "param", ";", "}", "$", "expr", "=", "$", "this", "->", "processOrder", "(", "$", "expr", ")", ";", "/** @deprecated 0.3 */", "if", "(", "is_array", "(", "$", "param", ")", "&&", "isset", "(", "$", "param", "[", "'options'", "]", ")", ")", "{", "$", "expr", "->", "setData", "(", "$", "param", "[", "'options'", "]", ")", ";", "}", "if", "(", "is_array", "(", "$", "options", ")", ")", "{", "$", "expr", "->", "setData", "(", "$", "options", ")", ";", "}", "$", "this", "->", "orders", "[", "]", "=", "$", "this", "->", "parseOrderWithModel", "(", "$", "expr", ")", ";", "return", "$", "this", ";", "}" ]
Append a query order on the source. @deprecated 0.3 To be replaced with OrderCollectionTrait::addOrder() @uses self::parseOrderWithModel() @uses OrderCollectionTrait::processOrder() @param mixed $param The property to sort by, a {@see OrderInterface} object, or a order array structure. @param string $mode Optional sorting mode. Defaults to ascending if a property is provided. @param array $options Optional extra settings to apply on the order. @throws InvalidArgumentException If the $param argument is invalid. @return self
[ "Append", "a", "query", "order", "on", "the", "source", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/AbstractSource.php#L337-L360
29,161
locomotivemtl/charcoal-core
src/Charcoal/Source/AbstractSource.php
AbstractSource.parseOrderWithModel
protected function parseOrderWithModel(OrderInterface $order) { if ($this->hasModel()) { if ($order->hasProperty()) { $model = $this->model(); $property = $order->property(); if (is_string($property) && $model->hasProperty($property)) { $property = $model->property($property); if ($property->l10n()) { $order->setProperty($property->l10nIdent()); } } } if ($order instanceof OrderCollectionInterface) { $order->traverseOrders(function (OrderInterface $expr) { $this->parseOrderWithModel($expr); }); } } return $order; }
php
protected function parseOrderWithModel(OrderInterface $order) { if ($this->hasModel()) { if ($order->hasProperty()) { $model = $this->model(); $property = $order->property(); if (is_string($property) && $model->hasProperty($property)) { $property = $model->property($property); if ($property->l10n()) { $order->setProperty($property->l10nIdent()); } } } if ($order instanceof OrderCollectionInterface) { $order->traverseOrders(function (OrderInterface $expr) { $this->parseOrderWithModel($expr); }); } } return $order; }
[ "protected", "function", "parseOrderWithModel", "(", "OrderInterface", "$", "order", ")", "{", "if", "(", "$", "this", "->", "hasModel", "(", ")", ")", "{", "if", "(", "$", "order", "->", "hasProperty", "(", ")", ")", "{", "$", "model", "=", "$", "this", "->", "model", "(", ")", ";", "$", "property", "=", "$", "order", "->", "property", "(", ")", ";", "if", "(", "is_string", "(", "$", "property", ")", "&&", "$", "model", "->", "hasProperty", "(", "$", "property", ")", ")", "{", "$", "property", "=", "$", "model", "->", "property", "(", "$", "property", ")", ";", "if", "(", "$", "property", "->", "l10n", "(", ")", ")", "{", "$", "order", "->", "setProperty", "(", "$", "property", "->", "l10nIdent", "(", ")", ")", ";", "}", "}", "}", "if", "(", "$", "order", "instanceof", "OrderCollectionInterface", ")", "{", "$", "order", "->", "traverseOrders", "(", "function", "(", "OrderInterface", "$", "expr", ")", "{", "$", "this", "->", "parseOrderWithModel", "(", "$", "expr", ")", ";", "}", ")", ";", "}", "}", "return", "$", "order", ";", "}" ]
Process a query order with the current model. @param OrderInterface $order The expression object. @return OrderInterface The parsed expression object.
[ "Process", "a", "query", "order", "with", "the", "current", "model", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/AbstractSource.php#L368-L391
29,162
locomotivemtl/charcoal-core
src/Charcoal/Source/AbstractSource.php
AbstractSource.createOrder
protected function createOrder(array $data = null) { $order = new Order(); if ($data !== null) { $order->setData($data); } return $order; }
php
protected function createOrder(array $data = null) { $order = new Order(); if ($data !== null) { $order->setData($data); } return $order; }
[ "protected", "function", "createOrder", "(", "array", "$", "data", "=", "null", ")", "{", "$", "order", "=", "new", "Order", "(", ")", ";", "if", "(", "$", "data", "!==", "null", ")", "{", "$", "order", "->", "setData", "(", "$", "data", ")", ";", "}", "return", "$", "order", ";", "}" ]
Create a new query order expression. @param array $data Optional expression data. @return OrderInterface
[ "Create", "a", "new", "query", "order", "expression", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/AbstractSource.php#L399-L406
29,163
locomotivemtl/charcoal-core
src/Charcoal/Source/AbstractSource.php
AbstractSource.setPagination
public function setPagination($param, $limit = null) { if ($param instanceof PaginationInterface) { $pager = $param; } elseif (is_numeric($param)) { $pager = $this->createPagination(); $pager->setPage($param); $pager->setNumPerPage($limit); } elseif (is_array($param)) { $pager = $this->createPagination(); $pager->setData($param); } else { throw new InvalidArgumentException( 'Can not set pagination, invalid argument.' ); } $this->pagination = $pager; return $this; }
php
public function setPagination($param, $limit = null) { if ($param instanceof PaginationInterface) { $pager = $param; } elseif (is_numeric($param)) { $pager = $this->createPagination(); $pager->setPage($param); $pager->setNumPerPage($limit); } elseif (is_array($param)) { $pager = $this->createPagination(); $pager->setData($param); } else { throw new InvalidArgumentException( 'Can not set pagination, invalid argument.' ); } $this->pagination = $pager; return $this; }
[ "public", "function", "setPagination", "(", "$", "param", ",", "$", "limit", "=", "null", ")", "{", "if", "(", "$", "param", "instanceof", "PaginationInterface", ")", "{", "$", "pager", "=", "$", "param", ";", "}", "elseif", "(", "is_numeric", "(", "$", "param", ")", ")", "{", "$", "pager", "=", "$", "this", "->", "createPagination", "(", ")", ";", "$", "pager", "->", "setPage", "(", "$", "param", ")", ";", "$", "pager", "->", "setNumPerPage", "(", "$", "limit", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "param", ")", ")", "{", "$", "pager", "=", "$", "this", "->", "createPagination", "(", ")", ";", "$", "pager", "->", "setData", "(", "$", "param", ")", ";", "}", "else", "{", "throw", "new", "InvalidArgumentException", "(", "'Can not set pagination, invalid argument.'", ")", ";", "}", "$", "this", "->", "pagination", "=", "$", "pager", ";", "return", "$", "this", ";", "}" ]
Set query pagination. @param mixed $param The pagination object or array. @param integer|null $limit The number of results to fetch if $param is a page number. @throws InvalidArgumentException If the $param argument is invalid. @return self
[ "Set", "query", "pagination", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/AbstractSource.php#L416-L436
29,164
locomotivemtl/charcoal-core
src/Charcoal/Source/AbstractSource.php
AbstractSource.pagination
public function pagination() { if ($this->pagination === null) { $this->pagination = $this->createPagination(); } return $this->pagination; }
php
public function pagination() { if ($this->pagination === null) { $this->pagination = $this->createPagination(); } return $this->pagination; }
[ "public", "function", "pagination", "(", ")", "{", "if", "(", "$", "this", "->", "pagination", "===", "null", ")", "{", "$", "this", "->", "pagination", "=", "$", "this", "->", "createPagination", "(", ")", ";", "}", "return", "$", "this", "->", "pagination", ";", "}" ]
Get query pagination. If the pagination wasn't previously define, a new Pagination object will be created. @return PaginationInterface
[ "Get", "query", "pagination", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/AbstractSource.php#L455-L462
29,165
timble/kodekit
code/http/message/parameters.php
HttpMessageParameters.all
public function all($filter) { $result = $this->toArray(); // If the value is null return the default if(!empty($result)) { // Handle magic quotes compatibility if (get_magic_quotes_gpc()) { $result = $this->_stripSlashes( $result ); } // Filter the data if(!($filter instanceof FilterInterface)) { $filter = $this->getObject('filter.factory')->createChain($filter); } $result = $filter->sanitize($result); } return $result; }
php
public function all($filter) { $result = $this->toArray(); // If the value is null return the default if(!empty($result)) { // Handle magic quotes compatibility if (get_magic_quotes_gpc()) { $result = $this->_stripSlashes( $result ); } // Filter the data if(!($filter instanceof FilterInterface)) { $filter = $this->getObject('filter.factory')->createChain($filter); } $result = $filter->sanitize($result); } return $result; }
[ "public", "function", "all", "(", "$", "filter", ")", "{", "$", "result", "=", "$", "this", "->", "toArray", "(", ")", ";", "// If the value is null return the default", "if", "(", "!", "empty", "(", "$", "result", ")", ")", "{", "// Handle magic quotes compatibility", "if", "(", "get_magic_quotes_gpc", "(", ")", ")", "{", "$", "result", "=", "$", "this", "->", "_stripSlashes", "(", "$", "result", ")", ";", "}", "// Filter the data", "if", "(", "!", "(", "$", "filter", "instanceof", "FilterInterface", ")", ")", "{", "$", "filter", "=", "$", "this", "->", "getObject", "(", "'filter.factory'", ")", "->", "createChain", "(", "$", "filter", ")", ";", "}", "$", "result", "=", "$", "filter", "->", "sanitize", "(", "$", "result", ")", ";", "}", "return", "$", "result", ";", "}" ]
Get all parameters and filter them @param mixed $filter Filter(s), can be a Filter object, a filter name, an array of filter names or a filter identifier @return mixed The sanitized data
[ "Get", "all", "parameters", "and", "filter", "them" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/http/message/parameters.php#L58-L79
29,166
timble/kodekit
code/http/message/parameters.php
HttpMessageParameters.get
public function get($identifier, $filter, $default = null) { $keys = $this->_parseIdentifier($identifier); $result = $this->toArray(); foreach($keys as $key) { if(array_key_exists($key, $result)) { $result = $result[$key]; } else { $result = null; break; } } // If the value is null return the default if(!is_null($result)) { // Handle magic quotes compatibility if (get_magic_quotes_gpc()) { $result = $this->_stripSlashes( $result ); } // Filter the data if(!($filter instanceof FilterInterface)) { $filter = $this->getObject('filter.factory')->createChain($filter); } $result = $filter->sanitize($result); } else $result = $default; return $result; }
php
public function get($identifier, $filter, $default = null) { $keys = $this->_parseIdentifier($identifier); $result = $this->toArray(); foreach($keys as $key) { if(array_key_exists($key, $result)) { $result = $result[$key]; } else { $result = null; break; } } // If the value is null return the default if(!is_null($result)) { // Handle magic quotes compatibility if (get_magic_quotes_gpc()) { $result = $this->_stripSlashes( $result ); } // Filter the data if(!($filter instanceof FilterInterface)) { $filter = $this->getObject('filter.factory')->createChain($filter); } $result = $filter->sanitize($result); } else $result = $default; return $result; }
[ "public", "function", "get", "(", "$", "identifier", ",", "$", "filter", ",", "$", "default", "=", "null", ")", "{", "$", "keys", "=", "$", "this", "->", "_parseIdentifier", "(", "$", "identifier", ")", ";", "$", "result", "=", "$", "this", "->", "toArray", "(", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "result", ")", ")", "{", "$", "result", "=", "$", "result", "[", "$", "key", "]", ";", "}", "else", "{", "$", "result", "=", "null", ";", "break", ";", "}", "}", "// If the value is null return the default", "if", "(", "!", "is_null", "(", "$", "result", ")", ")", "{", "// Handle magic quotes compatibility", "if", "(", "get_magic_quotes_gpc", "(", ")", ")", "{", "$", "result", "=", "$", "this", "->", "_stripSlashes", "(", "$", "result", ")", ";", "}", "// Filter the data", "if", "(", "!", "(", "$", "filter", "instanceof", "FilterInterface", ")", ")", "{", "$", "filter", "=", "$", "this", "->", "getObject", "(", "'filter.factory'", ")", "->", "createChain", "(", "$", "filter", ")", ";", "}", "$", "result", "=", "$", "filter", "->", "sanitize", "(", "$", "result", ")", ";", "}", "else", "$", "result", "=", "$", "default", ";", "return", "$", "result", ";", "}" ]
Get a filtered parameter @param string $identifier Parameter identifier, eg .foo.bar @param mixed $filter Filter(s), can be a Filter object, a filter name, an array of filter names or a filter identifier @param mixed $default Default value when the variable doesn't exist @return mixed The sanitized parameter
[ "Get", "a", "filtered", "parameter" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/http/message/parameters.php#L90-L123
29,167
timble/kodekit
code/http/message/parameters.php
HttpMessageParameters.set
public function set($identifier, $value, $replace = true) { if (!is_null($value) && !is_scalar($value) && !is_array($value) && !(is_object($value) && method_exists($value, '__toString'))) { throw new \UnexpectedValueException( 'The http parameter value must be a string or object implementing __toString(), "'.gettype($value).'" given.' ); } $keys = $this->_parseIdentifier($identifier); foreach(array_reverse($keys, true) as $key) { if ($replace !== true && isset($this[$key])) { break; } $value = array($key => $value); $this->_data = $this->_mergeArrays($this->_data, $value); } return $this; }
php
public function set($identifier, $value, $replace = true) { if (!is_null($value) && !is_scalar($value) && !is_array($value) && !(is_object($value) && method_exists($value, '__toString'))) { throw new \UnexpectedValueException( 'The http parameter value must be a string or object implementing __toString(), "'.gettype($value).'" given.' ); } $keys = $this->_parseIdentifier($identifier); foreach(array_reverse($keys, true) as $key) { if ($replace !== true && isset($this[$key])) { break; } $value = array($key => $value); $this->_data = $this->_mergeArrays($this->_data, $value); } return $this; }
[ "public", "function", "set", "(", "$", "identifier", ",", "$", "value", ",", "$", "replace", "=", "true", ")", "{", "if", "(", "!", "is_null", "(", "$", "value", ")", "&&", "!", "is_scalar", "(", "$", "value", ")", "&&", "!", "is_array", "(", "$", "value", ")", "&&", "!", "(", "is_object", "(", "$", "value", ")", "&&", "method_exists", "(", "$", "value", ",", "'__toString'", ")", ")", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "'The http parameter value must be a string or object implementing __toString(), \"'", ".", "gettype", "(", "$", "value", ")", ".", "'\" given.'", ")", ";", "}", "$", "keys", "=", "$", "this", "->", "_parseIdentifier", "(", "$", "identifier", ")", ";", "foreach", "(", "array_reverse", "(", "$", "keys", ",", "true", ")", "as", "$", "key", ")", "{", "if", "(", "$", "replace", "!==", "true", "&&", "isset", "(", "$", "this", "[", "$", "key", "]", ")", ")", "{", "break", ";", "}", "$", "value", "=", "array", "(", "$", "key", "=>", "$", "value", ")", ";", "$", "this", "->", "_data", "=", "$", "this", "->", "_mergeArrays", "(", "$", "this", "->", "_data", ",", "$", "value", ")", ";", "}", "return", "$", "this", ";", "}" ]
Set a parameter @param mixed $identifier Parameter identifier, eg foo.bar @param mixed $value Parameter value @param boolean $replace Whether to replace the actual value or not (true by default) @throws \UnexpectedValueException If the content is not a string are cannot be casted to a string. @return HttpMessageParameters
[ "Set", "a", "parameter" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/http/message/parameters.php#L134-L156
29,168
locomotivemtl/charcoal-core
src/Charcoal/Loader/CollectionLoader.php
CollectionLoader.setModel
public function setModel($model) { if (is_string($model)) { $model = $this->factory()->get($model); } if (!$model instanceof ModelInterface) { throw new InvalidArgumentException( sprintf( 'The model must be an instance of "%s"', ModelInterface::class ) ); } $this->model = $model; $this->setSource($model->source()); return $this; }
php
public function setModel($model) { if (is_string($model)) { $model = $this->factory()->get($model); } if (!$model instanceof ModelInterface) { throw new InvalidArgumentException( sprintf( 'The model must be an instance of "%s"', ModelInterface::class ) ); } $this->model = $model; $this->setSource($model->source()); return $this; }
[ "public", "function", "setModel", "(", "$", "model", ")", "{", "if", "(", "is_string", "(", "$", "model", ")", ")", "{", "$", "model", "=", "$", "this", "->", "factory", "(", ")", "->", "get", "(", "$", "model", ")", ";", "}", "if", "(", "!", "$", "model", "instanceof", "ModelInterface", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'The model must be an instance of \"%s\"'", ",", "ModelInterface", "::", "class", ")", ")", ";", "}", "$", "this", "->", "model", "=", "$", "model", ";", "$", "this", "->", "setSource", "(", "$", "model", "->", "source", "(", ")", ")", ";", "return", "$", "this", ";", "}" ]
Set the model to use for the loaded objects. @param string|ModelInterface $model An object model. @throws InvalidArgumentException If the given argument is not a model. @return self
[ "Set", "the", "model", "to", "use", "for", "the", "loaded", "objects", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Loader/CollectionLoader.php#L238-L258
29,169
locomotivemtl/charcoal-core
src/Charcoal/Loader/CollectionLoader.php
CollectionLoader.setKeywords
public function setKeywords(array $keywords) { foreach ($keywords as $query) { $keyword = $query[0]; $properties = (isset($query[1]) ? (array)$query[1] : null); $this->addKeyword($keyword, $properties); } return $this; }
php
public function setKeywords(array $keywords) { foreach ($keywords as $query) { $keyword = $query[0]; $properties = (isset($query[1]) ? (array)$query[1] : null); $this->addKeyword($keyword, $properties); } return $this; }
[ "public", "function", "setKeywords", "(", "array", "$", "keywords", ")", "{", "foreach", "(", "$", "keywords", "as", "$", "query", ")", "{", "$", "keyword", "=", "$", "query", "[", "0", "]", ";", "$", "properties", "=", "(", "isset", "(", "$", "query", "[", "1", "]", ")", "?", "(", "array", ")", "$", "query", "[", "1", "]", ":", "null", ")", ";", "$", "this", "->", "addKeyword", "(", "$", "keyword", ",", "$", "properties", ")", ";", "}", "return", "$", "this", ";", "}" ]
Set "search" keywords to filter multiple properties. @param array $keywords An array of keywords and properties. Expected format: `[ "search query", [ "field names…" ] ]`. @return self
[ "Set", "search", "keywords", "to", "filter", "multiple", "properties", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Loader/CollectionLoader.php#L321-L330
29,170
locomotivemtl/charcoal-core
src/Charcoal/Loader/CollectionLoader.php
CollectionLoader.addKeyword
public function addKeyword($keyword, array $properties = null) { if ($properties === null) { $properties = []; } foreach ($properties as $propertyIdent) { $val = ('%'.$keyword.'%'); $this->addFilter([ 'property' => $propertyIdent, 'operator' => 'LIKE', 'value' => $val, 'operand' => 'OR' ]); } return $this; }
php
public function addKeyword($keyword, array $properties = null) { if ($properties === null) { $properties = []; } foreach ($properties as $propertyIdent) { $val = ('%'.$keyword.'%'); $this->addFilter([ 'property' => $propertyIdent, 'operator' => 'LIKE', 'value' => $val, 'operand' => 'OR' ]); } return $this; }
[ "public", "function", "addKeyword", "(", "$", "keyword", ",", "array", "$", "properties", "=", "null", ")", "{", "if", "(", "$", "properties", "===", "null", ")", "{", "$", "properties", "=", "[", "]", ";", "}", "foreach", "(", "$", "properties", "as", "$", "propertyIdent", ")", "{", "$", "val", "=", "(", "'%'", ".", "$", "keyword", ".", "'%'", ")", ";", "$", "this", "->", "addFilter", "(", "[", "'property'", "=>", "$", "propertyIdent", ",", "'operator'", "=>", "'LIKE'", ",", "'value'", "=>", "$", "val", ",", "'operand'", "=>", "'OR'", "]", ")", ";", "}", "return", "$", "this", ";", "}" ]
Add a "search" keyword filter to multiple properties. @param string $keyword A value to match among $properties. @param array $properties One or more of properties to search amongst. @return self
[ "Add", "a", "search", "keyword", "filter", "to", "multiple", "properties", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Loader/CollectionLoader.php#L339-L356
29,171
locomotivemtl/charcoal-core
src/Charcoal/Loader/CollectionLoader.php
CollectionLoader.load
public function load($ident = null, callable $callback = null, callable $before = null) { // Unused. unset($ident); $query = $this->source()->sqlLoad(); return $this->loadFromQuery($query, $callback, $before); }
php
public function load($ident = null, callable $callback = null, callable $before = null) { // Unused. unset($ident); $query = $this->source()->sqlLoad(); return $this->loadFromQuery($query, $callback, $before); }
[ "public", "function", "load", "(", "$", "ident", "=", "null", ",", "callable", "$", "callback", "=", "null", ",", "callable", "$", "before", "=", "null", ")", "{", "// Unused.", "unset", "(", "$", "ident", ")", ";", "$", "query", "=", "$", "this", "->", "source", "(", ")", "->", "sqlLoad", "(", ")", ";", "return", "$", "this", "->", "loadFromQuery", "(", "$", "query", ",", "$", "callback", ",", "$", "before", ")", ";", "}" ]
Load a collection from source. @param string|null $ident Optional. A pre-defined list to use from the model. @param callable|null $callback Process each entity after applying raw data. Leave blank to use {@see CollectionLoader::callback()}. @param callable|null $before Process each entity before applying raw data. @throws Exception If the database connection fails. @return ModelInterface[]|ArrayAccess
[ "Load", "a", "collection", "from", "source", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Loader/CollectionLoader.php#L586-L594
29,172
locomotivemtl/charcoal-core
src/Charcoal/Loader/CollectionLoader.php
CollectionLoader.loadCount
public function loadCount() { $query = $this->source()->sqlLoadCount(); $db = $this->source()->db(); if (!$db) { throw new RuntimeException( 'Could not instanciate a database connection.' ); } $this->logger->debug($query); $sth = $db->prepare($query); $sth->execute(); $res = $sth->fetchColumn(0); return (int)$res; }
php
public function loadCount() { $query = $this->source()->sqlLoadCount(); $db = $this->source()->db(); if (!$db) { throw new RuntimeException( 'Could not instanciate a database connection.' ); } $this->logger->debug($query); $sth = $db->prepare($query); $sth->execute(); $res = $sth->fetchColumn(0); return (int)$res; }
[ "public", "function", "loadCount", "(", ")", "{", "$", "query", "=", "$", "this", "->", "source", "(", ")", "->", "sqlLoadCount", "(", ")", ";", "$", "db", "=", "$", "this", "->", "source", "(", ")", "->", "db", "(", ")", ";", "if", "(", "!", "$", "db", ")", "{", "throw", "new", "RuntimeException", "(", "'Could not instanciate a database connection.'", ")", ";", "}", "$", "this", "->", "logger", "->", "debug", "(", "$", "query", ")", ";", "$", "sth", "=", "$", "db", "->", "prepare", "(", "$", "query", ")", ";", "$", "sth", "->", "execute", "(", ")", ";", "$", "res", "=", "$", "sth", "->", "fetchColumn", "(", "0", ")", ";", "return", "(", "int", ")", "$", "res", ";", "}" ]
Get the total number of items for this collection query. @throws RuntimeException If the database connection fails. @return integer
[ "Get", "the", "total", "number", "of", "items", "for", "this", "collection", "query", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Loader/CollectionLoader.php#L602-L619
29,173
locomotivemtl/charcoal-core
src/Charcoal/Loader/CollectionLoader.php
CollectionLoader.loadFromQuery
public function loadFromQuery($query, callable $callback = null, callable $before = null) { $db = $this->source()->db(); if (!$db) { throw new RuntimeException( 'Could not instanciate a database connection.' ); } /** @todo Filter binds */ if (is_string($query)) { $this->logger->debug($query); $sth = $db->prepare($query); $sth->execute(); } elseif (is_array($query)) { list($query, $binds, $types) = array_pad($query, 3, []); $sth = $this->source()->dbQuery($query, $binds, $types); } else { throw new InvalidArgumentException(sprintf( 'The SQL query must be a string or an array: '. '[ string $query, array $binds, array $dataTypes ]; '. 'received %s', is_object($query) ? get_class($query) : $query )); } $sth->setFetchMode(PDO::FETCH_ASSOC); if ($callback === null) { $callback = $this->callback(); } return $this->processCollection($sth, $before, $callback); }
php
public function loadFromQuery($query, callable $callback = null, callable $before = null) { $db = $this->source()->db(); if (!$db) { throw new RuntimeException( 'Could not instanciate a database connection.' ); } /** @todo Filter binds */ if (is_string($query)) { $this->logger->debug($query); $sth = $db->prepare($query); $sth->execute(); } elseif (is_array($query)) { list($query, $binds, $types) = array_pad($query, 3, []); $sth = $this->source()->dbQuery($query, $binds, $types); } else { throw new InvalidArgumentException(sprintf( 'The SQL query must be a string or an array: '. '[ string $query, array $binds, array $dataTypes ]; '. 'received %s', is_object($query) ? get_class($query) : $query )); } $sth->setFetchMode(PDO::FETCH_ASSOC); if ($callback === null) { $callback = $this->callback(); } return $this->processCollection($sth, $before, $callback); }
[ "public", "function", "loadFromQuery", "(", "$", "query", ",", "callable", "$", "callback", "=", "null", ",", "callable", "$", "before", "=", "null", ")", "{", "$", "db", "=", "$", "this", "->", "source", "(", ")", "->", "db", "(", ")", ";", "if", "(", "!", "$", "db", ")", "{", "throw", "new", "RuntimeException", "(", "'Could not instanciate a database connection.'", ")", ";", "}", "/** @todo Filter binds */", "if", "(", "is_string", "(", "$", "query", ")", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "$", "query", ")", ";", "$", "sth", "=", "$", "db", "->", "prepare", "(", "$", "query", ")", ";", "$", "sth", "->", "execute", "(", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "query", ")", ")", "{", "list", "(", "$", "query", ",", "$", "binds", ",", "$", "types", ")", "=", "array_pad", "(", "$", "query", ",", "3", ",", "[", "]", ")", ";", "$", "sth", "=", "$", "this", "->", "source", "(", ")", "->", "dbQuery", "(", "$", "query", ",", "$", "binds", ",", "$", "types", ")", ";", "}", "else", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'The SQL query must be a string or an array: '", ".", "'[ string $query, array $binds, array $dataTypes ]; '", ".", "'received %s'", ",", "is_object", "(", "$", "query", ")", "?", "get_class", "(", "$", "query", ")", ":", "$", "query", ")", ")", ";", "}", "$", "sth", "->", "setFetchMode", "(", "PDO", "::", "FETCH_ASSOC", ")", ";", "if", "(", "$", "callback", "===", "null", ")", "{", "$", "callback", "=", "$", "this", "->", "callback", "(", ")", ";", "}", "return", "$", "this", "->", "processCollection", "(", "$", "sth", ",", "$", "before", ",", "$", "callback", ")", ";", "}" ]
Load list from query. **Example — Binding values to $query** ```php $this->loadFromQuery([ 'SELECT name, colour, calories FROM fruit WHERE calories < :calories AND colour = :colour', [ 'calories' => 150, 'colour' => 'red' ], [ 'calories' => PDO::PARAM_INT ] ]); ``` @param string|array $query The SQL query as a string or an array composed of the query, parameter binds, and types of parameter bindings. @param callable|null $callback Process each entity after applying raw data. Leave blank to use {@see CollectionLoader::callback()}. @param callable|null $before Process each entity before applying raw data. @throws RuntimeException If the database connection fails. @throws InvalidArgumentException If the SQL string/set is invalid. @return ModelInterface[]|ArrayAccess
[ "Load", "list", "from", "query", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Loader/CollectionLoader.php#L646-L680
29,174
locomotivemtl/charcoal-core
src/Charcoal/Loader/CollectionLoader.php
CollectionLoader.processCollection
protected function processCollection($results, callable $before = null, callable $after = null) { $collection = $this->createCollection(); foreach ($results as $objData) { $obj = $this->processModel($objData, $before, $after); if ($obj instanceof ModelInterface) { $collection[] = $obj; } } return $collection; }
php
protected function processCollection($results, callable $before = null, callable $after = null) { $collection = $this->createCollection(); foreach ($results as $objData) { $obj = $this->processModel($objData, $before, $after); if ($obj instanceof ModelInterface) { $collection[] = $obj; } } return $collection; }
[ "protected", "function", "processCollection", "(", "$", "results", ",", "callable", "$", "before", "=", "null", ",", "callable", "$", "after", "=", "null", ")", "{", "$", "collection", "=", "$", "this", "->", "createCollection", "(", ")", ";", "foreach", "(", "$", "results", "as", "$", "objData", ")", "{", "$", "obj", "=", "$", "this", "->", "processModel", "(", "$", "objData", ",", "$", "before", ",", "$", "after", ")", ";", "if", "(", "$", "obj", "instanceof", "ModelInterface", ")", "{", "$", "collection", "[", "]", "=", "$", "obj", ";", "}", "}", "return", "$", "collection", ";", "}" ]
Process the collection of raw data. @param mixed[]|Traversable $results The raw result set. @param callable|null $before Process each entity before applying raw data. @param callable|null $after Process each entity after applying raw data. @return ModelInterface[]|ArrayAccess
[ "Process", "the", "collection", "of", "raw", "data", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Loader/CollectionLoader.php#L690-L702
29,175
locomotivemtl/charcoal-core
src/Charcoal/Loader/CollectionLoader.php
CollectionLoader.processModel
protected function processModel($objData, callable $before = null, callable $after = null) { if ($this->dynamicTypeField && isset($objData[$this->dynamicTypeField])) { $objType = $objData[$this->dynamicTypeField]; } else { $objType = get_class($this->model()); } $obj = $this->factory()->create($objType); if ($before !== null) { call_user_func_array($before, [ &$obj ]); } $obj->setFlatData($objData); if ($after !== null) { call_user_func_array($after, [ &$obj ]); } return $obj; }
php
protected function processModel($objData, callable $before = null, callable $after = null) { if ($this->dynamicTypeField && isset($objData[$this->dynamicTypeField])) { $objType = $objData[$this->dynamicTypeField]; } else { $objType = get_class($this->model()); } $obj = $this->factory()->create($objType); if ($before !== null) { call_user_func_array($before, [ &$obj ]); } $obj->setFlatData($objData); if ($after !== null) { call_user_func_array($after, [ &$obj ]); } return $obj; }
[ "protected", "function", "processModel", "(", "$", "objData", ",", "callable", "$", "before", "=", "null", ",", "callable", "$", "after", "=", "null", ")", "{", "if", "(", "$", "this", "->", "dynamicTypeField", "&&", "isset", "(", "$", "objData", "[", "$", "this", "->", "dynamicTypeField", "]", ")", ")", "{", "$", "objType", "=", "$", "objData", "[", "$", "this", "->", "dynamicTypeField", "]", ";", "}", "else", "{", "$", "objType", "=", "get_class", "(", "$", "this", "->", "model", "(", ")", ")", ";", "}", "$", "obj", "=", "$", "this", "->", "factory", "(", ")", "->", "create", "(", "$", "objType", ")", ";", "if", "(", "$", "before", "!==", "null", ")", "{", "call_user_func_array", "(", "$", "before", ",", "[", "&", "$", "obj", "]", ")", ";", "}", "$", "obj", "->", "setFlatData", "(", "$", "objData", ")", ";", "if", "(", "$", "after", "!==", "null", ")", "{", "call_user_func_array", "(", "$", "after", ",", "[", "&", "$", "obj", "]", ")", ";", "}", "return", "$", "obj", ";", "}" ]
Process the raw data for one model. @param mixed $objData The raw dataset. @param callable|null $before Process each entity before applying raw data. @param callable|null $after Process each entity after applying raw data. @return ModelInterface|ArrayAccess|null
[ "Process", "the", "raw", "data", "for", "one", "model", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Loader/CollectionLoader.php#L712-L733
29,176
locomotivemtl/charcoal-core
src/Charcoal/Loader/CollectionLoader.php
CollectionLoader.createCollection
public function createCollection() { $collectClass = $this->collectionClass(); if ($collectClass === 'array') { return []; } if (!class_exists($collectClass)) { throw new RuntimeException(sprintf( 'Collection class [%s] does not exist.', $collectClass )); } if (!is_subclass_of($collectClass, ArrayAccess::class)) { throw new RuntimeException(sprintf( 'Collection class [%s] must implement ArrayAccess.', $collectClass )); } $collection = new $collectClass; return $collection; }
php
public function createCollection() { $collectClass = $this->collectionClass(); if ($collectClass === 'array') { return []; } if (!class_exists($collectClass)) { throw new RuntimeException(sprintf( 'Collection class [%s] does not exist.', $collectClass )); } if (!is_subclass_of($collectClass, ArrayAccess::class)) { throw new RuntimeException(sprintf( 'Collection class [%s] must implement ArrayAccess.', $collectClass )); } $collection = new $collectClass; return $collection; }
[ "public", "function", "createCollection", "(", ")", "{", "$", "collectClass", "=", "$", "this", "->", "collectionClass", "(", ")", ";", "if", "(", "$", "collectClass", "===", "'array'", ")", "{", "return", "[", "]", ";", "}", "if", "(", "!", "class_exists", "(", "$", "collectClass", ")", ")", "{", "throw", "new", "RuntimeException", "(", "sprintf", "(", "'Collection class [%s] does not exist.'", ",", "$", "collectClass", ")", ")", ";", "}", "if", "(", "!", "is_subclass_of", "(", "$", "collectClass", ",", "ArrayAccess", "::", "class", ")", ")", "{", "throw", "new", "RuntimeException", "(", "sprintf", "(", "'Collection class [%s] must implement ArrayAccess.'", ",", "$", "collectClass", ")", ")", ";", "}", "$", "collection", "=", "new", "$", "collectClass", ";", "return", "$", "collection", ";", "}" ]
Create a collection class or array. @throws RuntimeException If the collection class is invalid. @return array|ArrayAccess
[ "Create", "a", "collection", "class", "or", "array", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Loader/CollectionLoader.php#L741-L765
29,177
rosasurfer/ministruts
src/db/pgsql/PostgresConnector.php
PostgresConnector.getConnectionString
private function getConnectionString() { // supported keywords: https://www.postgresql.org/docs/9.6/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS $paramKeywords = [ 'host', 'hostaddr', 'port', 'dbname', 'user', 'password', 'connect_timeout', 'client_encoding', 'options', 'application_name', 'fallback_application_name', 'keepalives', 'keepalives_idle', 'keepalives_interval', 'keepalives_count', 'tty', // ignored 'sslmode', 'requiressl', // deprecated in favor of 'sslmode' 'sslcompression', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl', 'requirepeer', 'krbsrvname', //'gsslib', // rejected by php_pgsql 9.4.1 'service', ]; $paramKeywords = \array_flip($paramKeywords); $connStr = ''; foreach ($this->options as $key => $value) { $keyL = trim(strtolower($key)); if (!isset($paramKeywords[$keyL])) continue; // unknown keyword if (is_array($value)) { if ($keyL != 'options') continue; // "options" is the only allowed keyword with nested settings // split regular connection options and session variables if (isset($value[''])) { $this->options[$key] = $value['']; unset($value['']); $this->sessionVars = $value; $value = $this->options[$key]; // the root value goes into the connection string } else { unset($this->options[$key]); $this->sessionVars = $value; continue; // "options" has only session vars and no root value [""] } } if (!strlen($value)) { $value = "''"; } else { $value = str_replace(['\\', "'"], ['\\\\', "\'"], $value); if (strContains($value, ' ')) $value = "'".$value."'"; } $connStr .= $key.'='.$value.' '; } return trim($connStr); }
php
private function getConnectionString() { // supported keywords: https://www.postgresql.org/docs/9.6/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS $paramKeywords = [ 'host', 'hostaddr', 'port', 'dbname', 'user', 'password', 'connect_timeout', 'client_encoding', 'options', 'application_name', 'fallback_application_name', 'keepalives', 'keepalives_idle', 'keepalives_interval', 'keepalives_count', 'tty', // ignored 'sslmode', 'requiressl', // deprecated in favor of 'sslmode' 'sslcompression', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl', 'requirepeer', 'krbsrvname', //'gsslib', // rejected by php_pgsql 9.4.1 'service', ]; $paramKeywords = \array_flip($paramKeywords); $connStr = ''; foreach ($this->options as $key => $value) { $keyL = trim(strtolower($key)); if (!isset($paramKeywords[$keyL])) continue; // unknown keyword if (is_array($value)) { if ($keyL != 'options') continue; // "options" is the only allowed keyword with nested settings // split regular connection options and session variables if (isset($value[''])) { $this->options[$key] = $value['']; unset($value['']); $this->sessionVars = $value; $value = $this->options[$key]; // the root value goes into the connection string } else { unset($this->options[$key]); $this->sessionVars = $value; continue; // "options" has only session vars and no root value [""] } } if (!strlen($value)) { $value = "''"; } else { $value = str_replace(['\\', "'"], ['\\\\', "\'"], $value); if (strContains($value, ' ')) $value = "'".$value."'"; } $connStr .= $key.'='.$value.' '; } return trim($connStr); }
[ "private", "function", "getConnectionString", "(", ")", "{", "// supported keywords: https://www.postgresql.org/docs/9.6/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS", "$", "paramKeywords", "=", "[", "'host'", ",", "'hostaddr'", ",", "'port'", ",", "'dbname'", ",", "'user'", ",", "'password'", ",", "'connect_timeout'", ",", "'client_encoding'", ",", "'options'", ",", "'application_name'", ",", "'fallback_application_name'", ",", "'keepalives'", ",", "'keepalives_idle'", ",", "'keepalives_interval'", ",", "'keepalives_count'", ",", "'tty'", ",", "// ignored", "'sslmode'", ",", "'requiressl'", ",", "// deprecated in favor of 'sslmode'", "'sslcompression'", ",", "'sslcert'", ",", "'sslkey'", ",", "'sslrootcert'", ",", "'sslcrl'", ",", "'requirepeer'", ",", "'krbsrvname'", ",", "//'gsslib', // rejected by php_pgsql 9.4.1", "'service'", ",", "]", ";", "$", "paramKeywords", "=", "\\", "array_flip", "(", "$", "paramKeywords", ")", ";", "$", "connStr", "=", "''", ";", "foreach", "(", "$", "this", "->", "options", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "keyL", "=", "trim", "(", "strtolower", "(", "$", "key", ")", ")", ";", "if", "(", "!", "isset", "(", "$", "paramKeywords", "[", "$", "keyL", "]", ")", ")", "continue", ";", "// unknown keyword", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "if", "(", "$", "keyL", "!=", "'options'", ")", "continue", ";", "// \"options\" is the only allowed keyword with nested settings", "// split regular connection options and session variables", "if", "(", "isset", "(", "$", "value", "[", "''", "]", ")", ")", "{", "$", "this", "->", "options", "[", "$", "key", "]", "=", "$", "value", "[", "''", "]", ";", "unset", "(", "$", "value", "[", "''", "]", ")", ";", "$", "this", "->", "sessionVars", "=", "$", "value", ";", "$", "value", "=", "$", "this", "->", "options", "[", "$", "key", "]", ";", "// the root value goes into the connection string", "}", "else", "{", "unset", "(", "$", "this", "->", "options", "[", "$", "key", "]", ")", ";", "$", "this", "->", "sessionVars", "=", "$", "value", ";", "continue", ";", "// \"options\" has only session vars and no root value [\"\"]", "}", "}", "if", "(", "!", "strlen", "(", "$", "value", ")", ")", "{", "$", "value", "=", "\"''\"", ";", "}", "else", "{", "$", "value", "=", "str_replace", "(", "[", "'\\\\'", ",", "\"'\"", "]", ",", "[", "'\\\\\\\\'", ",", "\"\\'\"", "]", ",", "$", "value", ")", ";", "if", "(", "strContains", "(", "$", "value", ",", "' '", ")", ")", "$", "value", "=", "\"'\"", ".", "$", "value", ".", "\"'\"", ";", "}", "$", "connStr", ".=", "$", "key", ".", "'='", ".", "$", "value", ".", "' '", ";", "}", "return", "trim", "(", "$", "connStr", ")", ";", "}" ]
Resolve and return the PostgreSQL connection string from the passed connection options. @return string
[ "Resolve", "and", "return", "the", "PostgreSQL", "connection", "string", "from", "the", "passed", "connection", "options", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/pgsql/PostgresConnector.php#L112-L179
29,178
rosasurfer/ministruts
src/db/pgsql/PostgresConnector.php
PostgresConnector.getConnectionDescription
protected function getConnectionDescription() { $options = $this->options; if (is_resource($this->hConnection)) { $host = pg_host($this->hConnection); $port = pg_port($this->hConnection); $db = pg_dbname($this->hConnection); $path = $this->getSchemaSearchPath(); $description = $host.':'.$port.'/'.$db.' (schema search path: '.$path.')'; } else { if (isset($options['hostaddr'])) $host = $options['hostaddr']; else if (isset($options['host' ])) $host = $options['host' ]; else $host = ''; if (isset($options['port'])) $port = ':'.$options['port']; else $port = ''; if (isset($options['dbname'])) $db = $options['dbname']; else if (isset($options['user' ])) $db = $options['user' ]; else $db = ''; $description = $host.$port.'/'.$db; } return $description; }
php
protected function getConnectionDescription() { $options = $this->options; if (is_resource($this->hConnection)) { $host = pg_host($this->hConnection); $port = pg_port($this->hConnection); $db = pg_dbname($this->hConnection); $path = $this->getSchemaSearchPath(); $description = $host.':'.$port.'/'.$db.' (schema search path: '.$path.')'; } else { if (isset($options['hostaddr'])) $host = $options['hostaddr']; else if (isset($options['host' ])) $host = $options['host' ]; else $host = ''; if (isset($options['port'])) $port = ':'.$options['port']; else $port = ''; if (isset($options['dbname'])) $db = $options['dbname']; else if (isset($options['user' ])) $db = $options['user' ]; else $db = ''; $description = $host.$port.'/'.$db; } return $description; }
[ "protected", "function", "getConnectionDescription", "(", ")", "{", "$", "options", "=", "$", "this", "->", "options", ";", "if", "(", "is_resource", "(", "$", "this", "->", "hConnection", ")", ")", "{", "$", "host", "=", "pg_host", "(", "$", "this", "->", "hConnection", ")", ";", "$", "port", "=", "pg_port", "(", "$", "this", "->", "hConnection", ")", ";", "$", "db", "=", "pg_dbname", "(", "$", "this", "->", "hConnection", ")", ";", "$", "path", "=", "$", "this", "->", "getSchemaSearchPath", "(", ")", ";", "$", "description", "=", "$", "host", ".", "':'", ".", "$", "port", ".", "'/'", ".", "$", "db", ".", "' (schema search path: '", ".", "$", "path", ".", "')'", ";", "}", "else", "{", "if", "(", "isset", "(", "$", "options", "[", "'hostaddr'", "]", ")", ")", "$", "host", "=", "$", "options", "[", "'hostaddr'", "]", ";", "else", "if", "(", "isset", "(", "$", "options", "[", "'host'", "]", ")", ")", "$", "host", "=", "$", "options", "[", "'host'", "]", ";", "else", "$", "host", "=", "''", ";", "if", "(", "isset", "(", "$", "options", "[", "'port'", "]", ")", ")", "$", "port", "=", "':'", ".", "$", "options", "[", "'port'", "]", ";", "else", "$", "port", "=", "''", ";", "if", "(", "isset", "(", "$", "options", "[", "'dbname'", "]", ")", ")", "$", "db", "=", "$", "options", "[", "'dbname'", "]", ";", "else", "if", "(", "isset", "(", "$", "options", "[", "'user'", "]", ")", ")", "$", "db", "=", "$", "options", "[", "'user'", "]", ";", "else", "$", "db", "=", "''", ";", "$", "description", "=", "$", "host", ".", "$", "port", ".", "'/'", ".", "$", "db", ";", "}", "return", "$", "description", ";", "}" ]
Return a textual description of the database connection options. @return string
[ "Return", "a", "textual", "description", "of", "the", "database", "connection", "options", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/pgsql/PostgresConnector.php#L187-L212
29,179
rosasurfer/ministruts
src/db/pgsql/PostgresConnector.php
PostgresConnector.getSchemaSearchPath
protected function getSchemaSearchPath() { $options = $this->options; $path = null; while ($this->hConnection) { try { $result = pg_query($this->hConnection, 'show search_path'); $row = pg_fetch_array($result, null, PGSQL_NUM); $path = $row[0]; if (strContains($path, '"$user"') && isset($options['user'])) { $path = str_replace('"$user"', $options['user'], $path); } break; } catch (\Exception $ex) { if (strContainsI($ex->getMessage(), 'current transaction is aborted, commands ignored until end of transaction block')) { if ($this->transactionLevel > 0) { $this->transactionLevel = 1; // immediately skip nested transactions $this->rollback(); continue; } } throw $ex; } } return $path; }
php
protected function getSchemaSearchPath() { $options = $this->options; $path = null; while ($this->hConnection) { try { $result = pg_query($this->hConnection, 'show search_path'); $row = pg_fetch_array($result, null, PGSQL_NUM); $path = $row[0]; if (strContains($path, '"$user"') && isset($options['user'])) { $path = str_replace('"$user"', $options['user'], $path); } break; } catch (\Exception $ex) { if (strContainsI($ex->getMessage(), 'current transaction is aborted, commands ignored until end of transaction block')) { if ($this->transactionLevel > 0) { $this->transactionLevel = 1; // immediately skip nested transactions $this->rollback(); continue; } } throw $ex; } } return $path; }
[ "protected", "function", "getSchemaSearchPath", "(", ")", "{", "$", "options", "=", "$", "this", "->", "options", ";", "$", "path", "=", "null", ";", "while", "(", "$", "this", "->", "hConnection", ")", "{", "try", "{", "$", "result", "=", "pg_query", "(", "$", "this", "->", "hConnection", ",", "'show search_path'", ")", ";", "$", "row", "=", "pg_fetch_array", "(", "$", "result", ",", "null", ",", "PGSQL_NUM", ")", ";", "$", "path", "=", "$", "row", "[", "0", "]", ";", "if", "(", "strContains", "(", "$", "path", ",", "'\"$user\"'", ")", "&&", "isset", "(", "$", "options", "[", "'user'", "]", ")", ")", "{", "$", "path", "=", "str_replace", "(", "'\"$user\"'", ",", "$", "options", "[", "'user'", "]", ",", "$", "path", ")", ";", "}", "break", ";", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "if", "(", "strContainsI", "(", "$", "ex", "->", "getMessage", "(", ")", ",", "'current transaction is aborted, commands ignored until end of transaction block'", ")", ")", "{", "if", "(", "$", "this", "->", "transactionLevel", ">", "0", ")", "{", "$", "this", "->", "transactionLevel", "=", "1", ";", "// immediately skip nested transactions", "$", "this", "->", "rollback", "(", ")", ";", "continue", ";", "}", "}", "throw", "$", "ex", ";", "}", "}", "return", "$", "path", ";", "}" ]
Return the database's current schema search path. @return string|null - schema search path or NULL in case of errors
[ "Return", "the", "database", "s", "current", "schema", "search", "path", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/pgsql/PostgresConnector.php#L220-L247
29,180
rosasurfer/ministruts
src/db/pgsql/PostgresConnector.php
PostgresConnector.fixUtf8Encoding
private function fixUtf8Encoding($value) { $encoding = mb_detect_encoding($value, null, true); if ($encoding!='ASCII' && $encoding!='UTF-8') $value = utf8_encode($value); return $value; }
php
private function fixUtf8Encoding($value) { $encoding = mb_detect_encoding($value, null, true); if ($encoding!='ASCII' && $encoding!='UTF-8') $value = utf8_encode($value); return $value; }
[ "private", "function", "fixUtf8Encoding", "(", "$", "value", ")", "{", "$", "encoding", "=", "mb_detect_encoding", "(", "$", "value", ",", "null", ",", "true", ")", ";", "if", "(", "$", "encoding", "!=", "'ASCII'", "&&", "$", "encoding", "!=", "'UTF-8'", ")", "$", "value", "=", "utf8_encode", "(", "$", "value", ")", ";", "return", "$", "value", ";", "}" ]
Fix the encoding of a potentially non-UTF-8 encoded value. @param string $value - potentially non-UTF-8 encoded value @return string - UTF-8 encoded value @see https://www.drupal.org/node/434802
[ "Fix", "the", "encoding", "of", "a", "potentially", "non", "-", "UTF", "-", "8", "encoded", "value", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/pgsql/PostgresConnector.php#L393-L398
29,181
rosasurfer/ministruts
src/ministruts/Response.php
Response.setStatus
public function setStatus($status) { if (!is_int($status)) throw new IllegalTypeException('Illegal type of parameter $status: '.gettype($status)); if ($status < 1) throw new InvalidArgumentException('Invalid argument $status: '.$status); $this->status = $status; return $this; }
php
public function setStatus($status) { if (!is_int($status)) throw new IllegalTypeException('Illegal type of parameter $status: '.gettype($status)); if ($status < 1) throw new InvalidArgumentException('Invalid argument $status: '.$status); $this->status = $status; return $this; }
[ "public", "function", "setStatus", "(", "$", "status", ")", "{", "if", "(", "!", "is_int", "(", "$", "status", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $status: '", ".", "gettype", "(", "$", "status", ")", ")", ";", "if", "(", "$", "status", "<", "1", ")", "throw", "new", "InvalidArgumentException", "(", "'Invalid argument $status: '", ".", "$", "status", ")", ";", "$", "this", "->", "status", "=", "$", "status", ";", "return", "$", "this", ";", "}" ]
Set the response status code. @param int $status - HTTP response status @return $this
[ "Set", "the", "response", "status", "code", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Response.php#L60-L66
29,182
rosasurfer/ministruts
src/util/Windows.php
Windows.errorToString
public static function errorToString($error) { if (!is_int($error)) throw new IllegalTypeException('Illegal type of parameter $error: '.gettype($error)); if (key_exists($error, self::$win32Errors)) return self::$win32Errors[$error][0]; return (string) $error; }
php
public static function errorToString($error) { if (!is_int($error)) throw new IllegalTypeException('Illegal type of parameter $error: '.gettype($error)); if (key_exists($error, self::$win32Errors)) return self::$win32Errors[$error][0]; return (string) $error; }
[ "public", "static", "function", "errorToString", "(", "$", "error", ")", "{", "if", "(", "!", "is_int", "(", "$", "error", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $error: '", ".", "gettype", "(", "$", "error", ")", ")", ";", "if", "(", "key_exists", "(", "$", "error", ",", "self", "::", "$", "win32Errors", ")", ")", "return", "self", "::", "$", "win32Errors", "[", "$", "error", "]", "[", "0", "]", ";", "return", "(", "string", ")", "$", "error", ";", "}" ]
Return a human-readable version of a Win32 error code. @param int $error @return string
[ "Return", "a", "human", "-", "readable", "version", "of", "a", "Win32", "error", "code", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/util/Windows.php#L34-L40
29,183
deArcane/framework
src/View/View.php
View.only
public function only(...$layouts){ if( !in_array(app::$response->layout->_name, $layouts) ){ (new Report('Runtime/CantBeUsedInThisLayout'))->stop(); } }
php
public function only(...$layouts){ if( !in_array(app::$response->layout->_name, $layouts) ){ (new Report('Runtime/CantBeUsedInThisLayout'))->stop(); } }
[ "public", "function", "only", "(", "...", "$", "layouts", ")", "{", "if", "(", "!", "in_array", "(", "app", "::", "$", "response", "->", "layout", "->", "_name", ",", "$", "layouts", ")", ")", "{", "(", "new", "Report", "(", "'Runtime/CantBeUsedInThisLayout'", ")", ")", "->", "stop", "(", ")", ";", "}", "}" ]
Access to module through app.
[ "Access", "to", "module", "through", "app", "." ]
468da43678119f8c9e3f67183b5bec727c436404
https://github.com/deArcane/framework/blob/468da43678119f8c9e3f67183b5bec727c436404/src/View/View.php#L45-L49
29,184
rosasurfer/ministruts
src/ministruts/ActionForward.php
ActionForward.setName
public function setName($name) { if (!is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name)); if (!strlen($name)) throw new InvalidArgumentException('Invalid argument $name: '.$name); $this->name = $name; return $this; }
php
public function setName($name) { if (!is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name)); if (!strlen($name)) throw new InvalidArgumentException('Invalid argument $name: '.$name); $this->name = $name; return $this; }
[ "public", "function", "setName", "(", "$", "name", ")", "{", "if", "(", "!", "is_string", "(", "$", "name", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $name: '", ".", "gettype", "(", "$", "name", ")", ")", ";", "if", "(", "!", "strlen", "(", "$", "name", ")", ")", "throw", "new", "InvalidArgumentException", "(", "'Invalid argument $name: '", ".", "$", "name", ")", ";", "$", "this", "->", "name", "=", "$", "name", ";", "return", "$", "this", ";", "}" ]
Set the forward's name. @param string $name @return $this
[ "Set", "the", "forward", "s", "name", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/ActionForward.php#L121-L127
29,185
rosasurfer/ministruts
src/ministruts/ActionForward.php
ActionForward.setPath
public function setPath($path) { if (!is_string($path)) throw new IllegalTypeException('Illegal type of parameter $path: '.gettype($path)); if (!strlen($path)) throw new InvalidArgumentException('Invalid argument $path: '.$path); $this->path = $path; return $this; }
php
public function setPath($path) { if (!is_string($path)) throw new IllegalTypeException('Illegal type of parameter $path: '.gettype($path)); if (!strlen($path)) throw new InvalidArgumentException('Invalid argument $path: '.$path); $this->path = $path; return $this; }
[ "public", "function", "setPath", "(", "$", "path", ")", "{", "if", "(", "!", "is_string", "(", "$", "path", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $path: '", ".", "gettype", "(", "$", "path", ")", ")", ";", "if", "(", "!", "strlen", "(", "$", "path", ")", ")", "throw", "new", "InvalidArgumentException", "(", "'Invalid argument $path: '", ".", "$", "path", ")", ";", "$", "this", "->", "path", "=", "$", "path", ";", "return", "$", "this", ";", "}" ]
Set the forward's resource path. @param string $path @return $this
[ "Set", "the", "forward", "s", "resource", "path", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/ActionForward.php#L137-L143
29,186
rosasurfer/ministruts
src/ministruts/ActionForward.php
ActionForward.setRedirect
public function setRedirect($redirect) { if (!is_bool($redirect)) throw new IllegalTypeException('Illegal type of parameter $redirect: '.gettype($redirect)); $this->redirect = $redirect; return $this; }
php
public function setRedirect($redirect) { if (!is_bool($redirect)) throw new IllegalTypeException('Illegal type of parameter $redirect: '.gettype($redirect)); $this->redirect = $redirect; return $this; }
[ "public", "function", "setRedirect", "(", "$", "redirect", ")", "{", "if", "(", "!", "is_bool", "(", "$", "redirect", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $redirect: '", ".", "gettype", "(", "$", "redirect", ")", ")", ";", "$", "this", "->", "redirect", "=", "$", "redirect", ";", "return", "$", "this", ";", "}" ]
Set the forward's redirect status. @param bool $redirect @return $this
[ "Set", "the", "forward", "s", "redirect", "status", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/ActionForward.php#L169-L174
29,187
rosasurfer/ministruts
src/ministruts/ActionForward.php
ActionForward.setRedirectType
public function setRedirectType($type) { if (!is_int($type)) throw new IllegalTypeException('Illegal type of parameter $type: '.gettype($type)); $this->redirectType = $type; return $this; }
php
public function setRedirectType($type) { if (!is_int($type)) throw new IllegalTypeException('Illegal type of parameter $type: '.gettype($type)); $this->redirectType = $type; return $this; }
[ "public", "function", "setRedirectType", "(", "$", "type", ")", "{", "if", "(", "!", "is_int", "(", "$", "type", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $type: '", ".", "gettype", "(", "$", "type", ")", ")", ";", "$", "this", "->", "redirectType", "=", "$", "type", ";", "return", "$", "this", ";", "}" ]
Set the forward's redirect type. @param int $type - HTTP status type @return $this
[ "Set", "the", "forward", "s", "redirect", "type", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/ActionForward.php#L184-L189
29,188
rosasurfer/ministruts
src/ministruts/ActionForward.php
ActionForward.addQueryData
public function addQueryData($key, $value) { // TODO: freeze the instance after configuration and automatically call copy() if (!is_string($key)) throw new IllegalTypeException('Illegal type of parameter $key: '.gettype($key)); if (!isset($value)) $value = ''; elseif (is_bool($value)) $value = (int) $value; elseif (!is_scalar($value)) throw new IllegalTypeException('Illegal type of parameter $value: '.gettype($value)); $value = (string) $value; // TODO: extend to process multiple parameters at once $path = $this->getPath(); $separator = (strpos($path, '?')!==false) ? '&' : '?'; $this->setPath($path.$separator.$key.'='.str_replace([' ','#','&'], ['%20','%23','%26'], $value)); return $this; }
php
public function addQueryData($key, $value) { // TODO: freeze the instance after configuration and automatically call copy() if (!is_string($key)) throw new IllegalTypeException('Illegal type of parameter $key: '.gettype($key)); if (!isset($value)) $value = ''; elseif (is_bool($value)) $value = (int) $value; elseif (!is_scalar($value)) throw new IllegalTypeException('Illegal type of parameter $value: '.gettype($value)); $value = (string) $value; // TODO: extend to process multiple parameters at once $path = $this->getPath(); $separator = (strpos($path, '?')!==false) ? '&' : '?'; $this->setPath($path.$separator.$key.'='.str_replace([' ','#','&'], ['%20','%23','%26'], $value)); return $this; }
[ "public", "function", "addQueryData", "(", "$", "key", ",", "$", "value", ")", "{", "// TODO: freeze the instance after configuration and automatically call copy()", "if", "(", "!", "is_string", "(", "$", "key", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $key: '", ".", "gettype", "(", "$", "key", ")", ")", ";", "if", "(", "!", "isset", "(", "$", "value", ")", ")", "$", "value", "=", "''", ";", "elseif", "(", "is_bool", "(", "$", "value", ")", ")", "$", "value", "=", "(", "int", ")", "$", "value", ";", "elseif", "(", "!", "is_scalar", "(", "$", "value", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $value: '", ".", "gettype", "(", "$", "value", ")", ")", ";", "$", "value", "=", "(", "string", ")", "$", "value", ";", "// TODO: extend to process multiple parameters at once", "$", "path", "=", "$", "this", "->", "getPath", "(", ")", ";", "$", "separator", "=", "(", "strpos", "(", "$", "path", ",", "'?'", ")", "!==", "false", ")", "?", "'&'", ":", "'?'", ";", "$", "this", "->", "setPath", "(", "$", "path", ".", "$", "separator", ".", "$", "key", ".", "'='", ".", "str_replace", "(", "[", "' '", ",", "'#'", ",", "'&'", "]", ",", "[", "'%20'", ",", "'%23'", ",", "'%26'", "]", ",", "$", "value", ")", ")", ";", "return", "$", "this", ";", "}" ]
Add a query parameter to the forward's URL. @param string $key - parameter name @param scalar $value - parameter value @return $this
[ "Add", "a", "query", "parameter", "to", "the", "forward", "s", "URL", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/ActionForward.php#L200-L216
29,189
rosasurfer/ministruts
src/ministruts/ActionForward.php
ActionForward.setHash
public function setHash($value) { // TODO: freeze the instance after configuration and automatically call copy() if (isset($value)) { if (!is_scalar($value)) throw new IllegalTypeException('Illegal type of parameter $value: '.gettype($value)); if (is_bool($value)) $value = (int) $value; } $value = (string) $value; $path = $this->getPath(); $this->setPath(strLeftTo($path, '#', $count=1, $includeLimiter=false, $onNotFound=$path).'#'.$value); return $this; }
php
public function setHash($value) { // TODO: freeze the instance after configuration and automatically call copy() if (isset($value)) { if (!is_scalar($value)) throw new IllegalTypeException('Illegal type of parameter $value: '.gettype($value)); if (is_bool($value)) $value = (int) $value; } $value = (string) $value; $path = $this->getPath(); $this->setPath(strLeftTo($path, '#', $count=1, $includeLimiter=false, $onNotFound=$path).'#'.$value); return $this; }
[ "public", "function", "setHash", "(", "$", "value", ")", "{", "// TODO: freeze the instance after configuration and automatically call copy()", "if", "(", "isset", "(", "$", "value", ")", ")", "{", "if", "(", "!", "is_scalar", "(", "$", "value", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $value: '", ".", "gettype", "(", "$", "value", ")", ")", ";", "if", "(", "is_bool", "(", "$", "value", ")", ")", "$", "value", "=", "(", "int", ")", "$", "value", ";", "}", "$", "value", "=", "(", "string", ")", "$", "value", ";", "$", "path", "=", "$", "this", "->", "getPath", "(", ")", ";", "$", "this", "->", "setPath", "(", "strLeftTo", "(", "$", "path", ",", "'#'", ",", "$", "count", "=", "1", ",", "$", "includeLimiter", "=", "false", ",", "$", "onNotFound", "=", "$", "path", ")", ".", "'#'", ".", "$", "value", ")", ";", "return", "$", "this", ";", "}" ]
Set the hash fragment of the forward's URL. @param scalar $value - hash value @return $this
[ "Set", "the", "hash", "fragment", "of", "the", "forward", "s", "URL", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/ActionForward.php#L226-L239
29,190
timble/kodekit
code/model/behavior/searchable.php
ModelBehaviorSearchable._buildQuery
protected function _buildQuery(ModelContextInterface $context) { $model = $context->getSubject(); if ($model instanceof ModelDatabase && !$context->state->isUnique()) { $state = $context->state; $search = $state->search; if ($search) { $search_column = null; $columns = array_keys($this->getTable()->getColumns()); // Parse $state->search for possible column prefix if (preg_match('#^([a-z0-9\-_]+)\s*:\s*(.+)\s*$#i', $search, $matches)) { if (in_array($matches[1], $this->_columns) || $matches[1] === 'id') { $search_column = $matches[1]; $search = $matches[2]; } } // Search in the form of id:NUM if ($search_column === 'id') { $context->query->where('(tbl.' . $this->getTable()->getIdentityColumn() . ' = :search)') ->bind(array('search' => $search)); } else { $conditions = array(); foreach ($this->_columns as $column) { if (in_array($column, $columns) && (!$search_column || $column === $search_column)) { $conditions[] = 'tbl.' . $column . ' LIKE :search'; } } if ($conditions) { $context->query->where('(' . implode(' OR ', $conditions) . ')') ->bind(array('search' => '%' . $search . '%')); } } } } }
php
protected function _buildQuery(ModelContextInterface $context) { $model = $context->getSubject(); if ($model instanceof ModelDatabase && !$context->state->isUnique()) { $state = $context->state; $search = $state->search; if ($search) { $search_column = null; $columns = array_keys($this->getTable()->getColumns()); // Parse $state->search for possible column prefix if (preg_match('#^([a-z0-9\-_]+)\s*:\s*(.+)\s*$#i', $search, $matches)) { if (in_array($matches[1], $this->_columns) || $matches[1] === 'id') { $search_column = $matches[1]; $search = $matches[2]; } } // Search in the form of id:NUM if ($search_column === 'id') { $context->query->where('(tbl.' . $this->getTable()->getIdentityColumn() . ' = :search)') ->bind(array('search' => $search)); } else { $conditions = array(); foreach ($this->_columns as $column) { if (in_array($column, $columns) && (!$search_column || $column === $search_column)) { $conditions[] = 'tbl.' . $column . ' LIKE :search'; } } if ($conditions) { $context->query->where('(' . implode(' OR ', $conditions) . ')') ->bind(array('search' => '%' . $search . '%')); } } } } }
[ "protected", "function", "_buildQuery", "(", "ModelContextInterface", "$", "context", ")", "{", "$", "model", "=", "$", "context", "->", "getSubject", "(", ")", ";", "if", "(", "$", "model", "instanceof", "ModelDatabase", "&&", "!", "$", "context", "->", "state", "->", "isUnique", "(", ")", ")", "{", "$", "state", "=", "$", "context", "->", "state", ";", "$", "search", "=", "$", "state", "->", "search", ";", "if", "(", "$", "search", ")", "{", "$", "search_column", "=", "null", ";", "$", "columns", "=", "array_keys", "(", "$", "this", "->", "getTable", "(", ")", "->", "getColumns", "(", ")", ")", ";", "// Parse $state->search for possible column prefix", "if", "(", "preg_match", "(", "'#^([a-z0-9\\-_]+)\\s*:\\s*(.+)\\s*$#i'", ",", "$", "search", ",", "$", "matches", ")", ")", "{", "if", "(", "in_array", "(", "$", "matches", "[", "1", "]", ",", "$", "this", "->", "_columns", ")", "||", "$", "matches", "[", "1", "]", "===", "'id'", ")", "{", "$", "search_column", "=", "$", "matches", "[", "1", "]", ";", "$", "search", "=", "$", "matches", "[", "2", "]", ";", "}", "}", "// Search in the form of id:NUM", "if", "(", "$", "search_column", "===", "'id'", ")", "{", "$", "context", "->", "query", "->", "where", "(", "'(tbl.'", ".", "$", "this", "->", "getTable", "(", ")", "->", "getIdentityColumn", "(", ")", ".", "' = :search)'", ")", "->", "bind", "(", "array", "(", "'search'", "=>", "$", "search", ")", ")", ";", "}", "else", "{", "$", "conditions", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "_columns", "as", "$", "column", ")", "{", "if", "(", "in_array", "(", "$", "column", ",", "$", "columns", ")", "&&", "(", "!", "$", "search_column", "||", "$", "column", "===", "$", "search_column", ")", ")", "{", "$", "conditions", "[", "]", "=", "'tbl.'", ".", "$", "column", ".", "' LIKE :search'", ";", "}", "}", "if", "(", "$", "conditions", ")", "{", "$", "context", "->", "query", "->", "where", "(", "'('", ".", "implode", "(", "' OR '", ",", "$", "conditions", ")", ".", "')'", ")", "->", "bind", "(", "array", "(", "'search'", "=>", "'%'", ".", "$", "search", ".", "'%'", ")", ")", ";", "}", "}", "}", "}", "}" ]
Add search query @param ModelContextInterface $context A model context object @return void
[ "Add", "search", "query" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/model/behavior/searchable.php#L82-L124
29,191
TypiCMS/Users
src/Models/User.php
User.syncPermissions
public function syncPermissions(array $permissions) { $permissionIds = []; foreach ($permissions as $name) { $permissionIds[] = app(Permission::class)->firstOrCreate(['name' => $name])->id; } $this->permissions()->sync($permissionIds); }
php
public function syncPermissions(array $permissions) { $permissionIds = []; foreach ($permissions as $name) { $permissionIds[] = app(Permission::class)->firstOrCreate(['name' => $name])->id; } $this->permissions()->sync($permissionIds); }
[ "public", "function", "syncPermissions", "(", "array", "$", "permissions", ")", "{", "$", "permissionIds", "=", "[", "]", ";", "foreach", "(", "$", "permissions", "as", "$", "name", ")", "{", "$", "permissionIds", "[", "]", "=", "app", "(", "Permission", "::", "class", ")", "->", "firstOrCreate", "(", "[", "'name'", "=>", "$", "name", "]", ")", "->", "id", ";", "}", "$", "this", "->", "permissions", "(", ")", "->", "sync", "(", "$", "permissionIds", ")", ";", "}" ]
Sync permissions. @param array $permissions @return null
[ "Sync", "permissions", "." ]
8779444853df6d102a8e4b4b319f7519b93c9a23
https://github.com/TypiCMS/Users/blob/8779444853df6d102a8e4b4b319f7519b93c9a23/src/Models/User.php#L114-L121
29,192
timble/kodekit
code/http/url/url.php
HttpUrl.setUrl
public function setUrl($url) { if (!is_string($url) && !is_array($url) && !(is_object($url) && method_exists($url, '__toString'))) { throw new \UnexpectedValueException( 'The url must be a array as returned by parse_url() a string or object implementing __toString(), "'.gettype($url).'" given.' ); } if(!is_array($url)) { $parts = parse_url((string) $url); } else { $parts = $url; } if (is_array($parts)) { foreach ($parts as $key => $value) { $this->$key = $value; } } return $this; }
php
public function setUrl($url) { if (!is_string($url) && !is_array($url) && !(is_object($url) && method_exists($url, '__toString'))) { throw new \UnexpectedValueException( 'The url must be a array as returned by parse_url() a string or object implementing __toString(), "'.gettype($url).'" given.' ); } if(!is_array($url)) { $parts = parse_url((string) $url); } else { $parts = $url; } if (is_array($parts)) { foreach ($parts as $key => $value) { $this->$key = $value; } } return $this; }
[ "public", "function", "setUrl", "(", "$", "url", ")", "{", "if", "(", "!", "is_string", "(", "$", "url", ")", "&&", "!", "is_array", "(", "$", "url", ")", "&&", "!", "(", "is_object", "(", "$", "url", ")", "&&", "method_exists", "(", "$", "url", ",", "'__toString'", ")", ")", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "'The url must be a array as returned by parse_url() a string or object implementing __toString(), \"'", ".", "gettype", "(", "$", "url", ")", ".", "'\" given.'", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "url", ")", ")", "{", "$", "parts", "=", "parse_url", "(", "(", "string", ")", "$", "url", ")", ";", "}", "else", "{", "$", "parts", "=", "$", "url", ";", "}", "if", "(", "is_array", "(", "$", "parts", ")", ")", "{", "foreach", "(", "$", "parts", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "$", "key", "=", "$", "value", ";", "}", "}", "return", "$", "this", ";", "}" ]
Parse the url from a string Partial URLs are also accepted. setUrl() tries its best to parse them correctly. Function also accepts an associative array like parse_url returns. @param string|array $url Part(s) of an URL in form of a string or associative array like parse_url() returns @throws \UnexpectedValueException If the url is not an array a string or cannot be casted to one. @return HttpUrl @see parse_url()
[ "Parse", "the", "url", "from", "a", "string" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/http/url/url.php#L218-L240
29,193
timble/kodekit
code/http/url/url.php
HttpUrl.toArray
public function toArray($parts = self::FULL, $escape = null) { $result = array(); $escape = isset($escape) ? (bool) $escape : $this->isEscaped(); if (($parts & self::SCHEME) && !empty($this->scheme)) { $result['scheme'] = $this->scheme; } if (($parts & self::USER) && !empty($this->user)) { $result['user'] = $this->user; } if (($parts & self::PASS) && !empty($this->pass)) { $result['user'] = $this->pass; } if (($parts & self::PORT) && !empty($this->port)) { $result['port'] = $this->port; } if (($parts & self::HOST) && !empty($this->host)) { $result['host'] = $this->host; } if (($parts & self::PATH) && !empty($this->_path)) { $result['path'] = $this->_path; } if (($parts & self::QUERY) && !empty($this->_query)) { $result['query'] = $this->getQuery(false, $escape); } if (($parts & self::FRAGMENT) && trim($this->fragment) !== '') { $result['fragment'] = $this->fragment; } return $result; }
php
public function toArray($parts = self::FULL, $escape = null) { $result = array(); $escape = isset($escape) ? (bool) $escape : $this->isEscaped(); if (($parts & self::SCHEME) && !empty($this->scheme)) { $result['scheme'] = $this->scheme; } if (($parts & self::USER) && !empty($this->user)) { $result['user'] = $this->user; } if (($parts & self::PASS) && !empty($this->pass)) { $result['user'] = $this->pass; } if (($parts & self::PORT) && !empty($this->port)) { $result['port'] = $this->port; } if (($parts & self::HOST) && !empty($this->host)) { $result['host'] = $this->host; } if (($parts & self::PATH) && !empty($this->_path)) { $result['path'] = $this->_path; } if (($parts & self::QUERY) && !empty($this->_query)) { $result['query'] = $this->getQuery(false, $escape); } if (($parts & self::FRAGMENT) && trim($this->fragment) !== '') { $result['fragment'] = $this->fragment; } return $result; }
[ "public", "function", "toArray", "(", "$", "parts", "=", "self", "::", "FULL", ",", "$", "escape", "=", "null", ")", "{", "$", "result", "=", "array", "(", ")", ";", "$", "escape", "=", "isset", "(", "$", "escape", ")", "?", "(", "bool", ")", "$", "escape", ":", "$", "this", "->", "isEscaped", "(", ")", ";", "if", "(", "(", "$", "parts", "&", "self", "::", "SCHEME", ")", "&&", "!", "empty", "(", "$", "this", "->", "scheme", ")", ")", "{", "$", "result", "[", "'scheme'", "]", "=", "$", "this", "->", "scheme", ";", "}", "if", "(", "(", "$", "parts", "&", "self", "::", "USER", ")", "&&", "!", "empty", "(", "$", "this", "->", "user", ")", ")", "{", "$", "result", "[", "'user'", "]", "=", "$", "this", "->", "user", ";", "}", "if", "(", "(", "$", "parts", "&", "self", "::", "PASS", ")", "&&", "!", "empty", "(", "$", "this", "->", "pass", ")", ")", "{", "$", "result", "[", "'user'", "]", "=", "$", "this", "->", "pass", ";", "}", "if", "(", "(", "$", "parts", "&", "self", "::", "PORT", ")", "&&", "!", "empty", "(", "$", "this", "->", "port", ")", ")", "{", "$", "result", "[", "'port'", "]", "=", "$", "this", "->", "port", ";", "}", "if", "(", "(", "$", "parts", "&", "self", "::", "HOST", ")", "&&", "!", "empty", "(", "$", "this", "->", "host", ")", ")", "{", "$", "result", "[", "'host'", "]", "=", "$", "this", "->", "host", ";", "}", "if", "(", "(", "$", "parts", "&", "self", "::", "PATH", ")", "&&", "!", "empty", "(", "$", "this", "->", "_path", ")", ")", "{", "$", "result", "[", "'path'", "]", "=", "$", "this", "->", "_path", ";", "}", "if", "(", "(", "$", "parts", "&", "self", "::", "QUERY", ")", "&&", "!", "empty", "(", "$", "this", "->", "_query", ")", ")", "{", "$", "result", "[", "'query'", "]", "=", "$", "this", "->", "getQuery", "(", "false", ",", "$", "escape", ")", ";", "}", "if", "(", "(", "$", "parts", "&", "self", "::", "FRAGMENT", ")", "&&", "trim", "(", "$", "this", "->", "fragment", ")", "!==", "''", ")", "{", "$", "result", "[", "'fragment'", "]", "=", "$", "this", "->", "fragment", ";", "}", "return", "$", "result", ";", "}" ]
Return the url components @param integer $parts A bitmask of binary or'ed HTTP_URL constants; FULL is the default @param boolean|null $escape If TRUE escapes '&' to '&amp;' for xml compliance. If NULL use the default. @return array Associative array like parse_url() returns. @see parse_url()
[ "Return", "the", "url", "components" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/http/url/url.php#L537-L575
29,194
timble/kodekit
code/http/url/url.php
HttpUrl.fromString
public static function fromString($url) { if (!is_string($url) && !(is_object($url) && method_exists($url, '__toString'))) { throw new \UnexpectedValueException( 'The url must be a string or object implementing __toString(), "'.gettype($url).'" given.' ); } $url = self::fromArray(parse_url((string) $url)); return $url; }
php
public static function fromString($url) { if (!is_string($url) && !(is_object($url) && method_exists($url, '__toString'))) { throw new \UnexpectedValueException( 'The url must be a string or object implementing __toString(), "'.gettype($url).'" given.' ); } $url = self::fromArray(parse_url((string) $url)); return $url; }
[ "public", "static", "function", "fromString", "(", "$", "url", ")", "{", "if", "(", "!", "is_string", "(", "$", "url", ")", "&&", "!", "(", "is_object", "(", "$", "url", ")", "&&", "method_exists", "(", "$", "url", ",", "'__toString'", ")", ")", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "'The url must be a string or object implementing __toString(), \"'", ".", "gettype", "(", "$", "url", ")", ".", "'\" given.'", ")", ";", "}", "$", "url", "=", "self", "::", "fromArray", "(", "parse_url", "(", "(", "string", ")", "$", "url", ")", ")", ";", "return", "$", "url", ";", "}" ]
Build the url from a string Partial URLs are also accepted. fromString tries its best to parse them correctly. @param string $url @throws \UnexpectedValueException If the url is not a string or cannot be casted to one. @return HttpUrl @see parse_url()
[ "Build", "the", "url", "from", "a", "string" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/http/url/url.php#L600-L611
29,195
timble/kodekit
code/controller/behavior/localizable.php
ControllerBehaviorLocalizable._beforeRender
protected function _beforeRender(ControllerContext $context) { $controller = $context->getSubject(); if (!$controller->isDispatched()) { $controller->loadLanguage(); } }
php
protected function _beforeRender(ControllerContext $context) { $controller = $context->getSubject(); if (!$controller->isDispatched()) { $controller->loadLanguage(); } }
[ "protected", "function", "_beforeRender", "(", "ControllerContext", "$", "context", ")", "{", "$", "controller", "=", "$", "context", "->", "getSubject", "(", ")", ";", "if", "(", "!", "$", "controller", "->", "isDispatched", "(", ")", ")", "{", "$", "controller", "->", "loadLanguage", "(", ")", ";", "}", "}" ]
Load the language if the controller has not been dispatched @param ControllerContext $context A controller context object @return void
[ "Load", "the", "language", "if", "the", "controller", "has", "not", "been", "dispatched" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/controller/behavior/localizable.php#L26-L33
29,196
timble/kodekit
code/controller/behavior/localizable.php
ControllerBehaviorLocalizable.loadLanguage
public function loadLanguage() { $package = $this->getIdentifier()->package; $domain = $this->getIdentifier()->domain; if($domain) { $url = 'com://'.$domain.'/'.$package; } else { $url = 'com:'.$package; } $this->getObject('translator')->load($url); }
php
public function loadLanguage() { $package = $this->getIdentifier()->package; $domain = $this->getIdentifier()->domain; if($domain) { $url = 'com://'.$domain.'/'.$package; } else { $url = 'com:'.$package; } $this->getObject('translator')->load($url); }
[ "public", "function", "loadLanguage", "(", ")", "{", "$", "package", "=", "$", "this", "->", "getIdentifier", "(", ")", "->", "package", ";", "$", "domain", "=", "$", "this", "->", "getIdentifier", "(", ")", "->", "domain", ";", "if", "(", "$", "domain", ")", "{", "$", "url", "=", "'com://'", ".", "$", "domain", ".", "'/'", ".", "$", "package", ";", "}", "else", "{", "$", "url", "=", "'com:'", ".", "$", "package", ";", "}", "$", "this", "->", "getObject", "(", "'translator'", ")", "->", "load", "(", "$", "url", ")", ";", "}" ]
Load the language @return void
[ "Load", "the", "language" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/controller/behavior/localizable.php#L54-L66
29,197
rosasurfer/ministruts
src/util/Date.php
Date.diffDays
public static function diffDays($start, $end) { if (!is_string($start)) throw new IllegalTypeException('Illegal type of parameter $start: '.gettype($start)); if (Validator::isDateTime($start) === false) throw new InvalidArgumentException('Invalid argument $start: "'.$start.'"'); if (!is_string($end)) throw new IllegalTypeException('Illegal type of parameter $end: '.gettype($end)); if (Validator::isDateTime($end) === false) throw new InvalidArgumentException('Invalid argument $end: "'.$end.'"'); $ts1 = strtotime($start.' GMT'); // ohne Angabe einer Zeitzone wird die lokale DST einkalkuliert $ts2 = strtotime($end.' GMT'); $diff = $ts2 - $ts1; if ($diff % DAYS) Logger::log('('.$ts2.'-'.$ts1.') % DAYS != 0: '.($diff%DAYS), L_WARN); return (int)($diff / DAYS); }
php
public static function diffDays($start, $end) { if (!is_string($start)) throw new IllegalTypeException('Illegal type of parameter $start: '.gettype($start)); if (Validator::isDateTime($start) === false) throw new InvalidArgumentException('Invalid argument $start: "'.$start.'"'); if (!is_string($end)) throw new IllegalTypeException('Illegal type of parameter $end: '.gettype($end)); if (Validator::isDateTime($end) === false) throw new InvalidArgumentException('Invalid argument $end: "'.$end.'"'); $ts1 = strtotime($start.' GMT'); // ohne Angabe einer Zeitzone wird die lokale DST einkalkuliert $ts2 = strtotime($end.' GMT'); $diff = $ts2 - $ts1; if ($diff % DAYS) Logger::log('('.$ts2.'-'.$ts1.') % DAYS != 0: '.($diff%DAYS), L_WARN); return (int)($diff / DAYS); }
[ "public", "static", "function", "diffDays", "(", "$", "start", ",", "$", "end", ")", "{", "if", "(", "!", "is_string", "(", "$", "start", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $start: '", ".", "gettype", "(", "$", "start", ")", ")", ";", "if", "(", "Validator", "::", "isDateTime", "(", "$", "start", ")", "===", "false", ")", "throw", "new", "InvalidArgumentException", "(", "'Invalid argument $start: \"'", ".", "$", "start", ".", "'\"'", ")", ";", "if", "(", "!", "is_string", "(", "$", "end", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $end: '", ".", "gettype", "(", "$", "end", ")", ")", ";", "if", "(", "Validator", "::", "isDateTime", "(", "$", "end", ")", "===", "false", ")", "throw", "new", "InvalidArgumentException", "(", "'Invalid argument $end: \"'", ".", "$", "end", ".", "'\"'", ")", ";", "$", "ts1", "=", "strtotime", "(", "$", "start", ".", "' GMT'", ")", ";", "// ohne Angabe einer Zeitzone wird die lokale DST einkalkuliert", "$", "ts2", "=", "strtotime", "(", "$", "end", ".", "' GMT'", ")", ";", "$", "diff", "=", "$", "ts2", "-", "$", "ts1", ";", "if", "(", "$", "diff", "%", "DAYS", ")", "Logger", "::", "log", "(", "'('", ".", "$", "ts2", ".", "'-'", ".", "$", "ts1", ".", "') % DAYS != 0: '", ".", "(", "$", "diff", "%", "DAYS", ")", ",", "L_WARN", ")", ";", "return", "(", "int", ")", "(", "$", "diff", "/", "DAYS", ")", ";", "}" ]
Berechnet die Anzahl von Tagen zwischen zwei Zeitpunkten. @param string $start - erster Zeitpunkt (Format: yyyy-mm-dd) @param string $end - zweiter Zeitpunkt (Format: yyyy-mm-dd) @return int - Tage
[ "Berechnet", "die", "Anzahl", "von", "Tagen", "zwischen", "zwei", "Zeitpunkten", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/util/Date.php#L27-L42
29,198
rosasurfer/ministruts
src/util/Date.php
Date.getDateRange
public static function getDateRange($startDate, $days) { if (!is_string($startDate)) throw new IllegalTypeException('Illegal type of parameter $startDate: '.gettype($startDate)); if (Validator::isDateTime($startDate) === false) throw new InvalidArgumentException('Invalid argument $startDate: "'.$startDate.'"'); if (!is_int($days)) throw new IllegalTypeException('Illegal type of parameter $days: '.gettype($days)); if ($days < 0) throw new InvalidArgumentException('Invalid argument $days: '.$days); $range = array(); $date = new DateTime($startDate); for ($i=0; $i < $days; ++$i) { $range[] = $date->format('Y-m-d'); $date->modify('+1 day'); } return $range; }
php
public static function getDateRange($startDate, $days) { if (!is_string($startDate)) throw new IllegalTypeException('Illegal type of parameter $startDate: '.gettype($startDate)); if (Validator::isDateTime($startDate) === false) throw new InvalidArgumentException('Invalid argument $startDate: "'.$startDate.'"'); if (!is_int($days)) throw new IllegalTypeException('Illegal type of parameter $days: '.gettype($days)); if ($days < 0) throw new InvalidArgumentException('Invalid argument $days: '.$days); $range = array(); $date = new DateTime($startDate); for ($i=0; $i < $days; ++$i) { $range[] = $date->format('Y-m-d'); $date->modify('+1 day'); } return $range; }
[ "public", "static", "function", "getDateRange", "(", "$", "startDate", ",", "$", "days", ")", "{", "if", "(", "!", "is_string", "(", "$", "startDate", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $startDate: '", ".", "gettype", "(", "$", "startDate", ")", ")", ";", "if", "(", "Validator", "::", "isDateTime", "(", "$", "startDate", ")", "===", "false", ")", "throw", "new", "InvalidArgumentException", "(", "'Invalid argument $startDate: \"'", ".", "$", "startDate", ".", "'\"'", ")", ";", "if", "(", "!", "is_int", "(", "$", "days", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $days: '", ".", "gettype", "(", "$", "days", ")", ")", ";", "if", "(", "$", "days", "<", "0", ")", "throw", "new", "InvalidArgumentException", "(", "'Invalid argument $days: '", ".", "$", "days", ")", ";", "$", "range", "=", "array", "(", ")", ";", "$", "date", "=", "new", "DateTime", "(", "$", "startDate", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "days", ";", "++", "$", "i", ")", "{", "$", "range", "[", "]", "=", "$", "date", "->", "format", "(", "'Y-m-d'", ")", ";", "$", "date", "->", "modify", "(", "'+1 day'", ")", ";", "}", "return", "$", "range", ";", "}" ]
Gibt eine Anzahl von Datumswerten zurueck. @param string $startDate - Startzeitpunkt (Format: yyyy-mm-dd) @param int $days - Anzahl der zurueckzugebenden Werte @return array
[ "Gibt", "eine", "Anzahl", "von", "Datumswerten", "zurueck", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/util/Date.php#L53-L67
29,199
rosasurfer/ministruts
src/util/Date.php
Date.addDays
public static function addDays($date, $days) { if (Validator::isDateTime($date) === false) throw new InvalidArgumentException('Invalid argument $date: '.$date); if (!is_int($days)) throw new IllegalTypeException('Illegal type of parameter $days: '.gettype($days)); $parts = explode('-', $date); $year = (int) $parts[0]; $month = (int) $parts[1]; $day = (int) $parts[2]; return date('Y-m-d', mktime(0, 0, 0, $month, $day+$days, $year)); }
php
public static function addDays($date, $days) { if (Validator::isDateTime($date) === false) throw new InvalidArgumentException('Invalid argument $date: '.$date); if (!is_int($days)) throw new IllegalTypeException('Illegal type of parameter $days: '.gettype($days)); $parts = explode('-', $date); $year = (int) $parts[0]; $month = (int) $parts[1]; $day = (int) $parts[2]; return date('Y-m-d', mktime(0, 0, 0, $month, $day+$days, $year)); }
[ "public", "static", "function", "addDays", "(", "$", "date", ",", "$", "days", ")", "{", "if", "(", "Validator", "::", "isDateTime", "(", "$", "date", ")", "===", "false", ")", "throw", "new", "InvalidArgumentException", "(", "'Invalid argument $date: '", ".", "$", "date", ")", ";", "if", "(", "!", "is_int", "(", "$", "days", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $days: '", ".", "gettype", "(", "$", "days", ")", ")", ";", "$", "parts", "=", "explode", "(", "'-'", ",", "$", "date", ")", ";", "$", "year", "=", "(", "int", ")", "$", "parts", "[", "0", "]", ";", "$", "month", "=", "(", "int", ")", "$", "parts", "[", "1", "]", ";", "$", "day", "=", "(", "int", ")", "$", "parts", "[", "2", "]", ";", "return", "date", "(", "'Y-m-d'", ",", "mktime", "(", "0", ",", "0", ",", "0", ",", "$", "month", ",", "$", "day", "+", "$", "days", ",", "$", "year", ")", ")", ";", "}" ]
Add a number of days to a date. @param string $date - initial date (format: yyyy-mm-dd) @param int $days - number of days to add @return string - reslting date
[ "Add", "a", "number", "of", "days", "to", "a", "date", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/util/Date.php#L78-L88