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
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
jasny/entity
src/Traits/SetTrait.php
SetTrait.set
public function set($key, $value = null) { i\type_check($key, ['array', 'string']); if (func_num_args() === 1 && is_string($key)) { throw new BadMethodCallException(sprintf( "Too few arguments to method %s::%s(). If first argument is a string, a second argument is required", __CLASS__, __FUNCTION__ )); } $input = func_num_args() === 1 ? (array)$key : [$key => $value]; /** @var Event\BeforeSet $event */ $event = $this->dispatchEvent(new Event\BeforeSet($this, $input)); $data = $event->getPayload(); object_set_properties($this, $data, $this instanceof DynamicEntity); $this->dispatchEvent(new Event\AfterSet($this, $data)); return $this; }
php
public function set($key, $value = null) { i\type_check($key, ['array', 'string']); if (func_num_args() === 1 && is_string($key)) { throw new BadMethodCallException(sprintf( "Too few arguments to method %s::%s(). If first argument is a string, a second argument is required", __CLASS__, __FUNCTION__ )); } $input = func_num_args() === 1 ? (array)$key : [$key => $value]; /** @var Event\BeforeSet $event */ $event = $this->dispatchEvent(new Event\BeforeSet($this, $input)); $data = $event->getPayload(); object_set_properties($this, $data, $this instanceof DynamicEntity); $this->dispatchEvent(new Event\AfterSet($this, $data)); return $this; }
[ "public", "function", "set", "(", "$", "key", ",", "$", "value", "=", "null", ")", "{", "i", "\\", "type_check", "(", "$", "key", ",", "[", "'array'", ",", "'string'", "]", ")", ";", "if", "(", "func_num_args", "(", ")", "===", "1", "&&", "is_string", "(", "$", "key", ")", ")", "{", "throw", "new", "BadMethodCallException", "(", "sprintf", "(", "\"Too few arguments to method %s::%s(). If first argument is a string, a second argument is required\"", ",", "__CLASS__", ",", "__FUNCTION__", ")", ")", ";", "}", "$", "input", "=", "func_num_args", "(", ")", "===", "1", "?", "(", "array", ")", "$", "key", ":", "[", "$", "key", "=>", "$", "value", "]", ";", "/** @var Event\\BeforeSet $event */", "$", "event", "=", "$", "this", "->", "dispatchEvent", "(", "new", "Event", "\\", "BeforeSet", "(", "$", "this", ",", "$", "input", ")", ")", ";", "$", "data", "=", "$", "event", "->", "getPayload", "(", ")", ";", "object_set_properties", "(", "$", "this", ",", "$", "data", ",", "$", "this", "instanceof", "DynamicEntity", ")", ";", "$", "this", "->", "dispatchEvent", "(", "new", "Event", "\\", "AfterSet", "(", "$", "this", ",", "$", "data", ")", ")", ";", "return", "$", "this", ";", "}" ]
Set a value or multiple values. <code> $entity->set('foo', 22); $entity->set('bar', null); $entity->set(['qux' => 100, 'clr' => 'red']); </code> @param string|array $key Property or set of values @param mixed $value @return $this
[ "Set", "a", "value", "or", "multiple", "values", "." ]
5af7c94645671a3257d6565ff1891ff61fdcf69b
https://github.com/jasny/entity/blob/5af7c94645671a3257d6565ff1891ff61fdcf69b/src/Traits/SetTrait.php#L39-L62
train
znframework/package-hypertext
HtmlElementsTrait.php
HtmlElementsTrait.aria
public function aria(String $type, String $element) { $this->settings['attr']['aria-'.$type] = $element; return $this; }
php
public function aria(String $type, String $element) { $this->settings['attr']['aria-'.$type] = $element; return $this; }
[ "public", "function", "aria", "(", "String", "$", "type", ",", "String", "$", "element", ")", "{", "$", "this", "->", "settings", "[", "'attr'", "]", "[", "'aria-'", ".", "$", "type", "]", "=", "$", "element", ";", "return", "$", "this", ";", "}" ]
Sets aria attribute @param string $type @param string $element @return self
[ "Sets", "aria", "attribute" ]
12bbc3bd47a2fae735f638a3e01cc82c1b9c9005
https://github.com/znframework/package-hypertext/blob/12bbc3bd47a2fae735f638a3e01cc82c1b9c9005/HtmlElementsTrait.php#L22-L27
train
znframework/package-hypertext
HtmlElementsTrait.php
HtmlElementsTrait.data
public function data(String $type, String $element) { $this->settings['attr']['data-'.$type] = $element; return $this; }
php
public function data(String $type, String $element) { $this->settings['attr']['data-'.$type] = $element; return $this; }
[ "public", "function", "data", "(", "String", "$", "type", ",", "String", "$", "element", ")", "{", "$", "this", "->", "settings", "[", "'attr'", "]", "[", "'data-'", ".", "$", "type", "]", "=", "$", "element", ";", "return", "$", "this", ";", "}" ]
Sets data attribute @param string $type @param string $element @return self
[ "Sets", "data", "attribute" ]
12bbc3bd47a2fae735f638a3e01cc82c1b9c9005
https://github.com/znframework/package-hypertext/blob/12bbc3bd47a2fae735f638a3e01cc82c1b9c9005/HtmlElementsTrait.php#L37-L42
train
znframework/package-hypertext
HtmlElementsTrait.php
HtmlElementsTrait.spry
public function spry(String $type, String $element) { $this->settings['attr']['spry-'.$type] = $element; return $this; }
php
public function spry(String $type, String $element) { $this->settings['attr']['spry-'.$type] = $element; return $this; }
[ "public", "function", "spry", "(", "String", "$", "type", ",", "String", "$", "element", ")", "{", "$", "this", "->", "settings", "[", "'attr'", "]", "[", "'spry-'", ".", "$", "type", "]", "=", "$", "element", ";", "return", "$", "this", ";", "}" ]
Sets spry attribute @param string $type @param string $element @return self
[ "Sets", "spry", "attribute" ]
12bbc3bd47a2fae735f638a3e01cc82c1b9c9005
https://github.com/znframework/package-hypertext/blob/12bbc3bd47a2fae735f638a3e01cc82c1b9c9005/HtmlElementsTrait.php#L66-L71
train
bennybi/yii2-cza-base
models/statics/ResponseDatum.php
ResponseDatum.getSuccessDatum
public static function getSuccessDatum($meta = [], $data = null, $html = false) { $defaultMeta = array( 'result' => OperationResult::SUCCESS, 'type' => OperationResult::getType(OperationResult::SUCCESS), 'time' => date('Y-m-d H:i:s'), 'message' => Yii::t('cza', 'Operation completed.') ); if (isset($meta['message']) && is_array($meta['message'])) { $meta['message'] = self::formatMsg($meta['message']); } $result = array( '_data' => $data, '_meta' => array_merge($defaultMeta, $meta), ); if ($html) $result['_meta']['message'] = '<div class=\'alert-box done\'><i class=\'fa-check-circle\'></i> ' . $result['_meta']['message'] . '</div>'; return $result; }
php
public static function getSuccessDatum($meta = [], $data = null, $html = false) { $defaultMeta = array( 'result' => OperationResult::SUCCESS, 'type' => OperationResult::getType(OperationResult::SUCCESS), 'time' => date('Y-m-d H:i:s'), 'message' => Yii::t('cza', 'Operation completed.') ); if (isset($meta['message']) && is_array($meta['message'])) { $meta['message'] = self::formatMsg($meta['message']); } $result = array( '_data' => $data, '_meta' => array_merge($defaultMeta, $meta), ); if ($html) $result['_meta']['message'] = '<div class=\'alert-box done\'><i class=\'fa-check-circle\'></i> ' . $result['_meta']['message'] . '</div>'; return $result; }
[ "public", "static", "function", "getSuccessDatum", "(", "$", "meta", "=", "[", "]", ",", "$", "data", "=", "null", ",", "$", "html", "=", "false", ")", "{", "$", "defaultMeta", "=", "array", "(", "'result'", "=>", "OperationResult", "::", "SUCCESS", ",", "'type'", "=>", "OperationResult", "::", "getType", "(", "OperationResult", "::", "SUCCESS", ")", ",", "'time'", "=>", "date", "(", "'Y-m-d H:i:s'", ")", ",", "'message'", "=>", "Yii", "::", "t", "(", "'cza'", ",", "'Operation completed.'", ")", ")", ";", "if", "(", "isset", "(", "$", "meta", "[", "'message'", "]", ")", "&&", "is_array", "(", "$", "meta", "[", "'message'", "]", ")", ")", "{", "$", "meta", "[", "'message'", "]", "=", "self", "::", "formatMsg", "(", "$", "meta", "[", "'message'", "]", ")", ";", "}", "$", "result", "=", "array", "(", "'_data'", "=>", "$", "data", ",", "'_meta'", "=>", "array_merge", "(", "$", "defaultMeta", ",", "$", "meta", ")", ",", ")", ";", "if", "(", "$", "html", ")", "$", "result", "[", "'_meta'", "]", "[", "'message'", "]", "=", "'<div class=\\'alert-box done\\'><i class=\\'fa-check-circle\\'></i> '", ".", "$", "result", "[", "'_meta'", "]", "[", "'message'", "]", ".", "'</div>'", ";", "return", "$", "result", ";", "}" ]
standardize the datum format @param array $data - return data fields @param array $metaData - meta data @return ['_data'=>[], '_meta'=[]]
[ "standardize", "the", "datum", "format" ]
8257db8034bd948712fa469062921f210f0ba8da
https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/models/statics/ResponseDatum.php#L39-L58
train
buse974/Dal
src/Dal/Paginator/Paginator.php
Paginator.getItems
public function getItems() { $statement = (null !== $this->c && null !== $this->d) ? $this->getStatementDay() : $this->getStatementPagination(); $result = $statement->execute((is_array($this->select)) ? $this->select[1] : null); $resultSet = clone $this->resultSetPrototype; $this->result = $resultSet->initialize($result); return $this->result; }
php
public function getItems() { $statement = (null !== $this->c && null !== $this->d) ? $this->getStatementDay() : $this->getStatementPagination(); $result = $statement->execute((is_array($this->select)) ? $this->select[1] : null); $resultSet = clone $this->resultSetPrototype; $this->result = $resultSet->initialize($result); return $this->result; }
[ "public", "function", "getItems", "(", ")", "{", "$", "statement", "=", "(", "null", "!==", "$", "this", "->", "c", "&&", "null", "!==", "$", "this", "->", "d", ")", "?", "$", "this", "->", "getStatementDay", "(", ")", ":", "$", "this", "->", "getStatementPagination", "(", ")", ";", "$", "result", "=", "$", "statement", "->", "execute", "(", "(", "is_array", "(", "$", "this", "->", "select", ")", ")", "?", "$", "this", "->", "select", "[", "1", "]", ":", "null", ")", ";", "$", "resultSet", "=", "clone", "$", "this", "->", "resultSetPrototype", ";", "$", "this", "->", "result", "=", "$", "resultSet", "->", "initialize", "(", "$", "result", ")", ";", "return", "$", "this", "->", "result", ";", "}" ]
Returns an ResultSet of items for a page. @return \Dal\Db\ResultSet\ResultSet
[ "Returns", "an", "ResultSet", "of", "items", "for", "a", "page", "." ]
faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab
https://github.com/buse974/Dal/blob/faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab/src/Dal/Paginator/Paginator.php#L204-L213
train
buse974/Dal
src/Dal/Paginator/Paginator.php
Paginator.getStatementDay
public function getStatementDay() { if (null === $this->n) { $this->n = 1; } $date = new \DateTime($this->d, new \DateTimeZone('UTC')); $date->sub(new \DateInterval(sprintf('P%dD', ($this->p * $this->n) - 1))); $start_date = $date->format('Y-m-j'); $date->add(new \DateInterval(sprintf('P%dD', $this->n))); $end_date = $date->format('Y-m-j'); if (is_array($this->select)) { $query = sprintf('%s WHERE %s BETWEEN %s AND %s', $this->select[0], $this->c, $start_date, $end_date); $adt = $this->sql->getAdapter(); $statement = $adt->query($query, $adt::QUERY_MODE_PREPARE); } else { $select = clone $this->select; $select->where(new Between($this->c, $start_date, $end_date)); $statement = $this->sql->prepareStatementForSqlObject($select); } return $statement; }
php
public function getStatementDay() { if (null === $this->n) { $this->n = 1; } $date = new \DateTime($this->d, new \DateTimeZone('UTC')); $date->sub(new \DateInterval(sprintf('P%dD', ($this->p * $this->n) - 1))); $start_date = $date->format('Y-m-j'); $date->add(new \DateInterval(sprintf('P%dD', $this->n))); $end_date = $date->format('Y-m-j'); if (is_array($this->select)) { $query = sprintf('%s WHERE %s BETWEEN %s AND %s', $this->select[0], $this->c, $start_date, $end_date); $adt = $this->sql->getAdapter(); $statement = $adt->query($query, $adt::QUERY_MODE_PREPARE); } else { $select = clone $this->select; $select->where(new Between($this->c, $start_date, $end_date)); $statement = $this->sql->prepareStatementForSqlObject($select); } return $statement; }
[ "public", "function", "getStatementDay", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "n", ")", "{", "$", "this", "->", "n", "=", "1", ";", "}", "$", "date", "=", "new", "\\", "DateTime", "(", "$", "this", "->", "d", ",", "new", "\\", "DateTimeZone", "(", "'UTC'", ")", ")", ";", "$", "date", "->", "sub", "(", "new", "\\", "DateInterval", "(", "sprintf", "(", "'P%dD'", ",", "(", "$", "this", "->", "p", "*", "$", "this", "->", "n", ")", "-", "1", ")", ")", ")", ";", "$", "start_date", "=", "$", "date", "->", "format", "(", "'Y-m-j'", ")", ";", "$", "date", "->", "add", "(", "new", "\\", "DateInterval", "(", "sprintf", "(", "'P%dD'", ",", "$", "this", "->", "n", ")", ")", ")", ";", "$", "end_date", "=", "$", "date", "->", "format", "(", "'Y-m-j'", ")", ";", "if", "(", "is_array", "(", "$", "this", "->", "select", ")", ")", "{", "$", "query", "=", "sprintf", "(", "'%s WHERE %s BETWEEN %s AND %s'", ",", "$", "this", "->", "select", "[", "0", "]", ",", "$", "this", "->", "c", ",", "$", "start_date", ",", "$", "end_date", ")", ";", "$", "adt", "=", "$", "this", "->", "sql", "->", "getAdapter", "(", ")", ";", "$", "statement", "=", "$", "adt", "->", "query", "(", "$", "query", ",", "$", "adt", "::", "QUERY_MODE_PREPARE", ")", ";", "}", "else", "{", "$", "select", "=", "clone", "$", "this", "->", "select", ";", "$", "select", "->", "where", "(", "new", "Between", "(", "$", "this", "->", "c", ",", "$", "start_date", ",", "$", "end_date", ")", ")", ";", "$", "statement", "=", "$", "this", "->", "sql", "->", "prepareStatementForSqlObject", "(", "$", "select", ")", ";", "}", "return", "$", "statement", ";", "}" ]
Get Statement Pagination By Date @return \Zend\Db\Adapter\Driver\StatementInterface
[ "Get", "Statement", "Pagination", "By", "Date" ]
faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab
https://github.com/buse974/Dal/blob/faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab/src/Dal/Paginator/Paginator.php#L220-L246
train
buse974/Dal
src/Dal/Paginator/Paginator.php
Paginator.getTotalItemCount
public function getTotalItemCount() { if ($this->rowCount !== null) { return $this->rowCount; } $param = null; if (is_array($this->select)) { $select = $this->select[0]; $param = $this->select[1]; $adt = $this->sql->getAdapter(); $statement = $adt->query(sprintf("SELECT COUNT(1) AS c FROM (%s) AS original_select", $select), $adt::QUERY_MODE_PREPARE); } else { $select = clone $this->select; $select->reset(Select::LIMIT); $select->reset(Select::OFFSET); $select->reset(Select::ORDER); $countSelect = new Select(); $countSelect->columns(array('c' => new Expression('COUNT(1)'))); $countSelect->from(array('original_select' => $select)); $statement = $this->sql->prepareStatementForSqlObject($countSelect); } $result = $statement->execute($param); $row = $result->current(); $this->rowCount = $row['c']; return $this->rowCount; }
php
public function getTotalItemCount() { if ($this->rowCount !== null) { return $this->rowCount; } $param = null; if (is_array($this->select)) { $select = $this->select[0]; $param = $this->select[1]; $adt = $this->sql->getAdapter(); $statement = $adt->query(sprintf("SELECT COUNT(1) AS c FROM (%s) AS original_select", $select), $adt::QUERY_MODE_PREPARE); } else { $select = clone $this->select; $select->reset(Select::LIMIT); $select->reset(Select::OFFSET); $select->reset(Select::ORDER); $countSelect = new Select(); $countSelect->columns(array('c' => new Expression('COUNT(1)'))); $countSelect->from(array('original_select' => $select)); $statement = $this->sql->prepareStatementForSqlObject($countSelect); } $result = $statement->execute($param); $row = $result->current(); $this->rowCount = $row['c']; return $this->rowCount; }
[ "public", "function", "getTotalItemCount", "(", ")", "{", "if", "(", "$", "this", "->", "rowCount", "!==", "null", ")", "{", "return", "$", "this", "->", "rowCount", ";", "}", "$", "param", "=", "null", ";", "if", "(", "is_array", "(", "$", "this", "->", "select", ")", ")", "{", "$", "select", "=", "$", "this", "->", "select", "[", "0", "]", ";", "$", "param", "=", "$", "this", "->", "select", "[", "1", "]", ";", "$", "adt", "=", "$", "this", "->", "sql", "->", "getAdapter", "(", ")", ";", "$", "statement", "=", "$", "adt", "->", "query", "(", "sprintf", "(", "\"SELECT COUNT(1) AS c FROM (%s) AS original_select\"", ",", "$", "select", ")", ",", "$", "adt", "::", "QUERY_MODE_PREPARE", ")", ";", "}", "else", "{", "$", "select", "=", "clone", "$", "this", "->", "select", ";", "$", "select", "->", "reset", "(", "Select", "::", "LIMIT", ")", ";", "$", "select", "->", "reset", "(", "Select", "::", "OFFSET", ")", ";", "$", "select", "->", "reset", "(", "Select", "::", "ORDER", ")", ";", "$", "countSelect", "=", "new", "Select", "(", ")", ";", "$", "countSelect", "->", "columns", "(", "array", "(", "'c'", "=>", "new", "Expression", "(", "'COUNT(1)'", ")", ")", ")", ";", "$", "countSelect", "->", "from", "(", "array", "(", "'original_select'", "=>", "$", "select", ")", ")", ";", "$", "statement", "=", "$", "this", "->", "sql", "->", "prepareStatementForSqlObject", "(", "$", "countSelect", ")", ";", "}", "$", "result", "=", "$", "statement", "->", "execute", "(", "$", "param", ")", ";", "$", "row", "=", "$", "result", "->", "current", "(", ")", ";", "$", "this", "->", "rowCount", "=", "$", "row", "[", "'c'", "]", ";", "return", "$", "this", "->", "rowCount", ";", "}" ]
Returns the total number of rows in the result set @return int
[ "Returns", "the", "total", "number", "of", "rows", "in", "the", "result", "set" ]
faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab
https://github.com/buse974/Dal/blob/faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab/src/Dal/Paginator/Paginator.php#L354-L387
train
buse974/Dal
src/Dal/Paginator/Paginator.php
Paginator.checkColumns
private function checkColumns($ok, $table, $cols) { $fords = false; foreach ($cols as $ck => $cv) { if ($cv instanceof Expression || $cv instanceof Select || is_string($cv)) { if ($ok === $ck) { $fords = $ok; break; } elseif ( ($cv instanceof Expression && $ok === $cv->getExpression()) || (str_replace('.','$',$ok) === $ck) || (is_string($cv) && ($ok == $table . '.' . $cv) ) ) { $fords = $ck; break; } } } return $fords; }
php
private function checkColumns($ok, $table, $cols) { $fords = false; foreach ($cols as $ck => $cv) { if ($cv instanceof Expression || $cv instanceof Select || is_string($cv)) { if ($ok === $ck) { $fords = $ok; break; } elseif ( ($cv instanceof Expression && $ok === $cv->getExpression()) || (str_replace('.','$',$ok) === $ck) || (is_string($cv) && ($ok == $table . '.' . $cv) ) ) { $fords = $ck; break; } } } return $fords; }
[ "private", "function", "checkColumns", "(", "$", "ok", ",", "$", "table", ",", "$", "cols", ")", "{", "$", "fords", "=", "false", ";", "foreach", "(", "$", "cols", "as", "$", "ck", "=>", "$", "cv", ")", "{", "if", "(", "$", "cv", "instanceof", "Expression", "||", "$", "cv", "instanceof", "Select", "||", "is_string", "(", "$", "cv", ")", ")", "{", "if", "(", "$", "ok", "===", "$", "ck", ")", "{", "$", "fords", "=", "$", "ok", ";", "break", ";", "}", "elseif", "(", "(", "$", "cv", "instanceof", "Expression", "&&", "$", "ok", "===", "$", "cv", "->", "getExpression", "(", ")", ")", "||", "(", "str_replace", "(", "'.'", ",", "'$'", ",", "$", "ok", ")", "===", "$", "ck", ")", "||", "(", "is_string", "(", "$", "cv", ")", "&&", "(", "$", "ok", "==", "$", "table", ".", "'.'", ".", "$", "cv", ")", ")", ")", "{", "$", "fords", "=", "$", "ck", ";", "break", ";", "}", "}", "}", "return", "$", "fords", ";", "}" ]
Check Column name @param string $ok @return array
[ "Check", "Column", "name" ]
faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab
https://github.com/buse974/Dal/blob/faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab/src/Dal/Paginator/Paginator.php#L395-L414
train
thiagodp/http
lib/Mime.php
Mime.make
static function make( $mime, $param = null, $paramValue = null ) { if ( null === $param || null === $paramValue ) { return $mime; } return "$mime;$param=$paramValue"; }
php
static function make( $mime, $param = null, $paramValue = null ) { if ( null === $param || null === $paramValue ) { return $mime; } return "$mime;$param=$paramValue"; }
[ "static", "function", "make", "(", "$", "mime", ",", "$", "param", "=", "null", ",", "$", "paramValue", "=", "null", ")", "{", "if", "(", "null", "===", "$", "param", "||", "null", "===", "$", "paramValue", ")", "{", "return", "$", "mime", ";", "}", "return", "\"$mime;$param=$paramValue\"", ";", "}" ]
USEFUL STATIC METHODS
[ "USEFUL", "STATIC", "METHODS" ]
e9ccb5e352015213dfcbf1d648c81afb293f4f24
https://github.com/thiagodp/http/blob/e9ccb5e352015213dfcbf1d648c81afb293f4f24/lib/Mime.php#L70-L75
train
gwa/zero-library
src/Theme/AbstractTheme.php
AbstractTheme.addImageSize
final protected function addImageSize($name, $width, $height, $crop = false) { $this->getWpBridge()->addImageSize($name, $width, $height, $crop); }
php
final protected function addImageSize($name, $width, $height, $crop = false) { $this->getWpBridge()->addImageSize($name, $width, $height, $crop); }
[ "final", "protected", "function", "addImageSize", "(", "$", "name", ",", "$", "width", ",", "$", "height", ",", "$", "crop", "=", "false", ")", "{", "$", "this", "->", "getWpBridge", "(", ")", "->", "addImageSize", "(", "$", "name", ",", "$", "width", ",", "$", "height", ",", "$", "crop", ")", ";", "}" ]
Register a WP image size. @param string $name @param integer $width @param integer $height @param boolean|array $crop
[ "Register", "a", "WP", "image", "size", "." ]
2c1e700640f527ace3d58bc0e90bd71a096dcf41
https://github.com/gwa/zero-library/blob/2c1e700640f527ace3d58bc0e90bd71a096dcf41/src/Theme/AbstractTheme.php#L203-L206
train
crisu83/yii-seo
behaviors/SeoActiveRecordBehavior.php
SeoActiveRecordBehavior.createUrl
public function createUrl($params=array()) { return Yii::app()->createUrl($this->route, CMap::mergeArray($params, $this->evaluateParams($this->params))); }
php
public function createUrl($params=array()) { return Yii::app()->createUrl($this->route, CMap::mergeArray($params, $this->evaluateParams($this->params))); }
[ "public", "function", "createUrl", "(", "$", "params", "=", "array", "(", ")", ")", "{", "return", "Yii", "::", "app", "(", ")", "->", "createUrl", "(", "$", "this", "->", "route", ",", "CMap", "::", "mergeArray", "(", "$", "params", ",", "$", "this", "->", "evaluateParams", "(", "$", "this", "->", "params", ")", ")", ")", ";", "}" ]
Returns the URL for this model. @param array $params additional GET parameters (name=>value) @return string the URL
[ "Returns", "the", "URL", "for", "this", "model", "." ]
0cf100b2b89c09ba74a8b4c43b14539a023a9225
https://github.com/crisu83/yii-seo/blob/0cf100b2b89c09ba74a8b4c43b14539a023a9225/behaviors/SeoActiveRecordBehavior.php#L26-L29
train
crisu83/yii-seo
behaviors/SeoActiveRecordBehavior.php
SeoActiveRecordBehavior.evaluateParams
protected function evaluateParams($params) { foreach ($params as $name => $value) { if (is_callable($value)) $params[$name] = $this->evaluateExpression($value, array('data' => $this->owner)); } return $params; }
php
protected function evaluateParams($params) { foreach ($params as $name => $value) { if (is_callable($value)) $params[$name] = $this->evaluateExpression($value, array('data' => $this->owner)); } return $params; }
[ "protected", "function", "evaluateParams", "(", "$", "params", ")", "{", "foreach", "(", "$", "params", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "is_callable", "(", "$", "value", ")", ")", "$", "params", "[", "$", "name", "]", "=", "$", "this", "->", "evaluateExpression", "(", "$", "value", ",", "array", "(", "'data'", "=>", "$", "this", "->", "owner", ")", ")", ";", "}", "return", "$", "params", ";", "}" ]
Evaluates the given params. @param array $params the parameters. @return array the evaluated params.
[ "Evaluates", "the", "given", "params", "." ]
0cf100b2b89c09ba74a8b4c43b14539a023a9225
https://github.com/crisu83/yii-seo/blob/0cf100b2b89c09ba74a8b4c43b14539a023a9225/behaviors/SeoActiveRecordBehavior.php#L46-L54
train
smalldb/libSmalldb
class/Utils/UnionFind.php
UnionFind.findAll
public function findAll() { $a = []; foreach ($this->parents as $x => $r) { $a[$x] = $this->find($x); } return $a; }
php
public function findAll() { $a = []; foreach ($this->parents as $x => $r) { $a[$x] = $this->find($x); } return $a; }
[ "public", "function", "findAll", "(", ")", "{", "$", "a", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "parents", "as", "$", "x", "=>", "$", "r", ")", "{", "$", "a", "[", "$", "x", "]", "=", "$", "this", "->", "find", "(", "$", "x", ")", ";", "}", "return", "$", "a", ";", "}" ]
Get map of all items -> representative
[ "Get", "map", "of", "all", "items", "-", ">", "representative" ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Utils/UnionFind.php#L116-L123
train
smalldb/libSmalldb
class/Utils/UnionFind.php
UnionFind.findDistinct
public function findDistinct() { $a = []; foreach ($this->parents as $x => $r) { $a[$this->find($x)] = null; } return array_keys($a); }
php
public function findDistinct() { $a = []; foreach ($this->parents as $x => $r) { $a[$this->find($x)] = null; } return array_keys($a); }
[ "public", "function", "findDistinct", "(", ")", "{", "$", "a", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "parents", "as", "$", "x", "=>", "$", "r", ")", "{", "$", "a", "[", "$", "this", "->", "find", "(", "$", "x", ")", "]", "=", "null", ";", "}", "return", "array_keys", "(", "$", "a", ")", ";", "}" ]
Get a representative for each component.
[ "Get", "a", "representative", "for", "each", "component", "." ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Utils/UnionFind.php#L129-L136
train
phPoirot/Loader
fixes/LoaderAggregate.php
LoaderAggregate.loader
function loader($loaderName) { $loaderName = $this->_normalizeLoaderName($loaderName); if (!$this->hasAttached($loaderName)) throw new \Exception(sprintf( 'Loader with name (%s) has not attached.' , $loaderName )); return $this->_t_loader_aggregate_Names[$loaderName]; }
php
function loader($loaderName) { $loaderName = $this->_normalizeLoaderName($loaderName); if (!$this->hasAttached($loaderName)) throw new \Exception(sprintf( 'Loader with name (%s) has not attached.' , $loaderName )); return $this->_t_loader_aggregate_Names[$loaderName]; }
[ "function", "loader", "(", "$", "loaderName", ")", "{", "$", "loaderName", "=", "$", "this", "->", "_normalizeLoaderName", "(", "$", "loaderName", ")", ";", "if", "(", "!", "$", "this", "->", "hasAttached", "(", "$", "loaderName", ")", ")", "throw", "new", "\\", "Exception", "(", "sprintf", "(", "'Loader with name (%s) has not attached.'", ",", "$", "loaderName", ")", ")", ";", "return", "$", "this", "->", "_t_loader_aggregate_Names", "[", "$", "loaderName", "]", ";", "}" ]
Get Loader By Name [code:] $aggregateLoader->loader(\Poirot\Loader\Autoloader\LoaderAutoloadNamespace::class) ->with([..options]) [code] @param string $loaderName Loader Name, default is class name @throws \Exception Loader class not found @return iLoader
[ "Get", "Loader", "By", "Name" ]
c645a56bbb81aac99271e077652f6f53f58c0675
https://github.com/phPoirot/Loader/blob/c645a56bbb81aac99271e077652f6f53f58c0675/fixes/LoaderAggregate.php#L93-L104
train
phPoirot/Loader
fixes/LoaderAggregate.php
LoaderAggregate.hasAttached
function hasAttached($loaderName) { $loaderName = $this->_normalizeLoaderName($loaderName); return in_array($loaderName, $this->listAttached()); }
php
function hasAttached($loaderName) { $loaderName = $this->_normalizeLoaderName($loaderName); return in_array($loaderName, $this->listAttached()); }
[ "function", "hasAttached", "(", "$", "loaderName", ")", "{", "$", "loaderName", "=", "$", "this", "->", "_normalizeLoaderName", "(", "$", "loaderName", ")", ";", "return", "in_array", "(", "$", "loaderName", ",", "$", "this", "->", "listAttached", "(", ")", ")", ";", "}" ]
Has Loader With This Name Attached? [code:] $aggregateLoader->hasAttached(\Poirot\Loader\Autoloader\LoaderAutoloadNamespace::class) [code] @param string $loaderName Loader Name, default is class name @return bool
[ "Has", "Loader", "With", "This", "Name", "Attached?" ]
c645a56bbb81aac99271e077652f6f53f58c0675
https://github.com/phPoirot/Loader/blob/c645a56bbb81aac99271e077652f6f53f58c0675/fixes/LoaderAggregate.php#L117-L121
train
IftekherSunny/Planet-Framework
src/Sun/Security/Encrypter.php
Encrypter.encrypt
public function encrypt($data) { $iv = openssl_random_pseudo_bytes($this->getSize()); $value = openssl_encrypt(serialize($data), $this->method, $this->key, 0, $iv); $mac = $this->hash($iv = base64_encode($iv), $value); return base64_encode(json_encode(compact('iv', 'value', 'mac'))); }
php
public function encrypt($data) { $iv = openssl_random_pseudo_bytes($this->getSize()); $value = openssl_encrypt(serialize($data), $this->method, $this->key, 0, $iv); $mac = $this->hash($iv = base64_encode($iv), $value); return base64_encode(json_encode(compact('iv', 'value', 'mac'))); }
[ "public", "function", "encrypt", "(", "$", "data", ")", "{", "$", "iv", "=", "openssl_random_pseudo_bytes", "(", "$", "this", "->", "getSize", "(", ")", ")", ";", "$", "value", "=", "openssl_encrypt", "(", "serialize", "(", "$", "data", ")", ",", "$", "this", "->", "method", ",", "$", "this", "->", "key", ",", "0", ",", "$", "iv", ")", ";", "$", "mac", "=", "$", "this", "->", "hash", "(", "$", "iv", "=", "base64_encode", "(", "$", "iv", ")", ",", "$", "value", ")", ";", "return", "base64_encode", "(", "json_encode", "(", "compact", "(", "'iv'", ",", "'value'", ",", "'mac'", ")", ")", ")", ";", "}" ]
To encrypt data @param $data @return string
[ "To", "encrypt", "data" ]
530e772fb97695c1c4e1af73f81675f189474d9f
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Security/Encrypter.php#L63-L72
train
IftekherSunny/Planet-Framework
src/Sun/Security/Encrypter.php
Encrypter.decrypt
public function decrypt($data) { $json = base64_decode($data); $data = json_decode($json); // check mac if ($this->hashCheck($data->iv, $data->value, $data->mac)) { $iv = base64_decode($data->iv); $data = openssl_decrypt($data->value, $this->method, $this->key, 0, $iv); return unserialize($data); } throw new Exception('Mac not match.'); }
php
public function decrypt($data) { $json = base64_decode($data); $data = json_decode($json); // check mac if ($this->hashCheck($data->iv, $data->value, $data->mac)) { $iv = base64_decode($data->iv); $data = openssl_decrypt($data->value, $this->method, $this->key, 0, $iv); return unserialize($data); } throw new Exception('Mac not match.'); }
[ "public", "function", "decrypt", "(", "$", "data", ")", "{", "$", "json", "=", "base64_decode", "(", "$", "data", ")", ";", "$", "data", "=", "json_decode", "(", "$", "json", ")", ";", "// check mac\r", "if", "(", "$", "this", "->", "hashCheck", "(", "$", "data", "->", "iv", ",", "$", "data", "->", "value", ",", "$", "data", "->", "mac", ")", ")", "{", "$", "iv", "=", "base64_decode", "(", "$", "data", "->", "iv", ")", ";", "$", "data", "=", "openssl_decrypt", "(", "$", "data", "->", "value", ",", "$", "this", "->", "method", ",", "$", "this", "->", "key", ",", "0", ",", "$", "iv", ")", ";", "return", "unserialize", "(", "$", "data", ")", ";", "}", "throw", "new", "Exception", "(", "'Mac not match.'", ")", ";", "}" ]
To decrypt data @param $data @return mixed|string @throws Exception
[ "To", "decrypt", "data" ]
530e772fb97695c1c4e1af73f81675f189474d9f
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Security/Encrypter.php#L82-L99
train
IftekherSunny/Planet-Framework
src/Sun/Security/Encrypter.php
Encrypter.hashCheck
protected function hashCheck($iv, $value, $mac) { $salt = Str::random($this->keySize); $mainMac = hash_hmac('sha256', $this->hash($iv, $value), $salt); $checkMac = hash_hmac('sha256', $mac, $salt); if ($mainMac === $checkMac) { return true; } return false; }
php
protected function hashCheck($iv, $value, $mac) { $salt = Str::random($this->keySize); $mainMac = hash_hmac('sha256', $this->hash($iv, $value), $salt); $checkMac = hash_hmac('sha256', $mac, $salt); if ($mainMac === $checkMac) { return true; } return false; }
[ "protected", "function", "hashCheck", "(", "$", "iv", ",", "$", "value", ",", "$", "mac", ")", "{", "$", "salt", "=", "Str", "::", "random", "(", "$", "this", "->", "keySize", ")", ";", "$", "mainMac", "=", "hash_hmac", "(", "'sha256'", ",", "$", "this", "->", "hash", "(", "$", "iv", ",", "$", "value", ")", ",", "$", "salt", ")", ";", "$", "checkMac", "=", "hash_hmac", "(", "'sha256'", ",", "$", "mac", ",", "$", "salt", ")", ";", "if", "(", "$", "mainMac", "===", "$", "checkMac", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
To check mac @param $iv @param $value @param $mac @return bool
[ "To", "check", "mac" ]
530e772fb97695c1c4e1af73f81675f189474d9f
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Security/Encrypter.php#L110-L123
train
chadicus/coding-standard
Chadicus/Sniffs/Commenting/FunctionCommentSniff.php
Chadicus_Sniffs_Commenting_FunctionCommentSniff.process
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) { $methodProperties = $phpcsFile->getMethodProperties($stackPtr); if ($methodProperties['scope'] !== 'public') { return; } parent::process($phpcsFile, $stackPtr); }
php
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) { $methodProperties = $phpcsFile->getMethodProperties($stackPtr); if ($methodProperties['scope'] !== 'public') { return; } parent::process($phpcsFile, $stackPtr); }
[ "public", "function", "process", "(", "PHP_CodeSniffer_File", "$", "phpcsFile", ",", "$", "stackPtr", ")", "{", "$", "methodProperties", "=", "$", "phpcsFile", "->", "getMethodProperties", "(", "$", "stackPtr", ")", ";", "if", "(", "$", "methodProperties", "[", "'scope'", "]", "!==", "'public'", ")", "{", "return", ";", "}", "parent", "::", "process", "(", "$", "phpcsFile", ",", "$", "stackPtr", ")", ";", "}" ]
Ensures only public methods are processed. @param PHP_CodeSniffer_File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void
[ "Ensures", "only", "public", "methods", "are", "processed", "." ]
e877151eed0c300e4e33e00308470e3873aa04ea
https://github.com/chadicus/coding-standard/blob/e877151eed0c300e4e33e00308470e3873aa04ea/Chadicus/Sniffs/Commenting/FunctionCommentSniff.php#L27-L35
train
chadicus/coding-standard
Chadicus/Sniffs/Commenting/FunctionCommentSniff.php
Chadicus_Sniffs_Commenting_FunctionCommentSniff.checkSpacingAfterParamType
protected function checkSpacingAfterParamType(PHP_CodeSniffer_File $phpcsFile, $param, $maxType, $spacing = 1) { // Check number of spaces after the type. $spaces = ($maxType - strlen($param['type']) + $spacing); if ($param['type_space'] !== $spaces) { $error = 'Expected %s spaces after parameter type; %s found'; $data = array( $spaces, $param['type_space'], ); $fix = $phpcsFile->addFixableError($error, $param['tag'], 'SpacingAfterParamType', $data); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); $content = $param['type']; $content .= str_repeat(' ', $spaces); $content .= $param['var']; $content .= str_repeat(' ', $param['var_space']); $content .= $param['commentLines'][0]['comment']; $phpcsFile->fixer->replaceToken(($param['tag'] + 2), $content); // Fix up the indent of additional comment lines. foreach ($param['commentLines'] as $lineNum => $line) { if ($lineNum === 0 || $param['commentLines'][$lineNum]['indent'] === 0 ) { continue; } $diff = ($param['type_space'] - $spaces); $newIndent = ($param['commentLines'][$lineNum]['indent'] - $diff); $phpcsFile->fixer->replaceToken( ($param['commentLines'][$lineNum]['token'] - 1), str_repeat(' ', $newIndent) ); } $phpcsFile->fixer->endChangeset(); }//end if }//end if }
php
protected function checkSpacingAfterParamType(PHP_CodeSniffer_File $phpcsFile, $param, $maxType, $spacing = 1) { // Check number of spaces after the type. $spaces = ($maxType - strlen($param['type']) + $spacing); if ($param['type_space'] !== $spaces) { $error = 'Expected %s spaces after parameter type; %s found'; $data = array( $spaces, $param['type_space'], ); $fix = $phpcsFile->addFixableError($error, $param['tag'], 'SpacingAfterParamType', $data); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); $content = $param['type']; $content .= str_repeat(' ', $spaces); $content .= $param['var']; $content .= str_repeat(' ', $param['var_space']); $content .= $param['commentLines'][0]['comment']; $phpcsFile->fixer->replaceToken(($param['tag'] + 2), $content); // Fix up the indent of additional comment lines. foreach ($param['commentLines'] as $lineNum => $line) { if ($lineNum === 0 || $param['commentLines'][$lineNum]['indent'] === 0 ) { continue; } $diff = ($param['type_space'] - $spaces); $newIndent = ($param['commentLines'][$lineNum]['indent'] - $diff); $phpcsFile->fixer->replaceToken( ($param['commentLines'][$lineNum]['token'] - 1), str_repeat(' ', $newIndent) ); } $phpcsFile->fixer->endChangeset(); }//end if }//end if }
[ "protected", "function", "checkSpacingAfterParamType", "(", "PHP_CodeSniffer_File", "$", "phpcsFile", ",", "$", "param", ",", "$", "maxType", ",", "$", "spacing", "=", "1", ")", "{", "// Check number of spaces after the type.", "$", "spaces", "=", "(", "$", "maxType", "-", "strlen", "(", "$", "param", "[", "'type'", "]", ")", "+", "$", "spacing", ")", ";", "if", "(", "$", "param", "[", "'type_space'", "]", "!==", "$", "spaces", ")", "{", "$", "error", "=", "'Expected %s spaces after parameter type; %s found'", ";", "$", "data", "=", "array", "(", "$", "spaces", ",", "$", "param", "[", "'type_space'", "]", ",", ")", ";", "$", "fix", "=", "$", "phpcsFile", "->", "addFixableError", "(", "$", "error", ",", "$", "param", "[", "'tag'", "]", ",", "'SpacingAfterParamType'", ",", "$", "data", ")", ";", "if", "(", "$", "fix", "===", "true", ")", "{", "$", "phpcsFile", "->", "fixer", "->", "beginChangeset", "(", ")", ";", "$", "content", "=", "$", "param", "[", "'type'", "]", ";", "$", "content", ".=", "str_repeat", "(", "' '", ",", "$", "spaces", ")", ";", "$", "content", ".=", "$", "param", "[", "'var'", "]", ";", "$", "content", ".=", "str_repeat", "(", "' '", ",", "$", "param", "[", "'var_space'", "]", ")", ";", "$", "content", ".=", "$", "param", "[", "'commentLines'", "]", "[", "0", "]", "[", "'comment'", "]", ";", "$", "phpcsFile", "->", "fixer", "->", "replaceToken", "(", "(", "$", "param", "[", "'tag'", "]", "+", "2", ")", ",", "$", "content", ")", ";", "// Fix up the indent of additional comment lines.", "foreach", "(", "$", "param", "[", "'commentLines'", "]", "as", "$", "lineNum", "=>", "$", "line", ")", "{", "if", "(", "$", "lineNum", "===", "0", "||", "$", "param", "[", "'commentLines'", "]", "[", "$", "lineNum", "]", "[", "'indent'", "]", "===", "0", ")", "{", "continue", ";", "}", "$", "diff", "=", "(", "$", "param", "[", "'type_space'", "]", "-", "$", "spaces", ")", ";", "$", "newIndent", "=", "(", "$", "param", "[", "'commentLines'", "]", "[", "$", "lineNum", "]", "[", "'indent'", "]", "-", "$", "diff", ")", ";", "$", "phpcsFile", "->", "fixer", "->", "replaceToken", "(", "(", "$", "param", "[", "'commentLines'", "]", "[", "$", "lineNum", "]", "[", "'token'", "]", "-", "1", ")", ",", "str_repeat", "(", "' '", ",", "$", "newIndent", ")", ")", ";", "}", "$", "phpcsFile", "->", "fixer", "->", "endChangeset", "(", ")", ";", "}", "//end if", "}", "//end if", "}" ]
Check the spacing after the type of a parameter. @param PHP_CodeSniffer_File $phpcsFile The file being scanned. @param array $param The parameter to be checked. @param int $maxType The maxlength of the longest parameter type. @param int $spacing The number of spaces to add after the type. @return void
[ "Check", "the", "spacing", "after", "the", "type", "of", "a", "parameter", "." ]
e877151eed0c300e4e33e00308470e3873aa04ea
https://github.com/chadicus/coding-standard/blob/e877151eed0c300e4e33e00308470e3873aa04ea/Chadicus/Sniffs/Commenting/FunctionCommentSniff.php#L558-L600
train
martinvium/seine
src/Seine/Writer/OfficeOpenXML2007/SharedStringsHelper.php
SharedStringsHelper.writeString
public function writeString($string) { fwrite($this->stream, ' <si><t>' . Utils::escape($string) . '</t></si>' . MyWriter::EOL); return $this->id++; }
php
public function writeString($string) { fwrite($this->stream, ' <si><t>' . Utils::escape($string) . '</t></si>' . MyWriter::EOL); return $this->id++; }
[ "public", "function", "writeString", "(", "$", "string", ")", "{", "fwrite", "(", "$", "this", "->", "stream", ",", "' <si><t>'", ".", "Utils", "::", "escape", "(", "$", "string", ")", ".", "'</t></si>'", ".", "MyWriter", "::", "EOL", ")", ";", "return", "$", "this", "->", "id", "++", ";", "}" ]
String MUST already be escaped @param string $string @return integer id referencing string
[ "String", "MUST", "already", "be", "escaped" ]
b361241c88bb73e81c66259f59193b175223c2eb
https://github.com/martinvium/seine/blob/b361241c88bb73e81c66259f59193b175223c2eb/src/Seine/Writer/OfficeOpenXML2007/SharedStringsHelper.php#L65-L69
train
anklimsk/cakephp-console-installer
Model/InstallerInit.php
InstallerInit.initDbTable
public function initDbTable($table = null) { if (empty($table)) { return false; } $initModel = ClassRegistry::init(Inflector::classify($table), true); if ($initModel === false) { return false; } if (!method_exists($initModel, 'initDbTable')) { return false; } $ds = $initModel->getDataSource(); if (!$ds->truncate($initModel)) { return false; } return $initModel->initDbTable(); }
php
public function initDbTable($table = null) { if (empty($table)) { return false; } $initModel = ClassRegistry::init(Inflector::classify($table), true); if ($initModel === false) { return false; } if (!method_exists($initModel, 'initDbTable')) { return false; } $ds = $initModel->getDataSource(); if (!$ds->truncate($initModel)) { return false; } return $initModel->initDbTable(); }
[ "public", "function", "initDbTable", "(", "$", "table", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "table", ")", ")", "{", "return", "false", ";", "}", "$", "initModel", "=", "ClassRegistry", "::", "init", "(", "Inflector", "::", "classify", "(", "$", "table", ")", ",", "true", ")", ";", "if", "(", "$", "initModel", "===", "false", ")", "{", "return", "false", ";", "}", "if", "(", "!", "method_exists", "(", "$", "initModel", ",", "'initDbTable'", ")", ")", "{", "return", "false", ";", "}", "$", "ds", "=", "$", "initModel", "->", "getDataSource", "(", ")", ";", "if", "(", "!", "$", "ds", "->", "truncate", "(", "$", "initModel", ")", ")", "{", "return", "false", ";", "}", "return", "$", "initModel", "->", "initDbTable", "(", ")", ";", "}" ]
Initialization of database table the initial values @param string $table Database table name for initialization. Seeking method `initDbTable()` in the appropriate model and call it. @return bool Result of coll method `initDbTable()`
[ "Initialization", "of", "database", "table", "the", "initial", "values" ]
76136550e856ff4f8fd3634b77633f86510f63e9
https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerInit.php#L47-L67
train
deanblackborough/random-grab-bag
src/ImageResize/AbstractResize.php
AbstractResize.setCanvasColor
public function setCanvasColor(array $canvas_color) : AbstractResize { if (Helper::colorIndexValid('r', $canvas_color) === false || Helper::colorIndexValid('g', $canvas_color) === false || Helper::colorIndexValid('b', $canvas_color) === false ) { throw new \InvalidArgumentException(Helper::ERROR_CANVAS_COLOR_ARRAY_INVALID); } $this->canvas['color'] = $canvas_color; }
php
public function setCanvasColor(array $canvas_color) : AbstractResize { if (Helper::colorIndexValid('r', $canvas_color) === false || Helper::colorIndexValid('g', $canvas_color) === false || Helper::colorIndexValid('b', $canvas_color) === false ) { throw new \InvalidArgumentException(Helper::ERROR_CANVAS_COLOR_ARRAY_INVALID); } $this->canvas['color'] = $canvas_color; }
[ "public", "function", "setCanvasColor", "(", "array", "$", "canvas_color", ")", ":", "AbstractResize", "{", "if", "(", "Helper", "::", "colorIndexValid", "(", "'r'", ",", "$", "canvas_color", ")", "===", "false", "||", "Helper", "::", "colorIndexValid", "(", "'g'", ",", "$", "canvas_color", ")", "===", "false", "||", "Helper", "::", "colorIndexValid", "(", "'b'", ",", "$", "canvas_color", ")", "===", "false", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "Helper", "::", "ERROR_CANVAS_COLOR_ARRAY_INVALID", ")", ";", "}", "$", "this", "->", "canvas", "[", "'color'", "]", "=", "$", "canvas_color", ";", "}" ]
Set a new canvas color @param array $canvas_color Indexed array, r, g, b for color @return AbstractResize @throws \Exception
[ "Set", "a", "new", "canvas", "color" ]
b72814a80357d5dbd344b99c3d242678c8cf080f
https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L147-L157
train
deanblackborough/random-grab-bag
src/ImageResize/AbstractResize.php
AbstractResize.loadImage
public function loadImage(string $file, string $path = '') : AbstractResize { if (file_exists($path . $file) === true) { $this->source['path'] = $path; $this->source['file'] = $file; $this->sourceProperties(); } else { throw new \Exception("File couldn't be found in supplied destination: '" . $path . $file . "'"); } // Reset the processed status when a new image is loaded $this->processed = false; $this->file = null; $this->path = null; return $this; }
php
public function loadImage(string $file, string $path = '') : AbstractResize { if (file_exists($path . $file) === true) { $this->source['path'] = $path; $this->source['file'] = $file; $this->sourceProperties(); } else { throw new \Exception("File couldn't be found in supplied destination: '" . $path . $file . "'"); } // Reset the processed status when a new image is loaded $this->processed = false; $this->file = null; $this->path = null; return $this; }
[ "public", "function", "loadImage", "(", "string", "$", "file", ",", "string", "$", "path", "=", "''", ")", ":", "AbstractResize", "{", "if", "(", "file_exists", "(", "$", "path", ".", "$", "file", ")", "===", "true", ")", "{", "$", "this", "->", "source", "[", "'path'", "]", "=", "$", "path", ";", "$", "this", "->", "source", "[", "'file'", "]", "=", "$", "file", ";", "$", "this", "->", "sourceProperties", "(", ")", ";", "}", "else", "{", "throw", "new", "\\", "Exception", "(", "\"File couldn't be found in supplied destination: '\"", ".", "$", "path", ".", "$", "file", ".", "\"'\"", ")", ";", "}", "// Reset the processed status when a new image is loaded", "$", "this", "->", "processed", "=", "false", ";", "$", "this", "->", "file", "=", "null", ";", "$", "this", "->", "path", "=", "null", ";", "return", "$", "this", ";", "}" ]
Load the image @param string $file File name and extension @param string $path Full patch to image @return AbstractResize @throws \Exception Throws an exception if the image can't be loaded
[ "Load", "the", "image" ]
b72814a80357d5dbd344b99c3d242678c8cf080f
https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L168-L184
train
deanblackborough/random-grab-bag
src/ImageResize/AbstractResize.php
AbstractResize.sourceProperties
protected function sourceProperties() { $properties = Helper::imageProperties($this->source['file'], $this->source['path']); if ($properties['width'] !== null) { $this->source['width'] = $properties['width']; $this->source['height'] = $properties['height']; $this->source['aspect_ratio'] = $properties['aspect_ratio']; } else { throw new \Exception(Helper::ERROR_CALL_GETIMAGESIZE); } if ($this->canvas['width'] > $this->source['width'] || $this->canvas['height'] > $this->source['height']) { throw new \Exception(Helper::ERROR_UPSCALE); } }
php
protected function sourceProperties() { $properties = Helper::imageProperties($this->source['file'], $this->source['path']); if ($properties['width'] !== null) { $this->source['width'] = $properties['width']; $this->source['height'] = $properties['height']; $this->source['aspect_ratio'] = $properties['aspect_ratio']; } else { throw new \Exception(Helper::ERROR_CALL_GETIMAGESIZE); } if ($this->canvas['width'] > $this->source['width'] || $this->canvas['height'] > $this->source['height']) { throw new \Exception(Helper::ERROR_UPSCALE); } }
[ "protected", "function", "sourceProperties", "(", ")", "{", "$", "properties", "=", "Helper", "::", "imageProperties", "(", "$", "this", "->", "source", "[", "'file'", "]", ",", "$", "this", "->", "source", "[", "'path'", "]", ")", ";", "if", "(", "$", "properties", "[", "'width'", "]", "!==", "null", ")", "{", "$", "this", "->", "source", "[", "'width'", "]", "=", "$", "properties", "[", "'width'", "]", ";", "$", "this", "->", "source", "[", "'height'", "]", "=", "$", "properties", "[", "'height'", "]", ";", "$", "this", "->", "source", "[", "'aspect_ratio'", "]", "=", "$", "properties", "[", "'aspect_ratio'", "]", ";", "}", "else", "{", "throw", "new", "\\", "Exception", "(", "Helper", "::", "ERROR_CALL_GETIMAGESIZE", ")", ";", "}", "if", "(", "$", "this", "->", "canvas", "[", "'width'", "]", ">", "$", "this", "->", "source", "[", "'width'", "]", "||", "$", "this", "->", "canvas", "[", "'height'", "]", ">", "$", "this", "->", "source", "[", "'height'", "]", ")", "{", "throw", "new", "\\", "Exception", "(", "Helper", "::", "ERROR_UPSCALE", ")", ";", "}", "}" ]
Fetch the dimensions of the source image and calculate the aspect ratio. We also check to ensure that the image is being resized down, currently we don't support upscaling the image @return void @throws \Exception
[ "Fetch", "the", "dimensions", "of", "the", "source", "image", "and", "calculate", "the", "aspect", "ratio", ".", "We", "also", "check", "to", "ensure", "that", "the", "image", "is", "being", "resized", "down", "currently", "we", "don", "t", "support", "upscaling", "the", "image" ]
b72814a80357d5dbd344b99c3d242678c8cf080f
https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L194-L209
train
deanblackborough/random-grab-bag
src/ImageResize/AbstractResize.php
AbstractResize.resizeSource
public function resizeSource() : AbstractResize { if ($this->intermediate['maintain_aspect'] === true) { if ($this->source['aspect_ratio'] > 1.00) { $this->intermediateSizeLandscape(); } else { if ($this->source['aspect_ratio'] === 1.00) { $this->intermediateSizeSquare(); } else { $this->intermediateSizePortrait(); } } } else { $this->intermediate['width'] = $this->canvas['width']; $this->intermediate['height'] = $this->canvas['height']; } $this->canvasSpacingX(); $this->canvasSpacingY(); $this->processed = true; return $this; }
php
public function resizeSource() : AbstractResize { if ($this->intermediate['maintain_aspect'] === true) { if ($this->source['aspect_ratio'] > 1.00) { $this->intermediateSizeLandscape(); } else { if ($this->source['aspect_ratio'] === 1.00) { $this->intermediateSizeSquare(); } else { $this->intermediateSizePortrait(); } } } else { $this->intermediate['width'] = $this->canvas['width']; $this->intermediate['height'] = $this->canvas['height']; } $this->canvasSpacingX(); $this->canvasSpacingY(); $this->processed = true; return $this; }
[ "public", "function", "resizeSource", "(", ")", ":", "AbstractResize", "{", "if", "(", "$", "this", "->", "intermediate", "[", "'maintain_aspect'", "]", "===", "true", ")", "{", "if", "(", "$", "this", "->", "source", "[", "'aspect_ratio'", "]", ">", "1.00", ")", "{", "$", "this", "->", "intermediateSizeLandscape", "(", ")", ";", "}", "else", "{", "if", "(", "$", "this", "->", "source", "[", "'aspect_ratio'", "]", "===", "1.00", ")", "{", "$", "this", "->", "intermediateSizeSquare", "(", ")", ";", "}", "else", "{", "$", "this", "->", "intermediateSizePortrait", "(", ")", ";", "}", "}", "}", "else", "{", "$", "this", "->", "intermediate", "[", "'width'", "]", "=", "$", "this", "->", "canvas", "[", "'width'", "]", ";", "$", "this", "->", "intermediate", "[", "'height'", "]", "=", "$", "this", "->", "canvas", "[", "'height'", "]", ";", "}", "$", "this", "->", "canvasSpacingX", "(", ")", ";", "$", "this", "->", "canvasSpacingY", "(", ")", ";", "$", "this", "->", "processed", "=", "true", ";", "return", "$", "this", ";", "}" ]
Process the request, generate the size required for the image along with the canvas spacing @return AbstractResize @throws \Exception Throws an exception if unable to create image
[ "Process", "the", "request", "generate", "the", "size", "required", "for", "the", "image", "along", "with", "the", "canvas", "spacing" ]
b72814a80357d5dbd344b99c3d242678c8cf080f
https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L218-L241
train
deanblackborough/random-grab-bag
src/ImageResize/AbstractResize.php
AbstractResize.intermediateSizeLandscape
protected function intermediateSizeLandscape() { // Set width and then calculate height $this->intermediate['width'] = $this->canvas['width']; $this->intermediate['height'] = intval(round( $this->intermediate['width'] / $this->source['aspect_ratio'], 0)); // If height larger than requested, set and calculate new width if ($this->intermediate['height'] > $this->canvas['height']) { $this->intermediate['height'] = $this->canvas['height']; $this->intermediate['width'] = intval(round( $this->intermediate['height'] * $this->source['aspect_ratio'], 0)); } }
php
protected function intermediateSizeLandscape() { // Set width and then calculate height $this->intermediate['width'] = $this->canvas['width']; $this->intermediate['height'] = intval(round( $this->intermediate['width'] / $this->source['aspect_ratio'], 0)); // If height larger than requested, set and calculate new width if ($this->intermediate['height'] > $this->canvas['height']) { $this->intermediate['height'] = $this->canvas['height']; $this->intermediate['width'] = intval(round( $this->intermediate['height'] * $this->source['aspect_ratio'], 0)); } }
[ "protected", "function", "intermediateSizeLandscape", "(", ")", "{", "// Set width and then calculate height", "$", "this", "->", "intermediate", "[", "'width'", "]", "=", "$", "this", "->", "canvas", "[", "'width'", "]", ";", "$", "this", "->", "intermediate", "[", "'height'", "]", "=", "intval", "(", "round", "(", "$", "this", "->", "intermediate", "[", "'width'", "]", "/", "$", "this", "->", "source", "[", "'aspect_ratio'", "]", ",", "0", ")", ")", ";", "// If height larger than requested, set and calculate new width", "if", "(", "$", "this", "->", "intermediate", "[", "'height'", "]", ">", "$", "this", "->", "canvas", "[", "'height'", "]", ")", "{", "$", "this", "->", "intermediate", "[", "'height'", "]", "=", "$", "this", "->", "canvas", "[", "'height'", "]", ";", "$", "this", "->", "intermediate", "[", "'width'", "]", "=", "intval", "(", "round", "(", "$", "this", "->", "intermediate", "[", "'height'", "]", "*", "$", "this", "->", "source", "[", "'aspect_ratio'", "]", ",", "0", ")", ")", ";", "}", "}" ]
The source image is landscape, maintaining aspect ratio calculate the intermediate image height and width @return void
[ "The", "source", "image", "is", "landscape", "maintaining", "aspect", "ratio", "calculate", "the", "intermediate", "image", "height", "and", "width" ]
b72814a80357d5dbd344b99c3d242678c8cf080f
https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L249-L262
train
deanblackborough/random-grab-bag
src/ImageResize/AbstractResize.php
AbstractResize.intermediateSizeSquare
protected function intermediateSizeSquare() { if ($this->canvas['height'] === $this->canvas['width']) { $this->intermediate['width'] = $this->canvas['width']; $this->intermediate['height'] = $this->canvas['height']; } else { if ($this->canvas['width'] > $this->canvas['height']) { $this->intermediate['width'] = $this->canvas['height']; $this->intermediate['height'] = $this->canvas['height']; } else { $this->intermediate['height'] = $this->canvas['width']; $this->intermediate['width'] = $this->canvas['width']; } } }
php
protected function intermediateSizeSquare() { if ($this->canvas['height'] === $this->canvas['width']) { $this->intermediate['width'] = $this->canvas['width']; $this->intermediate['height'] = $this->canvas['height']; } else { if ($this->canvas['width'] > $this->canvas['height']) { $this->intermediate['width'] = $this->canvas['height']; $this->intermediate['height'] = $this->canvas['height']; } else { $this->intermediate['height'] = $this->canvas['width']; $this->intermediate['width'] = $this->canvas['width']; } } }
[ "protected", "function", "intermediateSizeSquare", "(", ")", "{", "if", "(", "$", "this", "->", "canvas", "[", "'height'", "]", "===", "$", "this", "->", "canvas", "[", "'width'", "]", ")", "{", "$", "this", "->", "intermediate", "[", "'width'", "]", "=", "$", "this", "->", "canvas", "[", "'width'", "]", ";", "$", "this", "->", "intermediate", "[", "'height'", "]", "=", "$", "this", "->", "canvas", "[", "'height'", "]", ";", "}", "else", "{", "if", "(", "$", "this", "->", "canvas", "[", "'width'", "]", ">", "$", "this", "->", "canvas", "[", "'height'", "]", ")", "{", "$", "this", "->", "intermediate", "[", "'width'", "]", "=", "$", "this", "->", "canvas", "[", "'height'", "]", ";", "$", "this", "->", "intermediate", "[", "'height'", "]", "=", "$", "this", "->", "canvas", "[", "'height'", "]", ";", "}", "else", "{", "$", "this", "->", "intermediate", "[", "'height'", "]", "=", "$", "this", "->", "canvas", "[", "'width'", "]", ";", "$", "this", "->", "intermediate", "[", "'width'", "]", "=", "$", "this", "->", "canvas", "[", "'width'", "]", ";", "}", "}", "}" ]
The source image is landscape, fit as appropriate @return void
[ "The", "source", "image", "is", "landscape", "fit", "as", "appropriate" ]
b72814a80357d5dbd344b99c3d242678c8cf080f
https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L269-L283
train
deanblackborough/random-grab-bag
src/ImageResize/AbstractResize.php
AbstractResize.intermediateSizePortrait
protected function intermediateSizePortrait() { // Set height and then calculate width $this->intermediate['height'] = $this->canvas['height']; $this->intermediate['width'] = intval(round( $this->intermediate['height'] * $this->source['aspect_ratio'], 0)); // If width larger than requested, set and calculate new height if ($this->intermediate['width'] > $this->canvas['width']) { $this->intermediate['width'] = $this->canvas['width']; $this->intermediate['height'] = intval(round( $this->intermediate['width'] / $this->source['aspect_ratio'], 0)); } }
php
protected function intermediateSizePortrait() { // Set height and then calculate width $this->intermediate['height'] = $this->canvas['height']; $this->intermediate['width'] = intval(round( $this->intermediate['height'] * $this->source['aspect_ratio'], 0)); // If width larger than requested, set and calculate new height if ($this->intermediate['width'] > $this->canvas['width']) { $this->intermediate['width'] = $this->canvas['width']; $this->intermediate['height'] = intval(round( $this->intermediate['width'] / $this->source['aspect_ratio'], 0)); } }
[ "protected", "function", "intermediateSizePortrait", "(", ")", "{", "// Set height and then calculate width", "$", "this", "->", "intermediate", "[", "'height'", "]", "=", "$", "this", "->", "canvas", "[", "'height'", "]", ";", "$", "this", "->", "intermediate", "[", "'width'", "]", "=", "intval", "(", "round", "(", "$", "this", "->", "intermediate", "[", "'height'", "]", "*", "$", "this", "->", "source", "[", "'aspect_ratio'", "]", ",", "0", ")", ")", ";", "// If width larger than requested, set and calculate new height", "if", "(", "$", "this", "->", "intermediate", "[", "'width'", "]", ">", "$", "this", "->", "canvas", "[", "'width'", "]", ")", "{", "$", "this", "->", "intermediate", "[", "'width'", "]", "=", "$", "this", "->", "canvas", "[", "'width'", "]", ";", "$", "this", "->", "intermediate", "[", "'height'", "]", "=", "intval", "(", "round", "(", "$", "this", "->", "intermediate", "[", "'width'", "]", "/", "$", "this", "->", "source", "[", "'aspect_ratio'", "]", ",", "0", ")", ")", ";", "}", "}" ]
The source image is portrait, maintaining aspect ratio calculate the intermediate image height and width @return void
[ "The", "source", "image", "is", "portrait", "maintaining", "aspect", "ratio", "calculate", "the", "intermediate", "image", "height", "and", "width" ]
b72814a80357d5dbd344b99c3d242678c8cf080f
https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L291-L304
train
deanblackborough/random-grab-bag
src/ImageResize/AbstractResize.php
AbstractResize.canvasSpacingX
protected function canvasSpacingX() { $this->canvas['spacing']['x'] = 0; if ($this->intermediate['width'] < $this->canvas['width']) { $difference = $this->canvas['width'] - $this->intermediate['width']; if ($difference % 2 === 0) { $this->canvas['spacing']['x'] = $difference / 2; } else { if ($difference > 1) { $this->canvas['spacing']['x'] = ($difference - 1) / 2 + 1; } else { $this->canvas['spacing']['x'] = 1; } } } }
php
protected function canvasSpacingX() { $this->canvas['spacing']['x'] = 0; if ($this->intermediate['width'] < $this->canvas['width']) { $difference = $this->canvas['width'] - $this->intermediate['width']; if ($difference % 2 === 0) { $this->canvas['spacing']['x'] = $difference / 2; } else { if ($difference > 1) { $this->canvas['spacing']['x'] = ($difference - 1) / 2 + 1; } else { $this->canvas['spacing']['x'] = 1; } } } }
[ "protected", "function", "canvasSpacingX", "(", ")", "{", "$", "this", "->", "canvas", "[", "'spacing'", "]", "[", "'x'", "]", "=", "0", ";", "if", "(", "$", "this", "->", "intermediate", "[", "'width'", "]", "<", "$", "this", "->", "canvas", "[", "'width'", "]", ")", "{", "$", "difference", "=", "$", "this", "->", "canvas", "[", "'width'", "]", "-", "$", "this", "->", "intermediate", "[", "'width'", "]", ";", "if", "(", "$", "difference", "%", "2", "===", "0", ")", "{", "$", "this", "->", "canvas", "[", "'spacing'", "]", "[", "'x'", "]", "=", "$", "difference", "/", "2", ";", "}", "else", "{", "if", "(", "$", "difference", ">", "1", ")", "{", "$", "this", "->", "canvas", "[", "'spacing'", "]", "[", "'x'", "]", "=", "(", "$", "difference", "-", "1", ")", "/", "2", "+", "1", ";", "}", "else", "{", "$", "this", "->", "canvas", "[", "'spacing'", "]", "[", "'x'", "]", "=", "1", ";", "}", "}", "}", "}" ]
Calculate any required x canvas spacing, necessary if the intermediate image will be smaller than the canvas @return void
[ "Calculate", "any", "required", "x", "canvas", "spacing", "necessary", "if", "the", "intermediate", "image", "will", "be", "smaller", "than", "the", "canvas" ]
b72814a80357d5dbd344b99c3d242678c8cf080f
https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L312-L329
train
deanblackborough/random-grab-bag
src/ImageResize/AbstractResize.php
AbstractResize.canvasSpacingY
protected function canvasSpacingY() { $this->canvas['spacing']['y'] = 0; if ($this->intermediate['height'] < $this->canvas['height']) { $difference = $this->canvas['height'] - $this->intermediate['height']; if ($difference % 2 === 0) { $this->canvas['spacing']['y'] = $difference / 2; } else { if ($difference > 1) { $this->canvas['spacing']['y'] = ($difference - 1) / 2 + 1; } else { $this->canvas['spacing']['y'] = 1; } } } }
php
protected function canvasSpacingY() { $this->canvas['spacing']['y'] = 0; if ($this->intermediate['height'] < $this->canvas['height']) { $difference = $this->canvas['height'] - $this->intermediate['height']; if ($difference % 2 === 0) { $this->canvas['spacing']['y'] = $difference / 2; } else { if ($difference > 1) { $this->canvas['spacing']['y'] = ($difference - 1) / 2 + 1; } else { $this->canvas['spacing']['y'] = 1; } } } }
[ "protected", "function", "canvasSpacingY", "(", ")", "{", "$", "this", "->", "canvas", "[", "'spacing'", "]", "[", "'y'", "]", "=", "0", ";", "if", "(", "$", "this", "->", "intermediate", "[", "'height'", "]", "<", "$", "this", "->", "canvas", "[", "'height'", "]", ")", "{", "$", "difference", "=", "$", "this", "->", "canvas", "[", "'height'", "]", "-", "$", "this", "->", "intermediate", "[", "'height'", "]", ";", "if", "(", "$", "difference", "%", "2", "===", "0", ")", "{", "$", "this", "->", "canvas", "[", "'spacing'", "]", "[", "'y'", "]", "=", "$", "difference", "/", "2", ";", "}", "else", "{", "if", "(", "$", "difference", ">", "1", ")", "{", "$", "this", "->", "canvas", "[", "'spacing'", "]", "[", "'y'", "]", "=", "(", "$", "difference", "-", "1", ")", "/", "2", "+", "1", ";", "}", "else", "{", "$", "this", "->", "canvas", "[", "'spacing'", "]", "[", "'y'", "]", "=", "1", ";", "}", "}", "}", "}" ]
Calculate any required y canvas spacing, necessary if the intermediate image will be smaller than the canvas @return void
[ "Calculate", "any", "required", "y", "canvas", "spacing", "necessary", "if", "the", "intermediate", "image", "will", "be", "smaller", "than", "the", "canvas" ]
b72814a80357d5dbd344b99c3d242678c8cf080f
https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L337-L355
train
deanblackborough/random-grab-bag
src/ImageResize/AbstractResize.php
AbstractResize.createCanvas
protected function createCanvas() { $this->canvas['canvas'] = imagecreatetruecolor($this->canvas['width'], $this->canvas['height']); if ($this->canvas['canvas'] === false) { throw new \Exception(Helper::ERROR_CALL_IMAGECREATETRUECOLOR); } $fill_color = imagecolorallocate($this->canvas['canvas'], $this->canvas['color']['r'], $this->canvas['color']['g'], $this->canvas['color']['b']); if ($fill_color === false) { throw new \Exception(Helper::ERROR_CALL_IMAGECOLORALLOCATE); } if (imagefill($this->canvas['canvas'], 0, 0, $fill_color) === false) { throw new \Exception(Helper::ERROR_CALL_IMAGEFILL); }; }
php
protected function createCanvas() { $this->canvas['canvas'] = imagecreatetruecolor($this->canvas['width'], $this->canvas['height']); if ($this->canvas['canvas'] === false) { throw new \Exception(Helper::ERROR_CALL_IMAGECREATETRUECOLOR); } $fill_color = imagecolorallocate($this->canvas['canvas'], $this->canvas['color']['r'], $this->canvas['color']['g'], $this->canvas['color']['b']); if ($fill_color === false) { throw new \Exception(Helper::ERROR_CALL_IMAGECOLORALLOCATE); } if (imagefill($this->canvas['canvas'], 0, 0, $fill_color) === false) { throw new \Exception(Helper::ERROR_CALL_IMAGEFILL); }; }
[ "protected", "function", "createCanvas", "(", ")", "{", "$", "this", "->", "canvas", "[", "'canvas'", "]", "=", "imagecreatetruecolor", "(", "$", "this", "->", "canvas", "[", "'width'", "]", ",", "$", "this", "->", "canvas", "[", "'height'", "]", ")", ";", "if", "(", "$", "this", "->", "canvas", "[", "'canvas'", "]", "===", "false", ")", "{", "throw", "new", "\\", "Exception", "(", "Helper", "::", "ERROR_CALL_IMAGECREATETRUECOLOR", ")", ";", "}", "$", "fill_color", "=", "imagecolorallocate", "(", "$", "this", "->", "canvas", "[", "'canvas'", "]", ",", "$", "this", "->", "canvas", "[", "'color'", "]", "[", "'r'", "]", ",", "$", "this", "->", "canvas", "[", "'color'", "]", "[", "'g'", "]", ",", "$", "this", "->", "canvas", "[", "'color'", "]", "[", "'b'", "]", ")", ";", "if", "(", "$", "fill_color", "===", "false", ")", "{", "throw", "new", "\\", "Exception", "(", "Helper", "::", "ERROR_CALL_IMAGECOLORALLOCATE", ")", ";", "}", "if", "(", "imagefill", "(", "$", "this", "->", "canvas", "[", "'canvas'", "]", ",", "0", ",", "0", ",", "$", "fill_color", ")", "===", "false", ")", "{", "throw", "new", "\\", "Exception", "(", "Helper", "::", "ERROR_CALL_IMAGEFILL", ")", ";", "}", ";", "}" ]
Create the canvas and fill with the canvas colour @throws \Exception
[ "Create", "the", "canvas", "and", "fill", "with", "the", "canvas", "colour" ]
b72814a80357d5dbd344b99c3d242678c8cf080f
https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L410-L426
train
deanblackborough/random-grab-bag
src/ImageResize/AbstractResize.php
AbstractResize.resampleCopy
protected function resampleCopy() { $result = imagecopyresampled($this->canvas['canvas'], $this->intermediate['copy'], $this->canvas['spacing']['x'], $this->canvas['spacing']['y'], 0 ,0, $this->intermediate['width'], $this->intermediate['height'], $this->source['width'], $this->source['height']); if($result === false) { throw new \Exception(Helper::ERROR_CALL_IMAGECOPYRESAMPLED); } }
php
protected function resampleCopy() { $result = imagecopyresampled($this->canvas['canvas'], $this->intermediate['copy'], $this->canvas['spacing']['x'], $this->canvas['spacing']['y'], 0 ,0, $this->intermediate['width'], $this->intermediate['height'], $this->source['width'], $this->source['height']); if($result === false) { throw new \Exception(Helper::ERROR_CALL_IMAGECOPYRESAMPLED); } }
[ "protected", "function", "resampleCopy", "(", ")", "{", "$", "result", "=", "imagecopyresampled", "(", "$", "this", "->", "canvas", "[", "'canvas'", "]", ",", "$", "this", "->", "intermediate", "[", "'copy'", "]", ",", "$", "this", "->", "canvas", "[", "'spacing'", "]", "[", "'x'", "]", ",", "$", "this", "->", "canvas", "[", "'spacing'", "]", "[", "'y'", "]", ",", "0", ",", "0", ",", "$", "this", "->", "intermediate", "[", "'width'", "]", ",", "$", "this", "->", "intermediate", "[", "'height'", "]", ",", "$", "this", "->", "source", "[", "'width'", "]", ",", "$", "this", "->", "source", "[", "'height'", "]", ")", ";", "if", "(", "$", "result", "===", "false", ")", "{", "throw", "new", "\\", "Exception", "(", "Helper", "::", "ERROR_CALL_IMAGECOPYRESAMPLED", ")", ";", "}", "}" ]
Resample the image copy @throws \Exception
[ "Resample", "the", "image", "copy" ]
b72814a80357d5dbd344b99c3d242678c8cf080f
https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L433-L443
train
deanblackborough/random-grab-bag
src/ImageResize/AbstractResize.php
AbstractResize.save
public function save() : AbstractResize { if ($this->file === null) { $this->file = str_replace($this->extension, '-copy' . $this->extension, $this->source['file']); } if ($this->path === null) { $this->path = $this->source['path']; } $this->saveFile(); return $this; }
php
public function save() : AbstractResize { if ($this->file === null) { $this->file = str_replace($this->extension, '-copy' . $this->extension, $this->source['file']); } if ($this->path === null) { $this->path = $this->source['path']; } $this->saveFile(); return $this; }
[ "public", "function", "save", "(", ")", ":", "AbstractResize", "{", "if", "(", "$", "this", "->", "file", "===", "null", ")", "{", "$", "this", "->", "file", "=", "str_replace", "(", "$", "this", "->", "extension", ",", "'-copy'", ".", "$", "this", "->", "extension", ",", "$", "this", "->", "source", "[", "'file'", "]", ")", ";", "}", "if", "(", "$", "this", "->", "path", "===", "null", ")", "{", "$", "this", "->", "path", "=", "$", "this", "->", "source", "[", "'path'", "]", ";", "}", "$", "this", "->", "saveFile", "(", ")", ";", "return", "$", "this", ";", "}" ]
Save the new image @return AbstractResize @throws \Exception Throws an exception if the save fails
[ "Save", "the", "new", "image" ]
b72814a80357d5dbd344b99c3d242678c8cf080f
https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L496-L508
train
foothing/laravel-wrappr
src/Foothing/Wrappr/Installer/Parser.php
Parser.getResourceFromPath
public function getResourceFromPath(Route $route, $path) { // Explode it. $chunks = explode("/", $path); return $route->resourceOffset ? $chunks[$route->resourceOffset ] : null; }
php
public function getResourceFromPath(Route $route, $path) { // Explode it. $chunks = explode("/", $path); return $route->resourceOffset ? $chunks[$route->resourceOffset ] : null; }
[ "public", "function", "getResourceFromPath", "(", "Route", "$", "route", ",", "$", "path", ")", "{", "// Explode it.", "$", "chunks", "=", "explode", "(", "\"/\"", ",", "$", "path", ")", ";", "return", "$", "route", "->", "resourceOffset", "?", "$", "chunks", "[", "$", "route", "->", "resourceOffset", "]", ":", "null", ";", "}" ]
Extract the resource identifier from the given path. @param Route $route @param $path @return mixed resource identifier
[ "Extract", "the", "resource", "identifier", "from", "the", "given", "path", "." ]
4f6b0181679866b2e42c2e86bdbc1d9fb5d2390b
https://github.com/foothing/laravel-wrappr/blob/4f6b0181679866b2e42c2e86bdbc1d9fb5d2390b/src/Foothing/Wrappr/Installer/Parser.php#L95-L99
train
foothing/laravel-wrappr
src/Foothing/Wrappr/Installer/Parser.php
Parser.trimPath
public function trimPath($path) { // Rewrite leading double slashes. $path = preg_replace("/^\/\//", "/", $path); // If there are more double slashes route is invalid. if (preg_match("/\/{2,}/", $path)) { throw new \Exception('Route path has invalid format ' . $path); } // Trim chars. return trim($path, " \t\n\r\0\x0B/"); }
php
public function trimPath($path) { // Rewrite leading double slashes. $path = preg_replace("/^\/\//", "/", $path); // If there are more double slashes route is invalid. if (preg_match("/\/{2,}/", $path)) { throw new \Exception('Route path has invalid format ' . $path); } // Trim chars. return trim($path, " \t\n\r\0\x0B/"); }
[ "public", "function", "trimPath", "(", "$", "path", ")", "{", "// Rewrite leading double slashes.", "$", "path", "=", "preg_replace", "(", "\"/^\\/\\//\"", ",", "\"/\"", ",", "$", "path", ")", ";", "// If there are more double slashes route is invalid.", "if", "(", "preg_match", "(", "\"/\\/{2,}/\"", ",", "$", "path", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'Route path has invalid format '", ".", "$", "path", ")", ";", "}", "// Trim chars.", "return", "trim", "(", "$", "path", ",", "\" \\t\\n\\r\\0\\x0B/\"", ")", ";", "}" ]
Right and left trim route from blanks and undesired characters. @param $path @return string @throws \Exception
[ "Right", "and", "left", "trim", "route", "from", "blanks", "and", "undesired", "characters", "." ]
4f6b0181679866b2e42c2e86bdbc1d9fb5d2390b
https://github.com/foothing/laravel-wrappr/blob/4f6b0181679866b2e42c2e86bdbc1d9fb5d2390b/src/Foothing/Wrappr/Installer/Parser.php#L109-L120
train
rawcreative/Receiptful
src/Api.php
Api.factory
public static function factory(array $config) { if ( ! array_key_exists('apiKey', $config)) { throw new \Exception('Api factory requires $apiKey parameter.'); } $client = new Client([ 'defaults' => [ 'headers' => [ 'X-ApiKey' => $config['apiKey'], ], ], ], [], $config); $description = self::getDescriptionFromConfig($config); $apiVersion = isset($config['apiVersion']) ? $config['apiVersion'] : 1; return new self($client, $description, ['defaults' => ['api_version' => $apiVersion]]); }
php
public static function factory(array $config) { if ( ! array_key_exists('apiKey', $config)) { throw new \Exception('Api factory requires $apiKey parameter.'); } $client = new Client([ 'defaults' => [ 'headers' => [ 'X-ApiKey' => $config['apiKey'], ], ], ], [], $config); $description = self::getDescriptionFromConfig($config); $apiVersion = isset($config['apiVersion']) ? $config['apiVersion'] : 1; return new self($client, $description, ['defaults' => ['api_version' => $apiVersion]]); }
[ "public", "static", "function", "factory", "(", "array", "$", "config", ")", "{", "if", "(", "!", "array_key_exists", "(", "'apiKey'", ",", "$", "config", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'Api factory requires $apiKey parameter.'", ")", ";", "}", "$", "client", "=", "new", "Client", "(", "[", "'defaults'", "=>", "[", "'headers'", "=>", "[", "'X-ApiKey'", "=>", "$", "config", "[", "'apiKey'", "]", ",", "]", ",", "]", ",", "]", ",", "[", "]", ",", "$", "config", ")", ";", "$", "description", "=", "self", "::", "getDescriptionFromConfig", "(", "$", "config", ")", ";", "$", "apiVersion", "=", "isset", "(", "$", "config", "[", "'apiVersion'", "]", ")", "?", "$", "config", "[", "'apiVersion'", "]", ":", "1", ";", "return", "new", "self", "(", "$", "client", ",", "$", "description", ",", "[", "'defaults'", "=>", "[", "'api_version'", "=>", "$", "apiVersion", "]", "]", ")", ";", "}" ]
Creates and returns an Api client instance @param array $config @return Api @throws \Exception
[ "Creates", "and", "returns", "an", "Api", "client", "instance" ]
1075a189a1e0c4ef01fcdfc5cd75c91cc2fb8f14
https://github.com/rawcreative/Receiptful/blob/1075a189a1e0c4ef01fcdfc5cd75c91cc2fb8f14/src/Api.php#L18-L37
train
rawcreative/Receiptful
src/Api.php
Api.getDescriptionFromConfig
private static function getDescriptionFromConfig(array $config) { $data = isset($config['descriptionPath']) && is_readable($config['descriptionPath']) ? include $config['descriptionPath'] : include __DIR__ . '/receiptful-api.php'; return new Description($data); }
php
private static function getDescriptionFromConfig(array $config) { $data = isset($config['descriptionPath']) && is_readable($config['descriptionPath']) ? include $config['descriptionPath'] : include __DIR__ . '/receiptful-api.php'; return new Description($data); }
[ "private", "static", "function", "getDescriptionFromConfig", "(", "array", "$", "config", ")", "{", "$", "data", "=", "isset", "(", "$", "config", "[", "'descriptionPath'", "]", ")", "&&", "is_readable", "(", "$", "config", "[", "'descriptionPath'", "]", ")", "?", "include", "$", "config", "[", "'descriptionPath'", "]", ":", "include", "__DIR__", ".", "'/receiptful-api.php'", ";", "return", "new", "Description", "(", "$", "data", ")", ";", "}" ]
Loads the api service description @param array $config @return Description
[ "Loads", "the", "api", "service", "description" ]
1075a189a1e0c4ef01fcdfc5cd75c91cc2fb8f14
https://github.com/rawcreative/Receiptful/blob/1075a189a1e0c4ef01fcdfc5cd75c91cc2fb8f14/src/Api.php#L45-L52
train
diatem-net/jin-social
src/Social/Jasig/CAS/CASSSO.php
CASSSO.getBaseUrl
protected static function getBaseUrl() { $baseUrl = 'https://'; if (!self::$ssl) { $baseUrl = 'http://'; } $baseUrl .= sprintf('%s:%s/%s/', self::$host, self::$port, self::$context); return $baseUrl; }
php
protected static function getBaseUrl() { $baseUrl = 'https://'; if (!self::$ssl) { $baseUrl = 'http://'; } $baseUrl .= sprintf('%s:%s/%s/', self::$host, self::$port, self::$context); return $baseUrl; }
[ "protected", "static", "function", "getBaseUrl", "(", ")", "{", "$", "baseUrl", "=", "'https://'", ";", "if", "(", "!", "self", "::", "$", "ssl", ")", "{", "$", "baseUrl", "=", "'http://'", ";", "}", "$", "baseUrl", ".=", "sprintf", "(", "'%s:%s/%s/'", ",", "self", "::", "$", "host", ",", "self", "::", "$", "port", ",", "self", "::", "$", "context", ")", ";", "return", "$", "baseUrl", ";", "}" ]
Construit l'url de connexion au serveur @return string
[ "Construit", "l", "url", "de", "connexion", "au", "serveur" ]
c49bc8d1b28264ae58e0af9e0452c8d17623e25d
https://github.com/diatem-net/jin-social/blob/c49bc8d1b28264ae58e0af9e0452c8d17623e25d/src/Social/Jasig/CAS/CASSSO.php#L149-L157
train
schpill/thin
src/Redisraw.php
Redisraw.run
public function run($method, $parameters) {dieDump($method); fwrite($this->connect(), $this->command($method, (array) $parameters)); $response = trim(fgets($this->connect())); return $this->parse($response); }
php
public function run($method, $parameters) {dieDump($method); fwrite($this->connect(), $this->command($method, (array) $parameters)); $response = trim(fgets($this->connect())); return $this->parse($response); }
[ "public", "function", "run", "(", "$", "method", ",", "$", "parameters", ")", "{", "dieDump", "(", "$", "method", ")", ";", "fwrite", "(", "$", "this", "->", "connect", "(", ")", ",", "$", "this", "->", "command", "(", "$", "method", ",", "(", "array", ")", "$", "parameters", ")", ")", ";", "$", "response", "=", "trim", "(", "fgets", "(", "$", "this", "->", "connect", "(", ")", ")", ")", ";", "return", "$", "this", "->", "parse", "(", "$", "response", ")", ";", "}" ]
Execute a command against the Redis database. <code> // Execute the GET command for the "name" key $name = Redis::db()->run('get', array('name')); // Execute the LRANGE command for the "list" key $list = Redis::db()->run('lrange', array(0, 5)); </code> @param string $method @param array $parameters @return mixed
[ "Execute", "a", "command", "against", "the", "Redis", "database", "." ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Redisraw.php#L101-L106
train
schpill/thin
src/Redisraw.php
Redisraw.parse
protected function parse($response) { switch (substr($response, 0, 1)) { case '-': throw new Exception('Redis error: ' . substr(trim($response), 4)); case '+': case ':': return $this->inline($response); case '$': return $this->bulk($response); case '*': return $this->multibulk($response); default: throw new Exception("Unknown Redis response: " . substr($response, 0, 1)); } }
php
protected function parse($response) { switch (substr($response, 0, 1)) { case '-': throw new Exception('Redis error: ' . substr(trim($response), 4)); case '+': case ':': return $this->inline($response); case '$': return $this->bulk($response); case '*': return $this->multibulk($response); default: throw new Exception("Unknown Redis response: " . substr($response, 0, 1)); } }
[ "protected", "function", "parse", "(", "$", "response", ")", "{", "switch", "(", "substr", "(", "$", "response", ",", "0", ",", "1", ")", ")", "{", "case", "'-'", ":", "throw", "new", "Exception", "(", "'Redis error: '", ".", "substr", "(", "trim", "(", "$", "response", ")", ",", "4", ")", ")", ";", "case", "'+'", ":", "case", "':'", ":", "return", "$", "this", "->", "inline", "(", "$", "response", ")", ";", "case", "'$'", ":", "return", "$", "this", "->", "bulk", "(", "$", "response", ")", ";", "case", "'*'", ":", "return", "$", "this", "->", "multibulk", "(", "$", "response", ")", ";", "default", ":", "throw", "new", "Exception", "(", "\"Unknown Redis response: \"", ".", "substr", "(", "$", "response", ",", "0", ",", "1", ")", ")", ";", "}", "}" ]
Parse and return the response from the Redis database. @param string $response @return mixed
[ "Parse", "and", "return", "the", "response", "from", "the", "Redis", "database", "." ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Redisraw.php#L114-L133
train
villermen/runescape-lookup-commons
src/HighScore/SkillHighScore.php
SkillHighScore.getCombatLevel
public function getCombatLevel($includeSummoning = true): int { $attackLevel = $this->getSkill(Skill::SKILL_ATTACK) ? $this->getSkill(Skill::SKILL_ATTACK)->getLevel() : 1; $defenceLevel = $this->getSkill(Skill::SKILL_DEFENCE) ? $this->getSkill(Skill::SKILL_DEFENCE)->getLevel() : 1; $strengthLevel = $this->getSkill(Skill::SKILL_STRENGTH) ? $this->getSkill(Skill::SKILL_STRENGTH)->getLevel() : 1; $constitutionLevel = $this->getSkill(Skill::SKILL_CONSTITUTION) ? $this->getSkill(Skill::SKILL_CONSTITUTION)->getLevel() : 10; $rangedLevel = $this->getSkill(Skill::SKILL_RANGED) ? $this->getSkill(Skill::SKILL_RANGED)->getLevel() : 1; $prayerLevel = $this->getSkill(Skill::SKILL_PRAYER) ? $this->getSkill(Skill::SKILL_PRAYER)->getLevel() : 1; $magicLevel = $this->getSkill(Skill::SKILL_MAGIC) ? $this->getSkill(Skill::SKILL_MAGIC)->getLevel() : 1; $summoningLevel = $includeSummoning && $this->getSkill(Skill::SKILL_SUMMONING) ? $this->getSkill(Skill::SKILL_SUMMONING)->getLevel() : 1; return (int)(( max($attackLevel + $strengthLevel, $magicLevel * 2, $rangedLevel * 2) * 1.3 + $defenceLevel + $constitutionLevel + floor($prayerLevel / 2) + floor($summoningLevel / 2) ) / 4); }
php
public function getCombatLevel($includeSummoning = true): int { $attackLevel = $this->getSkill(Skill::SKILL_ATTACK) ? $this->getSkill(Skill::SKILL_ATTACK)->getLevel() : 1; $defenceLevel = $this->getSkill(Skill::SKILL_DEFENCE) ? $this->getSkill(Skill::SKILL_DEFENCE)->getLevel() : 1; $strengthLevel = $this->getSkill(Skill::SKILL_STRENGTH) ? $this->getSkill(Skill::SKILL_STRENGTH)->getLevel() : 1; $constitutionLevel = $this->getSkill(Skill::SKILL_CONSTITUTION) ? $this->getSkill(Skill::SKILL_CONSTITUTION)->getLevel() : 10; $rangedLevel = $this->getSkill(Skill::SKILL_RANGED) ? $this->getSkill(Skill::SKILL_RANGED)->getLevel() : 1; $prayerLevel = $this->getSkill(Skill::SKILL_PRAYER) ? $this->getSkill(Skill::SKILL_PRAYER)->getLevel() : 1; $magicLevel = $this->getSkill(Skill::SKILL_MAGIC) ? $this->getSkill(Skill::SKILL_MAGIC)->getLevel() : 1; $summoningLevel = $includeSummoning && $this->getSkill(Skill::SKILL_SUMMONING) ? $this->getSkill(Skill::SKILL_SUMMONING)->getLevel() : 1; return (int)(( max($attackLevel + $strengthLevel, $magicLevel * 2, $rangedLevel * 2) * 1.3 + $defenceLevel + $constitutionLevel + floor($prayerLevel / 2) + floor($summoningLevel / 2) ) / 4); }
[ "public", "function", "getCombatLevel", "(", "$", "includeSummoning", "=", "true", ")", ":", "int", "{", "$", "attackLevel", "=", "$", "this", "->", "getSkill", "(", "Skill", "::", "SKILL_ATTACK", ")", "?", "$", "this", "->", "getSkill", "(", "Skill", "::", "SKILL_ATTACK", ")", "->", "getLevel", "(", ")", ":", "1", ";", "$", "defenceLevel", "=", "$", "this", "->", "getSkill", "(", "Skill", "::", "SKILL_DEFENCE", ")", "?", "$", "this", "->", "getSkill", "(", "Skill", "::", "SKILL_DEFENCE", ")", "->", "getLevel", "(", ")", ":", "1", ";", "$", "strengthLevel", "=", "$", "this", "->", "getSkill", "(", "Skill", "::", "SKILL_STRENGTH", ")", "?", "$", "this", "->", "getSkill", "(", "Skill", "::", "SKILL_STRENGTH", ")", "->", "getLevel", "(", ")", ":", "1", ";", "$", "constitutionLevel", "=", "$", "this", "->", "getSkill", "(", "Skill", "::", "SKILL_CONSTITUTION", ")", "?", "$", "this", "->", "getSkill", "(", "Skill", "::", "SKILL_CONSTITUTION", ")", "->", "getLevel", "(", ")", ":", "10", ";", "$", "rangedLevel", "=", "$", "this", "->", "getSkill", "(", "Skill", "::", "SKILL_RANGED", ")", "?", "$", "this", "->", "getSkill", "(", "Skill", "::", "SKILL_RANGED", ")", "->", "getLevel", "(", ")", ":", "1", ";", "$", "prayerLevel", "=", "$", "this", "->", "getSkill", "(", "Skill", "::", "SKILL_PRAYER", ")", "?", "$", "this", "->", "getSkill", "(", "Skill", "::", "SKILL_PRAYER", ")", "->", "getLevel", "(", ")", ":", "1", ";", "$", "magicLevel", "=", "$", "this", "->", "getSkill", "(", "Skill", "::", "SKILL_MAGIC", ")", "?", "$", "this", "->", "getSkill", "(", "Skill", "::", "SKILL_MAGIC", ")", "->", "getLevel", "(", ")", ":", "1", ";", "$", "summoningLevel", "=", "$", "includeSummoning", "&&", "$", "this", "->", "getSkill", "(", "Skill", "::", "SKILL_SUMMONING", ")", "?", "$", "this", "->", "getSkill", "(", "Skill", "::", "SKILL_SUMMONING", ")", "->", "getLevel", "(", ")", ":", "1", ";", "return", "(", "int", ")", "(", "(", "max", "(", "$", "attackLevel", "+", "$", "strengthLevel", ",", "$", "magicLevel", "*", "2", ",", "$", "rangedLevel", "*", "2", ")", "*", "1.3", "+", "$", "defenceLevel", "+", "$", "constitutionLevel", "+", "floor", "(", "$", "prayerLevel", "/", "2", ")", "+", "floor", "(", "$", "summoningLevel", "/", "2", ")", ")", "/", "4", ")", ";", "}" ]
Returns the combat level of this high score. @param bool $includeSummoning Whether to include the summoning skill while calculating the combat level. @return int
[ "Returns", "the", "combat", "level", "of", "this", "high", "score", "." ]
3e24dadbdc5e20b755280e5110f4ca0a1758b04c
https://github.com/villermen/runescape-lookup-commons/blob/3e24dadbdc5e20b755280e5110f4ca0a1758b04c/src/HighScore/SkillHighScore.php#L33-L48
train
chilimatic/chilimatic-framework
lib/file/Image.php
Image.create_thumbnail
public function create_thumbnail($width = 200, $height = 200, $bestfit = false, $fill = false) { if (empty($this->imagemagik) || empty($this->filename)) return false; try { $this->imagemagik->thumbnailimage($width, $height, $bestfit, $fill); } catch (\ImagickException $e) { throw $e; } return true; }
php
public function create_thumbnail($width = 200, $height = 200, $bestfit = false, $fill = false) { if (empty($this->imagemagik) || empty($this->filename)) return false; try { $this->imagemagik->thumbnailimage($width, $height, $bestfit, $fill); } catch (\ImagickException $e) { throw $e; } return true; }
[ "public", "function", "create_thumbnail", "(", "$", "width", "=", "200", ",", "$", "height", "=", "200", ",", "$", "bestfit", "=", "false", ",", "$", "fill", "=", "false", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "imagemagik", ")", "||", "empty", "(", "$", "this", "->", "filename", ")", ")", "return", "false", ";", "try", "{", "$", "this", "->", "imagemagik", "->", "thumbnailimage", "(", "$", "width", ",", "$", "height", ",", "$", "bestfit", ",", "$", "fill", ")", ";", "}", "catch", "(", "\\", "ImagickException", "$", "e", ")", "{", "throw", "$", "e", ";", "}", "return", "true", ";", "}" ]
Wrapper for Imagick thumbnail @param int $width @param int $height @param boolean $bestfit @param boolean $fill @throws \Exception @throws \ImagickException @return boolean
[ "Wrapper", "for", "Imagick", "thumbnail" ]
8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/file/Image.php#L72-L83
train
chilimatic/chilimatic-framework
lib/file/Image.php
Image.saveThumb
public function saveThumb($path = '', $filename = '') { if (empty($this->filename)) return false; try { $save_name = (empty($path) ? $this->path : $path); $save_name = "$save_name/" . (empty($filename) ? 'th_' . $this->filename : $filename); $this->imagemagik->writeImage($save_name); } catch (\ImagickException $e) { throw $e; } return $this->open($save_name); }
php
public function saveThumb($path = '', $filename = '') { if (empty($this->filename)) return false; try { $save_name = (empty($path) ? $this->path : $path); $save_name = "$save_name/" . (empty($filename) ? 'th_' . $this->filename : $filename); $this->imagemagik->writeImage($save_name); } catch (\ImagickException $e) { throw $e; } return $this->open($save_name); }
[ "public", "function", "saveThumb", "(", "$", "path", "=", "''", ",", "$", "filename", "=", "''", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "filename", ")", ")", "return", "false", ";", "try", "{", "$", "save_name", "=", "(", "empty", "(", "$", "path", ")", "?", "$", "this", "->", "path", ":", "$", "path", ")", ";", "$", "save_name", "=", "\"$save_name/\"", ".", "(", "empty", "(", "$", "filename", ")", "?", "'th_'", ".", "$", "this", "->", "filename", ":", "$", "filename", ")", ";", "$", "this", "->", "imagemagik", "->", "writeImage", "(", "$", "save_name", ")", ";", "}", "catch", "(", "\\", "ImagickException", "$", "e", ")", "{", "throw", "$", "e", ";", "}", "return", "$", "this", "->", "open", "(", "$", "save_name", ")", ";", "}" ]
saves the file and opens the fileinfo for this file @param string $path @param string $filename @throws \Exception @throws \ImagickException @return boolean
[ "saves", "the", "file", "and", "opens", "the", "fileinfo", "for", "this", "file" ]
8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/file/Image.php#L96-L109
train
BenGorFile/FileBundle
src/BenGorFile/FileBundle/Controller/OverwriteAction.php
OverwriteAction.overwriteAction
public function overwriteAction($anId, Request $aRequest, FileCommandBus $aCommandBus, $aProperty) { if (false === $aRequest->files->has($aProperty)) { throw new \InvalidArgumentException(sprintf('Given %s property is not in the request', $aProperty)); } $uploadedFile = $aRequest->files->get($aProperty); $command = new OverwriteFileCommand( $anId, $uploadedFile->getClientOriginalName(), file_get_contents($uploadedFile->getPathname()), $uploadedFile->getMimeType() ); $aCommandBus->handle($command); $aRequest->files->remove($aProperty); return [ 'id' => $command->id(), 'filename' => $uploadedFile->getClientOriginalName(), 'mime_type' => $uploadedFile->getMimeType(), ]; }
php
public function overwriteAction($anId, Request $aRequest, FileCommandBus $aCommandBus, $aProperty) { if (false === $aRequest->files->has($aProperty)) { throw new \InvalidArgumentException(sprintf('Given %s property is not in the request', $aProperty)); } $uploadedFile = $aRequest->files->get($aProperty); $command = new OverwriteFileCommand( $anId, $uploadedFile->getClientOriginalName(), file_get_contents($uploadedFile->getPathname()), $uploadedFile->getMimeType() ); $aCommandBus->handle($command); $aRequest->files->remove($aProperty); return [ 'id' => $command->id(), 'filename' => $uploadedFile->getClientOriginalName(), 'mime_type' => $uploadedFile->getMimeType(), ]; }
[ "public", "function", "overwriteAction", "(", "$", "anId", ",", "Request", "$", "aRequest", ",", "FileCommandBus", "$", "aCommandBus", ",", "$", "aProperty", ")", "{", "if", "(", "false", "===", "$", "aRequest", "->", "files", "->", "has", "(", "$", "aProperty", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Given %s property is not in the request'", ",", "$", "aProperty", ")", ")", ";", "}", "$", "uploadedFile", "=", "$", "aRequest", "->", "files", "->", "get", "(", "$", "aProperty", ")", ";", "$", "command", "=", "new", "OverwriteFileCommand", "(", "$", "anId", ",", "$", "uploadedFile", "->", "getClientOriginalName", "(", ")", ",", "file_get_contents", "(", "$", "uploadedFile", "->", "getPathname", "(", ")", ")", ",", "$", "uploadedFile", "->", "getMimeType", "(", ")", ")", ";", "$", "aCommandBus", "->", "handle", "(", "$", "command", ")", ";", "$", "aRequest", "->", "files", "->", "remove", "(", "$", "aProperty", ")", ";", "return", "[", "'id'", "=>", "$", "command", "->", "id", "(", ")", ",", "'filename'", "=>", "$", "uploadedFile", "->", "getClientOriginalName", "(", ")", ",", "'mime_type'", "=>", "$", "uploadedFile", "->", "getMimeType", "(", ")", ",", "]", ";", "}" ]
Overwrite action. @param string $anId The file id @param Request $aRequest The request @param FileCommandBus $aCommandBus The command bus @param string $aProperty The file property that want to get from request @return array
[ "Overwrite", "action", "." ]
82c1fa952e7e7b7a188141a34053ab612b699a21
https://github.com/BenGorFile/FileBundle/blob/82c1fa952e7e7b7a188141a34053ab612b699a21/src/BenGorFile/FileBundle/Controller/OverwriteAction.php#L36-L58
train
phPoirot/Stream
Wrapper/WrapperPsrToPhpResource.php
WrapperPsrToPhpResource.convertToResource
static function convertToResource(StreamInterface $stream) { # register wrapper if not $self = new self; if(!RegistryOfWrapperStream::isRegistered($self->getLabel())) RegistryOfWrapperStream::register($self); # make resource $mode = new AccessMode(); (!$stream->isWritable()) ?: $mode->openForWrite(); (!$stream->isReadable()) ?: $mode->openForRead(); $label = $self->getLabel(); $context = new ContextStreamBase( $label, array('stream' => $stream) ); $context = $context->toContext(); $resource = fopen($label.'://stream' , (string) $mode , null ## set options to wrapper , $context ); return $resource; }
php
static function convertToResource(StreamInterface $stream) { # register wrapper if not $self = new self; if(!RegistryOfWrapperStream::isRegistered($self->getLabel())) RegistryOfWrapperStream::register($self); # make resource $mode = new AccessMode(); (!$stream->isWritable()) ?: $mode->openForWrite(); (!$stream->isReadable()) ?: $mode->openForRead(); $label = $self->getLabel(); $context = new ContextStreamBase( $label, array('stream' => $stream) ); $context = $context->toContext(); $resource = fopen($label.'://stream' , (string) $mode , null ## set options to wrapper , $context ); return $resource; }
[ "static", "function", "convertToResource", "(", "StreamInterface", "$", "stream", ")", "{", "# register wrapper if not", "$", "self", "=", "new", "self", ";", "if", "(", "!", "RegistryOfWrapperStream", "::", "isRegistered", "(", "$", "self", "->", "getLabel", "(", ")", ")", ")", "RegistryOfWrapperStream", "::", "register", "(", "$", "self", ")", ";", "# make resource", "$", "mode", "=", "new", "AccessMode", "(", ")", ";", "(", "!", "$", "stream", "->", "isWritable", "(", ")", ")", "?", ":", "$", "mode", "->", "openForWrite", "(", ")", ";", "(", "!", "$", "stream", "->", "isReadable", "(", ")", ")", "?", ":", "$", "mode", "->", "openForRead", "(", ")", ";", "$", "label", "=", "$", "self", "->", "getLabel", "(", ")", ";", "$", "context", "=", "new", "ContextStreamBase", "(", "$", "label", ",", "array", "(", "'stream'", "=>", "$", "stream", ")", ")", ";", "$", "context", "=", "$", "context", "->", "toContext", "(", ")", ";", "$", "resource", "=", "fopen", "(", "$", "label", ".", "'://stream'", ",", "(", "string", ")", "$", "mode", ",", "null", "## set options to wrapper", ",", "$", "context", ")", ";", "return", "$", "resource", ";", "}" ]
Convert StreamInterface To PHP resource @param StreamInterface $stream @return resource
[ "Convert", "StreamInterface", "To", "PHP", "resource" ]
db448ee0528c2a5b07c594b8a30e2543fbc15f57
https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Wrapper/WrapperPsrToPhpResource.php#L47-L71
train
diasbruno/stc
lib/stc/DataLoader.php
DataLoader.read_file
private function read_file($file) { $handler = fopen($file, "r"); $file_content = fread($handler, filesize($file)); fclose($handler); return $file_content; }
php
private function read_file($file) { $handler = fopen($file, "r"); $file_content = fread($handler, filesize($file)); fclose($handler); return $file_content; }
[ "private", "function", "read_file", "(", "$", "file", ")", "{", "$", "handler", "=", "fopen", "(", "$", "file", ",", "\"r\"", ")", ";", "$", "file_content", "=", "fread", "(", "$", "handler", ",", "filesize", "(", "$", "file", ")", ")", ";", "fclose", "(", "$", "handler", ")", ";", "return", "$", "file_content", ";", "}" ]
Creates the handler and reads the files. @param $file string | The filename. @return string
[ "Creates", "the", "handler", "and", "reads", "the", "files", "." ]
43f62c3b28167bff76274f954e235413a9e9c707
https://github.com/diasbruno/stc/blob/43f62c3b28167bff76274f954e235413a9e9c707/lib/stc/DataLoader.php#L21-L28
train
diasbruno/stc
lib/stc/DataLoader.php
DataLoader.load
public function load($path, $file) { $the_file = $path . '/' . $file; return json_decode($this->read_file($the_file), true); }
php
public function load($path, $file) { $the_file = $path . '/' . $file; return json_decode($this->read_file($the_file), true); }
[ "public", "function", "load", "(", "$", "path", ",", "$", "file", ")", "{", "$", "the_file", "=", "$", "path", ".", "'/'", ".", "$", "file", ";", "return", "json_decode", "(", "$", "this", "->", "read_file", "(", "$", "the_file", ")", ",", "true", ")", ";", "}" ]
Load the file. @param $path string | The path where the file is located. @param $file string | The filename. @return string
[ "Load", "the", "file", "." ]
43f62c3b28167bff76274f954e235413a9e9c707
https://github.com/diasbruno/stc/blob/43f62c3b28167bff76274f954e235413a9e9c707/lib/stc/DataLoader.php#L36-L41
train
bennybi/yii2-cza-base
models/traits/TreeTrait.php
TreeTrait.initDefaults
public function initDefaults() { /** * @var Tree $this */ $module = Yii::$app->controller->module; $iconTypeAttribute = null; extract($module->dataStructure); $this->setDefault($iconTypeAttribute, TreeView::ICON_CSS); foreach (static::$boolAttribs as $attr) { $val = in_array($attr, static::$falseAttribs) ? false : true; $this->setDefault($attr, $val); } }
php
public function initDefaults() { /** * @var Tree $this */ $module = Yii::$app->controller->module; $iconTypeAttribute = null; extract($module->dataStructure); $this->setDefault($iconTypeAttribute, TreeView::ICON_CSS); foreach (static::$boolAttribs as $attr) { $val = in_array($attr, static::$falseAttribs) ? false : true; $this->setDefault($attr, $val); } }
[ "public", "function", "initDefaults", "(", ")", "{", "/**\n * @var Tree $this\n */", "$", "module", "=", "Yii", "::", "$", "app", "->", "controller", "->", "module", ";", "$", "iconTypeAttribute", "=", "null", ";", "extract", "(", "$", "module", "->", "dataStructure", ")", ";", "$", "this", "->", "setDefault", "(", "$", "iconTypeAttribute", ",", "TreeView", "::", "ICON_CSS", ")", ";", "foreach", "(", "static", "::", "$", "boolAttribs", "as", "$", "attr", ")", "{", "$", "val", "=", "in_array", "(", "$", "attr", ",", "static", "::", "$", "falseAttribs", ")", "?", "false", ":", "true", ";", "$", "this", "->", "setDefault", "(", "$", "attr", ",", "$", "val", ")", ";", "}", "}" ]
Initialize default values
[ "Initialize", "default", "values" ]
8257db8034bd948712fa469062921f210f0ba8da
https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/models/traits/TreeTrait.php#L146-L158
train
bennybi/yii2-cza-base
models/traits/TreeTrait.php
TreeTrait.removeNode
public function removeNode($softDelete = true, $currNode = true) { /** * @var Tree $this * @var Tree $child */ if ($softDelete) { $this->nodeRemovalErrors = []; $module = Yii::$app->controller->module; extract($module->treeStructure); extract($module->dataStructure); if ($this->isRemovableAll()) { $children = $this->children()->all(); foreach ($children as $child) { $child->active = false; if (!$child->save()) { /** @noinspection PhpUndefinedFieldInspection */ /** @noinspection PhpUndefinedVariableInspection */ $this->nodeRemovalErrors[] = [ 'id' => $child->$keyAttribute, 'name' => $child->$nameAttribute, 'error' => $child->getFirstErrors(), ]; } } } if ($currNode) { $this->active = false; if (!$this->save()) { /** @noinspection PhpUndefinedFieldInspection */ /** @noinspection PhpUndefinedVariableInspection */ $this->nodeRemovalErrors[] = [ 'id' => $this->$keyAttribute, 'name' => $this->$nameAttribute, 'error' => $this->getFirstErrors(), ]; return false; } } return true; } else { return $this->removable_all || $this->isRoot() && $this->children()->count() == 0 ? $this->deleteWithChildren() : $this->delete(); } }
php
public function removeNode($softDelete = true, $currNode = true) { /** * @var Tree $this * @var Tree $child */ if ($softDelete) { $this->nodeRemovalErrors = []; $module = Yii::$app->controller->module; extract($module->treeStructure); extract($module->dataStructure); if ($this->isRemovableAll()) { $children = $this->children()->all(); foreach ($children as $child) { $child->active = false; if (!$child->save()) { /** @noinspection PhpUndefinedFieldInspection */ /** @noinspection PhpUndefinedVariableInspection */ $this->nodeRemovalErrors[] = [ 'id' => $child->$keyAttribute, 'name' => $child->$nameAttribute, 'error' => $child->getFirstErrors(), ]; } } } if ($currNode) { $this->active = false; if (!$this->save()) { /** @noinspection PhpUndefinedFieldInspection */ /** @noinspection PhpUndefinedVariableInspection */ $this->nodeRemovalErrors[] = [ 'id' => $this->$keyAttribute, 'name' => $this->$nameAttribute, 'error' => $this->getFirstErrors(), ]; return false; } } return true; } else { return $this->removable_all || $this->isRoot() && $this->children()->count() == 0 ? $this->deleteWithChildren() : $this->delete(); } }
[ "public", "function", "removeNode", "(", "$", "softDelete", "=", "true", ",", "$", "currNode", "=", "true", ")", "{", "/**\n * @var Tree $this\n * @var Tree $child\n */", "if", "(", "$", "softDelete", ")", "{", "$", "this", "->", "nodeRemovalErrors", "=", "[", "]", ";", "$", "module", "=", "Yii", "::", "$", "app", "->", "controller", "->", "module", ";", "extract", "(", "$", "module", "->", "treeStructure", ")", ";", "extract", "(", "$", "module", "->", "dataStructure", ")", ";", "if", "(", "$", "this", "->", "isRemovableAll", "(", ")", ")", "{", "$", "children", "=", "$", "this", "->", "children", "(", ")", "->", "all", "(", ")", ";", "foreach", "(", "$", "children", "as", "$", "child", ")", "{", "$", "child", "->", "active", "=", "false", ";", "if", "(", "!", "$", "child", "->", "save", "(", ")", ")", "{", "/** @noinspection PhpUndefinedFieldInspection */", "/** @noinspection PhpUndefinedVariableInspection */", "$", "this", "->", "nodeRemovalErrors", "[", "]", "=", "[", "'id'", "=>", "$", "child", "->", "$", "keyAttribute", ",", "'name'", "=>", "$", "child", "->", "$", "nameAttribute", ",", "'error'", "=>", "$", "child", "->", "getFirstErrors", "(", ")", ",", "]", ";", "}", "}", "}", "if", "(", "$", "currNode", ")", "{", "$", "this", "->", "active", "=", "false", ";", "if", "(", "!", "$", "this", "->", "save", "(", ")", ")", "{", "/** @noinspection PhpUndefinedFieldInspection */", "/** @noinspection PhpUndefinedVariableInspection */", "$", "this", "->", "nodeRemovalErrors", "[", "]", "=", "[", "'id'", "=>", "$", "this", "->", "$", "keyAttribute", ",", "'name'", "=>", "$", "this", "->", "$", "nameAttribute", ",", "'error'", "=>", "$", "this", "->", "getFirstErrors", "(", ")", ",", "]", ";", "return", "false", ";", "}", "}", "return", "true", ";", "}", "else", "{", "return", "$", "this", "->", "removable_all", "||", "$", "this", "->", "isRoot", "(", ")", "&&", "$", "this", "->", "children", "(", ")", "->", "count", "(", ")", "==", "0", "?", "$", "this", "->", "deleteWithChildren", "(", ")", ":", "$", "this", "->", "delete", "(", ")", ";", "}", "}" ]
Removes a node @param boolean $softDelete whether to soft delete or hard delete @param boolean $currNode whether to update the current node value also @return boolean status of activation/inactivation
[ "Removes", "a", "node" ]
8257db8034bd948712fa469062921f210f0ba8da
https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/models/traits/TreeTrait.php#L300-L346
train
bennybi/yii2-cza-base
models/traits/TreeTrait.php
TreeTrait.getBreadcrumbs
public function getBreadcrumbs($depth = 1, $glue = ' &raquo; ', $currCss = 'kv-crumb-active', $new = 'Untitled') { /** * @var Tree $this */ if ($this->isNewRecord || empty($this)) { return $currCss ? Html::tag('span', $new, ['class' => $currCss]) : $new; } $depth = empty($depth) ? null : intval($depth); $module = Yii::$app->controller->module; $nameAttribute = ArrayHelper::getValue($module->dataStructure, 'nameAttribute', 'name'); $crumbNodes = $depth === null ? $this->parents()->all() : $this->parents($depth - 1)->all(); $crumbNodes[] = $this; $i = 1; $len = count($crumbNodes); $crumbs = []; foreach ($crumbNodes as $node) { $name = $node->$nameAttribute; if ($i === $len && $currCss) { $name = Html::tag('span', $name, ['class' => $currCss]); } $crumbs[] = $name; $i++; } return implode($glue, $crumbs); }
php
public function getBreadcrumbs($depth = 1, $glue = ' &raquo; ', $currCss = 'kv-crumb-active', $new = 'Untitled') { /** * @var Tree $this */ if ($this->isNewRecord || empty($this)) { return $currCss ? Html::tag('span', $new, ['class' => $currCss]) : $new; } $depth = empty($depth) ? null : intval($depth); $module = Yii::$app->controller->module; $nameAttribute = ArrayHelper::getValue($module->dataStructure, 'nameAttribute', 'name'); $crumbNodes = $depth === null ? $this->parents()->all() : $this->parents($depth - 1)->all(); $crumbNodes[] = $this; $i = 1; $len = count($crumbNodes); $crumbs = []; foreach ($crumbNodes as $node) { $name = $node->$nameAttribute; if ($i === $len && $currCss) { $name = Html::tag('span', $name, ['class' => $currCss]); } $crumbs[] = $name; $i++; } return implode($glue, $crumbs); }
[ "public", "function", "getBreadcrumbs", "(", "$", "depth", "=", "1", ",", "$", "glue", "=", "' &raquo; '", ",", "$", "currCss", "=", "'kv-crumb-active'", ",", "$", "new", "=", "'Untitled'", ")", "{", "/**\n * @var Tree $this\n */", "if", "(", "$", "this", "->", "isNewRecord", "||", "empty", "(", "$", "this", ")", ")", "{", "return", "$", "currCss", "?", "Html", "::", "tag", "(", "'span'", ",", "$", "new", ",", "[", "'class'", "=>", "$", "currCss", "]", ")", ":", "$", "new", ";", "}", "$", "depth", "=", "empty", "(", "$", "depth", ")", "?", "null", ":", "intval", "(", "$", "depth", ")", ";", "$", "module", "=", "Yii", "::", "$", "app", "->", "controller", "->", "module", ";", "$", "nameAttribute", "=", "ArrayHelper", "::", "getValue", "(", "$", "module", "->", "dataStructure", ",", "'nameAttribute'", ",", "'name'", ")", ";", "$", "crumbNodes", "=", "$", "depth", "===", "null", "?", "$", "this", "->", "parents", "(", ")", "->", "all", "(", ")", ":", "$", "this", "->", "parents", "(", "$", "depth", "-", "1", ")", "->", "all", "(", ")", ";", "$", "crumbNodes", "[", "]", "=", "$", "this", ";", "$", "i", "=", "1", ";", "$", "len", "=", "count", "(", "$", "crumbNodes", ")", ";", "$", "crumbs", "=", "[", "]", ";", "foreach", "(", "$", "crumbNodes", "as", "$", "node", ")", "{", "$", "name", "=", "$", "node", "->", "$", "nameAttribute", ";", "if", "(", "$", "i", "===", "$", "len", "&&", "$", "currCss", ")", "{", "$", "name", "=", "Html", "::", "tag", "(", "'span'", ",", "$", "name", ",", "[", "'class'", "=>", "$", "currCss", "]", ")", ";", "}", "$", "crumbs", "[", "]", "=", "$", "name", ";", "$", "i", "++", ";", "}", "return", "implode", "(", "$", "glue", ",", "$", "crumbs", ")", ";", "}" ]
Generate and return the breadcrumbs for the node. @param integer $depth the breadcrumbs parent depth @param string $glue the pattern to separate the breadcrumbs @param string $currCss the CSS class to be set for current node @param string $new the name to be displayed for a new node @return string the parsed breadcrumbs
[ "Generate", "and", "return", "the", "breadcrumbs", "for", "the", "node", "." ]
8257db8034bd948712fa469062921f210f0ba8da
https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/models/traits/TreeTrait.php#L393-L417
train
silvercommerce/contact-admin
src/bulkhandler/AddRelatedHandler.php
AddRelatedHandler.Link
public function Link($action = null) { return Controller::join_links( parent::Link(), $this->config()->url_segment, $action ); }
php
public function Link($action = null) { return Controller::join_links( parent::Link(), $this->config()->url_segment, $action ); }
[ "public", "function", "Link", "(", "$", "action", "=", "null", ")", "{", "return", "Controller", "::", "join_links", "(", "parent", "::", "Link", "(", ")", ",", "$", "this", "->", "config", "(", ")", "->", "url_segment", ",", "$", "action", ")", ";", "}" ]
Return URL to this RequestHandler @param string $action Action to append to URL @return string URL
[ "Return", "URL", "to", "this", "RequestHandler" ]
32cbc2ef2589f93f9dd1796e5db2f11ad15d888c
https://github.com/silvercommerce/contact-admin/blob/32cbc2ef2589f93f9dd1796e5db2f11ad15d888c/src/bulkhandler/AddRelatedHandler.php#L44-L51
train
atelierspierrot/templatengine
src/TemplateEngine/TemplateObject/TitleTag.php
TitleTag.set
public function set(array $strs) { if (!empty($strs)) { foreach ($strs as $_str) { $this->add($_str); } } return $this; }
php
public function set(array $strs) { if (!empty($strs)) { foreach ($strs as $_str) { $this->add($_str); } } return $this; }
[ "public", "function", "set", "(", "array", "$", "strs", ")", "{", "if", "(", "!", "empty", "(", "$", "strs", ")", ")", "{", "foreach", "(", "$", "strs", "as", "$", "_str", ")", "{", "$", "this", "->", "add", "(", "$", "_str", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Set a strings stack to build page header title @param array $strs An array of title strings @return self @see self::add()
[ "Set", "a", "strings", "stack", "to", "build", "page", "header", "title" ]
de01b117f882670bed7b322e2d3b8b30fa9ae45f
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/TemplateEngine/TemplateObject/TitleTag.php#L79-L87
train
luoxiaojun1992/lb_framework
controllers/web/WebController.php
WebController.injectDebugBar
protected function injectDebugBar($output) { if (!($debugBarConfig = Lb::app()->getConfigByName('debugbar'))) { return $output; } if (empty($debugBarConfig['enabled'])) { return $output; } if (empty($debugBarConfig['baseUrl'])) { return $output; } if (empty($debugBarConfig['basePath'])) { return $output; } /** * @var StandardDebugBar $debugBar */ $debugBar = DebugBar::getInstance(); $debugBarRenderer = $debugBar->getJavascriptRenderer($debugBarConfig['baseUrl'], $debugBarConfig['basePath']); $debugBarComponent = $debugBarRenderer->renderHead() . $debugBarRenderer->render(); $replace = <<<EOF {$debugBarComponent} </body> EOF; return str_replace('</body>', $replace, $output); }
php
protected function injectDebugBar($output) { if (!($debugBarConfig = Lb::app()->getConfigByName('debugbar'))) { return $output; } if (empty($debugBarConfig['enabled'])) { return $output; } if (empty($debugBarConfig['baseUrl'])) { return $output; } if (empty($debugBarConfig['basePath'])) { return $output; } /** * @var StandardDebugBar $debugBar */ $debugBar = DebugBar::getInstance(); $debugBarRenderer = $debugBar->getJavascriptRenderer($debugBarConfig['baseUrl'], $debugBarConfig['basePath']); $debugBarComponent = $debugBarRenderer->renderHead() . $debugBarRenderer->render(); $replace = <<<EOF {$debugBarComponent} </body> EOF; return str_replace('</body>', $replace, $output); }
[ "protected", "function", "injectDebugBar", "(", "$", "output", ")", "{", "if", "(", "!", "(", "$", "debugBarConfig", "=", "Lb", "::", "app", "(", ")", "->", "getConfigByName", "(", "'debugbar'", ")", ")", ")", "{", "return", "$", "output", ";", "}", "if", "(", "empty", "(", "$", "debugBarConfig", "[", "'enabled'", "]", ")", ")", "{", "return", "$", "output", ";", "}", "if", "(", "empty", "(", "$", "debugBarConfig", "[", "'baseUrl'", "]", ")", ")", "{", "return", "$", "output", ";", "}", "if", "(", "empty", "(", "$", "debugBarConfig", "[", "'basePath'", "]", ")", ")", "{", "return", "$", "output", ";", "}", "/**\n * @var StandardDebugBar $debugBar\n */", "$", "debugBar", "=", "DebugBar", "::", "getInstance", "(", ")", ";", "$", "debugBarRenderer", "=", "$", "debugBar", "->", "getJavascriptRenderer", "(", "$", "debugBarConfig", "[", "'baseUrl'", "]", ",", "$", "debugBarConfig", "[", "'basePath'", "]", ")", ";", "$", "debugBarComponent", "=", "$", "debugBarRenderer", "->", "renderHead", "(", ")", ".", "$", "debugBarRenderer", "->", "render", "(", ")", ";", "$", "replace", "=", " <<<EOF\n{$debugBarComponent}\n</body>\nEOF", ";", "return", "str_replace", "(", "'</body>'", ",", "$", "replace", ",", "$", "output", ")", ";", "}" ]
Inject debug bar to html output @param $output @return mixed
[ "Inject", "debug", "bar", "to", "html", "output" ]
12a865729e7738d7d1e07371ad7203243c4571fa
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/web/WebController.php#L169-L195
train
wearesho-team/cpa-integration
src/Postback/PostbackService.php
PostbackService.send
public function send(ConversionInterface $conversion): ResponseInterface { foreach ($this->services as $service) { if (is_null($service->getConfig())) { $config = $this->config->getConfiguredConfigInstance($service); if ($config instanceof PostbackServiceConfigInterface) { $service->setConfig($config); } else { continue; } } try { return $service->send($conversion); } catch (UnsupportedConversionTypeException $exception) { continue; } } throw new UnsupportedConversionTypeException($this, $conversion); }
php
public function send(ConversionInterface $conversion): ResponseInterface { foreach ($this->services as $service) { if (is_null($service->getConfig())) { $config = $this->config->getConfiguredConfigInstance($service); if ($config instanceof PostbackServiceConfigInterface) { $service->setConfig($config); } else { continue; } } try { return $service->send($conversion); } catch (UnsupportedConversionTypeException $exception) { continue; } } throw new UnsupportedConversionTypeException($this, $conversion); }
[ "public", "function", "send", "(", "ConversionInterface", "$", "conversion", ")", ":", "ResponseInterface", "{", "foreach", "(", "$", "this", "->", "services", "as", "$", "service", ")", "{", "if", "(", "is_null", "(", "$", "service", "->", "getConfig", "(", ")", ")", ")", "{", "$", "config", "=", "$", "this", "->", "config", "->", "getConfiguredConfigInstance", "(", "$", "service", ")", ";", "if", "(", "$", "config", "instanceof", "PostbackServiceConfigInterface", ")", "{", "$", "service", "->", "setConfig", "(", "$", "config", ")", ";", "}", "else", "{", "continue", ";", "}", "}", "try", "{", "return", "$", "service", "->", "send", "(", "$", "conversion", ")", ";", "}", "catch", "(", "UnsupportedConversionTypeException", "$", "exception", ")", "{", "continue", ";", "}", "}", "throw", "new", "UnsupportedConversionTypeException", "(", "$", "this", ",", "$", "conversion", ")", ";", "}" ]
Try each service to send conversion, while getting UnsupportedConversionException @param ConversionInterface $conversion @throws UnsupportedConversionTypeException @throws DuplicatedConversionException @throws RequestException @return ResponseInterface
[ "Try", "each", "service", "to", "send", "conversion", "while", "getting", "UnsupportedConversionException" ]
6b78d2315e893ecf09132ae3e9d8e8c1b5ae6291
https://github.com/wearesho-team/cpa-integration/blob/6b78d2315e893ecf09132ae3e9d8e8c1b5ae6291/src/Postback/PostbackService.php#L113-L132
train
ekyna/AdminBundle
Install/AdminInstaller.php
AdminInstaller.createGroups
private function createGroups(OutputInterface $output) { $em = $this->container->get('ekyna_user.group.manager'); $repository = $this->container->get('ekyna_user.group.repository'); foreach ($this->defaultGroups as $name => $options) { $output->write(sprintf( '- <comment>%s</comment> %s ', $name, str_pad('.', 44 - mb_strlen($name), '.', STR_PAD_LEFT) )); if (null !== $group = $repository->findOneBy(['name' => $name])) { $output->writeln('already exists.'); continue; } /** @var \Ekyna\Bundle\UserBundle\Model\GroupInterface $group */ $group = $repository->createNew(); $group ->setDefault($options[2]) ->setName($name) ->setRoles($options[0]) ; $em->persist($group); $output->writeln('created.'); } $em->flush(); }
php
private function createGroups(OutputInterface $output) { $em = $this->container->get('ekyna_user.group.manager'); $repository = $this->container->get('ekyna_user.group.repository'); foreach ($this->defaultGroups as $name => $options) { $output->write(sprintf( '- <comment>%s</comment> %s ', $name, str_pad('.', 44 - mb_strlen($name), '.', STR_PAD_LEFT) )); if (null !== $group = $repository->findOneBy(['name' => $name])) { $output->writeln('already exists.'); continue; } /** @var \Ekyna\Bundle\UserBundle\Model\GroupInterface $group */ $group = $repository->createNew(); $group ->setDefault($options[2]) ->setName($name) ->setRoles($options[0]) ; $em->persist($group); $output->writeln('created.'); } $em->flush(); }
[ "private", "function", "createGroups", "(", "OutputInterface", "$", "output", ")", "{", "$", "em", "=", "$", "this", "->", "container", "->", "get", "(", "'ekyna_user.group.manager'", ")", ";", "$", "repository", "=", "$", "this", "->", "container", "->", "get", "(", "'ekyna_user.group.repository'", ")", ";", "foreach", "(", "$", "this", "->", "defaultGroups", "as", "$", "name", "=>", "$", "options", ")", "{", "$", "output", "->", "write", "(", "sprintf", "(", "'- <comment>%s</comment> %s '", ",", "$", "name", ",", "str_pad", "(", "'.'", ",", "44", "-", "mb_strlen", "(", "$", "name", ")", ",", "'.'", ",", "STR_PAD_LEFT", ")", ")", ")", ";", "if", "(", "null", "!==", "$", "group", "=", "$", "repository", "->", "findOneBy", "(", "[", "'name'", "=>", "$", "name", "]", ")", ")", "{", "$", "output", "->", "writeln", "(", "'already exists.'", ")", ";", "continue", ";", "}", "/** @var \\Ekyna\\Bundle\\UserBundle\\Model\\GroupInterface $group */", "$", "group", "=", "$", "repository", "->", "createNew", "(", ")", ";", "$", "group", "->", "setDefault", "(", "$", "options", "[", "2", "]", ")", "->", "setName", "(", "$", "name", ")", "->", "setRoles", "(", "$", "options", "[", "0", "]", ")", ";", "$", "em", "->", "persist", "(", "$", "group", ")", ";", "$", "output", "->", "writeln", "(", "'created.'", ")", ";", "}", "$", "em", "->", "flush", "(", ")", ";", "}" ]
Creates default groups entities @param OutputInterface $output
[ "Creates", "default", "groups", "entities" ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Install/AdminInstaller.php#L70-L96
train
ekyna/AdminBundle
Install/AdminInstaller.php
AdminInstaller.createSuperAdmin
private function createSuperAdmin(Command $command, OutputInterface $output) { $groupRepository = $this->container->get('ekyna_user.group.repository'); $userRepository = $this->container->get('ekyna_user.user.repository'); /** @var \Ekyna\Bundle\UserBundle\Model\GroupInterface $group */ if (null === $group = $groupRepository->findOneBy(['name' => array_keys($this->defaultGroups)[0]])) { $output->writeln('Super admin group not found, aborting.'); return; } /** @var \Ekyna\Bundle\UserBundle\Model\UserInterface $superAdmin */ if (null !== $superAdmin = $userRepository->findOneBy(['group' => $group])) { $output->writeln(sprintf('Super admin already exists (<comment>%s</comment>).', $superAdmin->getEmail())); return; } $output->writeln('<question>Please provide initial informations ...</question>'); /** @var \Symfony\Component\Console\Helper\DialogHelper $dialog */ $dialog = $command->getHelperSet()->get('dialog'); $email = $dialog->askAndValidate($output, 'Email: ', function ($answer) use ($userRepository) { if (!filter_var($answer, FILTER_VALIDATE_EMAIL)) { throw new \RuntimeException('This is not a valid email address.'); } if (null !== $userRepository->findOneBy(['email' => $answer])) { throw new \RuntimeException('This email address is already used.'); } return $answer; }, 3); $password = $dialog->askAndValidate($output, 'Password: ', function ($answer) { if (!(preg_match('#^[a-zA-Z0-9]+$#', $answer) && strlen($answer) > 5)) { throw new \RuntimeException('Password should be composed of at least 6 letters and numbers.'); } return $answer; }, 3); $notBlankValidator = function ($answer) { if (0 === strlen($answer)) { throw new \RuntimeException('This cannot be blank.'); } return $answer; }; $firstName = $dialog->askAndValidate($output, 'First name: ', $notBlankValidator, 3); $lastName = $dialog->askAndValidate($output, 'Last name: ', $notBlankValidator, 3); $userManager = $this->container->get('fos_user.user_manager'); /** @var \Ekyna\Bundle\UserBundle\Model\UserInterface $user */ $user = $userManager->createUser(); $user ->setGroup($group) ->setGender('mr') ->setFirstName($firstName) ->setLastName($lastName) ->setPlainPassword($password) ->setEmail($email) ->setEnabled(true); $userManager->updateUser($user); $output->writeln('Super Admin has been successfully created.'); }
php
private function createSuperAdmin(Command $command, OutputInterface $output) { $groupRepository = $this->container->get('ekyna_user.group.repository'); $userRepository = $this->container->get('ekyna_user.user.repository'); /** @var \Ekyna\Bundle\UserBundle\Model\GroupInterface $group */ if (null === $group = $groupRepository->findOneBy(['name' => array_keys($this->defaultGroups)[0]])) { $output->writeln('Super admin group not found, aborting.'); return; } /** @var \Ekyna\Bundle\UserBundle\Model\UserInterface $superAdmin */ if (null !== $superAdmin = $userRepository->findOneBy(['group' => $group])) { $output->writeln(sprintf('Super admin already exists (<comment>%s</comment>).', $superAdmin->getEmail())); return; } $output->writeln('<question>Please provide initial informations ...</question>'); /** @var \Symfony\Component\Console\Helper\DialogHelper $dialog */ $dialog = $command->getHelperSet()->get('dialog'); $email = $dialog->askAndValidate($output, 'Email: ', function ($answer) use ($userRepository) { if (!filter_var($answer, FILTER_VALIDATE_EMAIL)) { throw new \RuntimeException('This is not a valid email address.'); } if (null !== $userRepository->findOneBy(['email' => $answer])) { throw new \RuntimeException('This email address is already used.'); } return $answer; }, 3); $password = $dialog->askAndValidate($output, 'Password: ', function ($answer) { if (!(preg_match('#^[a-zA-Z0-9]+$#', $answer) && strlen($answer) > 5)) { throw new \RuntimeException('Password should be composed of at least 6 letters and numbers.'); } return $answer; }, 3); $notBlankValidator = function ($answer) { if (0 === strlen($answer)) { throw new \RuntimeException('This cannot be blank.'); } return $answer; }; $firstName = $dialog->askAndValidate($output, 'First name: ', $notBlankValidator, 3); $lastName = $dialog->askAndValidate($output, 'Last name: ', $notBlankValidator, 3); $userManager = $this->container->get('fos_user.user_manager'); /** @var \Ekyna\Bundle\UserBundle\Model\UserInterface $user */ $user = $userManager->createUser(); $user ->setGroup($group) ->setGender('mr') ->setFirstName($firstName) ->setLastName($lastName) ->setPlainPassword($password) ->setEmail($email) ->setEnabled(true); $userManager->updateUser($user); $output->writeln('Super Admin has been successfully created.'); }
[ "private", "function", "createSuperAdmin", "(", "Command", "$", "command", ",", "OutputInterface", "$", "output", ")", "{", "$", "groupRepository", "=", "$", "this", "->", "container", "->", "get", "(", "'ekyna_user.group.repository'", ")", ";", "$", "userRepository", "=", "$", "this", "->", "container", "->", "get", "(", "'ekyna_user.user.repository'", ")", ";", "/** @var \\Ekyna\\Bundle\\UserBundle\\Model\\GroupInterface $group */", "if", "(", "null", "===", "$", "group", "=", "$", "groupRepository", "->", "findOneBy", "(", "[", "'name'", "=>", "array_keys", "(", "$", "this", "->", "defaultGroups", ")", "[", "0", "]", "]", ")", ")", "{", "$", "output", "->", "writeln", "(", "'Super admin group not found, aborting.'", ")", ";", "return", ";", "}", "/** @var \\Ekyna\\Bundle\\UserBundle\\Model\\UserInterface $superAdmin */", "if", "(", "null", "!==", "$", "superAdmin", "=", "$", "userRepository", "->", "findOneBy", "(", "[", "'group'", "=>", "$", "group", "]", ")", ")", "{", "$", "output", "->", "writeln", "(", "sprintf", "(", "'Super admin already exists (<comment>%s</comment>).'", ",", "$", "superAdmin", "->", "getEmail", "(", ")", ")", ")", ";", "return", ";", "}", "$", "output", "->", "writeln", "(", "'<question>Please provide initial informations ...</question>'", ")", ";", "/** @var \\Symfony\\Component\\Console\\Helper\\DialogHelper $dialog */", "$", "dialog", "=", "$", "command", "->", "getHelperSet", "(", ")", "->", "get", "(", "'dialog'", ")", ";", "$", "email", "=", "$", "dialog", "->", "askAndValidate", "(", "$", "output", ",", "'Email: '", ",", "function", "(", "$", "answer", ")", "use", "(", "$", "userRepository", ")", "{", "if", "(", "!", "filter_var", "(", "$", "answer", ",", "FILTER_VALIDATE_EMAIL", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'This is not a valid email address.'", ")", ";", "}", "if", "(", "null", "!==", "$", "userRepository", "->", "findOneBy", "(", "[", "'email'", "=>", "$", "answer", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'This email address is already used.'", ")", ";", "}", "return", "$", "answer", ";", "}", ",", "3", ")", ";", "$", "password", "=", "$", "dialog", "->", "askAndValidate", "(", "$", "output", ",", "'Password: '", ",", "function", "(", "$", "answer", ")", "{", "if", "(", "!", "(", "preg_match", "(", "'#^[a-zA-Z0-9]+$#'", ",", "$", "answer", ")", "&&", "strlen", "(", "$", "answer", ")", ">", "5", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Password should be composed of at least 6 letters and numbers.'", ")", ";", "}", "return", "$", "answer", ";", "}", ",", "3", ")", ";", "$", "notBlankValidator", "=", "function", "(", "$", "answer", ")", "{", "if", "(", "0", "===", "strlen", "(", "$", "answer", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'This cannot be blank.'", ")", ";", "}", "return", "$", "answer", ";", "}", ";", "$", "firstName", "=", "$", "dialog", "->", "askAndValidate", "(", "$", "output", ",", "'First name: '", ",", "$", "notBlankValidator", ",", "3", ")", ";", "$", "lastName", "=", "$", "dialog", "->", "askAndValidate", "(", "$", "output", ",", "'Last name: '", ",", "$", "notBlankValidator", ",", "3", ")", ";", "$", "userManager", "=", "$", "this", "->", "container", "->", "get", "(", "'fos_user.user_manager'", ")", ";", "/** @var \\Ekyna\\Bundle\\UserBundle\\Model\\UserInterface $user */", "$", "user", "=", "$", "userManager", "->", "createUser", "(", ")", ";", "$", "user", "->", "setGroup", "(", "$", "group", ")", "->", "setGender", "(", "'mr'", ")", "->", "setFirstName", "(", "$", "firstName", ")", "->", "setLastName", "(", "$", "lastName", ")", "->", "setPlainPassword", "(", "$", "password", ")", "->", "setEmail", "(", "$", "email", ")", "->", "setEnabled", "(", "true", ")", ";", "$", "userManager", "->", "updateUser", "(", "$", "user", ")", ";", "$", "output", "->", "writeln", "(", "'Super Admin has been successfully created.'", ")", ";", "}" ]
Creates the super admin user. @param Command $command @param OutputInterface $output
[ "Creates", "the", "super", "admin", "user", "." ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Install/AdminInstaller.php#L136-L199
train
phpalchemy/phpalchemy
Alchemy/Annotation/Reader/Adapter/NotojReader.php
NotojReader.createAnnotationObjects
protected function createAnnotationObjects(array $annotations) { $objects = array(); //var_dump($annotations); foreach ($annotations as $name => $args) { $name = ucfirst($name); $class = $this->defaultNamespace . $name . 'Annotation'; if (in_array(strtolower($name), self::getExcludeAnnotationList())) { continue; } if (! array_key_exists($class, $objects)) { if (!class_exists($class)) { if ($this->strict) { throw new \Exception(sprintf('Annotation Class Not Found: %s', $class)); } else { continue; } } $objects[$name] = new $class(); } //var_dump($args); foreach ($args as $key => $value) { $objects[$name]->set($key, $value); } } return $objects; }
php
protected function createAnnotationObjects(array $annotations) { $objects = array(); //var_dump($annotations); foreach ($annotations as $name => $args) { $name = ucfirst($name); $class = $this->defaultNamespace . $name . 'Annotation'; if (in_array(strtolower($name), self::getExcludeAnnotationList())) { continue; } if (! array_key_exists($class, $objects)) { if (!class_exists($class)) { if ($this->strict) { throw new \Exception(sprintf('Annotation Class Not Found: %s', $class)); } else { continue; } } $objects[$name] = new $class(); } //var_dump($args); foreach ($args as $key => $value) { $objects[$name]->set($key, $value); } } return $objects; }
[ "protected", "function", "createAnnotationObjects", "(", "array", "$", "annotations", ")", "{", "$", "objects", "=", "array", "(", ")", ";", "//var_dump($annotations);", "foreach", "(", "$", "annotations", "as", "$", "name", "=>", "$", "args", ")", "{", "$", "name", "=", "ucfirst", "(", "$", "name", ")", ";", "$", "class", "=", "$", "this", "->", "defaultNamespace", ".", "$", "name", ".", "'Annotation'", ";", "if", "(", "in_array", "(", "strtolower", "(", "$", "name", ")", ",", "self", "::", "getExcludeAnnotationList", "(", ")", ")", ")", "{", "continue", ";", "}", "if", "(", "!", "array_key_exists", "(", "$", "class", ",", "$", "objects", ")", ")", "{", "if", "(", "!", "class_exists", "(", "$", "class", ")", ")", "{", "if", "(", "$", "this", "->", "strict", ")", "{", "throw", "new", "\\", "Exception", "(", "sprintf", "(", "'Annotation Class Not Found: %s'", ",", "$", "class", ")", ")", ";", "}", "else", "{", "continue", ";", "}", "}", "$", "objects", "[", "$", "name", "]", "=", "new", "$", "class", "(", ")", ";", "}", "//var_dump($args);", "foreach", "(", "$", "args", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "objects", "[", "$", "name", "]", "->", "set", "(", "$", "key", ",", "$", "value", ")", ";", "}", "}", "return", "$", "objects", ";", "}" ]
Create annotations object @param array $annotations annotated elements @return array array of annoatated objects
[ "Create", "annotations", "object" ]
5b7e9b13acfda38c61b2da2639e8a56f298dc32e
https://github.com/phpalchemy/phpalchemy/blob/5b7e9b13acfda38c61b2da2639e8a56f298dc32e/Alchemy/Annotation/Reader/Adapter/NotojReader.php#L66-L98
train
phpalchemy/phpalchemy
Alchemy/Annotation/Reader/Adapter/NotojReader.php
NotojReader.convertAnnotationObj
protected function convertAnnotationObj($reflection) { $annotations = (array) $reflection->getAnnotations(); $result = array(); foreach ($annotations as $annotation) { if (! array_key_exists($annotation['method'], $result)) { $result[$annotation['method']] = array(); } foreach ($annotation['args'] as $key => $value) { if (is_numeric($key)) { $result[$annotation['method']][] = $value; } else { $result[$annotation['method']][$key] = $value; } } } return $result; }
php
protected function convertAnnotationObj($reflection) { $annotations = (array) $reflection->getAnnotations(); $result = array(); foreach ($annotations as $annotation) { if (! array_key_exists($annotation['method'], $result)) { $result[$annotation['method']] = array(); } foreach ($annotation['args'] as $key => $value) { if (is_numeric($key)) { $result[$annotation['method']][] = $value; } else { $result[$annotation['method']][$key] = $value; } } } return $result; }
[ "protected", "function", "convertAnnotationObj", "(", "$", "reflection", ")", "{", "$", "annotations", "=", "(", "array", ")", "$", "reflection", "->", "getAnnotations", "(", ")", ";", "$", "result", "=", "array", "(", ")", ";", "foreach", "(", "$", "annotations", "as", "$", "annotation", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "annotation", "[", "'method'", "]", ",", "$", "result", ")", ")", "{", "$", "result", "[", "$", "annotation", "[", "'method'", "]", "]", "=", "array", "(", ")", ";", "}", "foreach", "(", "$", "annotation", "[", "'args'", "]", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_numeric", "(", "$", "key", ")", ")", "{", "$", "result", "[", "$", "annotation", "[", "'method'", "]", "]", "[", "]", "=", "$", "value", ";", "}", "else", "{", "$", "result", "[", "$", "annotation", "[", "'method'", "]", "]", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "}", "return", "$", "result", ";", "}" ]
This method converts Notoj returned array to reader data @param Mixed/Reflection $reflection a Notoj reflection object @return array annoations array
[ "This", "method", "converts", "Notoj", "returned", "array", "to", "reader", "data" ]
5b7e9b13acfda38c61b2da2639e8a56f298dc32e
https://github.com/phpalchemy/phpalchemy/blob/5b7e9b13acfda38c61b2da2639e8a56f298dc32e/Alchemy/Annotation/Reader/Adapter/NotojReader.php#L106-L126
train
valu-digital/valuso
src/ValuSo/Annotation/AnnotationBuilderFactory.php
AnnotationBuilderFactory.createService
public function createService(ServiceLocatorInterface $serviceLocator) { $config = $serviceLocator->get('Config'); $config = empty($config['valu_so']) ? [] : $config['valu_so']; $annotationBuilder = new AnnotationBuilder(); // Attach custom annotations if (!empty($config['annotations'])) { $parser = new Parser\DoctrineAnnotationParser(); foreach($config['annotations'] as $name => $class){ $parser->registerAnnotation($class); } $annotationBuilder->getAnnotationManager()->attach($parser); } // Attach listeners for custom annotations if (!empty($config['annotation_listeners'])) { EventManagerConfigurator::configure( $annotationBuilder->getEventManager(), $serviceLocator, $config['annotation_listeners']); } return $annotationBuilder; }
php
public function createService(ServiceLocatorInterface $serviceLocator) { $config = $serviceLocator->get('Config'); $config = empty($config['valu_so']) ? [] : $config['valu_so']; $annotationBuilder = new AnnotationBuilder(); // Attach custom annotations if (!empty($config['annotations'])) { $parser = new Parser\DoctrineAnnotationParser(); foreach($config['annotations'] as $name => $class){ $parser->registerAnnotation($class); } $annotationBuilder->getAnnotationManager()->attach($parser); } // Attach listeners for custom annotations if (!empty($config['annotation_listeners'])) { EventManagerConfigurator::configure( $annotationBuilder->getEventManager(), $serviceLocator, $config['annotation_listeners']); } return $annotationBuilder; }
[ "public", "function", "createService", "(", "ServiceLocatorInterface", "$", "serviceLocator", ")", "{", "$", "config", "=", "$", "serviceLocator", "->", "get", "(", "'Config'", ")", ";", "$", "config", "=", "empty", "(", "$", "config", "[", "'valu_so'", "]", ")", "?", "[", "]", ":", "$", "config", "[", "'valu_so'", "]", ";", "$", "annotationBuilder", "=", "new", "AnnotationBuilder", "(", ")", ";", "// Attach custom annotations", "if", "(", "!", "empty", "(", "$", "config", "[", "'annotations'", "]", ")", ")", "{", "$", "parser", "=", "new", "Parser", "\\", "DoctrineAnnotationParser", "(", ")", ";", "foreach", "(", "$", "config", "[", "'annotations'", "]", "as", "$", "name", "=>", "$", "class", ")", "{", "$", "parser", "->", "registerAnnotation", "(", "$", "class", ")", ";", "}", "$", "annotationBuilder", "->", "getAnnotationManager", "(", ")", "->", "attach", "(", "$", "parser", ")", ";", "}", "// Attach listeners for custom annotations", "if", "(", "!", "empty", "(", "$", "config", "[", "'annotation_listeners'", "]", ")", ")", "{", "EventManagerConfigurator", "::", "configure", "(", "$", "annotationBuilder", "->", "getEventManager", "(", ")", ",", "$", "serviceLocator", ",", "$", "config", "[", "'annotation_listeners'", "]", ")", ";", "}", "return", "$", "annotationBuilder", ";", "}" ]
Create an annotation builder for service broker {@see ValuSo\Broker\ServiceBroker} uses {@see Zend\ServiceManager\ServiceManager} internally to initialize service instances. {@see Zend\Mvc\Service\ServiceManagerConfig} for how to configure service manager. This factory uses following configuration scheme: <code> [ 'valu_so' => [ 'annotations' => [ '<id>' => '', ], 'annotation_listeners' => [ '<ServiceID>' ] ] ] </code> @see \Zend\ServiceManager\FactoryInterface::createService() @return ServiceBroker
[ "Create", "an", "annotation", "builder", "for", "service", "broker" ]
c96bed0f6bd21551822334fe6cfe913a7436dd17
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Annotation/AnnotationBuilderFactory.php#L40-L67
train
PopSugar/php-yesmail-api
src/Yesmail/YesmailListload.php
YesmailListload.is_valid
public function is_valid() { $ret = false; if (is_null($this->division) === false && is_null($this->datafileURI) === false && is_null($this->subscribe) === false && is_null($this->profileUpdate) === false && is_null($this->listLoadName) === false && is_null($this->loadMode) === false && is_null($this->headers) === false && is_null($this->maxErrors) === false && is_null($this->errorType) === false ) { $ret = true; } return $ret; }
php
public function is_valid() { $ret = false; if (is_null($this->division) === false && is_null($this->datafileURI) === false && is_null($this->subscribe) === false && is_null($this->profileUpdate) === false && is_null($this->listLoadName) === false && is_null($this->loadMode) === false && is_null($this->headers) === false && is_null($this->maxErrors) === false && is_null($this->errorType) === false ) { $ret = true; } return $ret; }
[ "public", "function", "is_valid", "(", ")", "{", "$", "ret", "=", "false", ";", "if", "(", "is_null", "(", "$", "this", "->", "division", ")", "===", "false", "&&", "is_null", "(", "$", "this", "->", "datafileURI", ")", "===", "false", "&&", "is_null", "(", "$", "this", "->", "subscribe", ")", "===", "false", "&&", "is_null", "(", "$", "this", "->", "profileUpdate", ")", "===", "false", "&&", "is_null", "(", "$", "this", "->", "listLoadName", ")", "===", "false", "&&", "is_null", "(", "$", "this", "->", "loadMode", ")", "===", "false", "&&", "is_null", "(", "$", "this", "->", "headers", ")", "===", "false", "&&", "is_null", "(", "$", "this", "->", "maxErrors", ")", "===", "false", "&&", "is_null", "(", "$", "this", "->", "errorType", ")", "===", "false", ")", "{", "$", "ret", "=", "true", ";", "}", "return", "$", "ret", ";", "}" ]
Validates a listload @return bool True if the listload is valid, false otherwise @access public
[ "Validates", "a", "listload" ]
42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c
https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/YesmailListload.php#L134-L147
train
Synapse-Cmf/synapse-cmf
src/Synapse/Cmf/Framework/Media/File/Action/Dal/CreateAction.php
CreateAction.resolve
public function resolve() { $this->file = (new $this->fileClass()) ->setName( $this->physicalFile->getBasename() ) // calculate original name (keep it for user data display) ->setOriginalName($this->originalName ?: $this->physicalFile->getBasename() ) // calculate storage path (we only need path from config) ->setStorePath(str_replace(// trim base path realpath($this->storePath), '', str_replace(// trim filename $this->physicalFile->getBasename(), '', $this->physicalFile->getRealpath() ) )) ; $this->assertEntityIsValid($this->file, array('File', 'creation')); $this->fireEvent( FileEvents::FILE_CREATED, new FileEvent($this->file, $this) ); return $this->file; }
php
public function resolve() { $this->file = (new $this->fileClass()) ->setName( $this->physicalFile->getBasename() ) // calculate original name (keep it for user data display) ->setOriginalName($this->originalName ?: $this->physicalFile->getBasename() ) // calculate storage path (we only need path from config) ->setStorePath(str_replace(// trim base path realpath($this->storePath), '', str_replace(// trim filename $this->physicalFile->getBasename(), '', $this->physicalFile->getRealpath() ) )) ; $this->assertEntityIsValid($this->file, array('File', 'creation')); $this->fireEvent( FileEvents::FILE_CREATED, new FileEvent($this->file, $this) ); return $this->file; }
[ "public", "function", "resolve", "(", ")", "{", "$", "this", "->", "file", "=", "(", "new", "$", "this", "->", "fileClass", "(", ")", ")", "->", "setName", "(", "$", "this", "->", "physicalFile", "->", "getBasename", "(", ")", ")", "// calculate original name (keep it for user data display)", "->", "setOriginalName", "(", "$", "this", "->", "originalName", "?", ":", "$", "this", "->", "physicalFile", "->", "getBasename", "(", ")", ")", "// calculate storage path (we only need path from config)", "->", "setStorePath", "(", "str_replace", "(", "// trim base path", "realpath", "(", "$", "this", "->", "storePath", ")", ",", "''", ",", "str_replace", "(", "// trim filename", "$", "this", "->", "physicalFile", "->", "getBasename", "(", ")", ",", "''", ",", "$", "this", "->", "physicalFile", "->", "getRealpath", "(", ")", ")", ")", ")", ";", "$", "this", "->", "assertEntityIsValid", "(", "$", "this", "->", "file", ",", "array", "(", "'File'", ",", "'creation'", ")", ")", ";", "$", "this", "->", "fireEvent", "(", "FileEvents", "::", "FILE_CREATED", ",", "new", "FileEvent", "(", "$", "this", "->", "file", ",", "$", "this", ")", ")", ";", "return", "$", "this", "->", "file", ";", "}" ]
File creation method. @return File
[ "File", "creation", "method", "." ]
d8122a4150a83d5607289724425cf35c56a5e880
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Framework/Media/File/Action/Dal/CreateAction.php#L30-L60
train
aryelgois/medools-router
src/Router.php
Router.parseAccept
public static function parseAccept(string $accept) { $result = []; foreach (explode(',', $accept) as $directive) { $parts = explode(';', $directive, 2); $type = trim($parts[0]); $priority = ((float) filter_var( $parts[1] ?? 1, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION )); $priority = Utils::numberLimit($priority, 0, 1); if (strpos($type, '*') !== false) { $priority -= 0.0001; } $result[$type] = $priority; } return $result; }
php
public static function parseAccept(string $accept) { $result = []; foreach (explode(',', $accept) as $directive) { $parts = explode(';', $directive, 2); $type = trim($parts[0]); $priority = ((float) filter_var( $parts[1] ?? 1, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION )); $priority = Utils::numberLimit($priority, 0, 1); if (strpos($type, '*') !== false) { $priority -= 0.0001; } $result[$type] = $priority; } return $result; }
[ "public", "static", "function", "parseAccept", "(", "string", "$", "accept", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "explode", "(", "','", ",", "$", "accept", ")", "as", "$", "directive", ")", "{", "$", "parts", "=", "explode", "(", "';'", ",", "$", "directive", ",", "2", ")", ";", "$", "type", "=", "trim", "(", "$", "parts", "[", "0", "]", ")", ";", "$", "priority", "=", "(", "(", "float", ")", "filter_var", "(", "$", "parts", "[", "1", "]", "??", "1", ",", "FILTER_SANITIZE_NUMBER_FLOAT", ",", "FILTER_FLAG_ALLOW_FRACTION", ")", ")", ";", "$", "priority", "=", "Utils", "::", "numberLimit", "(", "$", "priority", ",", "0", ",", "1", ")", ";", "if", "(", "strpos", "(", "$", "type", ",", "'*'", ")", "!==", "false", ")", "{", "$", "priority", "-=", "0.0001", ";", "}", "$", "result", "[", "$", "type", "]", "=", "$", "priority", ";", "}", "return", "$", "result", ";", "}" ]
Parses Accept header @param string $accept Accept header @return float[] With 'type' => priority Keys may contain '*'
[ "Parses", "Accept", "header" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1302-L1325
train
aryelgois/medools-router
src/Router.php
Router.parseBody
protected function parseBody(string $resource, string $type, string $body) { $content_type = static::parseContentType($type); $mime = $content_type['mime'] ?? $content_type; if (($content_type['charset'] ?? null) !== null) { $body = mb_convert_encoding( $body, 'UTF-8', $content_type['charset'] ); } if ($mime === '') { if ($body === '') { return []; } } elseif ($mime === 'application/json') { $data = json_decode($body, true); if (!empty($data)) { return [ 'mime' => $mime, 'data' => $data, ]; } } else { if (!$this->safe_method) { $handlers = $this->resources[$resource]['handlers'] ?? []; if (!empty($handlers)) { $handlers = $handlers[$this->method] ?? null; if (is_array($handlers) && array_key_exists($mime, $handlers) ) { return [ 'mime' => $mime, 'body' => $body, ]; } } } $this->sendError( static::ERROR_UNSUPPORTED_MEDIA_TYPE, "Media-Type '$mime' is not supported" ); } $this->sendError( static::ERROR_INVALID_PAYLOAD, "Body payload could not be parsed" ); }
php
protected function parseBody(string $resource, string $type, string $body) { $content_type = static::parseContentType($type); $mime = $content_type['mime'] ?? $content_type; if (($content_type['charset'] ?? null) !== null) { $body = mb_convert_encoding( $body, 'UTF-8', $content_type['charset'] ); } if ($mime === '') { if ($body === '') { return []; } } elseif ($mime === 'application/json') { $data = json_decode($body, true); if (!empty($data)) { return [ 'mime' => $mime, 'data' => $data, ]; } } else { if (!$this->safe_method) { $handlers = $this->resources[$resource]['handlers'] ?? []; if (!empty($handlers)) { $handlers = $handlers[$this->method] ?? null; if (is_array($handlers) && array_key_exists($mime, $handlers) ) { return [ 'mime' => $mime, 'body' => $body, ]; } } } $this->sendError( static::ERROR_UNSUPPORTED_MEDIA_TYPE, "Media-Type '$mime' is not supported" ); } $this->sendError( static::ERROR_INVALID_PAYLOAD, "Body payload could not be parsed" ); }
[ "protected", "function", "parseBody", "(", "string", "$", "resource", ",", "string", "$", "type", ",", "string", "$", "body", ")", "{", "$", "content_type", "=", "static", "::", "parseContentType", "(", "$", "type", ")", ";", "$", "mime", "=", "$", "content_type", "[", "'mime'", "]", "??", "$", "content_type", ";", "if", "(", "(", "$", "content_type", "[", "'charset'", "]", "??", "null", ")", "!==", "null", ")", "{", "$", "body", "=", "mb_convert_encoding", "(", "$", "body", ",", "'UTF-8'", ",", "$", "content_type", "[", "'charset'", "]", ")", ";", "}", "if", "(", "$", "mime", "===", "''", ")", "{", "if", "(", "$", "body", "===", "''", ")", "{", "return", "[", "]", ";", "}", "}", "elseif", "(", "$", "mime", "===", "'application/json'", ")", "{", "$", "data", "=", "json_decode", "(", "$", "body", ",", "true", ")", ";", "if", "(", "!", "empty", "(", "$", "data", ")", ")", "{", "return", "[", "'mime'", "=>", "$", "mime", ",", "'data'", "=>", "$", "data", ",", "]", ";", "}", "}", "else", "{", "if", "(", "!", "$", "this", "->", "safe_method", ")", "{", "$", "handlers", "=", "$", "this", "->", "resources", "[", "$", "resource", "]", "[", "'handlers'", "]", "??", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "handlers", ")", ")", "{", "$", "handlers", "=", "$", "handlers", "[", "$", "this", "->", "method", "]", "??", "null", ";", "if", "(", "is_array", "(", "$", "handlers", ")", "&&", "array_key_exists", "(", "$", "mime", ",", "$", "handlers", ")", ")", "{", "return", "[", "'mime'", "=>", "$", "mime", ",", "'body'", "=>", "$", "body", ",", "]", ";", "}", "}", "}", "$", "this", "->", "sendError", "(", "static", "::", "ERROR_UNSUPPORTED_MEDIA_TYPE", ",", "\"Media-Type '$mime' is not supported\"", ")", ";", "}", "$", "this", "->", "sendError", "(", "static", "::", "ERROR_INVALID_PAYLOAD", ",", "\"Body payload could not be parsed\"", ")", ";", "}" ]
Parses request body @param string $resource Resource name @param string $type Content-Type header @param string $body Request Body @return array @throws RouterException If $type is not supported @throws RouterException If $body could not be parsed
[ "Parses", "request", "body" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1339-L1390
train
aryelgois/medools-router
src/Router.php
Router.parseContentType
public static function parseContentType(string $content_type) { $directives = array_map('trim', explode(';', $content_type)); $result = [ 'mime' => array_shift($directives) ]; if (empty($directives)) { return $result['mime']; } foreach ($directives as $directive) { $parts = explode('=', $directive); $result[$parts[0]] = $parts[1]; } return $result; }
php
public static function parseContentType(string $content_type) { $directives = array_map('trim', explode(';', $content_type)); $result = [ 'mime' => array_shift($directives) ]; if (empty($directives)) { return $result['mime']; } foreach ($directives as $directive) { $parts = explode('=', $directive); $result[$parts[0]] = $parts[1]; } return $result; }
[ "public", "static", "function", "parseContentType", "(", "string", "$", "content_type", ")", "{", "$", "directives", "=", "array_map", "(", "'trim'", ",", "explode", "(", "';'", ",", "$", "content_type", ")", ")", ";", "$", "result", "=", "[", "'mime'", "=>", "array_shift", "(", "$", "directives", ")", "]", ";", "if", "(", "empty", "(", "$", "directives", ")", ")", "{", "return", "$", "result", "[", "'mime'", "]", ";", "}", "foreach", "(", "$", "directives", "as", "$", "directive", ")", "{", "$", "parts", "=", "explode", "(", "'='", ",", "$", "directive", ")", ";", "$", "result", "[", "$", "parts", "[", "0", "]", "]", "=", "$", "parts", "[", "1", "]", ";", "}", "return", "$", "result", ";", "}" ]
Parses a Content-Type header @param string $content_type Content-Type header to be parsed @return string @return string[] With keys 'mime', and 'charset' and/or 'boundary'
[ "Parses", "a", "Content", "-", "Type", "header" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1400-L1418
train
aryelgois/medools-router
src/Router.php
Router.parseFields
protected function parseFields(Resource $resource) { $fields = $resource->getFields(); if (!is_array($fields)) { $this->sendError(static::ERROR_UNKNOWN_FIELDS, $fields); } return $fields; }
php
protected function parseFields(Resource $resource) { $fields = $resource->getFields(); if (!is_array($fields)) { $this->sendError(static::ERROR_UNKNOWN_FIELDS, $fields); } return $fields; }
[ "protected", "function", "parseFields", "(", "Resource", "$", "resource", ")", "{", "$", "fields", "=", "$", "resource", "->", "getFields", "(", ")", ";", "if", "(", "!", "is_array", "(", "$", "fields", ")", ")", "{", "$", "this", "->", "sendError", "(", "static", "::", "ERROR_UNKNOWN_FIELDS", ",", "$", "fields", ")", ";", "}", "return", "$", "fields", ";", "}" ]
Parses fields query and validate against a resource @param Resource $resource Resource @return string[] @throws RouterException If fields query parameter has invalid fields
[ "Parses", "fields", "query", "and", "validate", "against", "a", "resource" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1429-L1436
train
aryelgois/medools-router
src/Router.php
Router.createModel
protected function createModel(Resource $resource) { $model = new $resource->model_class; $model->fill($resource->data); $result = $model->save(); if ($result === true) { return $model; } $code = (empty($resource->data) || $result === null) ? static::ERROR_INVALID_PAYLOAD : static::ERROR_INTERNAL_SERVER; $message = "Resource '$resource->name' could not be created: "; if (is_string($result)) { $message .= "Database failure ($result)"; } elseif ($result === false) { $message .= 'post-save failure'; } else { $message .= 'pre-save failure'; } $this->sendError($code, $message); }
php
protected function createModel(Resource $resource) { $model = new $resource->model_class; $model->fill($resource->data); $result = $model->save(); if ($result === true) { return $model; } $code = (empty($resource->data) || $result === null) ? static::ERROR_INVALID_PAYLOAD : static::ERROR_INTERNAL_SERVER; $message = "Resource '$resource->name' could not be created: "; if (is_string($result)) { $message .= "Database failure ($result)"; } elseif ($result === false) { $message .= 'post-save failure'; } else { $message .= 'pre-save failure'; } $this->sendError($code, $message); }
[ "protected", "function", "createModel", "(", "Resource", "$", "resource", ")", "{", "$", "model", "=", "new", "$", "resource", "->", "model_class", ";", "$", "model", "->", "fill", "(", "$", "resource", "->", "data", ")", ";", "$", "result", "=", "$", "model", "->", "save", "(", ")", ";", "if", "(", "$", "result", "===", "true", ")", "{", "return", "$", "model", ";", "}", "$", "code", "=", "(", "empty", "(", "$", "resource", "->", "data", ")", "||", "$", "result", "===", "null", ")", "?", "static", "::", "ERROR_INVALID_PAYLOAD", ":", "static", "::", "ERROR_INTERNAL_SERVER", ";", "$", "message", "=", "\"Resource '$resource->name' could not be created: \"", ";", "if", "(", "is_string", "(", "$", "result", ")", ")", "{", "$", "message", ".=", "\"Database failure ($result)\"", ";", "}", "elseif", "(", "$", "result", "===", "false", ")", "{", "$", "message", ".=", "'post-save failure'", ";", "}", "else", "{", "$", "message", ".=", "'pre-save failure'", ";", "}", "$", "this", "->", "sendError", "(", "$", "code", ",", "$", "message", ")", ";", "}" ]
Creates a Model in the Database @param Resource $resource Processed route @return Model @throws RouterException If could not save the new Model
[ "Creates", "a", "Model", "in", "the", "Database" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1658-L1683
train
aryelgois/medools-router
src/Router.php
Router.deleteModel
protected function deleteModel( Model $model, Resource $resource, string $route = null ) { if ($model->delete()) { return; } $message = "Resource '" . ($route ?? $resource->route) . "' could not be deleted"; $this->sendError(static::ERROR_INTERNAL_SERVER, $message); }
php
protected function deleteModel( Model $model, Resource $resource, string $route = null ) { if ($model->delete()) { return; } $message = "Resource '" . ($route ?? $resource->route) . "' could not be deleted"; $this->sendError(static::ERROR_INTERNAL_SERVER, $message); }
[ "protected", "function", "deleteModel", "(", "Model", "$", "model", ",", "Resource", "$", "resource", ",", "string", "$", "route", "=", "null", ")", "{", "if", "(", "$", "model", "->", "delete", "(", ")", ")", "{", "return", ";", "}", "$", "message", "=", "\"Resource '\"", ".", "(", "$", "route", "??", "$", "resource", "->", "route", ")", ".", "\"' could not be deleted\"", ";", "$", "this", "->", "sendError", "(", "static", "::", "ERROR_INTERNAL_SERVER", ",", "$", "message", ")", ";", "}" ]
Deletes a Model @param Model $model Model to be deleted @param Resource $resource Resource that loaded $model @param string $route Alternative route to $model @throws RouterException If could not delete the Model
[ "Deletes", "a", "Model" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1694-L1707
train
aryelgois/medools-router
src/Router.php
Router.updateModel
protected function updateModel( Model $model, Resource $resource, string $route = null ) { $model->fill($resource->data); $result = $model->update(array_keys($resource->data)); if ($result === true) { return; } $message = "Resource '" . ($route ?? $resource->route) . "' could not be updated"; if (is_string($result)) { $message .= ": Database failure ($result)"; } $this->sendError(static::ERROR_INTERNAL_SERVER, $message); }
php
protected function updateModel( Model $model, Resource $resource, string $route = null ) { $model->fill($resource->data); $result = $model->update(array_keys($resource->data)); if ($result === true) { return; } $message = "Resource '" . ($route ?? $resource->route) . "' could not be updated"; if (is_string($result)) { $message .= ": Database failure ($result)"; } $this->sendError(static::ERROR_INTERNAL_SERVER, $message); }
[ "protected", "function", "updateModel", "(", "Model", "$", "model", ",", "Resource", "$", "resource", ",", "string", "$", "route", "=", "null", ")", "{", "$", "model", "->", "fill", "(", "$", "resource", "->", "data", ")", ";", "$", "result", "=", "$", "model", "->", "update", "(", "array_keys", "(", "$", "resource", "->", "data", ")", ")", ";", "if", "(", "$", "result", "===", "true", ")", "{", "return", ";", "}", "$", "message", "=", "\"Resource '\"", ".", "(", "$", "route", "??", "$", "resource", "->", "route", ")", ".", "\"' could not be updated\"", ";", "if", "(", "is_string", "(", "$", "result", ")", ")", "{", "$", "message", ".=", "\": Database failure ($result)\"", ";", "}", "$", "this", "->", "sendError", "(", "static", "::", "ERROR_INTERNAL_SERVER", ",", "$", "message", ")", ";", "}" ]
Updates a Model @param Model $model Model to be updated @param Resource $resource Resource that loaded $model @param string $route Alternative route to $model @throws RouterException If could not update the Model
[ "Updates", "a", "Model" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1718-L1738
train
aryelgois/medools-router
src/Router.php
Router.checkCache
protected function checkCache( Response $response, string $e_tags, int $max_age ) { $result = $response; $cache_method = $this->cache_method; if (is_callable($cache_method)) { $hash = '"' . $cache_method(serialize($response->body)) . '"'; if (strpos($e_tags, $hash) !== false) { $reuse_headers = Utils::arrayWhitelist( $response->headers, [ 'Content-Location', ] ); $result = $this->prepareResponse(); $result->status = HttpResponse::HTTP_NOT_MODIFIED; $result->headers = $reuse_headers; } $result->headers['ETag'] = $hash; $result->headers['Cache-Control'] = 'private, max-age=' . $max_age . ', must-revalidate'; } else { $this->sendError( static::ERROR_INTERNAL_SERVER, "Router config 'cache_method' is invalid" ); } return $result; }
php
protected function checkCache( Response $response, string $e_tags, int $max_age ) { $result = $response; $cache_method = $this->cache_method; if (is_callable($cache_method)) { $hash = '"' . $cache_method(serialize($response->body)) . '"'; if (strpos($e_tags, $hash) !== false) { $reuse_headers = Utils::arrayWhitelist( $response->headers, [ 'Content-Location', ] ); $result = $this->prepareResponse(); $result->status = HttpResponse::HTTP_NOT_MODIFIED; $result->headers = $reuse_headers; } $result->headers['ETag'] = $hash; $result->headers['Cache-Control'] = 'private, max-age=' . $max_age . ', must-revalidate'; } else { $this->sendError( static::ERROR_INTERNAL_SERVER, "Router config 'cache_method' is invalid" ); } return $result; }
[ "protected", "function", "checkCache", "(", "Response", "$", "response", ",", "string", "$", "e_tags", ",", "int", "$", "max_age", ")", "{", "$", "result", "=", "$", "response", ";", "$", "cache_method", "=", "$", "this", "->", "cache_method", ";", "if", "(", "is_callable", "(", "$", "cache_method", ")", ")", "{", "$", "hash", "=", "'\"'", ".", "$", "cache_method", "(", "serialize", "(", "$", "response", "->", "body", ")", ")", ".", "'\"'", ";", "if", "(", "strpos", "(", "$", "e_tags", ",", "$", "hash", ")", "!==", "false", ")", "{", "$", "reuse_headers", "=", "Utils", "::", "arrayWhitelist", "(", "$", "response", "->", "headers", ",", "[", "'Content-Location'", ",", "]", ")", ";", "$", "result", "=", "$", "this", "->", "prepareResponse", "(", ")", ";", "$", "result", "->", "status", "=", "HttpResponse", "::", "HTTP_NOT_MODIFIED", ";", "$", "result", "->", "headers", "=", "$", "reuse_headers", ";", "}", "$", "result", "->", "headers", "[", "'ETag'", "]", "=", "$", "hash", ";", "$", "result", "->", "headers", "[", "'Cache-Control'", "]", "=", "'private, max-age='", ".", "$", "max_age", ".", "', must-revalidate'", ";", "}", "else", "{", "$", "this", "->", "sendError", "(", "static", "::", "ERROR_INTERNAL_SERVER", ",", "\"Router config 'cache_method' is invalid\"", ")", ";", "}", "return", "$", "result", ";", "}" ]
Checks if Response is modified from Client's cache It adds caching headers @param Response $response Response to be checked @param string $e_tags Request If-None-Match Header @param integer $max_age Resource max_age @return Response With caching headers or with Not Modified status @throws RouterException If 'cache_method' config is invalid
[ "Checks", "if", "Response", "is", "modified", "from", "Client", "s", "cache" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1758-L1793
train
aryelgois/medools-router
src/Router.php
Router.checkMissingFields
protected function checkMissingFields(Resource $resource) { $missing = array_diff( $resource->model_class::getRequiredColumns(), array_keys($resource->data) ); if (!empty($missing)) { $message = "Resource '$resource->name' requires the following " . "missing fields: '" . implode("', '", $missing) . "'"; $this->sendError(static::ERROR_INVALID_PAYLOAD, $message); } }
php
protected function checkMissingFields(Resource $resource) { $missing = array_diff( $resource->model_class::getRequiredColumns(), array_keys($resource->data) ); if (!empty($missing)) { $message = "Resource '$resource->name' requires the following " . "missing fields: '" . implode("', '", $missing) . "'"; $this->sendError(static::ERROR_INVALID_PAYLOAD, $message); } }
[ "protected", "function", "checkMissingFields", "(", "Resource", "$", "resource", ")", "{", "$", "missing", "=", "array_diff", "(", "$", "resource", "->", "model_class", "::", "getRequiredColumns", "(", ")", ",", "array_keys", "(", "$", "resource", "->", "data", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "missing", ")", ")", "{", "$", "message", "=", "\"Resource '$resource->name' requires the following \"", ".", "\"missing fields: '\"", ".", "implode", "(", "\"', '\"", ",", "$", "missing", ")", ".", "\"'\"", ";", "$", "this", "->", "sendError", "(", "static", "::", "ERROR_INVALID_PAYLOAD", ",", "$", "message", ")", ";", "}", "}" ]
Checks if resource data fulfills the required columns @param Resource $resource Resource @throws RouterException If required fields are missing
[ "Checks", "if", "resource", "data", "fulfills", "the", "required", "columns" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1802-L1814
train
aryelgois/medools-router
src/Router.php
Router.checkUnknownField
protected function checkUnknownField(Resource $resource, array $fields) { $message = $resource->hasFields($fields); if ($message !== true) { $this->sendError(static::ERROR_UNKNOWN_FIELDS, $message); } }
php
protected function checkUnknownField(Resource $resource, array $fields) { $message = $resource->hasFields($fields); if ($message !== true) { $this->sendError(static::ERROR_UNKNOWN_FIELDS, $message); } }
[ "protected", "function", "checkUnknownField", "(", "Resource", "$", "resource", ",", "array", "$", "fields", ")", "{", "$", "message", "=", "$", "resource", "->", "hasFields", "(", "$", "fields", ")", ";", "if", "(", "$", "message", "!==", "true", ")", "{", "$", "this", "->", "sendError", "(", "static", "::", "ERROR_UNKNOWN_FIELDS", ",", "$", "message", ")", ";", "}", "}" ]
Checks if a resource has all fields passed @param Resource $resource Resource @param string[] $fields List of fields to test @throws RouterException If there are unknown fields
[ "Checks", "if", "a", "resource", "has", "all", "fields", "passed" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1824-L1830
train
aryelgois/medools-router
src/Router.php
Router.compareAccept
public static function compareAccept(string $accept, array $available) { $result = []; foreach (static::parseAccept($accept) as $type => $priority) { if (strpos($type, '*') === false) { if (in_array($type, $available)) { $result[$type] = max($result[$type] ?? 0, $priority); } } else { foreach ($available as $available_type) { if (fnmatch($type, $available_type)) { $result[$available_type] = max( $result[$available_type] ?? 0, $priority ); } } } } return $result; }
php
public static function compareAccept(string $accept, array $available) { $result = []; foreach (static::parseAccept($accept) as $type => $priority) { if (strpos($type, '*') === false) { if (in_array($type, $available)) { $result[$type] = max($result[$type] ?? 0, $priority); } } else { foreach ($available as $available_type) { if (fnmatch($type, $available_type)) { $result[$available_type] = max( $result[$available_type] ?? 0, $priority ); } } } } return $result; }
[ "public", "static", "function", "compareAccept", "(", "string", "$", "accept", ",", "array", "$", "available", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "static", "::", "parseAccept", "(", "$", "accept", ")", "as", "$", "type", "=>", "$", "priority", ")", "{", "if", "(", "strpos", "(", "$", "type", ",", "'*'", ")", "===", "false", ")", "{", "if", "(", "in_array", "(", "$", "type", ",", "$", "available", ")", ")", "{", "$", "result", "[", "$", "type", "]", "=", "max", "(", "$", "result", "[", "$", "type", "]", "??", "0", ",", "$", "priority", ")", ";", "}", "}", "else", "{", "foreach", "(", "$", "available", "as", "$", "available_type", ")", "{", "if", "(", "fnmatch", "(", "$", "type", ",", "$", "available_type", ")", ")", "{", "$", "result", "[", "$", "available_type", "]", "=", "max", "(", "$", "result", "[", "$", "available_type", "]", "??", "0", ",", "$", "priority", ")", ";", "}", "}", "}", "}", "return", "$", "result", ";", "}" ]
Compares content types in an Accept header with a list of available types @param string $accept Accept header @param string[] $available Available content types @return float[] With 'type' => priority
[ "Compares", "content", "types", "in", "an", "Accept", "header", "with", "a", "list", "of", "available", "types" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1840-L1860
train
aryelgois/medools-router
src/Router.php
Router.countResource
protected function countResource(string $resource, array $where = null) { $model = $this->resources[$resource]['model']; $database = $model::getDatabase(); return $database->count($model::TABLE, $where ?? []); }
php
protected function countResource(string $resource, array $where = null) { $model = $this->resources[$resource]['model']; $database = $model::getDatabase(); return $database->count($model::TABLE, $where ?? []); }
[ "protected", "function", "countResource", "(", "string", "$", "resource", ",", "array", "$", "where", "=", "null", ")", "{", "$", "model", "=", "$", "this", "->", "resources", "[", "$", "resource", "]", "[", "'model'", "]", ";", "$", "database", "=", "$", "model", "::", "getDatabase", "(", ")", ";", "return", "$", "database", "->", "count", "(", "$", "model", "::", "TABLE", ",", "$", "where", "??", "[", "]", ")", ";", "}" ]
Counts rows in Resource's table @param string $resource Resource name @param mixed[] $where \Medoo\Medoo $where clause @return integer
[ "Counts", "rows", "in", "Resource", "s", "table" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1870-L1875
train
aryelgois/medools-router
src/Router.php
Router.externalHandler
protected function externalHandler(Resource $resource) { $handlers = $this->resources[$resource->name]['handlers'] ?? []; if (!empty($handlers)) { if ($this->safe_method) { $handlers = $handlers['GET'] ?? null; if (is_array($handlers)) { $handlers = $this->getAvailableTypes($resource->name); $type = $resource->content_type; } } else { $handlers = $handlers[$this->method] ?? null; if (is_array($handlers)) { $type = $resource->payload['mime']; } } if (isset($type)) { $handler = $handlers[$type]; if (is_array($handler)) { $handler = $handler[$resource->kind]; } if ($type === 'application/json' && $handler == '__DEFAULT__') { $handler = null; } } else { $handler = $handlers; } if ($handler !== null) { if (is_callable($handler)) { if ($this->method === 'HEAD') { ob_start(); $handler($resource); ob_end_clean(); } else { $handler($resource); flush(); } return true; } $this->sendError(static::ERROR_INTERNAL_SERVER, sprintf( "Resource '%s' has invalid %s handler: '%s' (%s request)", $resource->name, $this->method, $handler, $resource->kind )); } } return false; }
php
protected function externalHandler(Resource $resource) { $handlers = $this->resources[$resource->name]['handlers'] ?? []; if (!empty($handlers)) { if ($this->safe_method) { $handlers = $handlers['GET'] ?? null; if (is_array($handlers)) { $handlers = $this->getAvailableTypes($resource->name); $type = $resource->content_type; } } else { $handlers = $handlers[$this->method] ?? null; if (is_array($handlers)) { $type = $resource->payload['mime']; } } if (isset($type)) { $handler = $handlers[$type]; if (is_array($handler)) { $handler = $handler[$resource->kind]; } if ($type === 'application/json' && $handler == '__DEFAULT__') { $handler = null; } } else { $handler = $handlers; } if ($handler !== null) { if (is_callable($handler)) { if ($this->method === 'HEAD') { ob_start(); $handler($resource); ob_end_clean(); } else { $handler($resource); flush(); } return true; } $this->sendError(static::ERROR_INTERNAL_SERVER, sprintf( "Resource '%s' has invalid %s handler: '%s' (%s request)", $resource->name, $this->method, $handler, $resource->kind )); } } return false; }
[ "protected", "function", "externalHandler", "(", "Resource", "$", "resource", ")", "{", "$", "handlers", "=", "$", "this", "->", "resources", "[", "$", "resource", "->", "name", "]", "[", "'handlers'", "]", "??", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "handlers", ")", ")", "{", "if", "(", "$", "this", "->", "safe_method", ")", "{", "$", "handlers", "=", "$", "handlers", "[", "'GET'", "]", "??", "null", ";", "if", "(", "is_array", "(", "$", "handlers", ")", ")", "{", "$", "handlers", "=", "$", "this", "->", "getAvailableTypes", "(", "$", "resource", "->", "name", ")", ";", "$", "type", "=", "$", "resource", "->", "content_type", ";", "}", "}", "else", "{", "$", "handlers", "=", "$", "handlers", "[", "$", "this", "->", "method", "]", "??", "null", ";", "if", "(", "is_array", "(", "$", "handlers", ")", ")", "{", "$", "type", "=", "$", "resource", "->", "payload", "[", "'mime'", "]", ";", "}", "}", "if", "(", "isset", "(", "$", "type", ")", ")", "{", "$", "handler", "=", "$", "handlers", "[", "$", "type", "]", ";", "if", "(", "is_array", "(", "$", "handler", ")", ")", "{", "$", "handler", "=", "$", "handler", "[", "$", "resource", "->", "kind", "]", ";", "}", "if", "(", "$", "type", "===", "'application/json'", "&&", "$", "handler", "==", "'__DEFAULT__'", ")", "{", "$", "handler", "=", "null", ";", "}", "}", "else", "{", "$", "handler", "=", "$", "handlers", ";", "}", "if", "(", "$", "handler", "!==", "null", ")", "{", "if", "(", "is_callable", "(", "$", "handler", ")", ")", "{", "if", "(", "$", "this", "->", "method", "===", "'HEAD'", ")", "{", "ob_start", "(", ")", ";", "$", "handler", "(", "$", "resource", ")", ";", "ob_end_clean", "(", ")", ";", "}", "else", "{", "$", "handler", "(", "$", "resource", ")", ";", "flush", "(", ")", ";", "}", "return", "true", ";", "}", "$", "this", "->", "sendError", "(", "static", "::", "ERROR_INTERNAL_SERVER", ",", "sprintf", "(", "\"Resource '%s' has invalid %s handler: '%s' (%s request)\"", ",", "$", "resource", "->", "name", ",", "$", "this", "->", "method", ",", "$", "handler", ",", "$", "resource", "->", "kind", ")", ")", ";", "}", "}", "return", "false", ";", "}" ]
Determines external handler for a Resource and executes it @param Resource $resource Resource to be sent to handler @return boolean For success or failure @throws RouterException If handler is invalid
[ "Determines", "external", "handler", "for", "a", "Resource", "and", "executes", "it" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1886-L1939
train
aryelgois/medools-router
src/Router.php
Router.firstHigher
public static function firstHigher( array $list, float $min = null, float $max = null ) { $bounded_list = array_merge([$min ?? 0, $max ?? 1], $list); $min = min($bounded_list); $max = max($bounded_list); $result = null; $higher = $min; foreach ($list as $key => $value) { $value = Utils::numberLimit($value, $min, $max); if ($value == $max) { return $key; } elseif ($value > $higher) { $result = $key; $higher = $value; } } return $result; }
php
public static function firstHigher( array $list, float $min = null, float $max = null ) { $bounded_list = array_merge([$min ?? 0, $max ?? 1], $list); $min = min($bounded_list); $max = max($bounded_list); $result = null; $higher = $min; foreach ($list as $key => $value) { $value = Utils::numberLimit($value, $min, $max); if ($value == $max) { return $key; } elseif ($value > $higher) { $result = $key; $higher = $value; } } return $result; }
[ "public", "static", "function", "firstHigher", "(", "array", "$", "list", ",", "float", "$", "min", "=", "null", ",", "float", "$", "max", "=", "null", ")", "{", "$", "bounded_list", "=", "array_merge", "(", "[", "$", "min", "??", "0", ",", "$", "max", "??", "1", "]", ",", "$", "list", ")", ";", "$", "min", "=", "min", "(", "$", "bounded_list", ")", ";", "$", "max", "=", "max", "(", "$", "bounded_list", ")", ";", "$", "result", "=", "null", ";", "$", "higher", "=", "$", "min", ";", "foreach", "(", "$", "list", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "value", "=", "Utils", "::", "numberLimit", "(", "$", "value", ",", "$", "min", ",", "$", "max", ")", ";", "if", "(", "$", "value", "==", "$", "max", ")", "{", "return", "$", "key", ";", "}", "elseif", "(", "$", "value", ">", "$", "higher", ")", "{", "$", "result", "=", "$", "key", ";", "$", "higher", "=", "$", "value", ";", "}", "}", "return", "$", "result", ";", "}" ]
Returns key for first highest value @param float[] $list List of numbers between min and max @param float $min Min value to test (default is 0) @param float $max Max value to test (default is 1) @return mixed $list key @return null If no value was higher than $min
[ "Returns", "key", "for", "first", "highest", "value" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1951-L1975
train
aryelgois/medools-router
src/Router.php
Router.getAcceptedResourceType
protected function getAcceptedResourceType(string $resource, string $accept) { $available = array_keys($this->getAvailableTypes($resource)); if (empty($available)) { $this->sendError( static::ERROR_INTERNAL_SERVER, "Resource '$resource' has invalid GET handlers" ); } $accepted = static::getAcceptedType($accept, $available); if ($accepted === false) { $message = "Resource '$resource' can not generate content" . ' complying to Accept header'; $this->sendError(static::ERROR_NOT_ACCEPTABLE, $message); } return $accepted; }
php
protected function getAcceptedResourceType(string $resource, string $accept) { $available = array_keys($this->getAvailableTypes($resource)); if (empty($available)) { $this->sendError( static::ERROR_INTERNAL_SERVER, "Resource '$resource' has invalid GET handlers" ); } $accepted = static::getAcceptedType($accept, $available); if ($accepted === false) { $message = "Resource '$resource' can not generate content" . ' complying to Accept header'; $this->sendError(static::ERROR_NOT_ACCEPTABLE, $message); } return $accepted; }
[ "protected", "function", "getAcceptedResourceType", "(", "string", "$", "resource", ",", "string", "$", "accept", ")", "{", "$", "available", "=", "array_keys", "(", "$", "this", "->", "getAvailableTypes", "(", "$", "resource", ")", ")", ";", "if", "(", "empty", "(", "$", "available", ")", ")", "{", "$", "this", "->", "sendError", "(", "static", "::", "ERROR_INTERNAL_SERVER", ",", "\"Resource '$resource' has invalid GET handlers\"", ")", ";", "}", "$", "accepted", "=", "static", "::", "getAcceptedType", "(", "$", "accept", ",", "$", "available", ")", ";", "if", "(", "$", "accepted", "===", "false", ")", "{", "$", "message", "=", "\"Resource '$resource' can not generate content\"", ".", "' complying to Accept header'", ";", "$", "this", "->", "sendError", "(", "static", "::", "ERROR_NOT_ACCEPTABLE", ",", "$", "message", ")", ";", "}", "return", "$", "accepted", ";", "}" ]
Determines an accepted Content-Type for a Resource @see getAcceptedType() @param string $resource Resource name @param string $accept Accept header @return string @throws RouterException If $resource has invalid Content-Type @throws RouterException If no content type is acceptable
[ "Determines", "an", "accepted", "Content", "-", "Type", "for", "a", "Resource" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1990-L2008
train
aryelgois/medools-router
src/Router.php
Router.getAcceptedType
public static function getAcceptedType(string $accept, array $available) { $list = static::compareAccept($accept, $available); if (empty($list)) { return array_values($available)[0]; } $result = static::firstHigher($list); if ($result !== null) { return $result; } $forbidden = array_filter($list, function ($value) { return $value === 0; }); $allowed = array_diff($available, array_keys($forbidden)); if (empty($allowed)) { return false; } return array_values($allowed)[0]; }
php
public static function getAcceptedType(string $accept, array $available) { $list = static::compareAccept($accept, $available); if (empty($list)) { return array_values($available)[0]; } $result = static::firstHigher($list); if ($result !== null) { return $result; } $forbidden = array_filter($list, function ($value) { return $value === 0; }); $allowed = array_diff($available, array_keys($forbidden)); if (empty($allowed)) { return false; } return array_values($allowed)[0]; }
[ "public", "static", "function", "getAcceptedType", "(", "string", "$", "accept", ",", "array", "$", "available", ")", "{", "$", "list", "=", "static", "::", "compareAccept", "(", "$", "accept", ",", "$", "available", ")", ";", "if", "(", "empty", "(", "$", "list", ")", ")", "{", "return", "array_values", "(", "$", "available", ")", "[", "0", "]", ";", "}", "$", "result", "=", "static", "::", "firstHigher", "(", "$", "list", ")", ";", "if", "(", "$", "result", "!==", "null", ")", "{", "return", "$", "result", ";", "}", "$", "forbidden", "=", "array_filter", "(", "$", "list", ",", "function", "(", "$", "value", ")", "{", "return", "$", "value", "===", "0", ";", "}", ")", ";", "$", "allowed", "=", "array_diff", "(", "$", "available", ",", "array_keys", "(", "$", "forbidden", ")", ")", ";", "if", "(", "empty", "(", "$", "allowed", ")", ")", "{", "return", "false", ";", "}", "return", "array_values", "(", "$", "allowed", ")", "[", "0", "]", ";", "}" ]
Determines an accepted Content-Type from a list NOTE: - If no $available content types match $accept, but at least one of them is not forbidden by $accept (i.e. ';q=0'), it is returned. It is better to respond something the client doesn't complain about than a useless error message @param string $accept Accept header @param string[] $available List of available content types @return string @return false If no content type is acceptable
[ "Determines", "an", "accepted", "Content", "-", "Type", "from", "a", "list" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2025-L2047
train
aryelgois/medools-router
src/Router.php
Router.getAllowedMethods
protected function getAllowedMethods(string $resource) { $cached = $this->cache['allowed_methods'][$resource] ?? null; if ($cached !== null) { return $cached; } $resource_data = $this->resources[$resource] ?? null; if ($resource_data === null) { throw new \DomainException("Invalid resource '$resource'"); } $allow = $this->implemented_methods; $methods = (array) ($resource_data['methods'] ?? null); if (!empty($methods)) { $allow = array_intersect( $allow, array_merge($methods, ['OPTIONS']) ); } $this->cache['allowed_methods'][$resource] = $allow; return $allow; }
php
protected function getAllowedMethods(string $resource) { $cached = $this->cache['allowed_methods'][$resource] ?? null; if ($cached !== null) { return $cached; } $resource_data = $this->resources[$resource] ?? null; if ($resource_data === null) { throw new \DomainException("Invalid resource '$resource'"); } $allow = $this->implemented_methods; $methods = (array) ($resource_data['methods'] ?? null); if (!empty($methods)) { $allow = array_intersect( $allow, array_merge($methods, ['OPTIONS']) ); } $this->cache['allowed_methods'][$resource] = $allow; return $allow; }
[ "protected", "function", "getAllowedMethods", "(", "string", "$", "resource", ")", "{", "$", "cached", "=", "$", "this", "->", "cache", "[", "'allowed_methods'", "]", "[", "$", "resource", "]", "??", "null", ";", "if", "(", "$", "cached", "!==", "null", ")", "{", "return", "$", "cached", ";", "}", "$", "resource_data", "=", "$", "this", "->", "resources", "[", "$", "resource", "]", "??", "null", ";", "if", "(", "$", "resource_data", "===", "null", ")", "{", "throw", "new", "\\", "DomainException", "(", "\"Invalid resource '$resource'\"", ")", ";", "}", "$", "allow", "=", "$", "this", "->", "implemented_methods", ";", "$", "methods", "=", "(", "array", ")", "(", "$", "resource_data", "[", "'methods'", "]", "??", "null", ")", ";", "if", "(", "!", "empty", "(", "$", "methods", ")", ")", "{", "$", "allow", "=", "array_intersect", "(", "$", "allow", ",", "array_merge", "(", "$", "methods", ",", "[", "'OPTIONS'", "]", ")", ")", ";", "}", "$", "this", "->", "cache", "[", "'allowed_methods'", "]", "[", "$", "resource", "]", "=", "$", "allow", ";", "return", "$", "allow", ";", "}" ]
Returns a list of allowed methods for a resource NOTE: - It caches results @param string $resource Resource name @return string[] @throws \DomainException If $resource is invalid
[ "Returns", "a", "list", "of", "allowed", "methods", "for", "a", "resource" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2061-L2085
train
aryelgois/medools-router
src/Router.php
Router.getAvailableTypes
protected function getAvailableTypes(string $resource) { $cached = $this->cache['available_types'][$resource] ?? null; if ($cached !== null) { return $cached; } $types = $this->resources[$resource]['handlers']['GET'] ?? []; $types = (is_array($types)) ? array_filter(array_replace($this->default_content_type, $types)) : []; $this->cache['available_types'][$resource] = $types; return $types; }
php
protected function getAvailableTypes(string $resource) { $cached = $this->cache['available_types'][$resource] ?? null; if ($cached !== null) { return $cached; } $types = $this->resources[$resource]['handlers']['GET'] ?? []; $types = (is_array($types)) ? array_filter(array_replace($this->default_content_type, $types)) : []; $this->cache['available_types'][$resource] = $types; return $types; }
[ "protected", "function", "getAvailableTypes", "(", "string", "$", "resource", ")", "{", "$", "cached", "=", "$", "this", "->", "cache", "[", "'available_types'", "]", "[", "$", "resource", "]", "??", "null", ";", "if", "(", "$", "cached", "!==", "null", ")", "{", "return", "$", "cached", ";", "}", "$", "types", "=", "$", "this", "->", "resources", "[", "$", "resource", "]", "[", "'handlers'", "]", "[", "'GET'", "]", "??", "[", "]", ";", "$", "types", "=", "(", "is_array", "(", "$", "types", ")", ")", "?", "array_filter", "(", "array_replace", "(", "$", "this", "->", "default_content_type", ",", "$", "types", ")", ")", ":", "[", "]", ";", "$", "this", "->", "cache", "[", "'available_types'", "]", "[", "$", "resource", "]", "=", "$", "types", ";", "return", "$", "types", ";", "}" ]
Computes GET Resource's content types NOTE: - It caches results @param string $resource Resource name @return mixed[]
[ "Computes", "GET", "Resource", "s", "content", "types" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2097-L2111
train
aryelgois/medools-router
src/Router.php
Router.getAuthorizedResources
protected function getAuthorizedResources($methods = null) { $resources = []; if ($this->auth instanceof Authentication) { $allow = (array) ($methods ?? $this->method); $authorizations = Authorization::dump( [ 'user' => $this->auth->id, ], [ 'resource', 'methods', 'filter', ] ); foreach ($authorizations as $authorization) { $resource = $authorization['resource']; if (array_key_exists($resource, $this->resources)) { if ($this->isPublic($resource, $methods)) { $resources[$resource] = null; } elseif (!empty(array_intersect( $this->getAllowedMethods($resource), array_merge( $authorization['methods'] ?? [], $allow ) ))) { $resources[$resource] = $authorization['filter']; } } } } else { $resources = array_keys($this->resources); if ($this->auth === false) { foreach ($resources as $id => $resource) { if (!$this->isPublic($resource, $methods)) { unset($resources[$id]); } } } $resources = array_fill_keys(array_values($resources), null); } return $resources; }
php
protected function getAuthorizedResources($methods = null) { $resources = []; if ($this->auth instanceof Authentication) { $allow = (array) ($methods ?? $this->method); $authorizations = Authorization::dump( [ 'user' => $this->auth->id, ], [ 'resource', 'methods', 'filter', ] ); foreach ($authorizations as $authorization) { $resource = $authorization['resource']; if (array_key_exists($resource, $this->resources)) { if ($this->isPublic($resource, $methods)) { $resources[$resource] = null; } elseif (!empty(array_intersect( $this->getAllowedMethods($resource), array_merge( $authorization['methods'] ?? [], $allow ) ))) { $resources[$resource] = $authorization['filter']; } } } } else { $resources = array_keys($this->resources); if ($this->auth === false) { foreach ($resources as $id => $resource) { if (!$this->isPublic($resource, $methods)) { unset($resources[$id]); } } } $resources = array_fill_keys(array_values($resources), null); } return $resources; }
[ "protected", "function", "getAuthorizedResources", "(", "$", "methods", "=", "null", ")", "{", "$", "resources", "=", "[", "]", ";", "if", "(", "$", "this", "->", "auth", "instanceof", "Authentication", ")", "{", "$", "allow", "=", "(", "array", ")", "(", "$", "methods", "??", "$", "this", "->", "method", ")", ";", "$", "authorizations", "=", "Authorization", "::", "dump", "(", "[", "'user'", "=>", "$", "this", "->", "auth", "->", "id", ",", "]", ",", "[", "'resource'", ",", "'methods'", ",", "'filter'", ",", "]", ")", ";", "foreach", "(", "$", "authorizations", "as", "$", "authorization", ")", "{", "$", "resource", "=", "$", "authorization", "[", "'resource'", "]", ";", "if", "(", "array_key_exists", "(", "$", "resource", ",", "$", "this", "->", "resources", ")", ")", "{", "if", "(", "$", "this", "->", "isPublic", "(", "$", "resource", ",", "$", "methods", ")", ")", "{", "$", "resources", "[", "$", "resource", "]", "=", "null", ";", "}", "elseif", "(", "!", "empty", "(", "array_intersect", "(", "$", "this", "->", "getAllowedMethods", "(", "$", "resource", ")", ",", "array_merge", "(", "$", "authorization", "[", "'methods'", "]", "??", "[", "]", ",", "$", "allow", ")", ")", ")", ")", "{", "$", "resources", "[", "$", "resource", "]", "=", "$", "authorization", "[", "'filter'", "]", ";", "}", "}", "}", "}", "else", "{", "$", "resources", "=", "array_keys", "(", "$", "this", "->", "resources", ")", ";", "if", "(", "$", "this", "->", "auth", "===", "false", ")", "{", "foreach", "(", "$", "resources", "as", "$", "id", "=>", "$", "resource", ")", "{", "if", "(", "!", "$", "this", "->", "isPublic", "(", "$", "resource", ",", "$", "methods", ")", ")", "{", "unset", "(", "$", "resources", "[", "$", "id", "]", ")", ";", "}", "}", "}", "$", "resources", "=", "array_fill_keys", "(", "array_values", "(", "$", "resources", ")", ",", "null", ")", ";", "}", "return", "$", "resources", ";", "}" ]
Returns authorized resources for the authenticated user and their filters @param string|string[] $methods Which methods to test Default is requested method @return mixed[] With 'resource' => filter
[ "Returns", "authorized", "resources", "for", "the", "authenticated", "user", "and", "their", "filters" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2121-L2170
train
aryelgois/medools-router
src/Router.php
Router.getContentLocation
protected function getContentLocation(Model $model, Resource $resource) { $query = http_build_query($resource->query); $content_location = "$this->url/$resource->name/" . $this->getPrimaryKey($model) . ($query !== '' ? '?' . $query : ''); return $content_location; }
php
protected function getContentLocation(Model $model, Resource $resource) { $query = http_build_query($resource->query); $content_location = "$this->url/$resource->name/" . $this->getPrimaryKey($model) . ($query !== '' ? '?' . $query : ''); return $content_location; }
[ "protected", "function", "getContentLocation", "(", "Model", "$", "model", ",", "Resource", "$", "resource", ")", "{", "$", "query", "=", "http_build_query", "(", "$", "resource", "->", "query", ")", ";", "$", "content_location", "=", "\"$this->url/$resource->name/\"", ".", "$", "this", "->", "getPrimaryKey", "(", "$", "model", ")", ".", "(", "$", "query", "!==", "''", "?", "'?'", ".", "$", "query", ":", "''", ")", ";", "return", "$", "content_location", ";", "}" ]
Returns Content-Location for a Model in a Resource @param Model $model Model to get Location @param Resource $resource Resource that loaded $model @return string
[ "Returns", "Content", "-", "Location", "for", "a", "Model", "in", "a", "Resource" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2180-L2189
train
aryelgois/medools-router
src/Router.php
Router.getForeignRoutes
protected function getForeignRoutes(Model $model, array $filter = null) { $routes = []; $foreigns = $model::FOREIGN_KEYS; if (!empty($filter)) { $foreigns = Utils::arrayWhitelist($foreigns, $filter); } foreach ($foreigns as $column => $fk) { foreach ($this->resources as $resource_name => $resource_data) { if ($resource_data['model'] === $fk[0]) { $foreign = $model->$column; if ($foreign !== null) { $routes[$column] = "/$resource_name/" . $this->getPrimaryKey($foreign); } break; } } } return $routes; }
php
protected function getForeignRoutes(Model $model, array $filter = null) { $routes = []; $foreigns = $model::FOREIGN_KEYS; if (!empty($filter)) { $foreigns = Utils::arrayWhitelist($foreigns, $filter); } foreach ($foreigns as $column => $fk) { foreach ($this->resources as $resource_name => $resource_data) { if ($resource_data['model'] === $fk[0]) { $foreign = $model->$column; if ($foreign !== null) { $routes[$column] = "/$resource_name/" . $this->getPrimaryKey($foreign); } break; } } } return $routes; }
[ "protected", "function", "getForeignRoutes", "(", "Model", "$", "model", ",", "array", "$", "filter", "=", "null", ")", "{", "$", "routes", "=", "[", "]", ";", "$", "foreigns", "=", "$", "model", "::", "FOREIGN_KEYS", ";", "if", "(", "!", "empty", "(", "$", "filter", ")", ")", "{", "$", "foreigns", "=", "Utils", "::", "arrayWhitelist", "(", "$", "foreigns", ",", "$", "filter", ")", ";", "}", "foreach", "(", "$", "foreigns", "as", "$", "column", "=>", "$", "fk", ")", "{", "foreach", "(", "$", "this", "->", "resources", "as", "$", "resource_name", "=>", "$", "resource_data", ")", "{", "if", "(", "$", "resource_data", "[", "'model'", "]", "===", "$", "fk", "[", "0", "]", ")", "{", "$", "foreign", "=", "$", "model", "->", "$", "column", ";", "if", "(", "$", "foreign", "!==", "null", ")", "{", "$", "routes", "[", "$", "column", "]", "=", "\"/$resource_name/\"", ".", "$", "this", "->", "getPrimaryKey", "(", "$", "foreign", ")", ";", "}", "break", ";", "}", "}", "}", "return", "$", "routes", ";", "}" ]
Returns list of routes to Model's Foreigns @param Model $model Model whose Foreigns' routes will be returned @param string[] $filter Only returns routes for foreigns listed here Invalid columns are silently ignored @return string[]
[ "Returns", "list", "of", "routes", "to", "Model", "s", "Foreigns" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2200-L2223
train
aryelgois/medools-router
src/Router.php
Router.headerLink
protected function headerLink(array $routes) { $links = []; foreach ($routes as $rel => $route) { $links[] = '<' . $this->url . $route . '>; rel="' . $rel . '"'; } return implode(', ', $links); }
php
protected function headerLink(array $routes) { $links = []; foreach ($routes as $rel => $route) { $links[] = '<' . $this->url . $route . '>; rel="' . $rel . '"'; } return implode(', ', $links); }
[ "protected", "function", "headerLink", "(", "array", "$", "routes", ")", "{", "$", "links", "=", "[", "]", ";", "foreach", "(", "$", "routes", "as", "$", "rel", "=>", "$", "route", ")", "{", "$", "links", "[", "]", "=", "'<'", ".", "$", "this", "->", "url", ".", "$", "route", ".", "'>; rel=\"'", ".", "$", "rel", ".", "'\"'", ";", "}", "return", "implode", "(", "', '", ",", "$", "links", ")", ";", "}" ]
Generates content for Link header @param string[] $routes List of routes @return string
[ "Generates", "content", "for", "Link", "header" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2244-L2251
train
aryelgois/medools-router
src/Router.php
Router.isPublic
protected function isPublic(string $resource, $methods = null) { if (($this->authentication ?? null) === null) { return true; } $resource_data = $this->resources[$resource] ?? null; if ($resource_data === null) { return false; } $public = $resource_data['public'] ?? $this->default_publicity; if (is_string($public)) { $public = [$public]; } $methods = (array) ($methods ?? $this->method); return (is_array($public)) ? !empty(array_intersect($public, $methods)) : (bool) $public; }
php
protected function isPublic(string $resource, $methods = null) { if (($this->authentication ?? null) === null) { return true; } $resource_data = $this->resources[$resource] ?? null; if ($resource_data === null) { return false; } $public = $resource_data['public'] ?? $this->default_publicity; if (is_string($public)) { $public = [$public]; } $methods = (array) ($methods ?? $this->method); return (is_array($public)) ? !empty(array_intersect($public, $methods)) : (bool) $public; }
[ "protected", "function", "isPublic", "(", "string", "$", "resource", ",", "$", "methods", "=", "null", ")", "{", "if", "(", "(", "$", "this", "->", "authentication", "??", "null", ")", "===", "null", ")", "{", "return", "true", ";", "}", "$", "resource_data", "=", "$", "this", "->", "resources", "[", "$", "resource", "]", "??", "null", ";", "if", "(", "$", "resource_data", "===", "null", ")", "{", "return", "false", ";", "}", "$", "public", "=", "$", "resource_data", "[", "'public'", "]", "??", "$", "this", "->", "default_publicity", ";", "if", "(", "is_string", "(", "$", "public", ")", ")", "{", "$", "public", "=", "[", "$", "public", "]", ";", "}", "$", "methods", "=", "(", "array", ")", "(", "$", "methods", "??", "$", "this", "->", "method", ")", ";", "return", "(", "is_array", "(", "$", "public", ")", ")", "?", "!", "empty", "(", "array_intersect", "(", "$", "public", ",", "$", "methods", ")", ")", ":", "(", "bool", ")", "$", "public", ";", "}" ]
Tells if a resource's method has public access @param string $resource Resource name @param string|string[] $methods Which methods to test Default is requested method @return boolean For success or failure
[ "Tells", "if", "a", "resource", "s", "method", "has", "public", "access" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2262-L2283
train
aryelgois/medools-router
src/Router.php
Router.prepareResponse
protected function prepareResponse() { $response = new Response; $response->method = $this->method; $response->zlib_compression = $this->zlib_compression; return $response; }
php
protected function prepareResponse() { $response = new Response; $response->method = $this->method; $response->zlib_compression = $this->zlib_compression; return $response; }
[ "protected", "function", "prepareResponse", "(", ")", "{", "$", "response", "=", "new", "Response", ";", "$", "response", "->", "method", "=", "$", "this", "->", "method", ";", "$", "response", "->", "zlib_compression", "=", "$", "this", "->", "zlib_compression", ";", "return", "$", "response", ";", "}" ]
Creates a new Response object with some properties filled @return Response
[ "Creates", "a", "new", "Response", "object", "with", "some", "properties", "filled" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2290-L2296
train
aryelgois/medools-router
src/Router.php
Router.reverseForeignKey
public static function reverseForeignKey( string $model_class, Model $target ) { $target_class = get_class($target); $column = null; $found = false; foreach ($model_class::FOREIGN_KEYS as $column => $fk) { if ($target_class === $fk[0]) { $found = true; break; } } if ($column === null || $found === false) { return; } return [$column => $target->__get($fk[1])]; }
php
public static function reverseForeignKey( string $model_class, Model $target ) { $target_class = get_class($target); $column = null; $found = false; foreach ($model_class::FOREIGN_KEYS as $column => $fk) { if ($target_class === $fk[0]) { $found = true; break; } } if ($column === null || $found === false) { return; } return [$column => $target->__get($fk[1])]; }
[ "public", "static", "function", "reverseForeignKey", "(", "string", "$", "model_class", ",", "Model", "$", "target", ")", "{", "$", "target_class", "=", "get_class", "(", "$", "target", ")", ";", "$", "column", "=", "null", ";", "$", "found", "=", "false", ";", "foreach", "(", "$", "model_class", "::", "FOREIGN_KEYS", "as", "$", "column", "=>", "$", "fk", ")", "{", "if", "(", "$", "target_class", "===", "$", "fk", "[", "0", "]", ")", "{", "$", "found", "=", "true", ";", "break", ";", "}", "}", "if", "(", "$", "column", "===", "null", "||", "$", "found", "===", "false", ")", "{", "return", ";", "}", "return", "[", "$", "column", "=>", "$", "target", "->", "__get", "(", "$", "fk", "[", "1", "]", ")", "]", ";", "}" ]
Finds the Foreign Key for a Model instance from a Model class NOTE: - If $model_class has multiple foreign keys for $target, only the first one is used. You should redesign your database, duplicate the target class with a new name or create a new class that extends target, if you want to match later $model_class foreign keys @param string $model_class Model with Foreign Key pointing to $target @param Model $target Model pointed by $model_class @return mixed[] \Medoo\Medoo $where clause for $target, using a Foreign Key in $model_class @return null On failure
[ "Finds", "the", "Foreign", "Key", "for", "a", "Model", "instance", "from", "a", "Model", "class" ]
5d755f53b8099952d60cf15a0eb209af5fa3ca8a
https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2314-L2333
train
ZhukV/LanguageDetector
src/Ideea/LanguageDetector/Dictionary/PhpFileDictionary.php
PhpFileDictionary.flush
public function flush() { if (!count($this->updated)) { // Not updated words return; } foreach ($this->updated as $lang => $true) { // Grouping all words by language $words = array(); foreach ($this->words as $word => $wordLanguages) { if (in_array($lang, $wordLanguages)) { $words[] = $word; } } $file = $this->dictionaryDir . '/' . $lang . '.php'; file_put_contents($file, '<?php return ' . var_export($words, 1) . ';'); } }
php
public function flush() { if (!count($this->updated)) { // Not updated words return; } foreach ($this->updated as $lang => $true) { // Grouping all words by language $words = array(); foreach ($this->words as $word => $wordLanguages) { if (in_array($lang, $wordLanguages)) { $words[] = $word; } } $file = $this->dictionaryDir . '/' . $lang . '.php'; file_put_contents($file, '<?php return ' . var_export($words, 1) . ';'); } }
[ "public", "function", "flush", "(", ")", "{", "if", "(", "!", "count", "(", "$", "this", "->", "updated", ")", ")", "{", "// Not updated words", "return", ";", "}", "foreach", "(", "$", "this", "->", "updated", "as", "$", "lang", "=>", "$", "true", ")", "{", "// Grouping all words by language", "$", "words", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "words", "as", "$", "word", "=>", "$", "wordLanguages", ")", "{", "if", "(", "in_array", "(", "$", "lang", ",", "$", "wordLanguages", ")", ")", "{", "$", "words", "[", "]", "=", "$", "word", ";", "}", "}", "$", "file", "=", "$", "this", "->", "dictionaryDir", ".", "'/'", ".", "$", "lang", ".", "'.php'", ";", "file_put_contents", "(", "$", "file", ",", "'<?php return '", ".", "var_export", "(", "$", "words", ",", "1", ")", ".", "';'", ")", ";", "}", "}" ]
Flush updated dictionaries
[ "Flush", "updated", "dictionaries" ]
e5138f4c789e899801e098ce1e719337b015af7c
https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/Dictionary/PhpFileDictionary.php#L112-L132
train
ZhukV/LanguageDetector
src/Ideea/LanguageDetector/Dictionary/PhpFileDictionary.php
PhpFileDictionary.loadDictionaries
private function loadDictionaries() { if (null !== $this->words) { // Dictionaries already loaded return; } $this->words = array(); $dictionaryFiles = glob($this->dictionaryDir . '/*'); foreach ($dictionaryFiles as $dictionaryFile) { $fileName = substr($dictionaryFile, strlen($this->dictionaryDir) + 1); preg_match('/^(.+)\./', $fileName, $parts); $lang = $parts[1]; $words = include $dictionaryFile; foreach ($words as $word) { if (!isset($this->words[$word])) { $this->words[$word] = array(); } if (!in_array($lang, $this->words[$word])) { $this->words[$word][] = $lang; } } } }
php
private function loadDictionaries() { if (null !== $this->words) { // Dictionaries already loaded return; } $this->words = array(); $dictionaryFiles = glob($this->dictionaryDir . '/*'); foreach ($dictionaryFiles as $dictionaryFile) { $fileName = substr($dictionaryFile, strlen($this->dictionaryDir) + 1); preg_match('/^(.+)\./', $fileName, $parts); $lang = $parts[1]; $words = include $dictionaryFile; foreach ($words as $word) { if (!isset($this->words[$word])) { $this->words[$word] = array(); } if (!in_array($lang, $this->words[$word])) { $this->words[$word][] = $lang; } } } }
[ "private", "function", "loadDictionaries", "(", ")", "{", "if", "(", "null", "!==", "$", "this", "->", "words", ")", "{", "// Dictionaries already loaded", "return", ";", "}", "$", "this", "->", "words", "=", "array", "(", ")", ";", "$", "dictionaryFiles", "=", "glob", "(", "$", "this", "->", "dictionaryDir", ".", "'/*'", ")", ";", "foreach", "(", "$", "dictionaryFiles", "as", "$", "dictionaryFile", ")", "{", "$", "fileName", "=", "substr", "(", "$", "dictionaryFile", ",", "strlen", "(", "$", "this", "->", "dictionaryDir", ")", "+", "1", ")", ";", "preg_match", "(", "'/^(.+)\\./'", ",", "$", "fileName", ",", "$", "parts", ")", ";", "$", "lang", "=", "$", "parts", "[", "1", "]", ";", "$", "words", "=", "include", "$", "dictionaryFile", ";", "foreach", "(", "$", "words", "as", "$", "word", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "words", "[", "$", "word", "]", ")", ")", "{", "$", "this", "->", "words", "[", "$", "word", "]", "=", "array", "(", ")", ";", "}", "if", "(", "!", "in_array", "(", "$", "lang", ",", "$", "this", "->", "words", "[", "$", "word", "]", ")", ")", "{", "$", "this", "->", "words", "[", "$", "word", "]", "[", "]", "=", "$", "lang", ";", "}", "}", "}", "}" ]
Load dictionaries from directory
[ "Load", "dictionaries", "from", "directory" ]
e5138f4c789e899801e098ce1e719337b015af7c
https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/Dictionary/PhpFileDictionary.php#L137-L166
train
pmdevelopment/tool-bundle
Command/FOSUserCommand.php
FOSUserCommand.actionPasswordReplace
private function actionPasswordReplace(SymfonyStyle $helper) { if (false === $helper->confirm('Are you sure? Only use this for development purposes!', false)) { return null; } $userClass = $this->getUserEntityClass(); if (null === $userClass) { throw new \RuntimeException('User entity not found'); } $password = $helper->ask('New password', 'login123'); $userManager = $this->getContainer()->get('fos_user.user_manager'); /** @var User $user */ foreach ($this->getDoctrine()->getRepository($userClass)->findAll() as $user) { $user->setPlainPassword($password); $userManager->updateUser($user); } return null; }
php
private function actionPasswordReplace(SymfonyStyle $helper) { if (false === $helper->confirm('Are you sure? Only use this for development purposes!', false)) { return null; } $userClass = $this->getUserEntityClass(); if (null === $userClass) { throw new \RuntimeException('User entity not found'); } $password = $helper->ask('New password', 'login123'); $userManager = $this->getContainer()->get('fos_user.user_manager'); /** @var User $user */ foreach ($this->getDoctrine()->getRepository($userClass)->findAll() as $user) { $user->setPlainPassword($password); $userManager->updateUser($user); } return null; }
[ "private", "function", "actionPasswordReplace", "(", "SymfonyStyle", "$", "helper", ")", "{", "if", "(", "false", "===", "$", "helper", "->", "confirm", "(", "'Are you sure? Only use this for development purposes!'", ",", "false", ")", ")", "{", "return", "null", ";", "}", "$", "userClass", "=", "$", "this", "->", "getUserEntityClass", "(", ")", ";", "if", "(", "null", "===", "$", "userClass", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'User entity not found'", ")", ";", "}", "$", "password", "=", "$", "helper", "->", "ask", "(", "'New password'", ",", "'login123'", ")", ";", "$", "userManager", "=", "$", "this", "->", "getContainer", "(", ")", "->", "get", "(", "'fos_user.user_manager'", ")", ";", "/** @var User $user */", "foreach", "(", "$", "this", "->", "getDoctrine", "(", ")", "->", "getRepository", "(", "$", "userClass", ")", "->", "findAll", "(", ")", "as", "$", "user", ")", "{", "$", "user", "->", "setPlainPassword", "(", "$", "password", ")", ";", "$", "userManager", "->", "updateUser", "(", "$", "user", ")", ";", "}", "return", "null", ";", "}" ]
Password Replace action @param SymfonyStyle $helper @return null
[ "Password", "Replace", "action" ]
2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Command/FOSUserCommand.php#L91-L112
train
pmdevelopment/tool-bundle
Command/FOSUserCommand.php
FOSUserCommand.getUserEntityClass
private function getUserEntityClass() { /** @var ClassMetadata $meta */ foreach ($this->getDoctrine()->getManager()->getMetadataFactory()->getAllMetadata() as $meta) { $reflectionClass = $meta->getReflectionClass(); if (true === $this->hasAbstractParent($reflectionClass, User::class)) { return $meta->getName(); } } return null; }
php
private function getUserEntityClass() { /** @var ClassMetadata $meta */ foreach ($this->getDoctrine()->getManager()->getMetadataFactory()->getAllMetadata() as $meta) { $reflectionClass = $meta->getReflectionClass(); if (true === $this->hasAbstractParent($reflectionClass, User::class)) { return $meta->getName(); } } return null; }
[ "private", "function", "getUserEntityClass", "(", ")", "{", "/** @var ClassMetadata $meta */", "foreach", "(", "$", "this", "->", "getDoctrine", "(", ")", "->", "getManager", "(", ")", "->", "getMetadataFactory", "(", ")", "->", "getAllMetadata", "(", ")", "as", "$", "meta", ")", "{", "$", "reflectionClass", "=", "$", "meta", "->", "getReflectionClass", "(", ")", ";", "if", "(", "true", "===", "$", "this", "->", "hasAbstractParent", "(", "$", "reflectionClass", ",", "User", "::", "class", ")", ")", "{", "return", "$", "meta", "->", "getName", "(", ")", ";", "}", "}", "return", "null", ";", "}" ]
Get User Entity Class @return null|string
[ "Get", "User", "Entity", "Class" ]
2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Command/FOSUserCommand.php#L119-L131
train
tarsana/syntax
src/OptionalSyntax.php
OptionalSyntax.parse
public function parse(string $text) { try { $result = $this->syntax->parse($text); $this->success = true; } catch (ParseException $e) { $result = $this->default; $this->success = false; } return $result; }
php
public function parse(string $text) { try { $result = $this->syntax->parse($text); $this->success = true; } catch (ParseException $e) { $result = $this->default; $this->success = false; } return $result; }
[ "public", "function", "parse", "(", "string", "$", "text", ")", "{", "try", "{", "$", "result", "=", "$", "this", "->", "syntax", "->", "parse", "(", "$", "text", ")", ";", "$", "this", "->", "success", "=", "true", ";", "}", "catch", "(", "ParseException", "$", "e", ")", "{", "$", "result", "=", "$", "this", "->", "default", ";", "$", "this", "->", "success", "=", "false", ";", "}", "return", "$", "result", ";", "}" ]
Tries to parse the string using the syntax and return the result. If the parse failed, `success` flag is set to false and the default value is returned. @param string $text the string to parse @return mixed
[ "Tries", "to", "parse", "the", "string", "using", "the", "syntax", "and", "return", "the", "result", ".", "If", "the", "parse", "failed", "success", "flag", "is", "set", "to", "false", "and", "the", "default", "value", "is", "returned", "." ]
fd3f8a25e3be0e391c8fd486ccfcffe913ade534
https://github.com/tarsana/syntax/blob/fd3f8a25e3be0e391c8fd486ccfcffe913ade534/src/OptionalSyntax.php#L110-L121
train
3ev/wordpress-core
src/Tev/Plugin/Loader.php
Loader.load
public function load($basePath) { $this->basePath = $basePath; $this->renderer = new Renderer($this->getViewsPath()); return $this ->loadCustomTables() ->loadPostTypes() ->loadFieldGroups() ->loadAcfJson() ->loadActions() ->loadShortCodes() ->loadOptionScreens() ->loadCliCommands(); }
php
public function load($basePath) { $this->basePath = $basePath; $this->renderer = new Renderer($this->getViewsPath()); return $this ->loadCustomTables() ->loadPostTypes() ->loadFieldGroups() ->loadAcfJson() ->loadActions() ->loadShortCodes() ->loadOptionScreens() ->loadCliCommands(); }
[ "public", "function", "load", "(", "$", "basePath", ")", "{", "$", "this", "->", "basePath", "=", "$", "basePath", ";", "$", "this", "->", "renderer", "=", "new", "Renderer", "(", "$", "this", "->", "getViewsPath", "(", ")", ")", ";", "return", "$", "this", "->", "loadCustomTables", "(", ")", "->", "loadPostTypes", "(", ")", "->", "loadFieldGroups", "(", ")", "->", "loadAcfJson", "(", ")", "->", "loadActions", "(", ")", "->", "loadShortCodes", "(", ")", "->", "loadOptionScreens", "(", ")", "->", "loadCliCommands", "(", ")", ";", "}" ]
Load all plugin configuration. @param string $basePath Plugin path @return \Tev\Plugin\Loader This, for chaining
[ "Load", "all", "plugin", "configuration", "." ]
da674fbec5bf3d5bd2a2141680a4c141113eb6b0
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L96-L111
train
3ev/wordpress-core
src/Tev/Plugin/Loader.php
Loader.loadCustomTables
protected function loadCustomTables() { if ($config = $this->loadConfigFile('tables.php')) { $app = $this->app; foreach ($config as $installerClass) { if (is_string($installerClass) && is_subclass_of($installerClass, 'Tev\Database\CustomTables\AbstractInstaller')) { register_activation_hook($this->getPluginFile(), function () use ($installerClass, $app) { global $wpdb; $installer = new $installerClass($wpdb, $app); $installer->install(); }); add_action('plugins_loaded', function () use ($installerClass, $app) { global $wpdb; $installer = new $installerClass($wpdb, $app); $installer->update(); }); } } } return $this; }
php
protected function loadCustomTables() { if ($config = $this->loadConfigFile('tables.php')) { $app = $this->app; foreach ($config as $installerClass) { if (is_string($installerClass) && is_subclass_of($installerClass, 'Tev\Database\CustomTables\AbstractInstaller')) { register_activation_hook($this->getPluginFile(), function () use ($installerClass, $app) { global $wpdb; $installer = new $installerClass($wpdb, $app); $installer->install(); }); add_action('plugins_loaded', function () use ($installerClass, $app) { global $wpdb; $installer = new $installerClass($wpdb, $app); $installer->update(); }); } } } return $this; }
[ "protected", "function", "loadCustomTables", "(", ")", "{", "if", "(", "$", "config", "=", "$", "this", "->", "loadConfigFile", "(", "'tables.php'", ")", ")", "{", "$", "app", "=", "$", "this", "->", "app", ";", "foreach", "(", "$", "config", "as", "$", "installerClass", ")", "{", "if", "(", "is_string", "(", "$", "installerClass", ")", "&&", "is_subclass_of", "(", "$", "installerClass", ",", "'Tev\\Database\\CustomTables\\AbstractInstaller'", ")", ")", "{", "register_activation_hook", "(", "$", "this", "->", "getPluginFile", "(", ")", ",", "function", "(", ")", "use", "(", "$", "installerClass", ",", "$", "app", ")", "{", "global", "$", "wpdb", ";", "$", "installer", "=", "new", "$", "installerClass", "(", "$", "wpdb", ",", "$", "app", ")", ";", "$", "installer", "->", "install", "(", ")", ";", "}", ")", ";", "add_action", "(", "'plugins_loaded'", ",", "function", "(", ")", "use", "(", "$", "installerClass", ",", "$", "app", ")", "{", "global", "$", "wpdb", ";", "$", "installer", "=", "new", "$", "installerClass", "(", "$", "wpdb", ",", "$", "app", ")", ";", "$", "installer", "->", "update", "(", ")", ";", "}", ")", ";", "}", "}", "}", "return", "$", "this", ";", "}" ]
Load custom database table installers from configuration files. @return \Tev\Plugin\Loader This, for chaining
[ "Load", "custom", "database", "table", "installers", "from", "configuration", "files", "." ]
da674fbec5bf3d5bd2a2141680a4c141113eb6b0
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L118-L141
train
3ev/wordpress-core
src/Tev/Plugin/Loader.php
Loader.loadPostTypes
protected function loadPostTypes() { if ($config = $this->loadConfigFile('post_types.php')) { $callbacks = array(); // Create one callback for each post type, and register in // init action foreach ($config as $postTypeName => $args) { $callbacks[] = $cb = function () use ($postTypeName, $args) { register_post_type($postTypeName, $args); }; add_action('init', $cb, 0); } // Flush URL caches for (you need to register custom post types // first) register_activation_hook($this->getPluginFile(), function () use ($callbacks) { foreach ($callbacks as $cb) { $cb(); } flush_rewrite_rules(); }); } return $this; }
php
protected function loadPostTypes() { if ($config = $this->loadConfigFile('post_types.php')) { $callbacks = array(); // Create one callback for each post type, and register in // init action foreach ($config as $postTypeName => $args) { $callbacks[] = $cb = function () use ($postTypeName, $args) { register_post_type($postTypeName, $args); }; add_action('init', $cb, 0); } // Flush URL caches for (you need to register custom post types // first) register_activation_hook($this->getPluginFile(), function () use ($callbacks) { foreach ($callbacks as $cb) { $cb(); } flush_rewrite_rules(); }); } return $this; }
[ "protected", "function", "loadPostTypes", "(", ")", "{", "if", "(", "$", "config", "=", "$", "this", "->", "loadConfigFile", "(", "'post_types.php'", ")", ")", "{", "$", "callbacks", "=", "array", "(", ")", ";", "// Create one callback for each post type, and register in", "// init action", "foreach", "(", "$", "config", "as", "$", "postTypeName", "=>", "$", "args", ")", "{", "$", "callbacks", "[", "]", "=", "$", "cb", "=", "function", "(", ")", "use", "(", "$", "postTypeName", ",", "$", "args", ")", "{", "register_post_type", "(", "$", "postTypeName", ",", "$", "args", ")", ";", "}", ";", "add_action", "(", "'init'", ",", "$", "cb", ",", "0", ")", ";", "}", "// Flush URL caches for (you need to register custom post types", "// first)", "register_activation_hook", "(", "$", "this", "->", "getPluginFile", "(", ")", ",", "function", "(", ")", "use", "(", "$", "callbacks", ")", "{", "foreach", "(", "$", "callbacks", "as", "$", "cb", ")", "{", "$", "cb", "(", ")", ";", "}", "flush_rewrite_rules", "(", ")", ";", "}", ")", ";", "}", "return", "$", "this", ";", "}" ]
Load custom post types from configuration files. @return \Tev\Plugin\Loader This, for chaining
[ "Load", "custom", "post", "types", "from", "configuration", "files", "." ]
da674fbec5bf3d5bd2a2141680a4c141113eb6b0
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L148-L177
train
3ev/wordpress-core
src/Tev/Plugin/Loader.php
Loader.loadFieldGroups
protected function loadFieldGroups() { if (function_exists('register_field_group') && ($config = $this->loadConfigFile('field_groups.php'))) { foreach ($config as $fieldGroupConfig) { register_field_group($fieldGroupConfig); } } return $this; }
php
protected function loadFieldGroups() { if (function_exists('register_field_group') && ($config = $this->loadConfigFile('field_groups.php'))) { foreach ($config as $fieldGroupConfig) { register_field_group($fieldGroupConfig); } } return $this; }
[ "protected", "function", "loadFieldGroups", "(", ")", "{", "if", "(", "function_exists", "(", "'register_field_group'", ")", "&&", "(", "$", "config", "=", "$", "this", "->", "loadConfigFile", "(", "'field_groups.php'", ")", ")", ")", "{", "foreach", "(", "$", "config", "as", "$", "fieldGroupConfig", ")", "{", "register_field_group", "(", "$", "fieldGroupConfig", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Load custom field groups from configuration files. @return \Tev\Plugin\Loader This, for chaining
[ "Load", "custom", "field", "groups", "from", "configuration", "files", "." ]
da674fbec5bf3d5bd2a2141680a4c141113eb6b0
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L184-L193
train
3ev/wordpress-core
src/Tev/Plugin/Loader.php
Loader.loadActions
protected function loadActions() { if ($config = $this->loadConfigFile('actions.php')) { $app = $this->app; $renderer = $this->renderer; foreach ($config as $actionName => $provider) { if (is_string($provider) && is_subclass_of($provider, 'Tev\Plugin\Action\AbstractProvider')) { $ap = new $provider($this->app, $this->renderer); add_action($actionName, function () use ($ap) { return call_user_func_array(array($ap, 'action'), func_get_args()); }, $ap->priority(), $ap->numArgs()); } elseif ($provider instanceof Closure) { add_action($actionName, function () use ($provider) { return call_user_func($provider, func_get_args()); }); } } } return $this; }
php
protected function loadActions() { if ($config = $this->loadConfigFile('actions.php')) { $app = $this->app; $renderer = $this->renderer; foreach ($config as $actionName => $provider) { if (is_string($provider) && is_subclass_of($provider, 'Tev\Plugin\Action\AbstractProvider')) { $ap = new $provider($this->app, $this->renderer); add_action($actionName, function () use ($ap) { return call_user_func_array(array($ap, 'action'), func_get_args()); }, $ap->priority(), $ap->numArgs()); } elseif ($provider instanceof Closure) { add_action($actionName, function () use ($provider) { return call_user_func($provider, func_get_args()); }); } } } return $this; }
[ "protected", "function", "loadActions", "(", ")", "{", "if", "(", "$", "config", "=", "$", "this", "->", "loadConfigFile", "(", "'actions.php'", ")", ")", "{", "$", "app", "=", "$", "this", "->", "app", ";", "$", "renderer", "=", "$", "this", "->", "renderer", ";", "foreach", "(", "$", "config", "as", "$", "actionName", "=>", "$", "provider", ")", "{", "if", "(", "is_string", "(", "$", "provider", ")", "&&", "is_subclass_of", "(", "$", "provider", ",", "'Tev\\Plugin\\Action\\AbstractProvider'", ")", ")", "{", "$", "ap", "=", "new", "$", "provider", "(", "$", "this", "->", "app", ",", "$", "this", "->", "renderer", ")", ";", "add_action", "(", "$", "actionName", ",", "function", "(", ")", "use", "(", "$", "ap", ")", "{", "return", "call_user_func_array", "(", "array", "(", "$", "ap", ",", "'action'", ")", ",", "func_get_args", "(", ")", ")", ";", "}", ",", "$", "ap", "->", "priority", "(", ")", ",", "$", "ap", "->", "numArgs", "(", ")", ")", ";", "}", "elseif", "(", "$", "provider", "instanceof", "Closure", ")", "{", "add_action", "(", "$", "actionName", ",", "function", "(", ")", "use", "(", "$", "provider", ")", "{", "return", "call_user_func", "(", "$", "provider", ",", "func_get_args", "(", ")", ")", ";", "}", ")", ";", "}", "}", "}", "return", "$", "this", ";", "}" ]
Load actions from configuration providers. @return \Tev\Plugin\Loader This, for chaining
[ "Load", "actions", "from", "configuration", "providers", "." ]
da674fbec5bf3d5bd2a2141680a4c141113eb6b0
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L200-L223
train
3ev/wordpress-core
src/Tev/Plugin/Loader.php
Loader.loadAcfJson
protected function loadAcfJson() { $config = $this->getConfigPath() . '/acf-json'; if (file_exists($config)) { add_filter('acf/settings/load_json', function ($paths) use ($config) { $paths[] = $config; return $paths; }); } return $this; }
php
protected function loadAcfJson() { $config = $this->getConfigPath() . '/acf-json'; if (file_exists($config)) { add_filter('acf/settings/load_json', function ($paths) use ($config) { $paths[] = $config; return $paths; }); } return $this; }
[ "protected", "function", "loadAcfJson", "(", ")", "{", "$", "config", "=", "$", "this", "->", "getConfigPath", "(", ")", ".", "'/acf-json'", ";", "if", "(", "file_exists", "(", "$", "config", ")", ")", "{", "add_filter", "(", "'acf/settings/load_json'", ",", "function", "(", "$", "paths", ")", "use", "(", "$", "config", ")", "{", "$", "paths", "[", "]", "=", "$", "config", ";", "return", "$", "paths", ";", "}", ")", ";", "}", "return", "$", "this", ";", "}" ]
Load ACF JSON config if supplied. @return \Tev\Plugin\Loader This, for chaining
[ "Load", "ACF", "JSON", "config", "if", "supplied", "." ]
da674fbec5bf3d5bd2a2141680a4c141113eb6b0
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L230-L242
train