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
partition
stringclasses
1 value
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", ".", "'.*'", ";", "}", ...
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
train
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", "=", "$", "th...
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
train
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", "->...
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
train
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", "$", ...
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
train
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",...
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
train
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", ")...
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
train
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", "[", "...
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
train
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", "(", "$"...
Returns mimetypes list @return array
[ "Returns", "mimetypes", "list" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/filesystem/mimetype/extension.php#L110-L122
train
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", "(", ...
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
train
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", "'ad...
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
train
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'",...
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
train
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", ";", "//Seria...
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
train
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'", ")", "?", ...
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
train
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", "->",...
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
train
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",...
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
train
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", ...
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
train
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", "]", ")", ";", ...
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
train
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", ...
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
train
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", "...
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
train
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", "=", "$", ...
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
train
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", "="...
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
train
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", "=", "$", "th...
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
train
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", ")", ";"...
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
train
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", "(", "$"...
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
train
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", "->", "pag...
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
train
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 comp...
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
train
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", "->", "...
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
train
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", "(", "$"...
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
train
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", "(", "!", ...
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
train
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", "(", "$", "que...
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
train
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...
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
train
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", ...
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
train
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", "(", "!", ...
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
train
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", ...
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
train
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", ...
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
train
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", "[", ...
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
train
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_exi...
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
train
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'", ...
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
train
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", "...
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
train
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", ...
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
train
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'",...
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
train
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", ")", ")", ";", ...
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
train
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", ")", ...
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
train
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/CantBeUsedInThisL...
Access to module through app.
[ "Access", "to", "module", "through", "app", "." ]
468da43678119f8c9e3f67183b5bec727c436404
https://github.com/deArcane/framework/blob/468da43678119f8c9e3f67183b5bec727c436404/src/View/View.php#L45-L49
train
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",...
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
train
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",...
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
train
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", ")", "...
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
train
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", ")", ")", ";", ...
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
train
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", "(", ...
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
train
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...
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
train
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", "->", "...
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
train
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",...
Sync permissions. @param array $permissions @return null
[ "Sync", "permissions", "." ]
8779444853df6d102a8e4b4b319f7519b93c9a23
https://github.com/TypiCMS/Users/blob/8779444853df6d102a8e4b4b319f7519b93c9a23/src/Models/User.php#L114-L121
train
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", ...
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
train
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", ")", "...
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
train
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'", ")", ")", ")...
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
train
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", "(", ")", ")", "{", "$", "co...
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
train
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", "(", "$", "doma...
Load the language @return void
[ "Load", "the", "language" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/controller/behavior/localizable.php#L54-L66
train
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", "(", "$",...
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
train
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: '", ".", "gettyp...
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
train
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: '", "....
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
train
rosasurfer/ministruts
src/cache/FileSystemCache.php
FileSystemCache.isCached
public function isCached($key) { // Hier wird die eigentliche Arbeit gemacht. Die Methode prueft nicht nur, ob der Wert im Cache // existiert, sondern speichert ihn auch im lokalen ReferencePool. Folgende Abfragen muessen so // nicht ein weiteres Mal auf den Cache zugreifen, sondern koennen aus dem lokalen Pool bedient // werden. // ReferencePool abfragen if ($this->getReferencePool()->isCached($key)) { return true; } else { // Datei suchen und auslesen $file = $this->getFilePath($key); $data = $this->readFile($file); if (!$data) // Cache-Miss return false; // Cache-Hit, $data Format: array(created, $expires, $value, $dependency) $created = $data[0]; $expires = $data[1]; $value = $data[2]; $dependency = $data[3]; // expires pruefen if ($expires && $created+$expires < time()) { $this->drop($key); return false; } // Dependency pruefen if ($dependency) { $minValid = $dependency->getMinValidity(); if ($minValid) { if (time() > $created+$minValid) { if (!$dependency->isValid()) { $this->drop($key); return false; } // created aktualisieren (Wert praktisch neu in den Cache schreiben) return $this->set($key, $value, $expires, $dependency); } } elseif (!$dependency->isValid()) { $this->drop($key); return false; } } // ok, Wert im ReferencePool speichern $this->getReferencePool()->set($key, $value, Cache::EXPIRES_NEVER, $dependency); return true; } }
php
public function isCached($key) { // Hier wird die eigentliche Arbeit gemacht. Die Methode prueft nicht nur, ob der Wert im Cache // existiert, sondern speichert ihn auch im lokalen ReferencePool. Folgende Abfragen muessen so // nicht ein weiteres Mal auf den Cache zugreifen, sondern koennen aus dem lokalen Pool bedient // werden. // ReferencePool abfragen if ($this->getReferencePool()->isCached($key)) { return true; } else { // Datei suchen und auslesen $file = $this->getFilePath($key); $data = $this->readFile($file); if (!$data) // Cache-Miss return false; // Cache-Hit, $data Format: array(created, $expires, $value, $dependency) $created = $data[0]; $expires = $data[1]; $value = $data[2]; $dependency = $data[3]; // expires pruefen if ($expires && $created+$expires < time()) { $this->drop($key); return false; } // Dependency pruefen if ($dependency) { $minValid = $dependency->getMinValidity(); if ($minValid) { if (time() > $created+$minValid) { if (!$dependency->isValid()) { $this->drop($key); return false; } // created aktualisieren (Wert praktisch neu in den Cache schreiben) return $this->set($key, $value, $expires, $dependency); } } elseif (!$dependency->isValid()) { $this->drop($key); return false; } } // ok, Wert im ReferencePool speichern $this->getReferencePool()->set($key, $value, Cache::EXPIRES_NEVER, $dependency); return true; } }
[ "public", "function", "isCached", "(", "$", "key", ")", "{", "// Hier wird die eigentliche Arbeit gemacht. Die Methode prueft nicht nur, ob der Wert im Cache", "// existiert, sondern speichert ihn auch im lokalen ReferencePool. Folgende Abfragen muessen so", "// nicht ein weiteres Mal auf den Ca...
Ob unter dem angegebenen Schluessel ein Wert im Cache gespeichert ist. @param string $key - Schluessel @return bool
[ "Ob", "unter", "dem", "angegebenen", "Schluessel", "ein", "Wert", "im", "Cache", "gespeichert", "ist", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/cache/FileSystemCache.php#L69-L122
train
rosasurfer/ministruts
src/cache/FileSystemCache.php
FileSystemCache.get
public function get($key, $default = null) { if ($this->isCached($key)) return $this->getReferencePool()->get($key); return $default; }
php
public function get($key, $default = null) { if ($this->isCached($key)) return $this->getReferencePool()->get($key); return $default; }
[ "public", "function", "get", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "if", "(", "$", "this", "->", "isCached", "(", "$", "key", ")", ")", "return", "$", "this", "->", "getReferencePool", "(", ")", "->", "get", "(", "$", "key"...
Gibt einen Wert aus dem Cache zurueck. Existiert der Wert nicht, wird der angegebene Defaultwert zurueckgegeben. @param string $key - Schluessel, unter dem der Wert gespeichert ist @param mixed $default [optional] - Defaultwert (kann selbst auch NULL sein) @return mixed - Der gespeicherte Wert oder NULL, falls kein solcher Schluessel existiert. Achtung: Ist im Cache ein NULL-Wert gespeichert, wird ebenfalls NULL zurueckgegeben.
[ "Gibt", "einen", "Wert", "aus", "dem", "Cache", "zurueck", ".", "Existiert", "der", "Wert", "nicht", "wird", "der", "angegebene", "Defaultwert", "zurueckgegeben", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/cache/FileSystemCache.php#L135-L140
train
rosasurfer/ministruts
src/cache/FileSystemCache.php
FileSystemCache.getFilePath
private function getFilePath($key) { $key = md5($key); return $this->directory.$key[0].DIRECTORY_SEPARATOR.$key[1].DIRECTORY_SEPARATOR.substr($key, 2); }
php
private function getFilePath($key) { $key = md5($key); return $this->directory.$key[0].DIRECTORY_SEPARATOR.$key[1].DIRECTORY_SEPARATOR.substr($key, 2); }
[ "private", "function", "getFilePath", "(", "$", "key", ")", "{", "$", "key", "=", "md5", "(", "$", "key", ")", ";", "return", "$", "this", "->", "directory", ".", "$", "key", "[", "0", "]", ".", "DIRECTORY_SEPARATOR", ".", "$", "key", "[", "1", "...
Gibt den vollstaendigen Pfad zur Cache-Datei fuer den angegebenen Schluessel zurueck. @param string $key - Schluessel des Wertes @return string - Dateipfad
[ "Gibt", "den", "vollstaendigen", "Pfad", "zur", "Cache", "-", "Datei", "fuer", "den", "angegebenen", "Schluessel", "zurueck", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/cache/FileSystemCache.php#L202-L205
train
rosasurfer/ministruts
src/cache/FileSystemCache.php
FileSystemCache.readFile
private function readFile($fileName) { try { $data = file_get_contents($fileName, false); } catch (PHPError $ex) { if (strEndsWith($ex->getMessage(), 'failed to open stream: No such file or directory')) return null; throw $ex; } if ($data === false) throw new RuntimeException('file_get_contents() returned FALSE, $fileName: "'.$fileName); return unserialize($data); }
php
private function readFile($fileName) { try { $data = file_get_contents($fileName, false); } catch (PHPError $ex) { if (strEndsWith($ex->getMessage(), 'failed to open stream: No such file or directory')) return null; throw $ex; } if ($data === false) throw new RuntimeException('file_get_contents() returned FALSE, $fileName: "'.$fileName); return unserialize($data); }
[ "private", "function", "readFile", "(", "$", "fileName", ")", "{", "try", "{", "$", "data", "=", "file_get_contents", "(", "$", "fileName", ",", "false", ")", ";", "}", "catch", "(", "PHPError", "$", "ex", ")", "{", "if", "(", "strEndsWith", "(", "$"...
Liest die Datei mit dem angegebenen Namen ein und gibt den deserialisierten Inhalt zurueck. @param string $fileName - vollstaendiger Dateiname @return mixed - Wert
[ "Liest", "die", "Datei", "mit", "dem", "angegebenen", "Namen", "ein", "und", "gibt", "den", "deserialisierten", "Inhalt", "zurueck", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/cache/FileSystemCache.php#L215-L229
train
rosasurfer/ministruts
src/cache/FileSystemCache.php
FileSystemCache.writeFile
private function writeFile($fileName, $value, $expires) { FS::mkDir(dirname($fileName)); file_put_contents($fileName, serialize($value)); // TODO: http://phpdevblog.niknovo.com/2009/11/serialize-vs-var-export-vs-json-encode.html return true; }
php
private function writeFile($fileName, $value, $expires) { FS::mkDir(dirname($fileName)); file_put_contents($fileName, serialize($value)); // TODO: http://phpdevblog.niknovo.com/2009/11/serialize-vs-var-export-vs-json-encode.html return true; }
[ "private", "function", "writeFile", "(", "$", "fileName", ",", "$", "value", ",", "$", "expires", ")", "{", "FS", "::", "mkDir", "(", "dirname", "(", "$", "fileName", ")", ")", ";", "file_put_contents", "(", "$", "fileName", ",", "serialize", "(", "$",...
Schreibt den angegebenen Wert in die Datei mit dem angegebenen Namen. @param string $fileName - vollstaendiger Dateiname @param mixed $value - der in die Datei zu schreibende Wert @return bool - TRUE bei Erfolg, FALSE andererseits
[ "Schreibt", "den", "angegebenen", "Wert", "in", "die", "Datei", "mit", "dem", "angegebenen", "Namen", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/cache/FileSystemCache.php#L240-L246
train
timble/kodekit
code/command/chain/chain.php
CommandChain.addHandler
public function addHandler(CommandHandlerInterface $handler) { $this->__queue->enqueue($handler, $handler->getPriority()); return $this; }
php
public function addHandler(CommandHandlerInterface $handler) { $this->__queue->enqueue($handler, $handler->getPriority()); return $this; }
[ "public", "function", "addHandler", "(", "CommandHandlerInterface", "$", "handler", ")", "{", "$", "this", "->", "__queue", "->", "enqueue", "(", "$", "handler", ",", "$", "handler", "->", "getPriority", "(", ")", ")", ";", "return", "$", "this", ";", "}...
Attach a command handler to the chain @param CommandHandlerInterface $handler The command handler @return CommandChain
[ "Attach", "a", "command", "handler", "to", "the", "chain" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/command/chain/chain.php#L149-L153
train
timble/kodekit
code/command/chain/chain.php
CommandChain.setHandlerPriority
public function setHandlerPriority(CommandHandlerInterface $handler, $priority) { $this->__queue->setPriority($handler, $priority); return $this; }
php
public function setHandlerPriority(CommandHandlerInterface $handler, $priority) { $this->__queue->setPriority($handler, $priority); return $this; }
[ "public", "function", "setHandlerPriority", "(", "CommandHandlerInterface", "$", "handler", ",", "$", "priority", ")", "{", "$", "this", "->", "__queue", "->", "setPriority", "(", "$", "handler", ",", "$", "priority", ")", ";", "return", "$", "this", ";", ...
Set the priority of a command handler @param CommandHandlerInterface $handler A command handler @param integer $priority The command priority @return CommandChain
[ "Set", "the", "priority", "of", "a", "command", "handler" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/command/chain/chain.php#L184-L188
train
rosasurfer/ministruts
src/db/orm/Worker.php
Worker.find
public function find($query, $allowMany = false) { // TODO: numRows() is not available on SQLite or with PDO and the $result = $this->query($query); // emulation is slow. The check can be improved with fetchRow() // when reset(-1) and internal record caching are implemented. $object = $this->makeObject($result); // if ($object && !$allowMany && $result->numRows() > 1) throw new MultipleRecordsException($query); return $object; }
php
public function find($query, $allowMany = false) { // TODO: numRows() is not available on SQLite or with PDO and the $result = $this->query($query); // emulation is slow. The check can be improved with fetchRow() // when reset(-1) and internal record caching are implemented. $object = $this->makeObject($result); // if ($object && !$allowMany && $result->numRows() > 1) throw new MultipleRecordsException($query); return $object; }
[ "public", "function", "find", "(", "$", "query", ",", "$", "allowMany", "=", "false", ")", "{", "// TODO: numRows() is not available on SQLite or with PDO and the", "$", "result", "=", "$", "this", "->", "query", "(", "$", "query", ")", ";", "// emulation is...
Find a single matching record and convert it to an instance of the entity class. @param string $query - SQL query with optional ORM syntax @param bool $allowMany [optional] - whether the query is allowed to return a multi-row result (default: no) @return PersistableObject|null @throws MultipleRecordsException if the query returned multiple rows and $allowMany was not set to TRUE.
[ "Find", "a", "single", "matching", "record", "and", "convert", "it", "to", "an", "instance", "of", "the", "entity", "class", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/Worker.php#L56-L63
train
rosasurfer/ministruts
src/db/orm/Worker.php
Worker.translateQuery
private function translateQuery($sql) { // model name pattern: ":User" => "t_user" (will also convert matching names in literals and comments) $pattern = '/[^:]:([a-z_]\w*)\b/i'; if (preg_match_all($pattern, $sql, $matches, PREG_OFFSET_CAPTURE)) { $namespace = strLeftTo($this->entityClass, '\\', -1, true, ''); foreach (\array_reverse($matches[1]) as $match) { $modelName = $match[0]; $offset = $match[1]; $className = $namespace.$modelName; if (is_a($className, PersistableObject::class, true)) { /** @var DAO $dao */ $dao = $className::dao(); $table = $dao->getMapping()['table']; $sql = substr_replace($sql, $table, $offset-1, strlen($modelName)+1); } } } return $sql; }
php
private function translateQuery($sql) { // model name pattern: ":User" => "t_user" (will also convert matching names in literals and comments) $pattern = '/[^:]:([a-z_]\w*)\b/i'; if (preg_match_all($pattern, $sql, $matches, PREG_OFFSET_CAPTURE)) { $namespace = strLeftTo($this->entityClass, '\\', -1, true, ''); foreach (\array_reverse($matches[1]) as $match) { $modelName = $match[0]; $offset = $match[1]; $className = $namespace.$modelName; if (is_a($className, PersistableObject::class, true)) { /** @var DAO $dao */ $dao = $className::dao(); $table = $dao->getMapping()['table']; $sql = substr_replace($sql, $table, $offset-1, strlen($modelName)+1); } } } return $sql; }
[ "private", "function", "translateQuery", "(", "$", "sql", ")", "{", "// model name pattern: \":User\" => \"t_user\" (will also convert matching names in literals and comments)", "$", "pattern", "=", "'/[^:]:([a-z_]\\w*)\\b/i'", ";", "if", "(", "preg_match_all", "(", "$", "patte...
Translate entity names in a SQL query into their DBMS table counterparts. At the moment this translation requires all entity classes to be in the same namespace as the worker's entity class. @param string $sql - original SQL query @return string - translated SQL query
[ "Translate", "entity", "names", "in", "a", "SQL", "query", "into", "their", "DBMS", "table", "counterparts", ".", "At", "the", "moment", "this", "translation", "requires", "all", "entity", "classes", "to", "be", "in", "the", "same", "namespace", "as", "the",...
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/Worker.php#L115-L134
train
rosasurfer/ministruts
src/db/orm/Worker.php
Worker.makeObject
protected function makeObject(IResult $result) { // TODO: Prefer to return existing instance from IdentityMap $row = $result->fetchRow(ARRAY_ASSOC); if ($row === null) return null; return PersistableObject::populateNew($this->entityClass, $row); }
php
protected function makeObject(IResult $result) { // TODO: Prefer to return existing instance from IdentityMap $row = $result->fetchRow(ARRAY_ASSOC); if ($row === null) return null; return PersistableObject::populateNew($this->entityClass, $row); }
[ "protected", "function", "makeObject", "(", "IResult", "$", "result", ")", "{", "// TODO: Prefer to return existing instance from IdentityMap", "$", "row", "=", "$", "result", "->", "fetchRow", "(", "ARRAY_ASSOC", ")", ";", "if", "(", "$", "row", "===", "null", ...
Convert the next row of a result to an object of the model class. @param IResult $result @return PersistableObject|null - instance or NULL if the result doesn't hold any more rows
[ "Convert", "the", "next", "row", "of", "a", "result", "to", "an", "object", "of", "the", "model", "class", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/Worker.php#L144-L152
train
rosasurfer/ministruts
src/db/orm/Worker.php
Worker.makeObjects
protected function makeObjects(IResult $result) { // TODO: Prefer to return existing instances from IdentityMap $instances = []; while ($row = $result->fetchRow(ARRAY_ASSOC)) { $instances[] = PersistableObject::populateNew($this->entityClass, $row); } return $instances; }
php
protected function makeObjects(IResult $result) { // TODO: Prefer to return existing instances from IdentityMap $instances = []; while ($row = $result->fetchRow(ARRAY_ASSOC)) { $instances[] = PersistableObject::populateNew($this->entityClass, $row); } return $instances; }
[ "protected", "function", "makeObjects", "(", "IResult", "$", "result", ")", "{", "// TODO: Prefer to return existing instances from IdentityMap", "$", "instances", "=", "[", "]", ";", "while", "(", "$", "row", "=", "$", "result", "->", "fetchRow", "(", "ARRAY_ASSO...
Convert all remaining rows of a result to objects of the model class. @param IResult $result @return PersistableObject[] - array of instances or an empty array if the result doesn't hold any more rows
[ "Convert", "all", "remaining", "rows", "of", "a", "result", "to", "objects", "of", "the", "model", "class", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/Worker.php#L162-L171
train
rosasurfer/ministruts
src/db/orm/Worker.php
Worker.getConnector
public function getConnector() { if (!$this->connector) { $mapping = $this->dao->getMapping(); $this->connector = ConnectionPool::getConnector($mapping['connection']); } return $this->connector; }
php
public function getConnector() { if (!$this->connector) { $mapping = $this->dao->getMapping(); $this->connector = ConnectionPool::getConnector($mapping['connection']); } return $this->connector; }
[ "public", "function", "getConnector", "(", ")", "{", "if", "(", "!", "$", "this", "->", "connector", ")", "{", "$", "mapping", "=", "$", "this", "->", "dao", "->", "getMapping", "(", ")", ";", "$", "this", "->", "connector", "=", "ConnectionPool", ":...
Return the database adapter of the Worker's model class. @return IConnector
[ "Return", "the", "database", "adapter", "of", "the", "Worker", "s", "model", "class", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/Worker.php#L179-L185
train
nicebooks-com/isbn
src/Internal/RangeService.php
RangeService.getRangeInfo
public static function getRangeInfo(string $isbn) : ?RangeInfo { $length = strlen($isbn); $isbnPrefix = ($length === 10) ? '978' : substr($isbn, 0, 3); $isbnDigits = ($length === 10) ? $isbn : substr($isbn, 3); foreach (self::getRanges() as $rangeData) { list ($eanPrefix, $groupIdentifier, $groupName, $ranges) = $rangeData; if ($isbnPrefix !== $eanPrefix) { continue; } $groupLength = strlen($groupIdentifier); $isbnGroup = substr($isbnDigits, 0, $groupLength); if ($isbnGroup !== $groupIdentifier) { continue; } $rangeInfo = new RangeInfo; $rangeInfo->groupIdentifier = ($length === 10 ? $groupIdentifier : $eanPrefix . '-' . $groupIdentifier); $rangeInfo->groupName = $groupName; foreach ($ranges as $range) { list ($rangeLength, $rangeStart, $rangeEnd) = $range; $rangeValue = substr($isbnDigits, $groupLength, $rangeLength); $lastDigits = substr($isbnDigits, $groupLength + $rangeLength, -1); $checkDigit = substr($isbnDigits, -1); if (strcmp($rangeValue, $rangeStart) >= 0 && strcmp($rangeValue, $rangeEnd) <= 0) { if ($length === 13) { $rangeInfo->parts = [$isbnPrefix, $isbnGroup, $rangeValue, $lastDigits, $checkDigit]; } else { $rangeInfo->parts = [$isbnGroup, $rangeValue, $lastDigits, $checkDigit]; } break; } } return $rangeInfo; } return null; }
php
public static function getRangeInfo(string $isbn) : ?RangeInfo { $length = strlen($isbn); $isbnPrefix = ($length === 10) ? '978' : substr($isbn, 0, 3); $isbnDigits = ($length === 10) ? $isbn : substr($isbn, 3); foreach (self::getRanges() as $rangeData) { list ($eanPrefix, $groupIdentifier, $groupName, $ranges) = $rangeData; if ($isbnPrefix !== $eanPrefix) { continue; } $groupLength = strlen($groupIdentifier); $isbnGroup = substr($isbnDigits, 0, $groupLength); if ($isbnGroup !== $groupIdentifier) { continue; } $rangeInfo = new RangeInfo; $rangeInfo->groupIdentifier = ($length === 10 ? $groupIdentifier : $eanPrefix . '-' . $groupIdentifier); $rangeInfo->groupName = $groupName; foreach ($ranges as $range) { list ($rangeLength, $rangeStart, $rangeEnd) = $range; $rangeValue = substr($isbnDigits, $groupLength, $rangeLength); $lastDigits = substr($isbnDigits, $groupLength + $rangeLength, -1); $checkDigit = substr($isbnDigits, -1); if (strcmp($rangeValue, $rangeStart) >= 0 && strcmp($rangeValue, $rangeEnd) <= 0) { if ($length === 13) { $rangeInfo->parts = [$isbnPrefix, $isbnGroup, $rangeValue, $lastDigits, $checkDigit]; } else { $rangeInfo->parts = [$isbnGroup, $rangeValue, $lastDigits, $checkDigit]; } break; } } return $rangeInfo; } return null; }
[ "public", "static", "function", "getRangeInfo", "(", "string", "$", "isbn", ")", ":", "?", "RangeInfo", "{", "$", "length", "=", "strlen", "(", "$", "isbn", ")", ";", "$", "isbnPrefix", "=", "(", "$", "length", "===", "10", ")", "?", "'978'", ":", ...
Splits an ISBN into parts. @param string $isbn The ISBN-10 or ISBN-13, regexp-validated. @return RangeInfo|null
[ "Splits", "an", "ISBN", "into", "parts", "." ]
f5ceb662e517b21e30c9dfa53c4d74823849232d
https://github.com/nicebooks-com/isbn/blob/f5ceb662e517b21e30c9dfa53c4d74823849232d/src/Internal/RangeService.php#L66-L111
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Service/MetadataLoader.php
MetadataLoader.load
public function load($ident, $metadata = [], array $idents = null) { if (!is_string($ident)) { throw new InvalidArgumentException(sprintf( 'Metadata identifier must be a string, received %s', is_object($ident) ? get_class($ident) : gettype($ident) )); } if (strpos($ident, '\\') !== false) { $ident = $this->metaKeyFromClassName($ident); } $valid = $this->validateMetadataContainer($metadata, $metadataType, $targetMetadata); if ($valid === false) { throw new InvalidArgumentException(sprintf( 'Metadata object must be a class name or instance of %s, received %s', MetadataInterface::class, is_object($metadata) ? get_class($metadata) : gettype($metadata) )); } if (isset(static::$metadataCache[$ident])) { $cachedMetadata = static::$metadataCache[$ident]; if (is_object($targetMetadata)) { return $targetMetadata->merge($cachedMetadata); } elseif (is_array($targetMetadata)) { return array_replace_recursive($targetMetadata, $cachedMetadata->data()); } return $cachedMetadata; } $data = $this->loadMetadataFromCache($ident, $idents); if (is_object($targetMetadata)) { return $targetMetadata->merge($data); } elseif (is_array($targetMetadata)) { return array_replace_recursive($targetMetadata, $data); } $targetMetadata = new $metadataType; $targetMetadata->setData($data); static::$metadataCache[$ident] = $targetMetadata; return $targetMetadata; }
php
public function load($ident, $metadata = [], array $idents = null) { if (!is_string($ident)) { throw new InvalidArgumentException(sprintf( 'Metadata identifier must be a string, received %s', is_object($ident) ? get_class($ident) : gettype($ident) )); } if (strpos($ident, '\\') !== false) { $ident = $this->metaKeyFromClassName($ident); } $valid = $this->validateMetadataContainer($metadata, $metadataType, $targetMetadata); if ($valid === false) { throw new InvalidArgumentException(sprintf( 'Metadata object must be a class name or instance of %s, received %s', MetadataInterface::class, is_object($metadata) ? get_class($metadata) : gettype($metadata) )); } if (isset(static::$metadataCache[$ident])) { $cachedMetadata = static::$metadataCache[$ident]; if (is_object($targetMetadata)) { return $targetMetadata->merge($cachedMetadata); } elseif (is_array($targetMetadata)) { return array_replace_recursive($targetMetadata, $cachedMetadata->data()); } return $cachedMetadata; } $data = $this->loadMetadataFromCache($ident, $idents); if (is_object($targetMetadata)) { return $targetMetadata->merge($data); } elseif (is_array($targetMetadata)) { return array_replace_recursive($targetMetadata, $data); } $targetMetadata = new $metadataType; $targetMetadata->setData($data); static::$metadataCache[$ident] = $targetMetadata; return $targetMetadata; }
[ "public", "function", "load", "(", "$", "ident", ",", "$", "metadata", "=", "[", "]", ",", "array", "$", "idents", "=", "null", ")", "{", "if", "(", "!", "is_string", "(", "$", "ident", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", ...
Load the metadata for the given identifier or interfaces. Notes: - If the requested dataset is found, it will be stored in the cache service. - If the provided metadata container is an {@see MetadataInterface object}, it will be stored for the lifetime of the script (whether it be a longer running process or a web request). @param string $ident The metadata identifier to load. @param mixed $metadata The metadata type to load the dataset into. If $metadata is a {@see MetadataInterface} instance, the requested dataset will be merged into the object. If $metadata is a class name, the requested dataset will be stored in a new instance of that class. If $metadata is an array, the requested dataset will be merged into the array. @param array $idents The metadata identifier(s) to load. If $idents is provided, $ident will be used as the cache key and $idents are loaded instead. @throws InvalidArgumentException If the identifier is not a string. @return MetadataInterface|array Returns the dataset, for the given $ident, as an array or an instance of {@see MetadataInterface}. See $metadata for more details.
[ "Load", "the", "metadata", "for", "the", "given", "identifier", "or", "interfaces", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/MetadataLoader.php#L127-L175
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Service/MetadataLoader.php
MetadataLoader.loadMetadataByKey
public function loadMetadataByKey($ident) { if (!is_string($ident)) { throw new InvalidArgumentException( 'Metadata identifier must be a string' ); } $lineage = $this->hierarchy($ident); $metadata = []; foreach ($lineage as $metaKey) { $data = $this->loadMetadataFromSource($metaKey); if (is_array($data)) { $metadata = array_replace_recursive($metadata, $data); } } return $metadata; }
php
public function loadMetadataByKey($ident) { if (!is_string($ident)) { throw new InvalidArgumentException( 'Metadata identifier must be a string' ); } $lineage = $this->hierarchy($ident); $metadata = []; foreach ($lineage as $metaKey) { $data = $this->loadMetadataFromSource($metaKey); if (is_array($data)) { $metadata = array_replace_recursive($metadata, $data); } } return $metadata; }
[ "public", "function", "loadMetadataByKey", "(", "$", "ident", ")", "{", "if", "(", "!", "is_string", "(", "$", "ident", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Metadata identifier must be a string'", ")", ";", "}", "$", "lineage", "="...
Fetch the metadata for the given identifier. @param string $ident The metadata identifier to load. @throws InvalidArgumentException If the identifier is not a string. @return array
[ "Fetch", "the", "metadata", "for", "the", "given", "identifier", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/MetadataLoader.php#L184-L202
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Service/MetadataLoader.php
MetadataLoader.loadMetadataByKeys
public function loadMetadataByKeys(array $idents) { $metadata = []; foreach ($idents as $metaKey) { $data = $this->loadMetadataByKey($metaKey); if (is_array($data)) { $metadata = array_replace_recursive($metadata, $data); } } return $metadata; }
php
public function loadMetadataByKeys(array $idents) { $metadata = []; foreach ($idents as $metaKey) { $data = $this->loadMetadataByKey($metaKey); if (is_array($data)) { $metadata = array_replace_recursive($metadata, $data); } } return $metadata; }
[ "public", "function", "loadMetadataByKeys", "(", "array", "$", "idents", ")", "{", "$", "metadata", "=", "[", "]", ";", "foreach", "(", "$", "idents", "as", "$", "metaKey", ")", "{", "$", "data", "=", "$", "this", "->", "loadMetadataByKey", "(", "$", ...
Fetch the metadata for the given identifiers. @param array $idents One or more metadata identifiers to load. @return array
[ "Fetch", "the", "metadata", "for", "the", "given", "identifiers", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/MetadataLoader.php#L210-L221
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Service/MetadataLoader.php
MetadataLoader.loadMetadataFromCache
private function loadMetadataFromCache($ident, array $idents = null) { $cacheKey = $this->cacheKeyFromMetaKey($ident); $cacheItem = $this->cachePool()->getItem($cacheKey); if ($cacheItem->isHit()) { $metadata = $cacheItem->get(); /** Backwards compatibility */ if ($metadata instanceof MetadataInterface) { $metadata = $metadata->data(); $cacheItem->set($metadata); $this->cachePool()->save($cacheItem); } return $metadata; } else { if (empty($idents)) { $metadata = $this->loadMetadataByKey($ident); } else { $metadata = $this->loadMetadataByKeys($idents); } $cacheItem->set($metadata); $this->cachePool()->save($cacheItem); } return $metadata; }
php
private function loadMetadataFromCache($ident, array $idents = null) { $cacheKey = $this->cacheKeyFromMetaKey($ident); $cacheItem = $this->cachePool()->getItem($cacheKey); if ($cacheItem->isHit()) { $metadata = $cacheItem->get(); /** Backwards compatibility */ if ($metadata instanceof MetadataInterface) { $metadata = $metadata->data(); $cacheItem->set($metadata); $this->cachePool()->save($cacheItem); } return $metadata; } else { if (empty($idents)) { $metadata = $this->loadMetadataByKey($ident); } else { $metadata = $this->loadMetadataByKeys($idents); } $cacheItem->set($metadata); $this->cachePool()->save($cacheItem); } return $metadata; }
[ "private", "function", "loadMetadataFromCache", "(", "$", "ident", ",", "array", "$", "idents", "=", "null", ")", "{", "$", "cacheKey", "=", "$", "this", "->", "cacheKeyFromMetaKey", "(", "$", "ident", ")", ";", "$", "cacheItem", "=", "$", "this", "->", ...
Load a metadataset from the cache. @param string $ident The metadata identifier to load / cache key for $idents. @param array $idents If provided, $ident is used as the cache key and these metadata identifiers are loaded instead. @return array The data associated with the metadata identifier.
[ "Load", "a", "metadataset", "from", "the", "cache", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/MetadataLoader.php#L300-L328
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Service/MetadataLoader.php
MetadataLoader.loadFile
private function loadFile($path) { if (file_exists($path)) { return $this->loadJsonFile($path); } $dirs = $this->paths(); if (empty($dirs)) { return null; } $data = []; $dirs = array_reverse($dirs); foreach ($dirs as $dir) { $file = $dir.DIRECTORY_SEPARATOR.$path; if (file_exists($file)) { $data = array_replace_recursive($data, $this->loadJsonFile($file)); } } if (empty($data)) { return null; } return $data; }
php
private function loadFile($path) { if (file_exists($path)) { return $this->loadJsonFile($path); } $dirs = $this->paths(); if (empty($dirs)) { return null; } $data = []; $dirs = array_reverse($dirs); foreach ($dirs as $dir) { $file = $dir.DIRECTORY_SEPARATOR.$path; if (file_exists($file)) { $data = array_replace_recursive($data, $this->loadJsonFile($file)); } } if (empty($data)) { return null; } return $data; }
[ "private", "function", "loadFile", "(", "$", "path", ")", "{", "if", "(", "file_exists", "(", "$", "path", ")", ")", "{", "return", "$", "this", "->", "loadJsonFile", "(", "$", "path", ")", ";", "}", "$", "dirs", "=", "$", "this", "->", "paths", ...
Load a file as an array. Supported file types: JSON. @param string $path A file path to resolve and fetch. @return array|null An associative array on success, NULL on failure.
[ "Load", "a", "file", "as", "an", "array", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/MetadataLoader.php#L352-L377
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Service/MetadataLoader.php
MetadataLoader.serializeMetaKey
public function serializeMetaKey($ident) { if (is_array($ident)) { sort($ident); $ident = implode(':', $ident); } return md5($ident); }
php
public function serializeMetaKey($ident) { if (is_array($ident)) { sort($ident); $ident = implode(':', $ident); } return md5($ident); }
[ "public", "function", "serializeMetaKey", "(", "$", "ident", ")", "{", "if", "(", "is_array", "(", "$", "ident", ")", ")", "{", "sort", "(", "$", "ident", ")", ";", "$", "ident", "=", "implode", "(", "':'", ",", "$", "ident", ")", ";", "}", "retu...
Generate a store key. @param string|string[] $ident The metadata identifier(s) to convert. @return string
[ "Generate", "a", "store", "key", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/MetadataLoader.php#L411-L419
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Service/MetadataLoader.php
MetadataLoader.classNameFromMetaKey
private function classNameFromMetaKey($ident) { $key = $ident; if (isset(static::$camelCache[$key])) { return static::$camelCache[$key]; } // Change "foo-bar" to "fooBar" $parts = explode('-', $ident); array_walk( $parts, function(&$i) { $i = ucfirst($i); } ); $ident = implode('', $parts); // Change "/foo/bar" to "\Foo\Bar" $classname = str_replace('/', '\\', $ident); $parts = explode('\\', $classname); array_walk( $parts, function(&$i) { $i = ucfirst($i); } ); $classname = trim(implode('\\', $parts), '\\'); static::$camelCache[$key] = $classname; static::$snakeCache[$classname] = $key; return $classname; }
php
private function classNameFromMetaKey($ident) { $key = $ident; if (isset(static::$camelCache[$key])) { return static::$camelCache[$key]; } // Change "foo-bar" to "fooBar" $parts = explode('-', $ident); array_walk( $parts, function(&$i) { $i = ucfirst($i); } ); $ident = implode('', $parts); // Change "/foo/bar" to "\Foo\Bar" $classname = str_replace('/', '\\', $ident); $parts = explode('\\', $classname); array_walk( $parts, function(&$i) { $i = ucfirst($i); } ); $classname = trim(implode('\\', $parts), '\\'); static::$camelCache[$key] = $classname; static::$snakeCache[$classname] = $key; return $classname; }
[ "private", "function", "classNameFromMetaKey", "(", "$", "ident", ")", "{", "$", "key", "=", "$", "ident", ";", "if", "(", "isset", "(", "static", "::", "$", "camelCache", "[", "$", "key", "]", ")", ")", "{", "return", "static", "::", "$", "camelCach...
Convert a kebab-cased namespace to CamelCase. @param string $ident The metadata identifier to convert. @return string Returns a valid PHP namespace.
[ "Convert", "a", "kebab", "-", "cased", "namespace", "to", "CamelCase", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/MetadataLoader.php#L453-L488
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Service/MetadataLoader.php
MetadataLoader.metaKeyFromClassName
private function metaKeyFromClassName($class) { $key = trim($class, '\\'); if (isset(static::$snakeCache[$key])) { return static::$snakeCache[$key]; } $ident = strtolower(preg_replace('/([a-z])([A-Z])/', '$1-$2', $class)); $ident = str_replace('\\', '/', strtolower($ident)); $ident = ltrim($ident, '/'); static::$snakeCache[$key] = $ident; static::$camelCache[$ident] = $key; return $ident; }
php
private function metaKeyFromClassName($class) { $key = trim($class, '\\'); if (isset(static::$snakeCache[$key])) { return static::$snakeCache[$key]; } $ident = strtolower(preg_replace('/([a-z])([A-Z])/', '$1-$2', $class)); $ident = str_replace('\\', '/', strtolower($ident)); $ident = ltrim($ident, '/'); static::$snakeCache[$key] = $ident; static::$camelCache[$ident] = $key; return $ident; }
[ "private", "function", "metaKeyFromClassName", "(", "$", "class", ")", "{", "$", "key", "=", "trim", "(", "$", "class", ",", "'\\\\'", ")", ";", "if", "(", "isset", "(", "static", "::", "$", "snakeCache", "[", "$", "key", "]", ")", ")", "{", "retur...
Convert a CamelCase namespace to kebab-case. @param string $class The FQCN to convert. @return string Returns a kebab-cased namespace.
[ "Convert", "a", "CamelCase", "namespace", "to", "kebab", "-", "case", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/MetadataLoader.php#L496-L512
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Service/MetadataLoader.php
MetadataLoader.validateMetadataContainer
private function validateMetadataContainer($metadata, &$type = null, &$bag = null) { // If variables are provided, clear existing values. $type = null; $bag = null; if (is_array($metadata)) { $type = 'array'; $bag = $metadata; return true; } if (is_a($metadata, MetadataInterface::class, true)) { if (is_object($metadata)) { $type = get_class($metadata); $bag = $metadata; return true; } if (is_string($metadata)) { $type = $metadata; return true; } } return false; }
php
private function validateMetadataContainer($metadata, &$type = null, &$bag = null) { // If variables are provided, clear existing values. $type = null; $bag = null; if (is_array($metadata)) { $type = 'array'; $bag = $metadata; return true; } if (is_a($metadata, MetadataInterface::class, true)) { if (is_object($metadata)) { $type = get_class($metadata); $bag = $metadata; return true; } if (is_string($metadata)) { $type = $metadata; return true; } } return false; }
[ "private", "function", "validateMetadataContainer", "(", "$", "metadata", ",", "&", "$", "type", "=", "null", ",", "&", "$", "bag", "=", "null", ")", "{", "// If variables are provided, clear existing values.", "$", "type", "=", "null", ";", "$", "bag", "=", ...
Validate a metadata type or container. If specified, the method will also resolve the metadata type or container. @param mixed $metadata The metadata type or container to validate. @param string|null $type If provided, then it is filled with the resolved metadata type. @param mixed|null $bag If provided, then it is filled with the resolved metadata container. @return boolean
[ "Validate", "a", "metadata", "type", "or", "container", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/MetadataLoader.php#L524-L549
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Service/MetadataLoader.php
MetadataLoader.addPath
private function addPath($path) { $path = $this->resolvePath($path); if ($this->validatePath($path)) { $this->paths[] = $path; } return $this; }
php
private function addPath($path) { $path = $this->resolvePath($path); if ($this->validatePath($path)) { $this->paths[] = $path; } return $this; }
[ "private", "function", "addPath", "(", "$", "path", ")", "{", "$", "path", "=", "$", "this", "->", "resolvePath", "(", "$", "path", ")", ";", "if", "(", "$", "this", "->", "validatePath", "(", "$", "path", ")", ")", "{", "$", "this", "->", "paths...
Append a search path. @param string $path A directory path. @return self
[ "Append", "a", "search", "path", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/MetadataLoader.php#L623-L632
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Service/MetadataLoader.php
MetadataLoader.resolvePath
private function resolvePath($path) { if (!is_string($path)) { throw new InvalidArgumentException( 'Path needs to be a string' ); } $basePath = $this->basePath(); $path = trim($path, '/\\'); if ($basePath && strpos($path, $basePath) === false) { $path = $basePath.$path; } return $path; }
php
private function resolvePath($path) { if (!is_string($path)) { throw new InvalidArgumentException( 'Path needs to be a string' ); } $basePath = $this->basePath(); $path = trim($path, '/\\'); if ($basePath && strpos($path, $basePath) === false) { $path = $basePath.$path; } return $path; }
[ "private", "function", "resolvePath", "(", "$", "path", ")", "{", "if", "(", "!", "is_string", "(", "$", "path", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Path needs to be a string'", ")", ";", "}", "$", "basePath", "=", "$", "this"...
Parse a relative path using the base path if needed. @param string $path The path to resolve. @throws InvalidArgumentException If the path is invalid. @return string
[ "Parse", "a", "relative", "path", "using", "the", "base", "path", "if", "needed", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/MetadataLoader.php#L641-L657
train
timble/kodekit
code/user/session/abstract.php
UserSessionAbstract.setHandler
public function setHandler($handler, $config = array()) { if (!($handler instanceof UserSessionHandlerInterface)) { if (is_string($handler) && strpos($handler, '.') === false) { $identifier = $this->getIdentifier()->toArray(); $identifier['path'] = array('session', 'handler'); $identifier['name'] = $handler; // reset the handler $handler = $identifier; } $identifier = $this->getIdentifier($handler); //Set the configuration $identifier->getConfig()->append($config); $handler = $identifier; } $this->_handler = $handler; return $this; }
php
public function setHandler($handler, $config = array()) { if (!($handler instanceof UserSessionHandlerInterface)) { if (is_string($handler) && strpos($handler, '.') === false) { $identifier = $this->getIdentifier()->toArray(); $identifier['path'] = array('session', 'handler'); $identifier['name'] = $handler; // reset the handler $handler = $identifier; } $identifier = $this->getIdentifier($handler); //Set the configuration $identifier->getConfig()->append($config); $handler = $identifier; } $this->_handler = $handler; return $this; }
[ "public", "function", "setHandler", "(", "$", "handler", ",", "$", "config", "=", "array", "(", ")", ")", "{", "if", "(", "!", "(", "$", "handler", "instanceof", "UserSessionHandlerInterface", ")", ")", "{", "if", "(", "is_string", "(", "$", "handler", ...
Method to set a session handler object @param mixed $handler An object that implements UserSessionHandlerInterface, ObjectIdentifier object or valid identifier string @param array $config An optional associative array of configuration settings @return $this
[ "Method", "to", "set", "a", "session", "handler", "object" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/user/session/abstract.php#L311-L334
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Collection.php
Collection.merge
public function merge($objs) { $objs = $this->asArray($objs); foreach ($objs as $obj) { if (!$this->isAcceptable($obj)) { throw new InvalidArgumentException( sprintf( 'Must be an array of models, contains %s', (is_object($obj) ? get_class($obj) : gettype($obj)) ) ); } $key = $this->modelKey($obj); $this->objects[$key] = $obj; } return $this; }
php
public function merge($objs) { $objs = $this->asArray($objs); foreach ($objs as $obj) { if (!$this->isAcceptable($obj)) { throw new InvalidArgumentException( sprintf( 'Must be an array of models, contains %s', (is_object($obj) ? get_class($obj) : gettype($obj)) ) ); } $key = $this->modelKey($obj); $this->objects[$key] = $obj; } return $this; }
[ "public", "function", "merge", "(", "$", "objs", ")", "{", "$", "objs", "=", "$", "this", "->", "asArray", "(", "$", "objs", ")", ";", "foreach", "(", "$", "objs", "as", "$", "obj", ")", "{", "if", "(", "!", "$", "this", "->", "isAcceptable", "...
Merge the collection with the given objects. @param array|Traversable $objs Array of objects to append to this collection. @throws InvalidArgumentException If the given array contains an unacceptable value. @return self
[ "Merge", "the", "collection", "with", "the", "given", "objects", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Collection.php#L91-L110
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Collection.php
Collection.add
public function add($obj) { if (!$this->isAcceptable($obj)) { throw new InvalidArgumentException( sprintf( 'Must be a model, received %s', (is_object($obj) ? get_class($obj) : gettype($obj)) ) ); } $key = $this->modelKey($obj); $this->objects[$key] = $obj; return $this; }
php
public function add($obj) { if (!$this->isAcceptable($obj)) { throw new InvalidArgumentException( sprintf( 'Must be a model, received %s', (is_object($obj) ? get_class($obj) : gettype($obj)) ) ); } $key = $this->modelKey($obj); $this->objects[$key] = $obj; return $this; }
[ "public", "function", "add", "(", "$", "obj", ")", "{", "if", "(", "!", "$", "this", "->", "isAcceptable", "(", "$", "obj", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Must be a model, received %s'", ",", "(", "is_obje...
Add an object to the collection. @param object $obj An acceptable object. @throws InvalidArgumentException If the given object is not acceptable. @return self
[ "Add", "an", "object", "to", "the", "collection", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Collection.php#L119-L134
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Collection.php
Collection.get
public function get($key) { if ($this->isAcceptable($key)) { $key = $this->modelKey($key); } if ($this->has($key)) { return $this->objects[$key]; } return null; }
php
public function get($key) { if ($this->isAcceptable($key)) { $key = $this->modelKey($key); } if ($this->has($key)) { return $this->objects[$key]; } return null; }
[ "public", "function", "get", "(", "$", "key", ")", "{", "if", "(", "$", "this", "->", "isAcceptable", "(", "$", "key", ")", ")", "{", "$", "key", "=", "$", "this", "->", "modelKey", "(", "$", "key", ")", ";", "}", "if", "(", "$", "this", "->"...
Retrieve the object by primary key. @param mixed $key The primary key. @return object|null Returns the requested object or NULL if not in the collection.
[ "Retrieve", "the", "object", "by", "primary", "key", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Collection.php#L142-L153
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Collection.php
Collection.has
public function has($key) { if ($this->isAcceptable($key)) { $key = $this->modelKey($key); } return array_key_exists($key, $this->objects); }
php
public function has($key) { if ($this->isAcceptable($key)) { $key = $this->modelKey($key); } return array_key_exists($key, $this->objects); }
[ "public", "function", "has", "(", "$", "key", ")", "{", "if", "(", "$", "this", "->", "isAcceptable", "(", "$", "key", ")", ")", "{", "$", "key", "=", "$", "this", "->", "modelKey", "(", "$", "key", ")", ";", "}", "return", "array_key_exists", "(...
Determine if an object exists in the collection by key. @param mixed $key The primary key to lookup. @return boolean
[ "Determine", "if", "an", "object", "exists", "in", "the", "collection", "by", "key", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Collection.php#L161-L168
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Collection.php
Collection.remove
public function remove($key) { if ($this->isAcceptable($key)) { $key = $this->modelKey($key); } unset($this->objects[$key]); return $this; }
php
public function remove($key) { if ($this->isAcceptable($key)) { $key = $this->modelKey($key); } unset($this->objects[$key]); return $this; }
[ "public", "function", "remove", "(", "$", "key", ")", "{", "if", "(", "$", "this", "->", "isAcceptable", "(", "$", "key", ")", ")", "{", "$", "key", "=", "$", "this", "->", "modelKey", "(", "$", "key", ")", ";", "}", "unset", "(", "$", "this", ...
Remove object from collection by primary key. @param mixed $key The object primary key to remove. @throws InvalidArgumentException If the given key is not acceptable. @return self
[ "Remove", "object", "from", "collection", "by", "primary", "key", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Collection.php#L177-L186
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Collection.php
Collection.resolveOffset
protected function resolveOffset($offset) { if (is_int($offset)) { if ($offset < 0) { $offset = ($this->count() - abs($offset)); } } return $offset; }
php
protected function resolveOffset($offset) { if (is_int($offset)) { if ($offset < 0) { $offset = ($this->count() - abs($offset)); } } return $offset; }
[ "protected", "function", "resolveOffset", "(", "$", "offset", ")", "{", "if", "(", "is_int", "(", "$", "offset", ")", ")", "{", "if", "(", "$", "offset", "<", "0", ")", "{", "$", "offset", "=", "(", "$", "this", "->", "count", "(", ")", "-", "a...
Parse the array offset. If offset is non-negative, the sequence will start at that offset in the collection. If offset is negative, the sequence will start that far from the end of the collection. @param integer $offset The array offset. @return integer Returns the resolved array offset.
[ "Parse", "the", "array", "offset", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Collection.php#L321-L330
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Collection.php
Collection.modelKey
protected function modelKey($obj) { if (!$this->isAcceptable($obj)) { throw new InvalidArgumentException( sprintf( 'Must be a model, received %s', (is_object($obj) ? get_class($obj) : gettype($obj)) ) ); } return $obj->id(); }
php
protected function modelKey($obj) { if (!$this->isAcceptable($obj)) { throw new InvalidArgumentException( sprintf( 'Must be a model, received %s', (is_object($obj) ? get_class($obj) : gettype($obj)) ) ); } return $obj->id(); }
[ "protected", "function", "modelKey", "(", "$", "obj", ")", "{", "if", "(", "!", "$", "this", "->", "isAcceptable", "(", "$", "obj", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Must be a model, received %s'", ",", "(", ...
Convert a given object into a model identifier. Note: Practical for specialized collections extending the base collection. @param object $obj An acceptable object. @throws InvalidArgumentException If the given object is not acceptable. @return boolean
[ "Convert", "a", "given", "object", "into", "a", "model", "identifier", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Collection.php#L436-L448
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Service/MetadataConfig.php
MetadataConfig.defaults
public function defaults($key = null) { $data = [ 'paths' => [], 'cache' => true, ]; if ($key) { return isset($data[$key]) ? $data[$key] : null; } return $data; }
php
public function defaults($key = null) { $data = [ 'paths' => [], 'cache' => true, ]; if ($key) { return isset($data[$key]) ? $data[$key] : null; } return $data; }
[ "public", "function", "defaults", "(", "$", "key", "=", "null", ")", "{", "$", "data", "=", "[", "'paths'", "=>", "[", "]", ",", "'cache'", "=>", "true", ",", "]", ";", "if", "(", "$", "key", ")", "{", "return", "isset", "(", "$", "data", "[", ...
Retrieve the default values. @param string|null $key Optional data key to retrieve. @return mixed An associative array if $key is NULL. If $key is specified, the value of that data key if it exists, NULL on failure.
[ "Retrieve", "the", "default", "values", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/MetadataConfig.php#L38-L50
train
locomotivemtl/charcoal-core
src/Charcoal/Model/Service/MetadataConfig.php
MetadataConfig.merge
public function merge($data) { foreach ($data as $key => $val) { if ($key === 'paths') { $this->addPaths((array)$val); } elseif ($key === 'cache') { $this->setCache($val); } else { $this->offsetReplace($key, $val); } } return $this; }
php
public function merge($data) { foreach ($data as $key => $val) { if ($key === 'paths') { $this->addPaths((array)$val); } elseif ($key === 'cache') { $this->setCache($val); } else { $this->offsetReplace($key, $val); } } return $this; }
[ "public", "function", "merge", "(", "$", "data", ")", "{", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "$", "key", "===", "'paths'", ")", "{", "$", "this", "->", "addPaths", "(", "(", "array", ")", "$",...
Add settings to configset, replacing existing settings with the same data key. @see \Charcoal\Config\AbstractConfig::merge() @param array|Traversable $data The data to merge. @return self
[ "Add", "settings", "to", "configset", "replacing", "existing", "settings", "with", "the", "same", "data", "key", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/MetadataConfig.php#L59-L72
train
timble/kodekit
code/model/state/state.php
ModelState.setProperty
public function setProperty($name, $property, $value) { if($this->has($name)) { if($this->hasProperty($name, $property)) { if($property !== 'value') { $this->_data[$name]->$property = $value; } else { $this->set($name, $value); } } } return $this; }
php
public function setProperty($name, $property, $value) { if($this->has($name)) { if($this->hasProperty($name, $property)) { if($property !== 'value') { $this->_data[$name]->$property = $value; } else { $this->set($name, $value); } } } return $this; }
[ "public", "function", "setProperty", "(", "$", "name", ",", "$", "property", ",", "$", "value", ")", "{", "if", "(", "$", "this", "->", "has", "(", "$", "name", ")", ")", "{", "if", "(", "$", "this", "->", "hasProperty", "(", "$", "name", ",", ...
Set a state property @param string $name The name of the state @param string $property The name of the property @param mixed $value The value of the property @return ModelState
[ "Set", "a", "state", "property" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/model/state/state.php#L289-L304
train
timble/kodekit
code/model/state/state.php
ModelState._sanitize
protected function _sanitize($state) { //Treat empty string as null if ($state->value === '') { $state->value = null; } //Only filter if we have a value if(!empty($state->value)) { //Only accepts scalar values and array if(!is_scalar($state->value) && !is_array($state->value)) { throw new \UnexpectedValueException( 'Value needs to be an array or a scalar, "'.gettype($state->value).'" given' ); } $filter = $state->filter; if(!($filter instanceof FilterInterface)) { $filter = $this->getObject('filter.factory')->createChain($filter); } $state->value = $filter->sanitize($state->value); } return $state; }
php
protected function _sanitize($state) { //Treat empty string as null if ($state->value === '') { $state->value = null; } //Only filter if we have a value if(!empty($state->value)) { //Only accepts scalar values and array if(!is_scalar($state->value) && !is_array($state->value)) { throw new \UnexpectedValueException( 'Value needs to be an array or a scalar, "'.gettype($state->value).'" given' ); } $filter = $state->filter; if(!($filter instanceof FilterInterface)) { $filter = $this->getObject('filter.factory')->createChain($filter); } $state->value = $filter->sanitize($state->value); } return $state; }
[ "protected", "function", "_sanitize", "(", "$", "state", ")", "{", "//Treat empty string as null", "if", "(", "$", "state", "->", "value", "===", "''", ")", "{", "$", "state", "->", "value", "=", "null", ";", "}", "//Only filter if we have a value", "if", "(...
Sanitize a state by filtering the state value @param object $state The state object. @throws \UnexpectedValueException If the value is not a scalar or an array @return object
[ "Sanitize", "a", "state", "by", "filtering", "the", "state", "value" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/model/state/state.php#L473-L501
train
locomotivemtl/charcoal-core
src/Charcoal/Source/Pagination.php
Pagination.setData
public function setData(array $data) { parent::setData($data); if (isset($data['page'])) { $this->setPage($data['page']); } if (isset($data['per_page'])) { $this->setNumPerPage($data['per_page']); } if (isset($data['num_per_page'])) { $this->setNumPerPage($data['num_per_page']); } return $this; }
php
public function setData(array $data) { parent::setData($data); if (isset($data['page'])) { $this->setPage($data['page']); } if (isset($data['per_page'])) { $this->setNumPerPage($data['per_page']); } if (isset($data['num_per_page'])) { $this->setNumPerPage($data['num_per_page']); } return $this; }
[ "public", "function", "setData", "(", "array", "$", "data", ")", "{", "parent", "::", "setData", "(", "$", "data", ")", ";", "if", "(", "isset", "(", "$", "data", "[", "'page'", "]", ")", ")", "{", "$", "this", "->", "setPage", "(", "$", "data", ...
Set the pagination clause data. @param array<string,mixed> $data The expression data; as an associative array. @return self
[ "Set", "the", "pagination", "clause", "data", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/Pagination.php#L43-L60
train
locomotivemtl/charcoal-core
src/Charcoal/Source/Pagination.php
Pagination.setPage
public function setPage($page) { if (!is_numeric($page)) { throw new InvalidArgumentException( 'Page number must be numeric.' ); } $page = (int)$page; if ($page === 0) { $page = 1; } elseif ($page < 0) { throw new InvalidArgumentException( 'Page number must be greater than zero.' ); } $this->page = $page; return $this; }
php
public function setPage($page) { if (!is_numeric($page)) { throw new InvalidArgumentException( 'Page number must be numeric.' ); } $page = (int)$page; if ($page === 0) { $page = 1; } elseif ($page < 0) { throw new InvalidArgumentException( 'Page number must be greater than zero.' ); } $this->page = $page; return $this; }
[ "public", "function", "setPage", "(", "$", "page", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "page", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Page number must be numeric.'", ")", ";", "}", "$", "page", "=", "(", "int", ")...
Set the page number. @param integer $page The current page. Pages should start at 1. @throws InvalidArgumentException If the parameter is not numeric or < 0. @return self
[ "Set", "the", "page", "number", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/Pagination.php#L100-L119
train
locomotivemtl/charcoal-core
src/Charcoal/Source/Pagination.php
Pagination.setNumPerPage
public function setNumPerPage($count) { if (!is_numeric($count)) { throw new InvalidArgumentException( 'Number Per Page must be numeric.' ); } $count = (int)$count; if ($count < 0) { throw new InvalidArgumentException( 'Number Per Page must be greater than zero.' ); } $this->numPerPage = $count; return $this; }
php
public function setNumPerPage($count) { if (!is_numeric($count)) { throw new InvalidArgumentException( 'Number Per Page must be numeric.' ); } $count = (int)$count; if ($count < 0) { throw new InvalidArgumentException( 'Number Per Page must be greater than zero.' ); } $this->numPerPage = $count; return $this; }
[ "public", "function", "setNumPerPage", "(", "$", "count", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "count", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Number Per Page must be numeric.'", ")", ";", "}", "$", "count", "=", "(", ...
Set the number of results per page. @param integer $count The number of results to return, per page. Use 0 to request all results. @throws InvalidArgumentException If the parameter is not numeric or < 0. @return self
[ "Set", "the", "number", "of", "results", "per", "page", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/Pagination.php#L139-L156
train
locomotivemtl/charcoal-core
src/Charcoal/Source/Pagination.php
Pagination.first
public function first() { $page = $this->page(); $limit = $this->numPerPage(); return max(0, (($page - 1) * $limit)); }
php
public function first() { $page = $this->page(); $limit = $this->numPerPage(); return max(0, (($page - 1) * $limit)); }
[ "public", "function", "first", "(", ")", "{", "$", "page", "=", "$", "this", "->", "page", "(", ")", ";", "$", "limit", "=", "$", "this", "->", "numPerPage", "(", ")", ";", "return", "max", "(", "0", ",", "(", "(", "$", "page", "-", "1", ")",...
Retrieve the pagination's lowest possible index. @return integer
[ "Retrieve", "the", "pagination", "s", "lowest", "possible", "index", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/Pagination.php#L173-L179
train