id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
29,400
rinvex/cortex-tenants
src/Http/Controllers/Adminarea/TenantsMediaController.php
TenantsMediaController.destroy
public function destroy(Tenant $tenant, Media $media) { $tenant->media()->where($media->getKeyName(), $media->getKey())->first()->delete(); return intend([ 'url' => route('adminarea.tenants.media.index', ['tenant' => $tenant]), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/foundation::common.media'), 'identifier' => $media->getRouteKey()])], ]); }
php
public function destroy(Tenant $tenant, Media $media) { $tenant->media()->where($media->getKeyName(), $media->getKey())->first()->delete(); return intend([ 'url' => route('adminarea.tenants.media.index', ['tenant' => $tenant]), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/foundation::common.media'), 'identifier' => $media->getRouteKey()])], ]); }
[ "public", "function", "destroy", "(", "Tenant", "$", "tenant", ",", "Media", "$", "media", ")", "{", "$", "tenant", "->", "media", "(", ")", "->", "where", "(", "$", "media", "->", "getKeyName", "(", ")", ",", "$", "media", "->", "getKey", "(", ")", ")", "->", "first", "(", ")", "->", "delete", "(", ")", ";", "return", "intend", "(", "[", "'url'", "=>", "route", "(", "'adminarea.tenants.media.index'", ",", "[", "'tenant'", "=>", "$", "tenant", "]", ")", ",", "'with'", "=>", "[", "'warning'", "=>", "trans", "(", "'cortex/foundation::messages.resource_deleted'", ",", "[", "'resource'", "=>", "trans", "(", "'cortex/foundation::common.media'", ")", ",", "'identifier'", "=>", "$", "media", "->", "getRouteKey", "(", ")", "]", ")", "]", ",", "]", ")", ";", "}" ]
Destroy given tenant media. @param \Cortex\Tenants\Models\Tenant $tenant @param \Spatie\MediaLibrary\Models\Media $media @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
[ "Destroy", "given", "tenant", "media", "." ]
b837a3d14fd4cf6bfb35f41c61ef41ee9a05a34a
https://github.com/rinvex/cortex-tenants/blob/b837a3d14fd4cf6bfb35f41c61ef41ee9a05a34a/src/Http/Controllers/Adminarea/TenantsMediaController.php#L83-L91
29,401
timble/kodekit
code/object/config/format.php
ObjectConfigFormat.toFile
public function toFile($filename) { $directory = dirname($filename); if(empty($filename)) { throw new \InvalidArgumentException('No file name specified'); } if (!is_dir($directory)) { throw new \RuntimeException(sprintf('Directory : %s does not exists!', $directory)); } if (!is_writable($directory)) { throw new \RuntimeException(sprintf("Cannot write in directory : %s", $directory)); } $result = file_put_contents($filename, $this->toString(), LOCK_EX); if($result === false) { throw new \RuntimeException(sprintf("Error writing to %s", $filename)); } }
php
public function toFile($filename) { $directory = dirname($filename); if(empty($filename)) { throw new \InvalidArgumentException('No file name specified'); } if (!is_dir($directory)) { throw new \RuntimeException(sprintf('Directory : %s does not exists!', $directory)); } if (!is_writable($directory)) { throw new \RuntimeException(sprintf("Cannot write in directory : %s", $directory)); } $result = file_put_contents($filename, $this->toString(), LOCK_EX); if($result === false) { throw new \RuntimeException(sprintf("Error writing to %s", $filename)); } }
[ "public", "function", "toFile", "(", "$", "filename", ")", "{", "$", "directory", "=", "dirname", "(", "$", "filename", ")", ";", "if", "(", "empty", "(", "$", "filename", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'No file name specified'", ")", ";", "}", "if", "(", "!", "is_dir", "(", "$", "directory", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Directory : %s does not exists!'", ",", "$", "directory", ")", ")", ";", "}", "if", "(", "!", "is_writable", "(", "$", "directory", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "\"Cannot write in directory : %s\"", ",", "$", "directory", ")", ")", ";", "}", "$", "result", "=", "file_put_contents", "(", "$", "filename", ",", "$", "this", "->", "toString", "(", ")", ",", "LOCK_EX", ")", ";", "if", "(", "$", "result", "===", "false", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "\"Error writing to %s\"", ",", "$", "filename", ")", ")", ";", "}", "}" ]
Write a config object to a file. @param string $filename @throws \InvalidArgumentException @throws \RuntimeException @return void
[ "Write", "a", "config", "object", "to", "a", "file", "." ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/object/config/format.php#L53-L74
29,402
rosasurfer/ministruts
src/net/http/HttpClient.php
HttpClient.setTimeout
public function setTimeout($timeout) { if (!is_int($timeout)) throw new IllegalTypeException('Illegal type of parameter $timeout: '.gettype($timeout)); if ($timeout < 1) throw new InvalidArgumentException('Invalid argument $timeout: '.$timeout); $this->timeout = $timeout; return $this; }
php
public function setTimeout($timeout) { if (!is_int($timeout)) throw new IllegalTypeException('Illegal type of parameter $timeout: '.gettype($timeout)); if ($timeout < 1) throw new InvalidArgumentException('Invalid argument $timeout: '.$timeout); $this->timeout = $timeout; return $this; }
[ "public", "function", "setTimeout", "(", "$", "timeout", ")", "{", "if", "(", "!", "is_int", "(", "$", "timeout", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $timeout: '", ".", "gettype", "(", "$", "timeout", ")", ")", ";", "if", "(", "$", "timeout", "<", "1", ")", "throw", "new", "InvalidArgumentException", "(", "'Invalid argument $timeout: '", ".", "$", "timeout", ")", ";", "$", "this", "->", "timeout", "=", "$", "timeout", ";", "return", "$", "this", ";", "}" ]
Setzt den Verbindungs-Timeout. @param int $timeout - Timeout in Sekunden @return $this
[ "Setzt", "den", "Verbindungs", "-", "Timeout", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/net/http/HttpClient.php#L38-L44
29,403
rosasurfer/ministruts
src/net/http/HttpClient.php
HttpClient.setFollowRedirects
public function setFollowRedirects($follow) { if (!is_bool($follow)) throw new IllegalTypeException('Illegal type of parameter $follow: '.gettype($follow)); $this->followRedirects = $follow; return $this; }
php
public function setFollowRedirects($follow) { if (!is_bool($follow)) throw new IllegalTypeException('Illegal type of parameter $follow: '.gettype($follow)); $this->followRedirects = $follow; return $this; }
[ "public", "function", "setFollowRedirects", "(", "$", "follow", ")", "{", "if", "(", "!", "is_bool", "(", "$", "follow", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $follow: '", ".", "gettype", "(", "$", "follow", ")", ")", ";", "$", "this", "->", "followRedirects", "=", "$", "follow", ";", "return", "$", "this", ";", "}" ]
Ob Redirect-Headern gefolgt werden soll oder nicht. @param bool $follow @return $this
[ "Ob", "Redirect", "-", "Headern", "gefolgt", "werden", "soll", "oder", "nicht", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/net/http/HttpClient.php#L64-L69
29,404
rosasurfer/ministruts
src/net/http/HttpClient.php
HttpClient.setMaxRedirects
public function setMaxRedirects($maxRedirects) { if (!is_int($maxRedirects)) throw new IllegalTypeException('Illegal type of parameter $maxRedirects: '.gettype($maxRedirects)); $this->maxRedirects = $maxRedirects; return $this; }
php
public function setMaxRedirects($maxRedirects) { if (!is_int($maxRedirects)) throw new IllegalTypeException('Illegal type of parameter $maxRedirects: '.gettype($maxRedirects)); $this->maxRedirects = $maxRedirects; return $this; }
[ "public", "function", "setMaxRedirects", "(", "$", "maxRedirects", ")", "{", "if", "(", "!", "is_int", "(", "$", "maxRedirects", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $maxRedirects: '", ".", "gettype", "(", "$", "maxRedirects", ")", ")", ";", "$", "this", "->", "maxRedirects", "=", "$", "maxRedirects", ";", "return", "$", "this", ";", "}" ]
Setzt die maximale Anzahl der Redirects, denen gefolgt werden soll. @param int $maxRedirects @return $this
[ "Setzt", "die", "maximale", "Anzahl", "der", "Redirects", "denen", "gefolgt", "werden", "soll", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/net/http/HttpClient.php#L89-L94
29,405
locomotivemtl/charcoal-core
src/Charcoal/Source/Database/DatabaseOrder.php
DatabaseOrder.sql
public function sql() { if ($this->active()) { switch ($this->mode()) { case self::MODE_RANDOM: return $this->byRandom(); case self::MODE_CUSTOM: return $this->byCondition(); case self::MODE_VALUES: return $this->byValues(); } if ($this->hasCondition()) { return $this->byCondition(); } if ($this->hasValues()) { return $this->byValues(); } if ($this->hasProperty()) { return $this->byProperty(); } } return ''; }
php
public function sql() { if ($this->active()) { switch ($this->mode()) { case self::MODE_RANDOM: return $this->byRandom(); case self::MODE_CUSTOM: return $this->byCondition(); case self::MODE_VALUES: return $this->byValues(); } if ($this->hasCondition()) { return $this->byCondition(); } if ($this->hasValues()) { return $this->byValues(); } if ($this->hasProperty()) { return $this->byProperty(); } } return ''; }
[ "public", "function", "sql", "(", ")", "{", "if", "(", "$", "this", "->", "active", "(", ")", ")", "{", "switch", "(", "$", "this", "->", "mode", "(", ")", ")", "{", "case", "self", "::", "MODE_RANDOM", ":", "return", "$", "this", "->", "byRandom", "(", ")", ";", "case", "self", "::", "MODE_CUSTOM", ":", "return", "$", "this", "->", "byCondition", "(", ")", ";", "case", "self", "::", "MODE_VALUES", ":", "return", "$", "this", "->", "byValues", "(", ")", ";", "}", "if", "(", "$", "this", "->", "hasCondition", "(", ")", ")", "{", "return", "$", "this", "->", "byCondition", "(", ")", ";", "}", "if", "(", "$", "this", "->", "hasValues", "(", ")", ")", "{", "return", "$", "this", "->", "byValues", "(", ")", ";", "}", "if", "(", "$", "this", "->", "hasProperty", "(", ")", ")", "{", "return", "$", "this", "->", "byProperty", "(", ")", ";", "}", "}", "return", "''", ";", "}" ]
Converts the order into a SQL expression for the ORDER BY clause. @return string A SQL string fragment.
[ "Converts", "the", "order", "into", "a", "SQL", "expression", "for", "the", "ORDER", "BY", "clause", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/Database/DatabaseOrder.php#L49-L77
29,406
locomotivemtl/charcoal-core
src/Charcoal/Source/Database/DatabaseOrder.php
DatabaseOrder.prepareValues
public function prepareValues($values) { if (empty($values)) { return []; } if (!is_array($values)) { $values = (array)$values; } $values = array_filter($values, 'is_scalar'); $values = array_map('self::quoteValue', $values); return $values; }
php
public function prepareValues($values) { if (empty($values)) { return []; } if (!is_array($values)) { $values = (array)$values; } $values = array_filter($values, 'is_scalar'); $values = array_map('self::quoteValue', $values); return $values; }
[ "public", "function", "prepareValues", "(", "$", "values", ")", "{", "if", "(", "empty", "(", "$", "values", ")", ")", "{", "return", "[", "]", ";", "}", "if", "(", "!", "is_array", "(", "$", "values", ")", ")", "{", "$", "values", "=", "(", "array", ")", "$", "values", ";", "}", "$", "values", "=", "array_filter", "(", "$", "values", ",", "'is_scalar'", ")", ";", "$", "values", "=", "array_map", "(", "'self::quoteValue'", ",", "$", "values", ")", ";", "return", "$", "values", ";", "}" ]
Parse the given values for SQL. @param mixed $values The value to be normalized. @return array Returns a collection of parsed values.
[ "Parse", "the", "given", "values", "for", "SQL", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/Database/DatabaseOrder.php#L168-L182
29,407
hakito/PHP-Stuzza-EPS-BankTransfer
src/SoCommunicator.php
SoCommunicator.GetBanks
public function GetBanks($validateXml = true, $url = null) { if ($url == null) $url = 'https://routing.eps.or.at/appl/epsSO/data/haendler/v2_5'; $body = $this->GetUrl($url, 'Requesting bank list'); if ($validateXml) XmlValidator::ValidateBankList($body); return $body; }
php
public function GetBanks($validateXml = true, $url = null) { if ($url == null) $url = 'https://routing.eps.or.at/appl/epsSO/data/haendler/v2_5'; $body = $this->GetUrl($url, 'Requesting bank list'); if ($validateXml) XmlValidator::ValidateBankList($body); return $body; }
[ "public", "function", "GetBanks", "(", "$", "validateXml", "=", "true", ",", "$", "url", "=", "null", ")", "{", "if", "(", "$", "url", "==", "null", ")", "$", "url", "=", "'https://routing.eps.or.at/appl/epsSO/data/haendler/v2_5'", ";", "$", "body", "=", "$", "this", "->", "GetUrl", "(", "$", "url", ",", "'Requesting bank list'", ")", ";", "if", "(", "$", "validateXml", ")", "XmlValidator", "::", "ValidateBankList", "(", "$", "body", ")", ";", "return", "$", "body", ";", "}" ]
Get XML of banks from scheme operator. Will throw an exception if data cannot be fetched, or XSD validation fails. @param bool $validateXml validate against XSD @param string $url Scheme operator URL for the banks list @throws XmlValidationException when the returned BankList does not validate against XSD and $validateXSD is set to TRUE @return string
[ "Get", "XML", "of", "banks", "from", "scheme", "operator", ".", "Will", "throw", "an", "exception", "if", "data", "cannot", "be", "fetched", "or", "XSD", "validation", "fails", "." ]
c2af496ecf4b9f095447a7b9f5c02d20924252bd
https://github.com/hakito/PHP-Stuzza-EPS-BankTransfer/blob/c2af496ecf4b9f095447a7b9f5c02d20924252bd/src/SoCommunicator.php#L87-L97
29,408
hakito/PHP-Stuzza-EPS-BankTransfer
src/SoCommunicator.php
SoCommunicator.SendTransferInitiatorDetails
public function SendTransferInitiatorDetails($transferInitiatorDetails, $targetUrl = null) { if ($transferInitiatorDetails->RemittanceIdentifier != null) $transferInitiatorDetails->RemittanceIdentifier = $this->AppendHash($transferInitiatorDetails->RemittanceIdentifier); if ($transferInitiatorDetails->UnstructuredRemittanceIdentifier != null) $transferInitiatorDetails->UnstructuredRemittanceIdentifier = $this->AppendHash($transferInitiatorDetails->UnstructuredRemittanceIdentifier); if ($targetUrl == null) $targetUrl = 'https://routing.eps.or.at/appl/epsSO/transinit/eps/v2_5'; $data = $transferInitiatorDetails->GetSimpleXml(); $xmlData = $data->asXML(); $response = $this->PostUrl($targetUrl, $xmlData, 'Send payment order'); XmlValidator::ValidateEpsProtocol($response); return $response; }
php
public function SendTransferInitiatorDetails($transferInitiatorDetails, $targetUrl = null) { if ($transferInitiatorDetails->RemittanceIdentifier != null) $transferInitiatorDetails->RemittanceIdentifier = $this->AppendHash($transferInitiatorDetails->RemittanceIdentifier); if ($transferInitiatorDetails->UnstructuredRemittanceIdentifier != null) $transferInitiatorDetails->UnstructuredRemittanceIdentifier = $this->AppendHash($transferInitiatorDetails->UnstructuredRemittanceIdentifier); if ($targetUrl == null) $targetUrl = 'https://routing.eps.or.at/appl/epsSO/transinit/eps/v2_5'; $data = $transferInitiatorDetails->GetSimpleXml(); $xmlData = $data->asXML(); $response = $this->PostUrl($targetUrl, $xmlData, 'Send payment order'); XmlValidator::ValidateEpsProtocol($response); return $response; }
[ "public", "function", "SendTransferInitiatorDetails", "(", "$", "transferInitiatorDetails", ",", "$", "targetUrl", "=", "null", ")", "{", "if", "(", "$", "transferInitiatorDetails", "->", "RemittanceIdentifier", "!=", "null", ")", "$", "transferInitiatorDetails", "->", "RemittanceIdentifier", "=", "$", "this", "->", "AppendHash", "(", "$", "transferInitiatorDetails", "->", "RemittanceIdentifier", ")", ";", "if", "(", "$", "transferInitiatorDetails", "->", "UnstructuredRemittanceIdentifier", "!=", "null", ")", "$", "transferInitiatorDetails", "->", "UnstructuredRemittanceIdentifier", "=", "$", "this", "->", "AppendHash", "(", "$", "transferInitiatorDetails", "->", "UnstructuredRemittanceIdentifier", ")", ";", "if", "(", "$", "targetUrl", "==", "null", ")", "$", "targetUrl", "=", "'https://routing.eps.or.at/appl/epsSO/transinit/eps/v2_5'", ";", "$", "data", "=", "$", "transferInitiatorDetails", "->", "GetSimpleXml", "(", ")", ";", "$", "xmlData", "=", "$", "data", "->", "asXML", "(", ")", ";", "$", "response", "=", "$", "this", "->", "PostUrl", "(", "$", "targetUrl", ",", "$", "xmlData", ",", "'Send payment order'", ")", ";", "XmlValidator", "::", "ValidateEpsProtocol", "(", "$", "response", ")", ";", "return", "$", "response", ";", "}" ]
Sends the given TransferInitiatorDetails to the Scheme Operator @param TransferInitiatorDetails $transferInitiatorDetails @param string $targetUrl url with preselected bank identifier @throws XmlValidationException when the returned BankResponseDetails does not validate against XSD @throws \UnexpectedValueException when using security suffix without security seed @return string BankResponseDetails
[ "Sends", "the", "given", "TransferInitiatorDetails", "to", "the", "Scheme", "Operator" ]
c2af496ecf4b9f095447a7b9f5c02d20924252bd
https://github.com/hakito/PHP-Stuzza-EPS-BankTransfer/blob/c2af496ecf4b9f095447a7b9f5c02d20924252bd/src/SoCommunicator.php#L107-L124
29,409
rosasurfer/ministruts
src/db/orm/PersistableObject.php
PersistableObject.get
protected function get($property) { $mapping = $this->dao()->getMapping(); if (isset($mapping['properties'][$property])) return $this->getNonRelationValue($property); if (isset($mapping['relations'][$property])) return $this->getRelationValue($property); throw new RuntimeException('Not a mapped property "'.$property.'"'); }
php
protected function get($property) { $mapping = $this->dao()->getMapping(); if (isset($mapping['properties'][$property])) return $this->getNonRelationValue($property); if (isset($mapping['relations'][$property])) return $this->getRelationValue($property); throw new RuntimeException('Not a mapped property "'.$property.'"'); }
[ "protected", "function", "get", "(", "$", "property", ")", "{", "$", "mapping", "=", "$", "this", "->", "dao", "(", ")", "->", "getMapping", "(", ")", ";", "if", "(", "isset", "(", "$", "mapping", "[", "'properties'", "]", "[", "$", "property", "]", ")", ")", "return", "$", "this", "->", "getNonRelationValue", "(", "$", "property", ")", ";", "if", "(", "isset", "(", "$", "mapping", "[", "'relations'", "]", "[", "$", "property", "]", ")", ")", "return", "$", "this", "->", "getRelationValue", "(", "$", "property", ")", ";", "throw", "new", "RuntimeException", "(", "'Not a mapped property \"'", ".", "$", "property", ".", "'\"'", ")", ";", "}" ]
Return the logical value of a mapped property. @param string $property - property name @return mixed - property value
[ "Return", "the", "logical", "value", "of", "a", "mapped", "property", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/PersistableObject.php#L104-L114
29,410
rosasurfer/ministruts
src/db/orm/PersistableObject.php
PersistableObject.getPhysicalValue
private function getPhysicalValue($column, $type = null) { $mapping = $this->dao()->getMapping(); $column = strtolower($column); if (!isset($mapping['columns'][$column])) throw new RuntimeException('Not a mapped column "'.func_get_arg(0).'"'); $property = &$mapping['columns'][$column]; $propertyName = $property['name']; $propertyValue = $this->$propertyName; // the logical or physical column value if ($propertyValue === null) return null; if (isset($property['assoc'])) { if ($propertyValue === false) return null; if (!is_object($propertyValue)) { // a foreign-key value of a not-yet-fetched relation if ($type !== null) throw new RuntimeException('Unexpected parameter $type="'.$type.'" (not null) for relation [name="'.$propertyName.'", column="'.$column.'", ...] of entity "'.$mapping['class'].'"'); return $propertyValue; } /** @var PersistableObject $object */ $object = $propertyValue; // a single instance of "one-to-one"|"many-to-one" relation, no join table if (!isset($property['ref-column'])) $property['ref-column'] = $object->dao()->getMapping()['identity']['column']; $fkColumn = $property['ref-column']; return $object->getPhysicalValue($fkColumn); } $columnType = $property['column-type']; switch ($columnType) { case 'bool' : case 'boolean': return (bool)(int) $propertyValue; case 'int' : case 'integer': return (int) $propertyValue; case 'real' : case 'float' : case 'double' : case 'decimal': return (float) $propertyValue; case 'text' : case 'string' : return (string) $propertyValue; default: // TODO: convert custom types (e.g. Enum|DateTime) to physical values //if (is_class($propertyType)) { // $object->$propertyName = new $propertyType($row[$column]); // break; //} } throw new RuntimeException('Unsupported attribute "column-type"="'.$columnType.'" in property [name="'.$propertyName.'", ...] of entity "'.$mapping['class'].'"'); }
php
private function getPhysicalValue($column, $type = null) { $mapping = $this->dao()->getMapping(); $column = strtolower($column); if (!isset($mapping['columns'][$column])) throw new RuntimeException('Not a mapped column "'.func_get_arg(0).'"'); $property = &$mapping['columns'][$column]; $propertyName = $property['name']; $propertyValue = $this->$propertyName; // the logical or physical column value if ($propertyValue === null) return null; if (isset($property['assoc'])) { if ($propertyValue === false) return null; if (!is_object($propertyValue)) { // a foreign-key value of a not-yet-fetched relation if ($type !== null) throw new RuntimeException('Unexpected parameter $type="'.$type.'" (not null) for relation [name="'.$propertyName.'", column="'.$column.'", ...] of entity "'.$mapping['class'].'"'); return $propertyValue; } /** @var PersistableObject $object */ $object = $propertyValue; // a single instance of "one-to-one"|"many-to-one" relation, no join table if (!isset($property['ref-column'])) $property['ref-column'] = $object->dao()->getMapping()['identity']['column']; $fkColumn = $property['ref-column']; return $object->getPhysicalValue($fkColumn); } $columnType = $property['column-type']; switch ($columnType) { case 'bool' : case 'boolean': return (bool)(int) $propertyValue; case 'int' : case 'integer': return (int) $propertyValue; case 'real' : case 'float' : case 'double' : case 'decimal': return (float) $propertyValue; case 'text' : case 'string' : return (string) $propertyValue; default: // TODO: convert custom types (e.g. Enum|DateTime) to physical values //if (is_class($propertyType)) { // $object->$propertyName = new $propertyType($row[$column]); // break; //} } throw new RuntimeException('Unsupported attribute "column-type"="'.$columnType.'" in property [name="'.$propertyName.'", ...] of entity "'.$mapping['class'].'"'); }
[ "private", "function", "getPhysicalValue", "(", "$", "column", ",", "$", "type", "=", "null", ")", "{", "$", "mapping", "=", "$", "this", "->", "dao", "(", ")", "->", "getMapping", "(", ")", ";", "$", "column", "=", "strtolower", "(", "$", "column", ")", ";", "if", "(", "!", "isset", "(", "$", "mapping", "[", "'columns'", "]", "[", "$", "column", "]", ")", ")", "throw", "new", "RuntimeException", "(", "'Not a mapped column \"'", ".", "func_get_arg", "(", "0", ")", ".", "'\"'", ")", ";", "$", "property", "=", "&", "$", "mapping", "[", "'columns'", "]", "[", "$", "column", "]", ";", "$", "propertyName", "=", "$", "property", "[", "'name'", "]", ";", "$", "propertyValue", "=", "$", "this", "->", "$", "propertyName", ";", "// the logical or physical column value", "if", "(", "$", "propertyValue", "===", "null", ")", "return", "null", ";", "if", "(", "isset", "(", "$", "property", "[", "'assoc'", "]", ")", ")", "{", "if", "(", "$", "propertyValue", "===", "false", ")", "return", "null", ";", "if", "(", "!", "is_object", "(", "$", "propertyValue", ")", ")", "{", "// a foreign-key value of a not-yet-fetched relation", "if", "(", "$", "type", "!==", "null", ")", "throw", "new", "RuntimeException", "(", "'Unexpected parameter $type=\"'", ".", "$", "type", ".", "'\" (not null) for relation [name=\"'", ".", "$", "propertyName", ".", "'\", column=\"'", ".", "$", "column", ".", "'\", ...] of entity \"'", ".", "$", "mapping", "[", "'class'", "]", ".", "'\"'", ")", ";", "return", "$", "propertyValue", ";", "}", "/** @var PersistableObject $object */", "$", "object", "=", "$", "propertyValue", ";", "// a single instance of \"one-to-one\"|\"many-to-one\" relation, no join table", "if", "(", "!", "isset", "(", "$", "property", "[", "'ref-column'", "]", ")", ")", "$", "property", "[", "'ref-column'", "]", "=", "$", "object", "->", "dao", "(", ")", "->", "getMapping", "(", ")", "[", "'identity'", "]", "[", "'column'", "]", ";", "$", "fkColumn", "=", "$", "property", "[", "'ref-column'", "]", ";", "return", "$", "object", "->", "getPhysicalValue", "(", "$", "fkColumn", ")", ";", "}", "$", "columnType", "=", "$", "property", "[", "'column-type'", "]", ";", "switch", "(", "$", "columnType", ")", "{", "case", "'bool'", ":", "case", "'boolean'", ":", "return", "(", "bool", ")", "(", "int", ")", "$", "propertyValue", ";", "case", "'int'", ":", "case", "'integer'", ":", "return", "(", "int", ")", "$", "propertyValue", ";", "case", "'real'", ":", "case", "'float'", ":", "case", "'double'", ":", "case", "'decimal'", ":", "return", "(", "float", ")", "$", "propertyValue", ";", "case", "'text'", ":", "case", "'string'", ":", "return", "(", "string", ")", "$", "propertyValue", ";", "default", ":", "// TODO: convert custom types (e.g. Enum|DateTime) to physical values", "//if (is_class($propertyType)) {", "// $object->$propertyName = new $propertyType($row[$column]);", "// break;", "//}", "}", "throw", "new", "RuntimeException", "(", "'Unsupported attribute \"column-type\"=\"'", ".", "$", "columnType", ".", "'\" in property [name=\"'", ".", "$", "propertyName", ".", "'\", ...] of entity \"'", ".", "$", "mapping", "[", "'class'", "]", ".", "'\"'", ")", ";", "}" ]
Return the value of a mapped column. @param string $column - column name @param string $type [optional] - column type (default: type as configured in the entity mapping) @return mixed - column value
[ "Return", "the", "value", "of", "a", "mapped", "column", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/PersistableObject.php#L249-L302
29,411
rosasurfer/ministruts
src/db/orm/PersistableObject.php
PersistableObject.isDeleted
final public function isDeleted() { foreach ($this->dao()->getMapping()['properties'] as $name => $property) { if (isset($property['soft-delete']) && $property['soft-delete']===true) { return ($this->$name !== null); } } return false; }
php
final public function isDeleted() { foreach ($this->dao()->getMapping()['properties'] as $name => $property) { if (isset($property['soft-delete']) && $property['soft-delete']===true) { return ($this->$name !== null); } } return false; }
[ "final", "public", "function", "isDeleted", "(", ")", "{", "foreach", "(", "$", "this", "->", "dao", "(", ")", "->", "getMapping", "(", ")", "[", "'properties'", "]", "as", "$", "name", "=>", "$", "property", ")", "{", "if", "(", "isset", "(", "$", "property", "[", "'soft-delete'", "]", ")", "&&", "$", "property", "[", "'soft-delete'", "]", "===", "true", ")", "{", "return", "(", "$", "this", "->", "$", "name", "!==", "null", ")", ";", "}", "}", "return", "false", ";", "}" ]
Whether the instance is marked as "soft deleted". @return bool
[ "Whether", "the", "instance", "is", "marked", "as", "soft", "deleted", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/PersistableObject.php#L334-L341
29,412
rosasurfer/ministruts
src/db/orm/PersistableObject.php
PersistableObject.save
public function save() { if (!$this->isPersistent()) { $this->dao()->transaction(function() { if ($this->beforeSave() !== true) // pre-processing hook return $this; $this->insert(); $this->afterSave(); // post-processing hook }); } elseif ($this->isModified()) { $this->dao()->transaction(function() { if ($this->beforeSave() !== true) // pre-processing hook return $this; $this->update(); $this->afterSave(); // post-processing hook }); } else { // persistent but not modified } return $this; }
php
public function save() { if (!$this->isPersistent()) { $this->dao()->transaction(function() { if ($this->beforeSave() !== true) // pre-processing hook return $this; $this->insert(); $this->afterSave(); // post-processing hook }); } elseif ($this->isModified()) { $this->dao()->transaction(function() { if ($this->beforeSave() !== true) // pre-processing hook return $this; $this->update(); $this->afterSave(); // post-processing hook }); } else { // persistent but not modified } return $this; }
[ "public", "function", "save", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isPersistent", "(", ")", ")", "{", "$", "this", "->", "dao", "(", ")", "->", "transaction", "(", "function", "(", ")", "{", "if", "(", "$", "this", "->", "beforeSave", "(", ")", "!==", "true", ")", "// pre-processing hook", "return", "$", "this", ";", "$", "this", "->", "insert", "(", ")", ";", "$", "this", "->", "afterSave", "(", ")", ";", "// post-processing hook", "}", ")", ";", "}", "elseif", "(", "$", "this", "->", "isModified", "(", ")", ")", "{", "$", "this", "->", "dao", "(", ")", "->", "transaction", "(", "function", "(", ")", "{", "if", "(", "$", "this", "->", "beforeSave", "(", ")", "!==", "true", ")", "// pre-processing hook", "return", "$", "this", ";", "$", "this", "->", "update", "(", ")", ";", "$", "this", "->", "afterSave", "(", ")", ";", "// post-processing hook", "}", ")", ";", "}", "else", "{", "// persistent but not modified", "}", "return", "$", "this", ";", "}" ]
Save the instance in the storage mechanism. @return $this
[ "Save", "the", "instance", "in", "the", "storage", "mechanism", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/PersistableObject.php#L370-L391
29,413
rosasurfer/ministruts
src/db/orm/PersistableObject.php
PersistableObject.insert
private function insert() { if ($this->isPersistent()) throw new RuntimeException('Cannot insert already persistent '.$this); // pre-processing hook if ($this->beforeInsert() !== true) return $this; $mapping = $this->dao()->getMapping(); // collect column values $values = []; foreach ($mapping['columns'] as $column => $property) { $values[$column] = $this->getPhysicalValue($column); }; // perform insertion $id = $this->doInsert($values); $this->_modified = false; // assign the returned identity value $idName = $mapping['identity']['name']; if ($this->$idName === null) $this->$idName = $id; // post-processing hook $this->afterInsert(); return $this; }
php
private function insert() { if ($this->isPersistent()) throw new RuntimeException('Cannot insert already persistent '.$this); // pre-processing hook if ($this->beforeInsert() !== true) return $this; $mapping = $this->dao()->getMapping(); // collect column values $values = []; foreach ($mapping['columns'] as $column => $property) { $values[$column] = $this->getPhysicalValue($column); }; // perform insertion $id = $this->doInsert($values); $this->_modified = false; // assign the returned identity value $idName = $mapping['identity']['name']; if ($this->$idName === null) $this->$idName = $id; // post-processing hook $this->afterInsert(); return $this; }
[ "private", "function", "insert", "(", ")", "{", "if", "(", "$", "this", "->", "isPersistent", "(", ")", ")", "throw", "new", "RuntimeException", "(", "'Cannot insert already persistent '", ".", "$", "this", ")", ";", "// pre-processing hook", "if", "(", "$", "this", "->", "beforeInsert", "(", ")", "!==", "true", ")", "return", "$", "this", ";", "$", "mapping", "=", "$", "this", "->", "dao", "(", ")", "->", "getMapping", "(", ")", ";", "// collect column values", "$", "values", "=", "[", "]", ";", "foreach", "(", "$", "mapping", "[", "'columns'", "]", "as", "$", "column", "=>", "$", "property", ")", "{", "$", "values", "[", "$", "column", "]", "=", "$", "this", "->", "getPhysicalValue", "(", "$", "column", ")", ";", "}", ";", "// perform insertion", "$", "id", "=", "$", "this", "->", "doInsert", "(", "$", "values", ")", ";", "$", "this", "->", "_modified", "=", "false", ";", "// assign the returned identity value", "$", "idName", "=", "$", "mapping", "[", "'identity'", "]", "[", "'name'", "]", ";", "if", "(", "$", "this", "->", "$", "idName", "===", "null", ")", "$", "this", "->", "$", "idName", "=", "$", "id", ";", "// post-processing hook", "$", "this", "->", "afterInsert", "(", ")", ";", "return", "$", "this", ";", "}" ]
Insert this instance into the storage mechanism. @return $this
[ "Insert", "this", "instance", "into", "the", "storage", "mechanism", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/PersistableObject.php#L399-L426
29,414
rosasurfer/ministruts
src/db/orm/PersistableObject.php
PersistableObject.update
private function update() { // pre-processing hook if ($this->beforeUpdate() !== true) return $this; $mapping = $this->dao()->getMapping(); $changes = []; // collect modified properties and their values foreach ($mapping['properties'] as $property) { // TODO: Until the dirty check is implemented all $propertyName = $property['name']; // properties are assumed dirty. $changes[$propertyName] = $this->$propertyName; } // perform update if ($this->doUpdate($changes)) { $this->_modified = false; // post-processing hook $this->afterUpdate(); } return $this; }
php
private function update() { // pre-processing hook if ($this->beforeUpdate() !== true) return $this; $mapping = $this->dao()->getMapping(); $changes = []; // collect modified properties and their values foreach ($mapping['properties'] as $property) { // TODO: Until the dirty check is implemented all $propertyName = $property['name']; // properties are assumed dirty. $changes[$propertyName] = $this->$propertyName; } // perform update if ($this->doUpdate($changes)) { $this->_modified = false; // post-processing hook $this->afterUpdate(); } return $this; }
[ "private", "function", "update", "(", ")", "{", "// pre-processing hook", "if", "(", "$", "this", "->", "beforeUpdate", "(", ")", "!==", "true", ")", "return", "$", "this", ";", "$", "mapping", "=", "$", "this", "->", "dao", "(", ")", "->", "getMapping", "(", ")", ";", "$", "changes", "=", "[", "]", ";", "// collect modified properties and their values", "foreach", "(", "$", "mapping", "[", "'properties'", "]", "as", "$", "property", ")", "{", "// TODO: Until the dirty check is implemented all", "$", "propertyName", "=", "$", "property", "[", "'name'", "]", ";", "// properties are assumed dirty.", "$", "changes", "[", "$", "propertyName", "]", "=", "$", "this", "->", "$", "propertyName", ";", "}", "// perform update", "if", "(", "$", "this", "->", "doUpdate", "(", "$", "changes", ")", ")", "{", "$", "this", "->", "_modified", "=", "false", ";", "// post-processing hook", "$", "this", "->", "afterUpdate", "(", ")", ";", "}", "return", "$", "this", ";", "}" ]
Update the instance. @return $this
[ "Update", "the", "instance", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/PersistableObject.php#L434-L456
29,415
rosasurfer/ministruts
src/db/orm/PersistableObject.php
PersistableObject.delete
public function delete() { if (!$this->isPersistent()) throw new IllegalStateException('Cannot delete non-persistent '.get_class($this)); $this->dao()->transaction(function() { if ($this->beforeDelete() !== true) // pre-processing hook return $this; if ($this->doDelete()) { // perform deletion // reset identity property $idName = $this->dao()->getMapping()['identity']['name']; $this->$idName = null; $this->afterDelete(); // post-processing hook } }); return $this; }
php
public function delete() { if (!$this->isPersistent()) throw new IllegalStateException('Cannot delete non-persistent '.get_class($this)); $this->dao()->transaction(function() { if ($this->beforeDelete() !== true) // pre-processing hook return $this; if ($this->doDelete()) { // perform deletion // reset identity property $idName = $this->dao()->getMapping()['identity']['name']; $this->$idName = null; $this->afterDelete(); // post-processing hook } }); return $this; }
[ "public", "function", "delete", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isPersistent", "(", ")", ")", "throw", "new", "IllegalStateException", "(", "'Cannot delete non-persistent '", ".", "get_class", "(", "$", "this", ")", ")", ";", "$", "this", "->", "dao", "(", ")", "->", "transaction", "(", "function", "(", ")", "{", "if", "(", "$", "this", "->", "beforeDelete", "(", ")", "!==", "true", ")", "// pre-processing hook", "return", "$", "this", ";", "if", "(", "$", "this", "->", "doDelete", "(", ")", ")", "{", "// perform deletion", "// reset identity property", "$", "idName", "=", "$", "this", "->", "dao", "(", ")", "->", "getMapping", "(", ")", "[", "'identity'", "]", "[", "'name'", "]", ";", "$", "this", "->", "$", "idName", "=", "null", ";", "$", "this", "->", "afterDelete", "(", ")", ";", "// post-processing hook", "}", "}", ")", ";", "return", "$", "this", ";", "}" ]
Delete the instance from the storage mechanism. @return $this
[ "Delete", "the", "instance", "from", "the", "storage", "mechanism", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/PersistableObject.php#L464-L480
29,416
rosasurfer/ministruts
src/db/orm/PersistableObject.php
PersistableObject.doInsert
private function doInsert(array $values) { $db = $this->db(); $mapping = $this->dao()->getMapping(); $table = $mapping['table']; $idColumn = $mapping['identity']['column']; $id = null; if (isset($values[$idColumn])) $id = $values[$idColumn]; else unset($values[$idColumn]); // translate column values foreach ($values as &$value) { $value = $db->escapeLiteral($value); }; unset($value); // create SQL statement $sql = 'insert into '.$table.' ('.join(', ', \array_keys($values)).') values ('.join(', ', $values).')'; // execute SQL statement if ($id) { $db->execute($sql); } else if ($db->supportsInsertReturn()) { $id = $db->query($sql.' returning '.$idColumn)->fetchInt(); } else { $id = $db->execute($sql)->lastInsertId(); } return $id; }
php
private function doInsert(array $values) { $db = $this->db(); $mapping = $this->dao()->getMapping(); $table = $mapping['table']; $idColumn = $mapping['identity']['column']; $id = null; if (isset($values[$idColumn])) $id = $values[$idColumn]; else unset($values[$idColumn]); // translate column values foreach ($values as &$value) { $value = $db->escapeLiteral($value); }; unset($value); // create SQL statement $sql = 'insert into '.$table.' ('.join(', ', \array_keys($values)).') values ('.join(', ', $values).')'; // execute SQL statement if ($id) { $db->execute($sql); } else if ($db->supportsInsertReturn()) { $id = $db->query($sql.' returning '.$idColumn)->fetchInt(); } else { $id = $db->execute($sql)->lastInsertId(); } return $id; }
[ "private", "function", "doInsert", "(", "array", "$", "values", ")", "{", "$", "db", "=", "$", "this", "->", "db", "(", ")", ";", "$", "mapping", "=", "$", "this", "->", "dao", "(", ")", "->", "getMapping", "(", ")", ";", "$", "table", "=", "$", "mapping", "[", "'table'", "]", ";", "$", "idColumn", "=", "$", "mapping", "[", "'identity'", "]", "[", "'column'", "]", ";", "$", "id", "=", "null", ";", "if", "(", "isset", "(", "$", "values", "[", "$", "idColumn", "]", ")", ")", "$", "id", "=", "$", "values", "[", "$", "idColumn", "]", ";", "else", "unset", "(", "$", "values", "[", "$", "idColumn", "]", ")", ";", "// translate column values", "foreach", "(", "$", "values", "as", "&", "$", "value", ")", "{", "$", "value", "=", "$", "db", "->", "escapeLiteral", "(", "$", "value", ")", ";", "}", ";", "unset", "(", "$", "value", ")", ";", "// create SQL statement", "$", "sql", "=", "'insert into '", ".", "$", "table", ".", "' ('", ".", "join", "(", "', '", ",", "\\", "array_keys", "(", "$", "values", ")", ")", ".", "')\n values ('", ".", "join", "(", "', '", ",", "$", "values", ")", ".", "')'", ";", "// execute SQL statement", "if", "(", "$", "id", ")", "{", "$", "db", "->", "execute", "(", "$", "sql", ")", ";", "}", "else", "if", "(", "$", "db", "->", "supportsInsertReturn", "(", ")", ")", "{", "$", "id", "=", "$", "db", "->", "query", "(", "$", "sql", ".", "' returning '", ".", "$", "idColumn", ")", "->", "fetchInt", "(", ")", ";", "}", "else", "{", "$", "id", "=", "$", "db", "->", "execute", "(", "$", "sql", ")", "->", "lastInsertId", "(", ")", ";", "}", "return", "$", "id", ";", "}" ]
Perform the actual insertion of a data record representing the instance. @param array $values - record values @return mixed - the inserted record's identity value
[ "Perform", "the", "actual", "insertion", "of", "a", "data", "record", "representing", "the", "instance", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/PersistableObject.php#L490-L519
29,417
rosasurfer/ministruts
src/db/orm/PersistableObject.php
PersistableObject.doUpdate
private function doUpdate(array $changes) { $db = $this->db(); $entity = $this->dao()->getEntityMapping(); $table = $entity->getTableName(); // collect identity infos $identity = $entity->getIdentity(); $idColumn = $identity->getColumn(); $idValue = $identity->convertToDBValue($this->getObjectId(), $db); // collect version infos $versionMapping = $versionName = $versionColumn = $oldVersion = null; //if ($versionMapping = $entity->getVersion()) { // $versionName = $versionMapping->getName(); // $versionColumn = $versionMapping->getColumn(); // $oldVersion = $object->getSnapshot()->$versionName; // TODO: implement dirty check via snapshot // $oldVersion = $versionMapping->convertToDBValue($oldVersion, $db); //} // create SQL $sql = 'update '.$table.' set'; // update table foreach ($changes as $name => $value) { // set ... $mapping = $entity->getProperty($name); // ... $columnName = $mapping->getColumn(); // ... $columnValue = $mapping->convertToDBValue($value, $db); // column1 = value1, $sql .= ' '.$columnName.' = '.$columnValue.','; // column2 = value2, } // ... $sql = strLeft($sql, -1); // ... $sql .= ' where '.$idColumn.' = '.$idValue; // where id = value if ($versionMapping) { // ... $op = $oldVersion=='null' ? 'is':'='; // ... $sql .= ' and '.$versionColumn.' '.$op.' '.$oldVersion; // and version = oldVersion } // execute SQL and check for concurrent modifications if ($db->execute($sql)->lastAffectedRows() != 1) { if ($versionMapping) { $this->reload(); $msg = 'expected version: '.$oldVersion.', found version: '.$this->$versionName; } else $msg = 'record not found'; throw new ConcurrentModificationException('Error updating '.get_class($this).' (oid='.$this->getObjectId().'), '.$msg); } return true; }
php
private function doUpdate(array $changes) { $db = $this->db(); $entity = $this->dao()->getEntityMapping(); $table = $entity->getTableName(); // collect identity infos $identity = $entity->getIdentity(); $idColumn = $identity->getColumn(); $idValue = $identity->convertToDBValue($this->getObjectId(), $db); // collect version infos $versionMapping = $versionName = $versionColumn = $oldVersion = null; //if ($versionMapping = $entity->getVersion()) { // $versionName = $versionMapping->getName(); // $versionColumn = $versionMapping->getColumn(); // $oldVersion = $object->getSnapshot()->$versionName; // TODO: implement dirty check via snapshot // $oldVersion = $versionMapping->convertToDBValue($oldVersion, $db); //} // create SQL $sql = 'update '.$table.' set'; // update table foreach ($changes as $name => $value) { // set ... $mapping = $entity->getProperty($name); // ... $columnName = $mapping->getColumn(); // ... $columnValue = $mapping->convertToDBValue($value, $db); // column1 = value1, $sql .= ' '.$columnName.' = '.$columnValue.','; // column2 = value2, } // ... $sql = strLeft($sql, -1); // ... $sql .= ' where '.$idColumn.' = '.$idValue; // where id = value if ($versionMapping) { // ... $op = $oldVersion=='null' ? 'is':'='; // ... $sql .= ' and '.$versionColumn.' '.$op.' '.$oldVersion; // and version = oldVersion } // execute SQL and check for concurrent modifications if ($db->execute($sql)->lastAffectedRows() != 1) { if ($versionMapping) { $this->reload(); $msg = 'expected version: '.$oldVersion.', found version: '.$this->$versionName; } else $msg = 'record not found'; throw new ConcurrentModificationException('Error updating '.get_class($this).' (oid='.$this->getObjectId().'), '.$msg); } return true; }
[ "private", "function", "doUpdate", "(", "array", "$", "changes", ")", "{", "$", "db", "=", "$", "this", "->", "db", "(", ")", ";", "$", "entity", "=", "$", "this", "->", "dao", "(", ")", "->", "getEntityMapping", "(", ")", ";", "$", "table", "=", "$", "entity", "->", "getTableName", "(", ")", ";", "// collect identity infos", "$", "identity", "=", "$", "entity", "->", "getIdentity", "(", ")", ";", "$", "idColumn", "=", "$", "identity", "->", "getColumn", "(", ")", ";", "$", "idValue", "=", "$", "identity", "->", "convertToDBValue", "(", "$", "this", "->", "getObjectId", "(", ")", ",", "$", "db", ")", ";", "// collect version infos", "$", "versionMapping", "=", "$", "versionName", "=", "$", "versionColumn", "=", "$", "oldVersion", "=", "null", ";", "//if ($versionMapping = $entity->getVersion()) {", "// $versionName = $versionMapping->getName();", "// $versionColumn = $versionMapping->getColumn();", "// $oldVersion = $object->getSnapshot()->$versionName; // TODO: implement dirty check via snapshot", "// $oldVersion = $versionMapping->convertToDBValue($oldVersion, $db);", "//}", "// create SQL", "$", "sql", "=", "'update '", ".", "$", "table", ".", "' set'", ";", "// update table", "foreach", "(", "$", "changes", "as", "$", "name", "=>", "$", "value", ")", "{", "// set ...", "$", "mapping", "=", "$", "entity", "->", "getProperty", "(", "$", "name", ")", ";", "// ...", "$", "columnName", "=", "$", "mapping", "->", "getColumn", "(", ")", ";", "// ...", "$", "columnValue", "=", "$", "mapping", "->", "convertToDBValue", "(", "$", "value", ",", "$", "db", ")", ";", "// column1 = value1,", "$", "sql", ".=", "' '", ".", "$", "columnName", ".", "' = '", ".", "$", "columnValue", ".", "','", ";", "// column2 = value2,", "}", "// ...", "$", "sql", "=", "strLeft", "(", "$", "sql", ",", "-", "1", ")", ";", "// ...", "$", "sql", ".=", "' where '", ".", "$", "idColumn", ".", "' = '", ".", "$", "idValue", ";", "// where id = value", "if", "(", "$", "versionMapping", ")", "{", "// ...", "$", "op", "=", "$", "oldVersion", "==", "'null'", "?", "'is'", ":", "'='", ";", "// ...", "$", "sql", ".=", "' and '", ".", "$", "versionColumn", ".", "' '", ".", "$", "op", ".", "' '", ".", "$", "oldVersion", ";", "// and version = oldVersion", "}", "// execute SQL and check for concurrent modifications", "if", "(", "$", "db", "->", "execute", "(", "$", "sql", ")", "->", "lastAffectedRows", "(", ")", "!=", "1", ")", "{", "if", "(", "$", "versionMapping", ")", "{", "$", "this", "->", "reload", "(", ")", ";", "$", "msg", "=", "'expected version: '", ".", "$", "oldVersion", ".", "', found version: '", ".", "$", "this", "->", "$", "versionName", ";", "}", "else", "$", "msg", "=", "'record not found'", ";", "throw", "new", "ConcurrentModificationException", "(", "'Error updating '", ".", "get_class", "(", "$", "this", ")", ".", "' (oid='", ".", "$", "this", "->", "getObjectId", "(", ")", ".", "'), '", ".", "$", "msg", ")", ";", "}", "return", "true", ";", "}" ]
Perform the actual update and write modifications of the instance to the storage mechanism. @param array $changes - modifications @return bool - success status
[ "Perform", "the", "actual", "update", "and", "write", "modifications", "of", "the", "instance", "to", "the", "storage", "mechanism", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/PersistableObject.php#L529-L573
29,418
rosasurfer/ministruts
src/db/orm/PersistableObject.php
PersistableObject.doDelete
private function doDelete() { $db = $this->db(); $entity = $this->dao()->getEntityMapping(); $table = $entity->getTableName(); // collect identity infos $identity = $entity->getIdentity(); $idColumn = $identity->getColumn(); $idValue = $identity->convertToDBValue($this->getObjectId(), $db); // create SQL $sql = 'delete from '.$table.' where '.$idColumn.' = '.$idValue; // execute SQL and check for concurrent modifications if ($db->execute($sql)->lastAffectedRows() != 1) throw new ConcurrentModificationException('Error deleting '.get_class($this).' (oid='.$this->getObjectId().'): record not found'); return true; }
php
private function doDelete() { $db = $this->db(); $entity = $this->dao()->getEntityMapping(); $table = $entity->getTableName(); // collect identity infos $identity = $entity->getIdentity(); $idColumn = $identity->getColumn(); $idValue = $identity->convertToDBValue($this->getObjectId(), $db); // create SQL $sql = 'delete from '.$table.' where '.$idColumn.' = '.$idValue; // execute SQL and check for concurrent modifications if ($db->execute($sql)->lastAffectedRows() != 1) throw new ConcurrentModificationException('Error deleting '.get_class($this).' (oid='.$this->getObjectId().'): record not found'); return true; }
[ "private", "function", "doDelete", "(", ")", "{", "$", "db", "=", "$", "this", "->", "db", "(", ")", ";", "$", "entity", "=", "$", "this", "->", "dao", "(", ")", "->", "getEntityMapping", "(", ")", ";", "$", "table", "=", "$", "entity", "->", "getTableName", "(", ")", ";", "// collect identity infos", "$", "identity", "=", "$", "entity", "->", "getIdentity", "(", ")", ";", "$", "idColumn", "=", "$", "identity", "->", "getColumn", "(", ")", ";", "$", "idValue", "=", "$", "identity", "->", "convertToDBValue", "(", "$", "this", "->", "getObjectId", "(", ")", ",", "$", "db", ")", ";", "// create SQL", "$", "sql", "=", "'delete from '", ".", "$", "table", ".", "'\n where '", ".", "$", "idColumn", ".", "' = '", ".", "$", "idValue", ";", "// execute SQL and check for concurrent modifications", "if", "(", "$", "db", "->", "execute", "(", "$", "sql", ")", "->", "lastAffectedRows", "(", ")", "!=", "1", ")", "throw", "new", "ConcurrentModificationException", "(", "'Error deleting '", ".", "get_class", "(", "$", "this", ")", ".", "' (oid='", ".", "$", "this", "->", "getObjectId", "(", ")", ".", "'): record not found'", ")", ";", "return", "true", ";", "}" ]
Perform the actual deletion of the instance. @return bool - success status
[ "Perform", "the", "actual", "deletion", "of", "the", "instance", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/PersistableObject.php#L581-L599
29,419
rosasurfer/ministruts
src/db/orm/PersistableObject.php
PersistableObject.populateNew
public static function populateNew($class, array $row) { if (static::class != __CLASS__) throw new IllegalAccessException('Cannot access method '.__METHOD__.'() on a derived class.'); if (!is_a($class, __CLASS__, $allowString=true)) throw new InvalidArgumentException('Not a '.__CLASS__.' subclass: '.$class); /** @var self $object */ $object = new $class(); $object->populate($row); return $object; }
php
public static function populateNew($class, array $row) { if (static::class != __CLASS__) throw new IllegalAccessException('Cannot access method '.__METHOD__.'() on a derived class.'); if (!is_a($class, __CLASS__, $allowString=true)) throw new InvalidArgumentException('Not a '.__CLASS__.' subclass: '.$class); /** @var self $object */ $object = new $class(); $object->populate($row); return $object; }
[ "public", "static", "function", "populateNew", "(", "$", "class", ",", "array", "$", "row", ")", "{", "if", "(", "static", "::", "class", "!=", "__CLASS__", ")", "throw", "new", "IllegalAccessException", "(", "'Cannot access method '", ".", "__METHOD__", ".", "'() on a derived class.'", ")", ";", "if", "(", "!", "is_a", "(", "$", "class", ",", "__CLASS__", ",", "$", "allowString", "=", "true", ")", ")", "throw", "new", "InvalidArgumentException", "(", "'Not a '", ".", "__CLASS__", ".", "' subclass: '", ".", "$", "class", ")", ";", "/** @var self $object */", "$", "object", "=", "new", "$", "class", "(", ")", ";", "$", "object", "->", "populate", "(", "$", "row", ")", ";", "return", "$", "object", ";", "}" ]
Create a new instance and populate it with the specified properties. This method is called by the ORM to transform database query result records to instances of the respective entity class. @param string $class - entity class name @param array $row - array with property values (a result row from a database query) @return self
[ "Create", "a", "new", "instance", "and", "populate", "it", "with", "the", "specified", "properties", ".", "This", "method", "is", "called", "by", "the", "ORM", "to", "transform", "database", "query", "result", "records", "to", "instances", "of", "the", "respective", "entity", "class", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/PersistableObject.php#L677-L685
29,420
rosasurfer/ministruts
src/db/orm/PersistableObject.php
PersistableObject.reload
public function reload($resetRelations = false) { // TODO: implement and set default=TRUE if (!$this->isPersistent()) throw new IllegalStateException('Cannot reload non-persistent '.get_class($this)); // TODO: This method cannot yet handle composite primary keys. $db = $this->db(); $dao = $this->dao(); $entity = $dao->getEntityMapping(); $table = $entity->getTableName(); // collect identity infos $identity = $entity->getIdentity(); $idColumn = $identity->getColumn(); $idName = $identity->getName(); $idValue = $identity->convertToDBValue($this->$idName, $db); // create and execute SQL $sql = 'select * from '.$table.' where '.$idColumn.' = '.$idValue; $row = $db->query($sql)->fetchRow(); if ($row === null) throw new ConcurrentModificationException('Error reloading '.get_class($this).' ('.$this->getObjectId().'), record not found'); // apply record values return $this->populate($row); }
php
public function reload($resetRelations = false) { // TODO: implement and set default=TRUE if (!$this->isPersistent()) throw new IllegalStateException('Cannot reload non-persistent '.get_class($this)); // TODO: This method cannot yet handle composite primary keys. $db = $this->db(); $dao = $this->dao(); $entity = $dao->getEntityMapping(); $table = $entity->getTableName(); // collect identity infos $identity = $entity->getIdentity(); $idColumn = $identity->getColumn(); $idName = $identity->getName(); $idValue = $identity->convertToDBValue($this->$idName, $db); // create and execute SQL $sql = 'select * from '.$table.' where '.$idColumn.' = '.$idValue; $row = $db->query($sql)->fetchRow(); if ($row === null) throw new ConcurrentModificationException('Error reloading '.get_class($this).' ('.$this->getObjectId().'), record not found'); // apply record values return $this->populate($row); }
[ "public", "function", "reload", "(", "$", "resetRelations", "=", "false", ")", "{", "// TODO: implement and set default=TRUE", "if", "(", "!", "$", "this", "->", "isPersistent", "(", ")", ")", "throw", "new", "IllegalStateException", "(", "'Cannot reload non-persistent '", ".", "get_class", "(", "$", "this", ")", ")", ";", "// TODO: This method cannot yet handle composite primary keys.", "$", "db", "=", "$", "this", "->", "db", "(", ")", ";", "$", "dao", "=", "$", "this", "->", "dao", "(", ")", ";", "$", "entity", "=", "$", "dao", "->", "getEntityMapping", "(", ")", ";", "$", "table", "=", "$", "entity", "->", "getTableName", "(", ")", ";", "// collect identity infos", "$", "identity", "=", "$", "entity", "->", "getIdentity", "(", ")", ";", "$", "idColumn", "=", "$", "identity", "->", "getColumn", "(", ")", ";", "$", "idName", "=", "$", "identity", "->", "getName", "(", ")", ";", "$", "idValue", "=", "$", "identity", "->", "convertToDBValue", "(", "$", "this", "->", "$", "idName", ",", "$", "db", ")", ";", "// create and execute SQL", "$", "sql", "=", "'select *\n from '", ".", "$", "table", ".", "'\n where '", ".", "$", "idColumn", ".", "' = '", ".", "$", "idValue", ";", "$", "row", "=", "$", "db", "->", "query", "(", "$", "sql", ")", "->", "fetchRow", "(", ")", ";", "if", "(", "$", "row", "===", "null", ")", "throw", "new", "ConcurrentModificationException", "(", "'Error reloading '", ".", "get_class", "(", "$", "this", ")", ".", "' ('", ".", "$", "this", "->", "getObjectId", "(", ")", ".", "'), record not found'", ")", ";", "// apply record values", "return", "$", "this", "->", "populate", "(", "$", "row", ")", ";", "}" ]
Reload this instance from the database and optionally reset relations. @param bool $resetRelations [optional] - NOT YET IMPLEMENTED Whether to reset relations and re-fetch on next access. (default: no) @return $this
[ "Reload", "this", "instance", "from", "the", "database", "and", "optionally", "reset", "relations", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/orm/PersistableObject.php#L696-L721
29,421
timble/kodekit
code/template/helper/paginator.php
TemplateHelperPaginator.limit
public function limit($config = array()) { $config = new ObjectConfigJson($config); $config->append(array( 'limit' => 0, 'attribs' => array('class' => 'k-form-control'), 'values' => array(5, 10, 15, 20, 25, 30, 50, 100) )); $html = ''; $selected = 0; $options = array(); $values = ObjectConfig::unbox($config->values); if ($config->limit && !in_array($config->limit, $values)) { $values[] = $config->limit; sort($values); } foreach($values as $value) { if($value == $config->limit) { $selected = $value; } $options[] = $this->option(array('label' => $value, 'value' => $value)); } if ($config->limit == $config->total) { $options[] = $this->option(array('label' => $this->getObject('translator')->translate('All'), 'value' => 0)); } $html .= $this->optionlist(array('options' => $options, 'name' => 'limit', 'attribs' => $config->attribs, 'selected' => $selected)); return $html; }
php
public function limit($config = array()) { $config = new ObjectConfigJson($config); $config->append(array( 'limit' => 0, 'attribs' => array('class' => 'k-form-control'), 'values' => array(5, 10, 15, 20, 25, 30, 50, 100) )); $html = ''; $selected = 0; $options = array(); $values = ObjectConfig::unbox($config->values); if ($config->limit && !in_array($config->limit, $values)) { $values[] = $config->limit; sort($values); } foreach($values as $value) { if($value == $config->limit) { $selected = $value; } $options[] = $this->option(array('label' => $value, 'value' => $value)); } if ($config->limit == $config->total) { $options[] = $this->option(array('label' => $this->getObject('translator')->translate('All'), 'value' => 0)); } $html .= $this->optionlist(array('options' => $options, 'name' => 'limit', 'attribs' => $config->attribs, 'selected' => $selected)); return $html; }
[ "public", "function", "limit", "(", "$", "config", "=", "array", "(", ")", ")", "{", "$", "config", "=", "new", "ObjectConfigJson", "(", "$", "config", ")", ";", "$", "config", "->", "append", "(", "array", "(", "'limit'", "=>", "0", ",", "'attribs'", "=>", "array", "(", "'class'", "=>", "'k-form-control'", ")", ",", "'values'", "=>", "array", "(", "5", ",", "10", ",", "15", ",", "20", ",", "25", ",", "30", ",", "50", ",", "100", ")", ")", ")", ";", "$", "html", "=", "''", ";", "$", "selected", "=", "0", ";", "$", "options", "=", "array", "(", ")", ";", "$", "values", "=", "ObjectConfig", "::", "unbox", "(", "$", "config", "->", "values", ")", ";", "if", "(", "$", "config", "->", "limit", "&&", "!", "in_array", "(", "$", "config", "->", "limit", ",", "$", "values", ")", ")", "{", "$", "values", "[", "]", "=", "$", "config", "->", "limit", ";", "sort", "(", "$", "values", ")", ";", "}", "foreach", "(", "$", "values", "as", "$", "value", ")", "{", "if", "(", "$", "value", "==", "$", "config", "->", "limit", ")", "{", "$", "selected", "=", "$", "value", ";", "}", "$", "options", "[", "]", "=", "$", "this", "->", "option", "(", "array", "(", "'label'", "=>", "$", "value", ",", "'value'", "=>", "$", "value", ")", ")", ";", "}", "if", "(", "$", "config", "->", "limit", "==", "$", "config", "->", "total", ")", "{", "$", "options", "[", "]", "=", "$", "this", "->", "option", "(", "array", "(", "'label'", "=>", "$", "this", "->", "getObject", "(", "'translator'", ")", "->", "translate", "(", "'All'", ")", ",", "'value'", "=>", "0", ")", ")", ";", "}", "$", "html", ".=", "$", "this", "->", "optionlist", "(", "array", "(", "'options'", "=>", "$", "options", ",", "'name'", "=>", "'limit'", ",", "'attribs'", "=>", "$", "config", "->", "attribs", ",", "'selected'", "=>", "$", "selected", ")", ")", ";", "return", "$", "html", ";", "}" ]
Render a select box with limit values @param array|ObjectConfig $config An optional array with configuration options @return string Html select box
[ "Render", "a", "select", "box", "with", "limit", "values" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/template/helper/paginator.php#L77-L111
29,422
timble/kodekit
code/template/helper/paginator.php
TemplateHelperPaginator.pages
public function pages($config = array()) { $config = new ModelPaginator($config); $config->append(array( 'url' => null, 'total' => 0, 'display' => 2, 'offset' => 0, 'limit' => 0, 'show_limit' => true, 'show_count' => false ))->append(array( 'show_pages' => $config->count !== 1 )); $pages = $config->pages; $html = ''; $html .= $pages->previous->active ? '<li>'.$this->page($pages->previous, $config->url).'</li>' : ''; $previous = null; foreach ($pages->offsets as $page) { if ($previous && $page->page - $previous->page > 1) { $html .= '<li class="k-is-disabled"><span>&hellip;</span></li>'; } $html .= '<li class="'.($page->active && !$page->current ? '' : 'k-is-active').'">'; $html .= $this->page($page, $config->url); $html .= '</li>'; $previous = $page; } $html .= $pages->next->active ? '<li>'.$this->page($pages->next, $config->url).'</li>' : ''; return $html; }
php
public function pages($config = array()) { $config = new ModelPaginator($config); $config->append(array( 'url' => null, 'total' => 0, 'display' => 2, 'offset' => 0, 'limit' => 0, 'show_limit' => true, 'show_count' => false ))->append(array( 'show_pages' => $config->count !== 1 )); $pages = $config->pages; $html = ''; $html .= $pages->previous->active ? '<li>'.$this->page($pages->previous, $config->url).'</li>' : ''; $previous = null; foreach ($pages->offsets as $page) { if ($previous && $page->page - $previous->page > 1) { $html .= '<li class="k-is-disabled"><span>&hellip;</span></li>'; } $html .= '<li class="'.($page->active && !$page->current ? '' : 'k-is-active').'">'; $html .= $this->page($page, $config->url); $html .= '</li>'; $previous = $page; } $html .= $pages->next->active ? '<li>'.$this->page($pages->next, $config->url).'</li>' : ''; return $html; }
[ "public", "function", "pages", "(", "$", "config", "=", "array", "(", ")", ")", "{", "$", "config", "=", "new", "ModelPaginator", "(", "$", "config", ")", ";", "$", "config", "->", "append", "(", "array", "(", "'url'", "=>", "null", ",", "'total'", "=>", "0", ",", "'display'", "=>", "2", ",", "'offset'", "=>", "0", ",", "'limit'", "=>", "0", ",", "'show_limit'", "=>", "true", ",", "'show_count'", "=>", "false", ")", ")", "->", "append", "(", "array", "(", "'show_pages'", "=>", "$", "config", "->", "count", "!==", "1", ")", ")", ";", "$", "pages", "=", "$", "config", "->", "pages", ";", "$", "html", "=", "''", ";", "$", "html", ".=", "$", "pages", "->", "previous", "->", "active", "?", "'<li>'", ".", "$", "this", "->", "page", "(", "$", "pages", "->", "previous", ",", "$", "config", "->", "url", ")", ".", "'</li>'", ":", "''", ";", "$", "previous", "=", "null", ";", "foreach", "(", "$", "pages", "->", "offsets", "as", "$", "page", ")", "{", "if", "(", "$", "previous", "&&", "$", "page", "->", "page", "-", "$", "previous", "->", "page", ">", "1", ")", "{", "$", "html", ".=", "'<li class=\"k-is-disabled\"><span>&hellip;</span></li>'", ";", "}", "$", "html", ".=", "'<li class=\"'", ".", "(", "$", "page", "->", "active", "&&", "!", "$", "page", "->", "current", "?", "''", ":", "'k-is-active'", ")", ".", "'\">'", ";", "$", "html", ".=", "$", "this", "->", "page", "(", "$", "page", ",", "$", "config", "->", "url", ")", ";", "$", "html", ".=", "'</li>'", ";", "$", "previous", "=", "$", "page", ";", "}", "$", "html", ".=", "$", "pages", "->", "next", "->", "active", "?", "'<li>'", ".", "$", "this", "->", "page", "(", "$", "pages", "->", "next", ",", "$", "config", "->", "url", ")", ".", "'</li>'", ":", "''", ";", "return", "$", "html", ";", "}" ]
Render a list of pages links @param array $config An optional array with configuration options @return string Html
[ "Render", "a", "list", "of", "pages", "links" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/template/helper/paginator.php#L119-L157
29,423
timble/kodekit
code/template/helper/paginator.php
TemplateHelperPaginator.page
public function page(ObjectConfigInterface $page, HttpUrlInterface $url) { $page->append(array( 'title' => '', 'current' => false, 'active' => false, 'offset' => 0, 'limit' => 0, 'rel' => '', 'attribs' => array(), )); //Set the offset and limit $url->query['limit'] = $page->limit; $url->query['offset'] = $page->offset; $link_attribs = []; if (!empty($page->rel)) { $link_attribs['rel'] = $page->rel; } if ($page->active && !$page->current) { $link_attribs['href'] = (string)$url; } $html = '<a '.$this->buildAttributes($link_attribs).'>'.$this->getObject('translator')->translate($page->title).'</a>'; return $html; }
php
public function page(ObjectConfigInterface $page, HttpUrlInterface $url) { $page->append(array( 'title' => '', 'current' => false, 'active' => false, 'offset' => 0, 'limit' => 0, 'rel' => '', 'attribs' => array(), )); //Set the offset and limit $url->query['limit'] = $page->limit; $url->query['offset'] = $page->offset; $link_attribs = []; if (!empty($page->rel)) { $link_attribs['rel'] = $page->rel; } if ($page->active && !$page->current) { $link_attribs['href'] = (string)$url; } $html = '<a '.$this->buildAttributes($link_attribs).'>'.$this->getObject('translator')->translate($page->title).'</a>'; return $html; }
[ "public", "function", "page", "(", "ObjectConfigInterface", "$", "page", ",", "HttpUrlInterface", "$", "url", ")", "{", "$", "page", "->", "append", "(", "array", "(", "'title'", "=>", "''", ",", "'current'", "=>", "false", ",", "'active'", "=>", "false", ",", "'offset'", "=>", "0", ",", "'limit'", "=>", "0", ",", "'rel'", "=>", "''", ",", "'attribs'", "=>", "array", "(", ")", ",", ")", ")", ";", "//Set the offset and limit", "$", "url", "->", "query", "[", "'limit'", "]", "=", "$", "page", "->", "limit", ";", "$", "url", "->", "query", "[", "'offset'", "]", "=", "$", "page", "->", "offset", ";", "$", "link_attribs", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "page", "->", "rel", ")", ")", "{", "$", "link_attribs", "[", "'rel'", "]", "=", "$", "page", "->", "rel", ";", "}", "if", "(", "$", "page", "->", "active", "&&", "!", "$", "page", "->", "current", ")", "{", "$", "link_attribs", "[", "'href'", "]", "=", "(", "string", ")", "$", "url", ";", "}", "$", "html", "=", "'<a '", ".", "$", "this", "->", "buildAttributes", "(", "$", "link_attribs", ")", ".", "'>'", ".", "$", "this", "->", "getObject", "(", "'translator'", ")", "->", "translate", "(", "$", "page", "->", "title", ")", ".", "'</a>'", ";", "return", "$", "html", ";", "}" ]
Render a page link @param ObjectConfigInterface $page The page data @param HttpUrlInterface $url The base url to create the link @return string Html
[ "Render", "a", "page", "link" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/template/helper/paginator.php#L166-L195
29,424
timble/kodekit
code/database/behavior/accessible.php
DatabaseBehaviorAccessible.canAccess
public function canAccess() { //Check if the user needs to be authentic to access if($this->hasProperty('access') && !empty($this->access)) { if(!$this->getObject('user')->isAuthentic()) { return false; } } //Check if the user is in the group(s) to access if($this->hasProperty('access_group') && !empty($this->access_group)) { $groups = $this->getObject('user')->getGroups(); if(!in_array($this->access_group, $groups)) { return false; } } //Check if the user has the right role(s) to access if($this->hasProperty('access_role') && !empty($this->access_role)) { if(!$this->getObject('user')->hasRole($this->access_role)) { return false; } } return true; }
php
public function canAccess() { //Check if the user needs to be authentic to access if($this->hasProperty('access') && !empty($this->access)) { if(!$this->getObject('user')->isAuthentic()) { return false; } } //Check if the user is in the group(s) to access if($this->hasProperty('access_group') && !empty($this->access_group)) { $groups = $this->getObject('user')->getGroups(); if(!in_array($this->access_group, $groups)) { return false; } } //Check if the user has the right role(s) to access if($this->hasProperty('access_role') && !empty($this->access_role)) { if(!$this->getObject('user')->hasRole($this->access_role)) { return false; } } return true; }
[ "public", "function", "canAccess", "(", ")", "{", "//Check if the user needs to be authentic to access", "if", "(", "$", "this", "->", "hasProperty", "(", "'access'", ")", "&&", "!", "empty", "(", "$", "this", "->", "access", ")", ")", "{", "if", "(", "!", "$", "this", "->", "getObject", "(", "'user'", ")", "->", "isAuthentic", "(", ")", ")", "{", "return", "false", ";", "}", "}", "//Check if the user is in the group(s) to access", "if", "(", "$", "this", "->", "hasProperty", "(", "'access_group'", ")", "&&", "!", "empty", "(", "$", "this", "->", "access_group", ")", ")", "{", "$", "groups", "=", "$", "this", "->", "getObject", "(", "'user'", ")", "->", "getGroups", "(", ")", ";", "if", "(", "!", "in_array", "(", "$", "this", "->", "access_group", ",", "$", "groups", ")", ")", "{", "return", "false", ";", "}", "}", "//Check if the user has the right role(s) to access", "if", "(", "$", "this", "->", "hasProperty", "(", "'access_role'", ")", "&&", "!", "empty", "(", "$", "this", "->", "access_role", ")", ")", "{", "if", "(", "!", "$", "this", "->", "getObject", "(", "'user'", ")", "->", "hasRole", "(", "$", "this", "->", "access_role", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Check if the row can be accessed @return boolean True on success, false otherwise
[ "Check", "if", "the", "row", "can", "be", "accessed" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/database/behavior/accessible.php#L29-L58
29,425
timble/kodekit
code/filesystem/mimetype/mimetype.php
FilesystemMimetype.registerResolver
public function registerResolver($resolver, array $config = array()) { if(!($resolver instanceof FilesystemMimetypeInterface)) { if(is_string($resolver) && strpos($resolver, '.') === false ) { $identifier = $this->getIdentifier()->toArray(); $identifier['path'][] = 'mimetype'; $identifier['name'] = $resolver; $identifier = $this->getIdentifier($identifier); } else $identifier = $this->getIdentifier($resolver); $resolver = $identifier; } else $identifier = $resolver->getIdentifier(); //Merge the config for the resolver $identifier->getConfig()->merge($config); //Store the resolver $name = $identifier->name; if(isset($this->__resolvers[$name])) { unset($this->__resolvers[$name]); } $this->__resolvers[$name] = $resolver; return $this; }
php
public function registerResolver($resolver, array $config = array()) { if(!($resolver instanceof FilesystemMimetypeInterface)) { if(is_string($resolver) && strpos($resolver, '.') === false ) { $identifier = $this->getIdentifier()->toArray(); $identifier['path'][] = 'mimetype'; $identifier['name'] = $resolver; $identifier = $this->getIdentifier($identifier); } else $identifier = $this->getIdentifier($resolver); $resolver = $identifier; } else $identifier = $resolver->getIdentifier(); //Merge the config for the resolver $identifier->getConfig()->merge($config); //Store the resolver $name = $identifier->name; if(isset($this->__resolvers[$name])) { unset($this->__resolvers[$name]); } $this->__resolvers[$name] = $resolver; return $this; }
[ "public", "function", "registerResolver", "(", "$", "resolver", ",", "array", "$", "config", "=", "array", "(", ")", ")", "{", "if", "(", "!", "(", "$", "resolver", "instanceof", "FilesystemMimetypeInterface", ")", ")", "{", "if", "(", "is_string", "(", "$", "resolver", ")", "&&", "strpos", "(", "$", "resolver", ",", "'.'", ")", "===", "false", ")", "{", "$", "identifier", "=", "$", "this", "->", "getIdentifier", "(", ")", "->", "toArray", "(", ")", ";", "$", "identifier", "[", "'path'", "]", "[", "]", "=", "'mimetype'", ";", "$", "identifier", "[", "'name'", "]", "=", "$", "resolver", ";", "$", "identifier", "=", "$", "this", "->", "getIdentifier", "(", "$", "identifier", ")", ";", "}", "else", "$", "identifier", "=", "$", "this", "->", "getIdentifier", "(", "$", "resolver", ")", ";", "$", "resolver", "=", "$", "identifier", ";", "}", "else", "$", "identifier", "=", "$", "resolver", "->", "getIdentifier", "(", ")", ";", "//Merge the config for the resolver", "$", "identifier", "->", "getConfig", "(", ")", "->", "merge", "(", "$", "config", ")", ";", "//Store the resolver", "$", "name", "=", "$", "identifier", "->", "name", ";", "if", "(", "isset", "(", "$", "this", "->", "__resolvers", "[", "$", "name", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "__resolvers", "[", "$", "name", "]", ")", ";", "}", "$", "this", "->", "__resolvers", "[", "$", "name", "]", "=", "$", "resolver", ";", "return", "$", "this", ";", "}" ]
Registers a new mime type resolver. The last added mimetype resolver is preferred over previously registered ones. @param mixed $resolver An object that implements FilesystemMimetypeInterface, ObjectIdentifier object or valid identifier string @param array $config An optional associative array of configuration options @return $this
[ "Registers", "a", "new", "mime", "type", "resolver", "." ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/filesystem/mimetype/mimetype.php#L95-L126
29,426
timble/kodekit
code/filesystem/mimetype/mimetype.php
FilesystemMimetype.fromPath
public function fromPath($path) { if (!is_file($path)) { throw new \RuntimeException('File not found at '.$path); } if (!is_readable($path)) { throw new \RuntimeException('File not readable at '.$path); } $mimetype = null; foreach (array_reverse($this->__resolvers) as $name => $resolver) { //Lazy create the resolver if(!($resolver instanceof FilesystemMimetypeInterface)) { $resolver = $this->getObject($resolver); if (!$resolver instanceof FilesystemMimetypeInterface) { throw new \UnexpectedValueException('Resolver does not implement FilesystemMimetypeInterface'); } $this->__resolvers[$name] = $resolver; } /* @var $resolver FilesystemMimetypeInterface */ if (null !== $mimetype = $resolver->fromPath($path)) { break; } } return $mimetype; }
php
public function fromPath($path) { if (!is_file($path)) { throw new \RuntimeException('File not found at '.$path); } if (!is_readable($path)) { throw new \RuntimeException('File not readable at '.$path); } $mimetype = null; foreach (array_reverse($this->__resolvers) as $name => $resolver) { //Lazy create the resolver if(!($resolver instanceof FilesystemMimetypeInterface)) { $resolver = $this->getObject($resolver); if (!$resolver instanceof FilesystemMimetypeInterface) { throw new \UnexpectedValueException('Resolver does not implement FilesystemMimetypeInterface'); } $this->__resolvers[$name] = $resolver; } /* @var $resolver FilesystemMimetypeInterface */ if (null !== $mimetype = $resolver->fromPath($path)) { break; } } return $mimetype; }
[ "public", "function", "fromPath", "(", "$", "path", ")", "{", "if", "(", "!", "is_file", "(", "$", "path", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'File not found at '", ".", "$", "path", ")", ";", "}", "if", "(", "!", "is_readable", "(", "$", "path", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'File not readable at '", ".", "$", "path", ")", ";", "}", "$", "mimetype", "=", "null", ";", "foreach", "(", "array_reverse", "(", "$", "this", "->", "__resolvers", ")", "as", "$", "name", "=>", "$", "resolver", ")", "{", "//Lazy create the resolver", "if", "(", "!", "(", "$", "resolver", "instanceof", "FilesystemMimetypeInterface", ")", ")", "{", "$", "resolver", "=", "$", "this", "->", "getObject", "(", "$", "resolver", ")", ";", "if", "(", "!", "$", "resolver", "instanceof", "FilesystemMimetypeInterface", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "'Resolver does not implement FilesystemMimetypeInterface'", ")", ";", "}", "$", "this", "->", "__resolvers", "[", "$", "name", "]", "=", "$", "resolver", ";", "}", "/* @var $resolver FilesystemMimetypeInterface */", "if", "(", "null", "!==", "$", "mimetype", "=", "$", "resolver", "->", "fromPath", "(", "$", "path", ")", ")", "{", "break", ";", "}", "}", "return", "$", "mimetype", ";", "}" ]
Tries to find the mime type of the given file from it's file path. The file is passed to each registered mime type resolver in FILO order. Once a resolver returns a value that is not NULL, the result is returned. @param string $path The path to the file @throws \LogicException If the file cannot be found @throws \RuntimeException If the file is not readable @throws \UnexpectedValueException If the resolver doesn't implement FilesystemMimetypeInterface @return string The mime type or NULL, if none could be found
[ "Tries", "to", "find", "the", "mime", "type", "of", "the", "given", "file", "from", "it", "s", "file", "path", "." ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/filesystem/mimetype/mimetype.php#L142-L175
29,427
locomotivemtl/charcoal-core
src/Charcoal/Model/AbstractMetadata.php
AbstractMetadata.property
public function property($propertyIdent = null) { if (isset($this->properties[$propertyIdent])) { return $this->properties[$propertyIdent]; } else { return null; } }
php
public function property($propertyIdent = null) { if (isset($this->properties[$propertyIdent])) { return $this->properties[$propertyIdent]; } else { return null; } }
[ "public", "function", "property", "(", "$", "propertyIdent", "=", "null", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "properties", "[", "$", "propertyIdent", "]", ")", ")", "{", "return", "$", "this", "->", "properties", "[", "$", "propertyIdent", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Retrieve the given property. @param string $propertyIdent The property identifier. @return array|null
[ "Retrieve", "the", "given", "property", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/AbstractMetadata.php#L96-L103
29,428
locomotivemtl/charcoal-core
src/Charcoal/Model/AbstractMetadata.php
AbstractMetadata.propertyObject
public function propertyObject($propertyIdent) { if (!isset($this->propertiesObjects[$propertyIdent])) { return null; } else { return $this->propertiesObjects[$propertyIdent]; } }
php
public function propertyObject($propertyIdent) { if (!isset($this->propertiesObjects[$propertyIdent])) { return null; } else { return $this->propertiesObjects[$propertyIdent]; } }
[ "public", "function", "propertyObject", "(", "$", "propertyIdent", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "propertiesObjects", "[", "$", "propertyIdent", "]", ")", ")", "{", "return", "null", ";", "}", "else", "{", "return", "$", "this", "->", "propertiesObjects", "[", "$", "propertyIdent", "]", ";", "}", "}" ]
Retrieve the given property as an object. @param string $propertyIdent The property (identifier) to return, as an object. @return PropertyInterface|null
[ "Retrieve", "the", "given", "property", "as", "an", "object", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/AbstractMetadata.php#L124-L131
29,429
timble/kodekit
code/template/helper/actionbar.php
TemplateHelperActionbar.render
public function render($config = array()) { $config = new ObjectConfigJson($config); $config->append(array( 'toolbar' => null, 'attribs' => array('class' => array('k-toolbar', 'k-js-toolbar')) )); $html = ''; if(isset($config->toolbar) && count($config->toolbar)) { //Force the id $config->attribs['id'] = 'toolbar-'.$config->toolbar->getType(); $html .= '<div '.$this->buildAttributes($config->attribs).'>'; foreach ($config->toolbar as $command) { $name = $command->getName(); if(method_exists($this, $name)) { $html .= $this->$name(ObjectConfig::unbox($command)); } else { $html .= $this->command(ObjectConfig::unbox($command)); } } $html .= '</div>'; } return $html; }
php
public function render($config = array()) { $config = new ObjectConfigJson($config); $config->append(array( 'toolbar' => null, 'attribs' => array('class' => array('k-toolbar', 'k-js-toolbar')) )); $html = ''; if(isset($config->toolbar) && count($config->toolbar)) { //Force the id $config->attribs['id'] = 'toolbar-'.$config->toolbar->getType(); $html .= '<div '.$this->buildAttributes($config->attribs).'>'; foreach ($config->toolbar as $command) { $name = $command->getName(); if(method_exists($this, $name)) { $html .= $this->$name(ObjectConfig::unbox($command)); } else { $html .= $this->command(ObjectConfig::unbox($command)); } } $html .= '</div>'; } return $html; }
[ "public", "function", "render", "(", "$", "config", "=", "array", "(", ")", ")", "{", "$", "config", "=", "new", "ObjectConfigJson", "(", "$", "config", ")", ";", "$", "config", "->", "append", "(", "array", "(", "'toolbar'", "=>", "null", ",", "'attribs'", "=>", "array", "(", "'class'", "=>", "array", "(", "'k-toolbar'", ",", "'k-js-toolbar'", ")", ")", ")", ")", ";", "$", "html", "=", "''", ";", "if", "(", "isset", "(", "$", "config", "->", "toolbar", ")", "&&", "count", "(", "$", "config", "->", "toolbar", ")", ")", "{", "//Force the id", "$", "config", "->", "attribs", "[", "'id'", "]", "=", "'toolbar-'", ".", "$", "config", "->", "toolbar", "->", "getType", "(", ")", ";", "$", "html", ".=", "'<div '", ".", "$", "this", "->", "buildAttributes", "(", "$", "config", "->", "attribs", ")", ".", "'>'", ";", "foreach", "(", "$", "config", "->", "toolbar", "as", "$", "command", ")", "{", "$", "name", "=", "$", "command", "->", "getName", "(", ")", ";", "if", "(", "method_exists", "(", "$", "this", ",", "$", "name", ")", ")", "{", "$", "html", ".=", "$", "this", "->", "$", "name", "(", "ObjectConfig", "::", "unbox", "(", "$", "command", ")", ")", ";", "}", "else", "{", "$", "html", ".=", "$", "this", "->", "command", "(", "ObjectConfig", "::", "unbox", "(", "$", "command", ")", ")", ";", "}", "}", "$", "html", ".=", "'</div>'", ";", "}", "return", "$", "html", ";", "}" ]
Render the action bar @param array $config An optional array with configuration options @return string Html
[ "Render", "the", "action", "bar" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/template/helper/actionbar.php#L26-L57
29,430
timble/kodekit
code/template/helper/actionbar.php
TemplateHelperActionbar.dialog
public function dialog($config = array()) { $html = $this->createHelper('behavior')->modal(); $html .= $this->command($config); return $html; }
php
public function dialog($config = array()) { $html = $this->createHelper('behavior')->modal(); $html .= $this->command($config); return $html; }
[ "public", "function", "dialog", "(", "$", "config", "=", "array", "(", ")", ")", "{", "$", "html", "=", "$", "this", "->", "createHelper", "(", "'behavior'", ")", "->", "modal", "(", ")", ";", "$", "html", ".=", "$", "this", "->", "command", "(", "$", "config", ")", ";", "return", "$", "html", ";", "}" ]
Render a dialog button @param array $config An optional array with configuration options @return string Html
[ "Render", "a", "dialog", "button" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/template/helper/actionbar.php#L144-L150
29,431
rosasurfer/ministruts
src/ministruts/ActionMapping.php
ActionMapping.setName
public function setName($name) { if ($this->configured) throw new IllegalStateException('Configuration is frozen'); if (!strlen($name=trim($name))) throw new StrutsConfigException('<mapping name="'.func_get_arg(0).'"'.($this->path ? ' path="'.$this->path.'"':'').': Illegal name (empty value).'); $this->name = $name; return $this; }
php
public function setName($name) { if ($this->configured) throw new IllegalStateException('Configuration is frozen'); if (!strlen($name=trim($name))) throw new StrutsConfigException('<mapping name="'.func_get_arg(0).'"'.($this->path ? ' path="'.$this->path.'"':'').': Illegal name (empty value).'); $this->name = $name; return $this; }
[ "public", "function", "setName", "(", "$", "name", ")", "{", "if", "(", "$", "this", "->", "configured", ")", "throw", "new", "IllegalStateException", "(", "'Configuration is frozen'", ")", ";", "if", "(", "!", "strlen", "(", "$", "name", "=", "trim", "(", "$", "name", ")", ")", ")", "throw", "new", "StrutsConfigException", "(", "'<mapping name=\"'", ".", "func_get_arg", "(", "0", ")", ".", "'\"'", ".", "(", "$", "this", "->", "path", "?", "' path=\"'", ".", "$", "this", "->", "path", ".", "'\"'", ":", "''", ")", ".", "': Illegal name (empty value).'", ")", ";", "$", "this", "->", "name", "=", "$", "name", ";", "return", "$", "this", ";", "}" ]
Set the mapping's name. @param string $name @return $this @throws StrutsConfigException on configuration errors
[ "Set", "the", "mapping", "s", "name", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/ActionMapping.php#L90-L96
29,432
rosasurfer/ministruts
src/ministruts/ActionMapping.php
ActionMapping.setPath
public function setPath($path) { if ($this->configured) throw new IllegalStateException('Configuration is frozen'); if ($path[0] != '/') throw new StrutsConfigException('<mapping'.($this->name ? ' name="'.$this->name.'"':'').' path="'.$path.'": Illegal path (value must start with a slash "/").'); $this->path = $path; return $this; }
php
public function setPath($path) { if ($this->configured) throw new IllegalStateException('Configuration is frozen'); if ($path[0] != '/') throw new StrutsConfigException('<mapping'.($this->name ? ' name="'.$this->name.'"':'').' path="'.$path.'": Illegal path (value must start with a slash "/").'); $this->path = $path; return $this; }
[ "public", "function", "setPath", "(", "$", "path", ")", "{", "if", "(", "$", "this", "->", "configured", ")", "throw", "new", "IllegalStateException", "(", "'Configuration is frozen'", ")", ";", "if", "(", "$", "path", "[", "0", "]", "!=", "'/'", ")", "throw", "new", "StrutsConfigException", "(", "'<mapping'", ".", "(", "$", "this", "->", "name", "?", "' name=\"'", ".", "$", "this", "->", "name", ".", "'\"'", ":", "''", ")", ".", "' path=\"'", ".", "$", "path", ".", "'\": Illegal path (value must start with a slash \"/\").'", ")", ";", "$", "this", "->", "path", "=", "$", "path", ";", "return", "$", "this", ";", "}" ]
Set the mapping's path. @param string $path @return $this @throws StrutsConfigException on configuration errors
[ "Set", "the", "mapping", "s", "path", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/ActionMapping.php#L118-L124
29,433
rosasurfer/ministruts
src/ministruts/ActionMapping.php
ActionMapping.isSupportedMethod
public function isSupportedMethod($method) { if (!is_string($method)) throw new IllegalTypeException('Illegal type of parameter $method: '.gettype($method)); return isset($this->methods[strtoupper($method)]); }
php
public function isSupportedMethod($method) { if (!is_string($method)) throw new IllegalTypeException('Illegal type of parameter $method: '.gettype($method)); return isset($this->methods[strtoupper($method)]); }
[ "public", "function", "isSupportedMethod", "(", "$", "method", ")", "{", "if", "(", "!", "is_string", "(", "$", "method", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $method: '", ".", "gettype", "(", "$", "method", ")", ")", ";", "return", "isset", "(", "$", "this", "->", "methods", "[", "strtoupper", "(", "$", "method", ")", "]", ")", ";", "}" ]
Whether the mapping is configured to handle requests of the specified HTTP method. @param string $method - HTTP method verb @return bool
[ "Whether", "the", "mapping", "is", "configured", "to", "handle", "requests", "of", "the", "specified", "HTTP", "method", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/ActionMapping.php#L144-L147
29,434
rosasurfer/ministruts
src/ministruts/ActionMapping.php
ActionMapping.setMethod
public function setMethod($method) { if ($this->configured) throw new IllegalStateException('Configuration is frozen'); $name = $this->name ? ' name="'.$this->name.'"':''; $path = $this->path ? ' path="'.$this->path.'"':''; $method = strtoupper($method); if ($method!='GET' && $method!='POST') throw new StrutsConfigException('<mapping'.$name.''.$path.' methods="'.func_get_arg(0).'": Invalid HTTP method.'); $this->methods[$method] = true; return $this; }
php
public function setMethod($method) { if ($this->configured) throw new IllegalStateException('Configuration is frozen'); $name = $this->name ? ' name="'.$this->name.'"':''; $path = $this->path ? ' path="'.$this->path.'"':''; $method = strtoupper($method); if ($method!='GET' && $method!='POST') throw new StrutsConfigException('<mapping'.$name.''.$path.' methods="'.func_get_arg(0).'": Invalid HTTP method.'); $this->methods[$method] = true; return $this; }
[ "public", "function", "setMethod", "(", "$", "method", ")", "{", "if", "(", "$", "this", "->", "configured", ")", "throw", "new", "IllegalStateException", "(", "'Configuration is frozen'", ")", ";", "$", "name", "=", "$", "this", "->", "name", "?", "' name=\"'", ".", "$", "this", "->", "name", ".", "'\"'", ":", "''", ";", "$", "path", "=", "$", "this", "->", "path", "?", "' path=\"'", ".", "$", "this", "->", "path", ".", "'\"'", ":", "''", ";", "$", "method", "=", "strtoupper", "(", "$", "method", ")", ";", "if", "(", "$", "method", "!=", "'GET'", "&&", "$", "method", "!=", "'POST'", ")", "throw", "new", "StrutsConfigException", "(", "'<mapping'", ".", "$", "name", ".", "''", ".", "$", "path", ".", "' methods=\"'", ".", "func_get_arg", "(", "0", ")", ".", "'\": Invalid HTTP method.'", ")", ";", "$", "this", "->", "methods", "[", "$", "method", "]", "=", "true", ";", "return", "$", "this", ";", "}" ]
Set the HTTP methods the mapping will be able to handle. @param string $method - HTTP method verb @return $this @throws StrutsConfigException on configuration errors
[ "Set", "the", "HTTP", "methods", "the", "mapping", "will", "be", "able", "to", "handle", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/ActionMapping.php#L159-L169
29,435
rosasurfer/ministruts
src/ministruts/ActionMapping.php
ActionMapping.setRoles
public function setRoles($roles) { if ($this->configured) throw new IllegalStateException('Configuration is frozen'); $name = $this->name ? ' name="'.$this->name.'"':''; $path = $this->path ? ' path="'.$this->path.'"':''; //static $pattern = '/^!?[A-Za-z_][A-Za-z0-9_]*(,!?[A-Za-z_][A-Za-z0-9_]*)*$/'; static $pattern = '/^!?[A-Za-z_][A-Za-z0-9_]*$/'; if (!strlen($roles) || !preg_match($pattern, $roles)) throw new StrutsConfigException('<mapping'.$name.$path.' roles="'.$roles.'": Invalid roles expression.'); // check for invalid id combinations, e.g. "Member,!Member" $tokens = explode(',', $roles); $keys = \array_flip($tokens); foreach ($tokens as $role) { if (isset($keys['!'.$role])) throw new StrutsConfigException('<mapping'.$name.$path.' roles="'.$roles.'": Invalid roles expression.'); } // remove duplicates $this->roles = join(',', \array_flip($keys)); return $this; }
php
public function setRoles($roles) { if ($this->configured) throw new IllegalStateException('Configuration is frozen'); $name = $this->name ? ' name="'.$this->name.'"':''; $path = $this->path ? ' path="'.$this->path.'"':''; //static $pattern = '/^!?[A-Za-z_][A-Za-z0-9_]*(,!?[A-Za-z_][A-Za-z0-9_]*)*$/'; static $pattern = '/^!?[A-Za-z_][A-Za-z0-9_]*$/'; if (!strlen($roles) || !preg_match($pattern, $roles)) throw new StrutsConfigException('<mapping'.$name.$path.' roles="'.$roles.'": Invalid roles expression.'); // check for invalid id combinations, e.g. "Member,!Member" $tokens = explode(',', $roles); $keys = \array_flip($tokens); foreach ($tokens as $role) { if (isset($keys['!'.$role])) throw new StrutsConfigException('<mapping'.$name.$path.' roles="'.$roles.'": Invalid roles expression.'); } // remove duplicates $this->roles = join(',', \array_flip($keys)); return $this; }
[ "public", "function", "setRoles", "(", "$", "roles", ")", "{", "if", "(", "$", "this", "->", "configured", ")", "throw", "new", "IllegalStateException", "(", "'Configuration is frozen'", ")", ";", "$", "name", "=", "$", "this", "->", "name", "?", "' name=\"'", ".", "$", "this", "->", "name", ".", "'\"'", ":", "''", ";", "$", "path", "=", "$", "this", "->", "path", "?", "' path=\"'", ".", "$", "this", "->", "path", ".", "'\"'", ":", "''", ";", "//static $pattern = '/^!?[A-Za-z_][A-Za-z0-9_]*(,!?[A-Za-z_][A-Za-z0-9_]*)*$/';", "static", "$", "pattern", "=", "'/^!?[A-Za-z_][A-Za-z0-9_]*$/'", ";", "if", "(", "!", "strlen", "(", "$", "roles", ")", "||", "!", "preg_match", "(", "$", "pattern", ",", "$", "roles", ")", ")", "throw", "new", "StrutsConfigException", "(", "'<mapping'", ".", "$", "name", ".", "$", "path", ".", "' roles=\"'", ".", "$", "roles", ".", "'\": Invalid roles expression.'", ")", ";", "// check for invalid id combinations, e.g. \"Member,!Member\"", "$", "tokens", "=", "explode", "(", "','", ",", "$", "roles", ")", ";", "$", "keys", "=", "\\", "array_flip", "(", "$", "tokens", ")", ";", "foreach", "(", "$", "tokens", "as", "$", "role", ")", "{", "if", "(", "isset", "(", "$", "keys", "[", "'!'", ".", "$", "role", "]", ")", ")", "throw", "new", "StrutsConfigException", "(", "'<mapping'", ".", "$", "name", ".", "$", "path", ".", "' roles=\"'", ".", "$", "roles", ".", "'\": Invalid roles expression.'", ")", ";", "}", "// remove duplicates", "$", "this", "->", "roles", "=", "join", "(", "','", ",", "\\", "array_flip", "(", "$", "keys", ")", ")", ";", "return", "$", "this", ";", "}" ]
Set the mapping's role restrictions. @param string $roles - role expression @return $this @throws StrutsConfigException on configuration errors
[ "Set", "the", "mapping", "s", "role", "restrictions", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/ActionMapping.php#L191-L211
29,436
rosasurfer/ministruts
src/ministruts/ActionMapping.php
ActionMapping.freeze
public function freeze() { if ($this->configured) throw new IllegalStateException('Configuration is frozen'); $name = $this->name ? ' name="'.$this->name.'"':''; $path = $this->path ? ' path="'.$this->path.'"':''; $mapping = $name.$path; if (!$this->path) throw new StrutsConfigException('<mapping'.$mapping.': A "path" attribute must be configured for '.$this); if (!$this->formClassName && $this->formValidateFirst) throw new StrutsConfigException('<mapping'.$mapping.': A form must be configured if "form-validate-first" is set to "true".'); if (!$this->actionClassName && !$this->forward) { if (!$this->formClassName || !$this->formValidateFirst) throw new StrutsConfigException('<mapping'.$mapping.': Either an "action", "include", "forward" or "redirect" attribute must be specified.'); if (!$this->formClassName || !$this->formValidateFirst) { throw new StrutsConfigException('<mapping'.$mapping.': Either an "action", "include", "forward" or "redirect" attribute must be specified.'); } elseif ($this->formClassName && $this->formValidateFirst) { if (!isset($this->forwards[ActionForward::VALIDATION_SUCCESS_KEY]) || !isset($this->forwards[ActionForward::VALIDATION_ERROR_KEY])) throw new StrutsConfigException('<mapping'.$mapping.' form="'.$this->formClassName.'": A "success" and "error" forward must be configured to validate the form.'); } } $this->configured = true; return $this; }
php
public function freeze() { if ($this->configured) throw new IllegalStateException('Configuration is frozen'); $name = $this->name ? ' name="'.$this->name.'"':''; $path = $this->path ? ' path="'.$this->path.'"':''; $mapping = $name.$path; if (!$this->path) throw new StrutsConfigException('<mapping'.$mapping.': A "path" attribute must be configured for '.$this); if (!$this->formClassName && $this->formValidateFirst) throw new StrutsConfigException('<mapping'.$mapping.': A form must be configured if "form-validate-first" is set to "true".'); if (!$this->actionClassName && !$this->forward) { if (!$this->formClassName || !$this->formValidateFirst) throw new StrutsConfigException('<mapping'.$mapping.': Either an "action", "include", "forward" or "redirect" attribute must be specified.'); if (!$this->formClassName || !$this->formValidateFirst) { throw new StrutsConfigException('<mapping'.$mapping.': Either an "action", "include", "forward" or "redirect" attribute must be specified.'); } elseif ($this->formClassName && $this->formValidateFirst) { if (!isset($this->forwards[ActionForward::VALIDATION_SUCCESS_KEY]) || !isset($this->forwards[ActionForward::VALIDATION_ERROR_KEY])) throw new StrutsConfigException('<mapping'.$mapping.' form="'.$this->formClassName.'": A "success" and "error" forward must be configured to validate the form.'); } } $this->configured = true; return $this; }
[ "public", "function", "freeze", "(", ")", "{", "if", "(", "$", "this", "->", "configured", ")", "throw", "new", "IllegalStateException", "(", "'Configuration is frozen'", ")", ";", "$", "name", "=", "$", "this", "->", "name", "?", "' name=\"'", ".", "$", "this", "->", "name", ".", "'\"'", ":", "''", ";", "$", "path", "=", "$", "this", "->", "path", "?", "' path=\"'", ".", "$", "this", "->", "path", ".", "'\"'", ":", "''", ";", "$", "mapping", "=", "$", "name", ".", "$", "path", ";", "if", "(", "!", "$", "this", "->", "path", ")", "throw", "new", "StrutsConfigException", "(", "'<mapping'", ".", "$", "mapping", ".", "': A \"path\" attribute must be configured for '", ".", "$", "this", ")", ";", "if", "(", "!", "$", "this", "->", "formClassName", "&&", "$", "this", "->", "formValidateFirst", ")", "throw", "new", "StrutsConfigException", "(", "'<mapping'", ".", "$", "mapping", ".", "': A form must be configured if \"form-validate-first\" is set to \"true\".'", ")", ";", "if", "(", "!", "$", "this", "->", "actionClassName", "&&", "!", "$", "this", "->", "forward", ")", "{", "if", "(", "!", "$", "this", "->", "formClassName", "||", "!", "$", "this", "->", "formValidateFirst", ")", "throw", "new", "StrutsConfigException", "(", "'<mapping'", ".", "$", "mapping", ".", "': Either an \"action\", \"include\", \"forward\" or \"redirect\" attribute must be specified.'", ")", ";", "if", "(", "!", "$", "this", "->", "formClassName", "||", "!", "$", "this", "->", "formValidateFirst", ")", "{", "throw", "new", "StrutsConfigException", "(", "'<mapping'", ".", "$", "mapping", ".", "': Either an \"action\", \"include\", \"forward\" or \"redirect\" attribute must be specified.'", ")", ";", "}", "elseif", "(", "$", "this", "->", "formClassName", "&&", "$", "this", "->", "formValidateFirst", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "forwards", "[", "ActionForward", "::", "VALIDATION_SUCCESS_KEY", "]", ")", "||", "!", "isset", "(", "$", "this", "->", "forwards", "[", "ActionForward", "::", "VALIDATION_ERROR_KEY", "]", ")", ")", "throw", "new", "StrutsConfigException", "(", "'<mapping'", ".", "$", "mapping", ".", "' form=\"'", ".", "$", "this", "->", "formClassName", ".", "'\": A \"success\" and \"error\" forward must be configured to validate the form.'", ")", ";", "}", "}", "$", "this", "->", "configured", "=", "true", ";", "return", "$", "this", ";", "}" ]
Lock the mapping's configuration. Called after all properties of the mapping are set. @return $this @throws StrutsConfigException on configuration errors
[ "Lock", "the", "mapping", "s", "configuration", ".", "Called", "after", "all", "properties", "of", "the", "mapping", "are", "set", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/ActionMapping.php#L443-L466
29,437
rosasurfer/ministruts
src/util/Validator.php
Validator.isIPAddress
public static function isIPAddress($string, $returnBytes = false) { static $pattern = '/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/'; $result = is_string($string) && strlen($string) && preg_match($pattern, $string, $bytes); if ($result) { \array_shift($bytes); foreach ($bytes as $i => $byte) { $b = (int) $byte; if (!is_string($byte) || $b > 255) return false; $bytes[$i] = $b; } if ($bytes[0] == 0) return false; return $returnBytes ? $bytes : true; } return false; }
php
public static function isIPAddress($string, $returnBytes = false) { static $pattern = '/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/'; $result = is_string($string) && strlen($string) && preg_match($pattern, $string, $bytes); if ($result) { \array_shift($bytes); foreach ($bytes as $i => $byte) { $b = (int) $byte; if (!is_string($byte) || $b > 255) return false; $bytes[$i] = $b; } if ($bytes[0] == 0) return false; return $returnBytes ? $bytes : true; } return false; }
[ "public", "static", "function", "isIPAddress", "(", "$", "string", ",", "$", "returnBytes", "=", "false", ")", "{", "static", "$", "pattern", "=", "'/^([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/'", ";", "$", "result", "=", "is_string", "(", "$", "string", ")", "&&", "strlen", "(", "$", "string", ")", "&&", "preg_match", "(", "$", "pattern", ",", "$", "string", ",", "$", "bytes", ")", ";", "if", "(", "$", "result", ")", "{", "\\", "array_shift", "(", "$", "bytes", ")", ";", "foreach", "(", "$", "bytes", "as", "$", "i", "=>", "$", "byte", ")", "{", "$", "b", "=", "(", "int", ")", "$", "byte", ";", "if", "(", "!", "is_string", "(", "$", "byte", ")", "||", "$", "b", ">", "255", ")", "return", "false", ";", "$", "bytes", "[", "$", "i", "]", "=", "$", "b", ";", "}", "if", "(", "$", "bytes", "[", "0", "]", "==", "0", ")", "return", "false", ";", "return", "$", "returnBytes", "?", "$", "bytes", ":", "true", ";", "}", "return", "false", ";", "}" ]
Ob der uebergebene String eine syntaktisch gueltige IP-Adresse ist. @param string $string - der zu ueberpruefende String @param bool $returnBytes [optional] - Typ des Rueckgabewertes FALSE: Boolean (default) TRUE: Array mit den Adressbytes oder FALSE, wenn der String keine gueltige IP-Adresse darstellt @return bool|array
[ "Ob", "der", "uebergebene", "String", "eine", "syntaktisch", "gueltige", "IP", "-", "Adresse", "ist", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/util/Validator.php#L25-L46
29,438
rosasurfer/ministruts
src/util/Validator.php
Validator.isIPLanAddress
public static function isIPLanAddress($string) { $bytes = self::isIPAddress($string, true); if ($bytes) { if ($bytes[0] == 10) // 10.0.0.0 - 10.255.255.255 return true; if ($bytes[0] == 172) // 172.16.0.0 - 172.31.255.255 return (15 < $bytes[1] && $bytes[1] < 32); if ($bytes[0]==192 && $bytes[1]==168) // 192.168.0.0 - 192.168.255.255 return true; } return false; }
php
public static function isIPLanAddress($string) { $bytes = self::isIPAddress($string, true); if ($bytes) { if ($bytes[0] == 10) // 10.0.0.0 - 10.255.255.255 return true; if ($bytes[0] == 172) // 172.16.0.0 - 172.31.255.255 return (15 < $bytes[1] && $bytes[1] < 32); if ($bytes[0]==192 && $bytes[1]==168) // 192.168.0.0 - 192.168.255.255 return true; } return false; }
[ "public", "static", "function", "isIPLanAddress", "(", "$", "string", ")", "{", "$", "bytes", "=", "self", "::", "isIPAddress", "(", "$", "string", ",", "true", ")", ";", "if", "(", "$", "bytes", ")", "{", "if", "(", "$", "bytes", "[", "0", "]", "==", "10", ")", "// 10.0.0.0 - 10.255.255.255", "return", "true", ";", "if", "(", "$", "bytes", "[", "0", "]", "==", "172", ")", "// 172.16.0.0 - 172.31.255.255", "return", "(", "15", "<", "$", "bytes", "[", "1", "]", "&&", "$", "bytes", "[", "1", "]", "<", "32", ")", ";", "if", "(", "$", "bytes", "[", "0", "]", "==", "192", "&&", "$", "bytes", "[", "1", "]", "==", "168", ")", "// 192.168.0.0 - 192.168.255.255", "return", "true", ";", "}", "return", "false", ";", "}" ]
Ob der uebergebene String eine syntaktisch gueltige IP-Adresse eines lokalen Netzwerks ist. @param string $string - der zu ueberpruefende String @return bool
[ "Ob", "der", "uebergebene", "String", "eine", "syntaktisch", "gueltige", "IP", "-", "Adresse", "eines", "lokalen", "Netzwerks", "ist", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/util/Validator.php#L56-L71
29,439
rosasurfer/ministruts
src/util/Validator.php
Validator.isIPWanAddress
public static function isIPWanAddress($string) { $bytes = self::isIPAddress($string, true); // Die Logik entspricht dem Gegenteil von self:: isIPLanAdress() + zusaetzlicher Tests. if ($bytes) { if ($bytes[0] == 10) // 10.0.0.0 - 10.255.255.255 return false; if ($bytes[0] == 127) // 127.0.0.0 - 127.255.255.255 return false; if ($bytes[0]==169) // 169.0.0.0 - 169.255.255.255 !!! wem zugewiesen? niemandem? return false; if ($bytes[0] == 172) // 172.16.0.0 - 172.31.255.255 return !(15 < $bytes[1] && $bytes[1] < 32); if ($bytes[0]==192) // 192.168.0.0 - 192.168.255.255 return ($bytes[1]!=168); } // dieses TRUE ist eher spekulativ return true; }
php
public static function isIPWanAddress($string) { $bytes = self::isIPAddress($string, true); // Die Logik entspricht dem Gegenteil von self:: isIPLanAdress() + zusaetzlicher Tests. if ($bytes) { if ($bytes[0] == 10) // 10.0.0.0 - 10.255.255.255 return false; if ($bytes[0] == 127) // 127.0.0.0 - 127.255.255.255 return false; if ($bytes[0]==169) // 169.0.0.0 - 169.255.255.255 !!! wem zugewiesen? niemandem? return false; if ($bytes[0] == 172) // 172.16.0.0 - 172.31.255.255 return !(15 < $bytes[1] && $bytes[1] < 32); if ($bytes[0]==192) // 192.168.0.0 - 192.168.255.255 return ($bytes[1]!=168); } // dieses TRUE ist eher spekulativ return true; }
[ "public", "static", "function", "isIPWanAddress", "(", "$", "string", ")", "{", "$", "bytes", "=", "self", "::", "isIPAddress", "(", "$", "string", ",", "true", ")", ";", "// Die Logik entspricht dem Gegenteil von self:: isIPLanAdress() + zusaetzlicher Tests.", "if", "(", "$", "bytes", ")", "{", "if", "(", "$", "bytes", "[", "0", "]", "==", "10", ")", "// 10.0.0.0 - 10.255.255.255", "return", "false", ";", "if", "(", "$", "bytes", "[", "0", "]", "==", "127", ")", "// 127.0.0.0 - 127.255.255.255", "return", "false", ";", "if", "(", "$", "bytes", "[", "0", "]", "==", "169", ")", "// 169.0.0.0 - 169.255.255.255 !!! wem zugewiesen? niemandem?", "return", "false", ";", "if", "(", "$", "bytes", "[", "0", "]", "==", "172", ")", "// 172.16.0.0 - 172.31.255.255", "return", "!", "(", "15", "<", "$", "bytes", "[", "1", "]", "&&", "$", "bytes", "[", "1", "]", "<", "32", ")", ";", "if", "(", "$", "bytes", "[", "0", "]", "==", "192", ")", "// 192.168.0.0 - 192.168.255.255", "return", "(", "$", "bytes", "[", "1", "]", "!=", "168", ")", ";", "}", "// dieses TRUE ist eher spekulativ", "return", "true", ";", "}" ]
Ob der uebergebene String eine syntaktisch gueltige IP-Adresse eines externen Netzwerks ist. @param string $string - der zu ueberpruefende String @return bool
[ "Ob", "der", "uebergebene", "String", "eine", "syntaktisch", "gueltige", "IP", "-", "Adresse", "eines", "externen", "Netzwerks", "ist", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/util/Validator.php#L81-L104
29,440
rosasurfer/ministruts
src/util/Validator.php
Validator.isPhoneNumber
public static function isPhoneNumber($value) { if (!is_string($value)) return false; // handle empty value $value = trim($value); if (!strlen($value)) return false; // remove spaces $value = str_replace(' ', '', $value); // match numbers from BE, ES, BG, CH, A, UK, DE return (bool) preg_match('/^(00|\+)(32|34|359|41|43|44|49)-?[1-9](-?[0-9]){2,}$/', $value); // TODO: implement via https://github.com/giggsey/libphonenumber-for-php }
php
public static function isPhoneNumber($value) { if (!is_string($value)) return false; // handle empty value $value = trim($value); if (!strlen($value)) return false; // remove spaces $value = str_replace(' ', '', $value); // match numbers from BE, ES, BG, CH, A, UK, DE return (bool) preg_match('/^(00|\+)(32|34|359|41|43|44|49)-?[1-9](-?[0-9]){2,}$/', $value); // TODO: implement via https://github.com/giggsey/libphonenumber-for-php }
[ "public", "static", "function", "isPhoneNumber", "(", "$", "value", ")", "{", "if", "(", "!", "is_string", "(", "$", "value", ")", ")", "return", "false", ";", "// handle empty value", "$", "value", "=", "trim", "(", "$", "value", ")", ";", "if", "(", "!", "strlen", "(", "$", "value", ")", ")", "return", "false", ";", "// remove spaces", "$", "value", "=", "str_replace", "(", "' '", ",", "''", ",", "$", "value", ")", ";", "// match numbers from BE, ES, BG, CH, A, UK, DE", "return", "(", "bool", ")", "preg_match", "(", "'/^(00|\\+)(32|34|359|41|43|44|49)-?[1-9](-?[0-9]){2,}$/'", ",", "$", "value", ")", ";", "// TODO: implement via https://github.com/giggsey/libphonenumber-for-php", "}" ]
Whether the passed string represents a valid phone number. @param string $value @return bool
[ "Whether", "the", "passed", "string", "represents", "a", "valid", "phone", "number", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/util/Validator.php#L313-L327
29,441
rosasurfer/ministruts
src/util/Validator.php
Validator.isStreetNumber
public static function isStreetNumber($string) { static $pattern = '/^[0-9A-Za-z-\/]+$/'; return is_string($string) && strlen($string) && preg_match($pattern, strtolower($string)); }
php
public static function isStreetNumber($string) { static $pattern = '/^[0-9A-Za-z-\/]+$/'; return is_string($string) && strlen($string) && preg_match($pattern, strtolower($string)); }
[ "public", "static", "function", "isStreetNumber", "(", "$", "string", ")", "{", "static", "$", "pattern", "=", "'/^[0-9A-Za-z-\\/]+$/'", ";", "return", "is_string", "(", "$", "string", ")", "&&", "strlen", "(", "$", "string", ")", "&&", "preg_match", "(", "$", "pattern", ",", "strtolower", "(", "$", "string", ")", ")", ";", "}" ]
Ob der uebergebene String eine gueltige Hausnummer ist. @param string $string - der zu pruefende String @return bool
[ "Ob", "der", "uebergebene", "String", "eine", "gueltige", "Hausnummer", "ist", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/util/Validator.php#L402-L405
29,442
rosasurfer/ministruts
src/db/mysql/MySQLConnector.php
MySQLConnector.setUsername
protected function setUsername($name) { if (!is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name)); if (!strlen($name)) throw new InvalidArgumentException('Invalid parameter $name: "'.$name.'" (empty)'); $this->username = $name; return $this; }
php
protected function setUsername($name) { if (!is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name)); if (!strlen($name)) throw new InvalidArgumentException('Invalid parameter $name: "'.$name.'" (empty)'); $this->username = $name; return $this; }
[ "protected", "function", "setUsername", "(", "$", "name", ")", "{", "if", "(", "!", "is_string", "(", "$", "name", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $name: '", ".", "gettype", "(", "$", "name", ")", ")", ";", "if", "(", "!", "strlen", "(", "$", "name", ")", ")", "throw", "new", "InvalidArgumentException", "(", "'Invalid parameter $name: \"'", ".", "$", "name", ".", "'\" (empty)'", ")", ";", "$", "this", "->", "username", "=", "$", "name", ";", "return", "$", "this", ";", "}" ]
Set the username for the connection. @param string $name @return $this
[ "Set", "the", "username", "for", "the", "connection", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/mysql/MySQLConnector.php#L136-L142
29,443
rosasurfer/ministruts
src/db/mysql/MySQLConnector.php
MySQLConnector.setDatabase
protected function setDatabase($name) { if (isset($name) && !is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name)); if (!strlen($name)) $name = null; $this->database = $name; return $this; }
php
protected function setDatabase($name) { if (isset($name) && !is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name)); if (!strlen($name)) $name = null; $this->database = $name; return $this; }
[ "protected", "function", "setDatabase", "(", "$", "name", ")", "{", "if", "(", "isset", "(", "$", "name", ")", "&&", "!", "is_string", "(", "$", "name", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $name: '", ".", "gettype", "(", "$", "name", ")", ")", ";", "if", "(", "!", "strlen", "(", "$", "name", ")", ")", "$", "name", "=", "null", ";", "$", "this", "->", "database", "=", "$", "name", ";", "return", "$", "this", ";", "}" ]
Set the name of the default database schema to use. @param string $name - schema name @return $this
[ "Set", "the", "name", "of", "the", "default", "database", "schema", "to", "use", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/mysql/MySQLConnector.php#L168-L175
29,444
rosasurfer/ministruts
src/db/mysql/MySQLConnector.php
MySQLConnector.getConnectionDescription
protected function getConnectionDescription() { $host = $this->host; $port = $this->port ? ':'.$this->port : ''; $db = $this->database ? '/'.$this->database : ''; return $host.$port.$db; }
php
protected function getConnectionDescription() { $host = $this->host; $port = $this->port ? ':'.$this->port : ''; $db = $this->database ? '/'.$this->database : ''; return $host.$port.$db; }
[ "protected", "function", "getConnectionDescription", "(", ")", "{", "$", "host", "=", "$", "this", "->", "host", ";", "$", "port", "=", "$", "this", "->", "port", "?", "':'", ".", "$", "this", "->", "port", ":", "''", ";", "$", "db", "=", "$", "this", "->", "database", "?", "'/'", ".", "$", "this", "->", "database", ":", "''", ";", "return", "$", "host", ".", "$", "port", ".", "$", "db", ";", "}" ]
Return a textual description of the main database connection options. @return string
[ "Return", "a", "textual", "description", "of", "the", "main", "database", "connection", "options", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/mysql/MySQLConnector.php#L197-L202
29,445
rosasurfer/ministruts
src/db/mysql/MySQLConnector.php
MySQLConnector.selectDatabase
protected function selectDatabase() { if ($this->database !== null) { try { mysql_select_db($this->database, $this->hConnection) || trigger_error(mysql_error($this->hConnection), E_USER_ERROR); } catch (\Exception $ex) { $ex = new DatabaseException($ex->getMessage(), mysql_errno($this->hConnection), $ex); throw $ex->addMessage('Can not select database "'.$this->database.'"'); } } return $this; }
php
protected function selectDatabase() { if ($this->database !== null) { try { mysql_select_db($this->database, $this->hConnection) || trigger_error(mysql_error($this->hConnection), E_USER_ERROR); } catch (\Exception $ex) { $ex = new DatabaseException($ex->getMessage(), mysql_errno($this->hConnection), $ex); throw $ex->addMessage('Can not select database "'.$this->database.'"'); } } return $this; }
[ "protected", "function", "selectDatabase", "(", ")", "{", "if", "(", "$", "this", "->", "database", "!==", "null", ")", "{", "try", "{", "mysql_select_db", "(", "$", "this", "->", "database", ",", "$", "this", "->", "hConnection", ")", "||", "trigger_error", "(", "mysql_error", "(", "$", "this", "->", "hConnection", ")", ",", "E_USER_ERROR", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "$", "ex", "=", "new", "DatabaseException", "(", "$", "ex", "->", "getMessage", "(", ")", ",", "mysql_errno", "(", "$", "this", "->", "hConnection", ")", ",", "$", "ex", ")", ";", "throw", "$", "ex", "->", "addMessage", "(", "'Can not select database \"'", ".", "$", "this", "->", "database", ".", "'\"'", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Pre-select a configured database. @return $this
[ "Pre", "-", "select", "a", "configured", "database", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/mysql/MySQLConnector.php#L268-L279
29,446
rosasurfer/ministruts
src/db/mysql/MySQLConnector.php
MySQLConnector.begin
public function begin() { if ($this->transactionLevel < 0) throw new RuntimeException('Negative transaction nesting level detected: '.$this->transactionLevel); if (!$this->transactionLevel) $this->execute('start transaction'); $this->transactionLevel++; return $this; }
php
public function begin() { if ($this->transactionLevel < 0) throw new RuntimeException('Negative transaction nesting level detected: '.$this->transactionLevel); if (!$this->transactionLevel) $this->execute('start transaction'); $this->transactionLevel++; return $this; }
[ "public", "function", "begin", "(", ")", "{", "if", "(", "$", "this", "->", "transactionLevel", "<", "0", ")", "throw", "new", "RuntimeException", "(", "'Negative transaction nesting level detected: '", ".", "$", "this", "->", "transactionLevel", ")", ";", "if", "(", "!", "$", "this", "->", "transactionLevel", ")", "$", "this", "->", "execute", "(", "'start transaction'", ")", ";", "$", "this", "->", "transactionLevel", "++", ";", "return", "$", "this", ";", "}" ]
Start a new transaction. If there is already an active transaction only the transaction nesting level is increased. @return $this
[ "Start", "a", "new", "transaction", ".", "If", "there", "is", "already", "an", "active", "transaction", "only", "the", "transaction", "nesting", "level", "is", "increased", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/mysql/MySQLConnector.php#L448-L456
29,447
rosasurfer/ministruts
src/net/TorHelper.php
TorHelper.init
private static function init() { if (self::$logDebug === null) { $loglevel = Logger::getLogLevel(__CLASS__); self::$logDebug = ($loglevel <= L_DEBUG ); self::$logInfo = ($loglevel <= L_INFO ); self::$logNotice = ($loglevel <= L_NOTICE); } }
php
private static function init() { if (self::$logDebug === null) { $loglevel = Logger::getLogLevel(__CLASS__); self::$logDebug = ($loglevel <= L_DEBUG ); self::$logInfo = ($loglevel <= L_INFO ); self::$logNotice = ($loglevel <= L_NOTICE); } }
[ "private", "static", "function", "init", "(", ")", "{", "if", "(", "self", "::", "$", "logDebug", "===", "null", ")", "{", "$", "loglevel", "=", "Logger", "::", "getLogLevel", "(", "__CLASS__", ")", ";", "self", "::", "$", "logDebug", "=", "(", "$", "loglevel", "<=", "L_DEBUG", ")", ";", "self", "::", "$", "logInfo", "=", "(", "$", "loglevel", "<=", "L_INFO", ")", ";", "self", "::", "$", "logNotice", "=", "(", "$", "loglevel", "<=", "L_NOTICE", ")", ";", "}", "}" ]
Initialisiert die Klasse.
[ "Initialisiert", "die", "Klasse", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/net/TorHelper.php#L59-L66
29,448
rosasurfer/ministruts
src/net/TorHelper.php
TorHelper.isExitNode
public static function isExitNode($ip) { self::init(); if (!is_string($ip)) throw new IllegalTypeException('Illegal type of parameter $ip: '.gettype($ip)); // TODO: mit Filter-Extension lokale Netze abfangen if ($ip == '127.0.0.1') return false; $nodes = self::getExitNodes(); return isset($nodes[$ip]); }
php
public static function isExitNode($ip) { self::init(); if (!is_string($ip)) throw new IllegalTypeException('Illegal type of parameter $ip: '.gettype($ip)); // TODO: mit Filter-Extension lokale Netze abfangen if ($ip == '127.0.0.1') return false; $nodes = self::getExitNodes(); return isset($nodes[$ip]); }
[ "public", "static", "function", "isExitNode", "(", "$", "ip", ")", "{", "self", "::", "init", "(", ")", ";", "if", "(", "!", "is_string", "(", "$", "ip", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $ip: '", ".", "gettype", "(", "$", "ip", ")", ")", ";", "// TODO: mit Filter-Extension lokale Netze abfangen", "if", "(", "$", "ip", "==", "'127.0.0.1'", ")", "return", "false", ";", "$", "nodes", "=", "self", "::", "getExitNodes", "(", ")", ";", "return", "isset", "(", "$", "nodes", "[", "$", "ip", "]", ")", ";", "}" ]
Prueft, ob die uebergebene IP-Adresse ein aktueller Tor-Exit-Node ist. @param string $ip - IP-Adresse @return bool
[ "Prueft", "ob", "die", "uebergebene", "IP", "-", "Adresse", "ein", "aktueller", "Tor", "-", "Exit", "-", "Node", "ist", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/net/TorHelper.php#L76-L86
29,449
rosasurfer/ministruts
src/net/TorHelper.php
TorHelper.getExitNodes
private static function getExitNodes() { $cache = Cache::me(__CLASS__); $nodes = $cache->get($key='tor_exit_nodes'); if ($nodes == null) { // Einlesen der Nodes synchronisieren synchronized(function() use ($cache, $key, &$nodes) { $nodes = $cache->get($key); if ($nodes == null) { $content = ''; $size = sizeof(self::$torMirrors); for ($i=0; $i < $size; ++$i) { $request = new HttpRequest('http://'.self::$torMirrors[$i].'/ip_list_exit.php/Tor_ip_list_EXIT.csv'); try { // TODO: Warnung ausgeben und Reihenfolge aendern, wenn ein Server nicht antwortet $response = (new CurlHttpClient())->send($request); $status = $response->getStatus(); if ($status != 200) { self::$logNotice && Logger::log('Could not get TOR exit nodes from '.self::$torMirrors[$i].', HTTP status '.$status.' ('.HttpResponse::$sc[$status]."),\n URL: ".$request->getUrl(), L_NOTICE); continue; } } catch (IOException $ex) { self::$logNotice && Logger::log('Could not get TOR exit nodes from '.self::$torMirrors[$i], L_NOTICE, ['exception'=>$ex]); continue; } $content = trim($response->getContent()); break; } $nodes = strlen($content) ? \array_flip(explode(NL, normalizeEOL($content))) : []; if (!$nodes) Logger::log('Could not get TOR exit nodes from any server', L_ERROR); $cache->set($key, $nodes, 30 * MINUTES); } }); } return $nodes; }
php
private static function getExitNodes() { $cache = Cache::me(__CLASS__); $nodes = $cache->get($key='tor_exit_nodes'); if ($nodes == null) { // Einlesen der Nodes synchronisieren synchronized(function() use ($cache, $key, &$nodes) { $nodes = $cache->get($key); if ($nodes == null) { $content = ''; $size = sizeof(self::$torMirrors); for ($i=0; $i < $size; ++$i) { $request = new HttpRequest('http://'.self::$torMirrors[$i].'/ip_list_exit.php/Tor_ip_list_EXIT.csv'); try { // TODO: Warnung ausgeben und Reihenfolge aendern, wenn ein Server nicht antwortet $response = (new CurlHttpClient())->send($request); $status = $response->getStatus(); if ($status != 200) { self::$logNotice && Logger::log('Could not get TOR exit nodes from '.self::$torMirrors[$i].', HTTP status '.$status.' ('.HttpResponse::$sc[$status]."),\n URL: ".$request->getUrl(), L_NOTICE); continue; } } catch (IOException $ex) { self::$logNotice && Logger::log('Could not get TOR exit nodes from '.self::$torMirrors[$i], L_NOTICE, ['exception'=>$ex]); continue; } $content = trim($response->getContent()); break; } $nodes = strlen($content) ? \array_flip(explode(NL, normalizeEOL($content))) : []; if (!$nodes) Logger::log('Could not get TOR exit nodes from any server', L_ERROR); $cache->set($key, $nodes, 30 * MINUTES); } }); } return $nodes; }
[ "private", "static", "function", "getExitNodes", "(", ")", "{", "$", "cache", "=", "Cache", "::", "me", "(", "__CLASS__", ")", ";", "$", "nodes", "=", "$", "cache", "->", "get", "(", "$", "key", "=", "'tor_exit_nodes'", ")", ";", "if", "(", "$", "nodes", "==", "null", ")", "{", "// Einlesen der Nodes synchronisieren", "synchronized", "(", "function", "(", ")", "use", "(", "$", "cache", ",", "$", "key", ",", "&", "$", "nodes", ")", "{", "$", "nodes", "=", "$", "cache", "->", "get", "(", "$", "key", ")", ";", "if", "(", "$", "nodes", "==", "null", ")", "{", "$", "content", "=", "''", ";", "$", "size", "=", "sizeof", "(", "self", "::", "$", "torMirrors", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "size", ";", "++", "$", "i", ")", "{", "$", "request", "=", "new", "HttpRequest", "(", "'http://'", ".", "self", "::", "$", "torMirrors", "[", "$", "i", "]", ".", "'/ip_list_exit.php/Tor_ip_list_EXIT.csv'", ")", ";", "try", "{", "// TODO: Warnung ausgeben und Reihenfolge aendern, wenn ein Server nicht antwortet", "$", "response", "=", "(", "new", "CurlHttpClient", "(", ")", ")", "->", "send", "(", "$", "request", ")", ";", "$", "status", "=", "$", "response", "->", "getStatus", "(", ")", ";", "if", "(", "$", "status", "!=", "200", ")", "{", "self", "::", "$", "logNotice", "&&", "Logger", "::", "log", "(", "'Could not get TOR exit nodes from '", ".", "self", "::", "$", "torMirrors", "[", "$", "i", "]", ".", "', HTTP status '", ".", "$", "status", ".", "' ('", ".", "HttpResponse", "::", "$", "sc", "[", "$", "status", "]", ".", "\"),\\n URL: \"", ".", "$", "request", "->", "getUrl", "(", ")", ",", "L_NOTICE", ")", ";", "continue", ";", "}", "}", "catch", "(", "IOException", "$", "ex", ")", "{", "self", "::", "$", "logNotice", "&&", "Logger", "::", "log", "(", "'Could not get TOR exit nodes from '", ".", "self", "::", "$", "torMirrors", "[", "$", "i", "]", ",", "L_NOTICE", ",", "[", "'exception'", "=>", "$", "ex", "]", ")", ";", "continue", ";", "}", "$", "content", "=", "trim", "(", "$", "response", "->", "getContent", "(", ")", ")", ";", "break", ";", "}", "$", "nodes", "=", "strlen", "(", "$", "content", ")", "?", "\\", "array_flip", "(", "explode", "(", "NL", ",", "normalizeEOL", "(", "$", "content", ")", ")", ")", ":", "[", "]", ";", "if", "(", "!", "$", "nodes", ")", "Logger", "::", "log", "(", "'Could not get TOR exit nodes from any server'", ",", "L_ERROR", ")", ";", "$", "cache", "->", "set", "(", "$", "key", ",", "$", "nodes", ",", "30", "*", "MINUTES", ")", ";", "}", "}", ")", ";", "}", "return", "$", "nodes", ";", "}" ]
Gibt die aktuellen Exit-Nodes zurueck. @return array - assoziatives Array mit den IP-Adressen aller Exit-Nodes
[ "Gibt", "die", "aktuellen", "Exit", "-", "Nodes", "zurueck", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/net/TorHelper.php#L94-L138
29,450
timble/kodekit
code/translator/inflector/inflector.php
TranslatorInflector.setPluralRule
public static function setPluralRule(callable $rule, $language) { // temporary set a language for brazilian if ("pt_BR" == $language) { $language = "xbr"; } if (strlen($language) > 3) { $language = substr($language, 0, -strlen(strrchr($language, '_'))); } if (!is_callable($rule)) { throw new \LogicException('The given rule can not be called'); } self::$position_rules[$language] = $rule; }
php
public static function setPluralRule(callable $rule, $language) { // temporary set a language for brazilian if ("pt_BR" == $language) { $language = "xbr"; } if (strlen($language) > 3) { $language = substr($language, 0, -strlen(strrchr($language, '_'))); } if (!is_callable($rule)) { throw new \LogicException('The given rule can not be called'); } self::$position_rules[$language] = $rule; }
[ "public", "static", "function", "setPluralRule", "(", "callable", "$", "rule", ",", "$", "language", ")", "{", "// temporary set a language for brazilian", "if", "(", "\"pt_BR\"", "==", "$", "language", ")", "{", "$", "language", "=", "\"xbr\"", ";", "}", "if", "(", "strlen", "(", "$", "language", ")", ">", "3", ")", "{", "$", "language", "=", "substr", "(", "$", "language", ",", "0", ",", "-", "strlen", "(", "strrchr", "(", "$", "language", ",", "'_'", ")", ")", ")", ";", "}", "if", "(", "!", "is_callable", "(", "$", "rule", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "'The given rule can not be called'", ")", ";", "}", "self", "::", "$", "position_rules", "[", "$", "language", "]", "=", "$", "rule", ";", "}" ]
Overrides the default plural rule for a given language. @param callable $rule A PHP callable @param string $language The language @throws \LogicException @return void
[ "Overrides", "the", "default", "plural", "rule", "for", "a", "given", "language", "." ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/translator/inflector/inflector.php#L200-L216
29,451
timble/kodekit
code/dispatcher/behavior/routable.php
DispatcherBehaviorRoutable._beforeDispatch
protected function _beforeDispatch(DispatcherContext $context) { $view = $context->request->query->get('view', 'cmd'); //Redirect if no view information can be found in the request if(empty($view)) { $url = clone($context->request->getUrl()); $url->query['view'] = $this->getController()->getView()->getName(); $this->redirect($url); return false; } return true; }
php
protected function _beforeDispatch(DispatcherContext $context) { $view = $context->request->query->get('view', 'cmd'); //Redirect if no view information can be found in the request if(empty($view)) { $url = clone($context->request->getUrl()); $url->query['view'] = $this->getController()->getView()->getName(); $this->redirect($url); return false; } return true; }
[ "protected", "function", "_beforeDispatch", "(", "DispatcherContext", "$", "context", ")", "{", "$", "view", "=", "$", "context", "->", "request", "->", "query", "->", "get", "(", "'view'", ",", "'cmd'", ")", ";", "//Redirect if no view information can be found in the request", "if", "(", "empty", "(", "$", "view", ")", ")", "{", "$", "url", "=", "clone", "(", "$", "context", "->", "request", "->", "getUrl", "(", ")", ")", ";", "$", "url", "->", "query", "[", "'view'", "]", "=", "$", "this", "->", "getController", "(", ")", "->", "getView", "(", ")", "->", "getName", "(", ")", ";", "$", "this", "->", "redirect", "(", "$", "url", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Redirects the page to the default view @param DispatcherContext $context The active command context @return bool
[ "Redirects", "the", "page", "to", "the", "default", "view" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/dispatcher/behavior/routable.php#L28-L44
29,452
locomotivemtl/charcoal-core
src/Charcoal/Model/AbstractModel.php
AbstractModel.mergeData
public function mergeData(array $data) { $data = $this->setIdFromData($data); foreach ($data as $propIdent => $val) { if (!$this->hasProperty($propIdent)) { $this->logger->warning(sprintf( 'Cannot set property "%s" on object; not defined in metadata.', $propIdent )); continue; } $property = $this->p($propIdent); if ($property->l10n() && is_array($val)) { $currentValue = json_decode(json_encode($this[$propIdent]), true); if (is_array($currentValue)) { $this[$propIdent] = array_merge($currentValue, $val); } else { $this[$propIdent] = $val; } } else { $this[$propIdent] = $val; } } return $this; }
php
public function mergeData(array $data) { $data = $this->setIdFromData($data); foreach ($data as $propIdent => $val) { if (!$this->hasProperty($propIdent)) { $this->logger->warning(sprintf( 'Cannot set property "%s" on object; not defined in metadata.', $propIdent )); continue; } $property = $this->p($propIdent); if ($property->l10n() && is_array($val)) { $currentValue = json_decode(json_encode($this[$propIdent]), true); if (is_array($currentValue)) { $this[$propIdent] = array_merge($currentValue, $val); } else { $this[$propIdent] = $val; } } else { $this[$propIdent] = $val; } } return $this; }
[ "public", "function", "mergeData", "(", "array", "$", "data", ")", "{", "$", "data", "=", "$", "this", "->", "setIdFromData", "(", "$", "data", ")", ";", "foreach", "(", "$", "data", "as", "$", "propIdent", "=>", "$", "val", ")", "{", "if", "(", "!", "$", "this", "->", "hasProperty", "(", "$", "propIdent", ")", ")", "{", "$", "this", "->", "logger", "->", "warning", "(", "sprintf", "(", "'Cannot set property \"%s\" on object; not defined in metadata.'", ",", "$", "propIdent", ")", ")", ";", "continue", ";", "}", "$", "property", "=", "$", "this", "->", "p", "(", "$", "propIdent", ")", ";", "if", "(", "$", "property", "->", "l10n", "(", ")", "&&", "is_array", "(", "$", "val", ")", ")", "{", "$", "currentValue", "=", "json_decode", "(", "json_encode", "(", "$", "this", "[", "$", "propIdent", "]", ")", ",", "true", ")", ";", "if", "(", "is_array", "(", "$", "currentValue", ")", ")", "{", "$", "this", "[", "$", "propIdent", "]", "=", "array_merge", "(", "$", "currentValue", ",", "$", "val", ")", ";", "}", "else", "{", "$", "this", "[", "$", "propIdent", "]", "=", "$", "val", ";", "}", "}", "else", "{", "$", "this", "[", "$", "propIdent", "]", "=", "$", "val", ";", "}", "}", "return", "$", "this", ";", "}" ]
Merge data on the model. Overrides `\Charcoal\Config\AbstractEntity::setData()` to take properties into consideration. Also add a special case, to merge values for l10n properties. @param array $data The data to merge. @return self
[ "Merge", "data", "on", "the", "model", "." ]
db3a7af547ccf96efe2d9be028b252bc8646f5d5
https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/AbstractModel.php#L155-L182
29,453
rosasurfer/ministruts
src/log/Logger.php
Logger.init
private static function init() { static $initialized = false; if ($initialized) return; /** @var ConfigInterface $config */ $config = self::di('config'); // (1) Get the application's default loglevel configuration (fall back to the built-in default). $logLevel = $config->get('log.level', ''); if (is_array($logLevel)) $logLevel = isset($logLevel['']) ? $logLevel[''] : ''; $logLevel = self::logLevelToId($logLevel) ?: self::DEFAULT_LOGLEVEL; self::$appLogLevel = $logLevel; // (2) mail handler: enabled if mail receivers are configured $receivers = []; foreach (explode(',', $config->get('log.mail.receiver', '')) as $receiver) { if ($receiver = trim($receiver)) { if (filter_var($receiver, FILTER_VALIDATE_EMAIL)) { // silently skip invalid addresses $receivers[] = $receiver; } } } self::$mailHandler = (bool) $receivers; self::$mailReceivers = $receivers; // (3) L_FATAL print handler: enabled on local/white-listed access or if explicitely enabled self::$printFatalHandler = CLI || Application::isAdminIP() || ini_get_bool('display_errors'); // (4) non L_FATAL print handler: enabled on local access, if explicitely enabled or if the mail handler is disabled self::$printNonfatalHandler = CLI || in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', $_SERVER['SERVER_ADDR']]) || ini_get_bool('display_errors') || (self::$printFatalHandler && !self::$mailHandler); // (5) SMS handler: enabled if SMS receivers are configured (operator settings are checked at log time) self::$smsReceivers = []; foreach (explode(',', $config->get('log.sms.receiver', '')) as $receiver) { if ($receiver=trim($receiver)) { if (strStartsWith($receiver, '+' )) $receiver = substr($receiver, 1); if (strStartsWith($receiver, '00')) $receiver = substr($receiver, 2); if (!ctype_digit($receiver)) { self::log('Invalid SMS receiver configuration: "'.$receiver.'"', L_WARN, ['class'=>__CLASS__, 'file'=>__FILE__, 'line'=>__LINE__]); continue; } self::$smsReceivers[] = $receiver; } } $logLevel = $config->get('log.sms.level', self::$appLogLevel); if (is_string($logLevel)) // a string if configured $logLevel = self::logLevelToId($logLevel) ?: self::$appLogLevel; self::$smsLogLevel = $logLevel; $options = $config->get('sms', []); if (!is_array($options)) throw new IllegalTypeException('Invalid type of config value "sms": '.gettype($options).' (not array)'); self::$smsOptions = $options; self::$smsHandler = self::$smsReceivers && self::$smsOptions; // (6) PHP error_log handler: enabled if the mail handler is disabled self::$errorLogHandler = !self::$mailHandler; $initialized = true; }
php
private static function init() { static $initialized = false; if ($initialized) return; /** @var ConfigInterface $config */ $config = self::di('config'); // (1) Get the application's default loglevel configuration (fall back to the built-in default). $logLevel = $config->get('log.level', ''); if (is_array($logLevel)) $logLevel = isset($logLevel['']) ? $logLevel[''] : ''; $logLevel = self::logLevelToId($logLevel) ?: self::DEFAULT_LOGLEVEL; self::$appLogLevel = $logLevel; // (2) mail handler: enabled if mail receivers are configured $receivers = []; foreach (explode(',', $config->get('log.mail.receiver', '')) as $receiver) { if ($receiver = trim($receiver)) { if (filter_var($receiver, FILTER_VALIDATE_EMAIL)) { // silently skip invalid addresses $receivers[] = $receiver; } } } self::$mailHandler = (bool) $receivers; self::$mailReceivers = $receivers; // (3) L_FATAL print handler: enabled on local/white-listed access or if explicitely enabled self::$printFatalHandler = CLI || Application::isAdminIP() || ini_get_bool('display_errors'); // (4) non L_FATAL print handler: enabled on local access, if explicitely enabled or if the mail handler is disabled self::$printNonfatalHandler = CLI || in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', $_SERVER['SERVER_ADDR']]) || ini_get_bool('display_errors') || (self::$printFatalHandler && !self::$mailHandler); // (5) SMS handler: enabled if SMS receivers are configured (operator settings are checked at log time) self::$smsReceivers = []; foreach (explode(',', $config->get('log.sms.receiver', '')) as $receiver) { if ($receiver=trim($receiver)) { if (strStartsWith($receiver, '+' )) $receiver = substr($receiver, 1); if (strStartsWith($receiver, '00')) $receiver = substr($receiver, 2); if (!ctype_digit($receiver)) { self::log('Invalid SMS receiver configuration: "'.$receiver.'"', L_WARN, ['class'=>__CLASS__, 'file'=>__FILE__, 'line'=>__LINE__]); continue; } self::$smsReceivers[] = $receiver; } } $logLevel = $config->get('log.sms.level', self::$appLogLevel); if (is_string($logLevel)) // a string if configured $logLevel = self::logLevelToId($logLevel) ?: self::$appLogLevel; self::$smsLogLevel = $logLevel; $options = $config->get('sms', []); if (!is_array($options)) throw new IllegalTypeException('Invalid type of config value "sms": '.gettype($options).' (not array)'); self::$smsOptions = $options; self::$smsHandler = self::$smsReceivers && self::$smsOptions; // (6) PHP error_log handler: enabled if the mail handler is disabled self::$errorLogHandler = !self::$mailHandler; $initialized = true; }
[ "private", "static", "function", "init", "(", ")", "{", "static", "$", "initialized", "=", "false", ";", "if", "(", "$", "initialized", ")", "return", ";", "/** @var ConfigInterface $config */", "$", "config", "=", "self", "::", "di", "(", "'config'", ")", ";", "// (1) Get the application's default loglevel configuration (fall back to the built-in default).", "$", "logLevel", "=", "$", "config", "->", "get", "(", "'log.level'", ",", "''", ")", ";", "if", "(", "is_array", "(", "$", "logLevel", ")", ")", "$", "logLevel", "=", "isset", "(", "$", "logLevel", "[", "''", "]", ")", "?", "$", "logLevel", "[", "''", "]", ":", "''", ";", "$", "logLevel", "=", "self", "::", "logLevelToId", "(", "$", "logLevel", ")", "?", ":", "self", "::", "DEFAULT_LOGLEVEL", ";", "self", "::", "$", "appLogLevel", "=", "$", "logLevel", ";", "// (2) mail handler: enabled if mail receivers are configured", "$", "receivers", "=", "[", "]", ";", "foreach", "(", "explode", "(", "','", ",", "$", "config", "->", "get", "(", "'log.mail.receiver'", ",", "''", ")", ")", "as", "$", "receiver", ")", "{", "if", "(", "$", "receiver", "=", "trim", "(", "$", "receiver", ")", ")", "{", "if", "(", "filter_var", "(", "$", "receiver", ",", "FILTER_VALIDATE_EMAIL", ")", ")", "{", "// silently skip invalid addresses", "$", "receivers", "[", "]", "=", "$", "receiver", ";", "}", "}", "}", "self", "::", "$", "mailHandler", "=", "(", "bool", ")", "$", "receivers", ";", "self", "::", "$", "mailReceivers", "=", "$", "receivers", ";", "// (3) L_FATAL print handler: enabled on local/white-listed access or if explicitely enabled", "self", "::", "$", "printFatalHandler", "=", "CLI", "||", "Application", "::", "isAdminIP", "(", ")", "||", "ini_get_bool", "(", "'display_errors'", ")", ";", "// (4) non L_FATAL print handler: enabled on local access, if explicitely enabled or if the mail handler is disabled", "self", "::", "$", "printNonfatalHandler", "=", "CLI", "||", "in_array", "(", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ",", "[", "'127.0.0.1'", ",", "$", "_SERVER", "[", "'SERVER_ADDR'", "]", "]", ")", "||", "ini_get_bool", "(", "'display_errors'", ")", "||", "(", "self", "::", "$", "printFatalHandler", "&&", "!", "self", "::", "$", "mailHandler", ")", ";", "// (5) SMS handler: enabled if SMS receivers are configured (operator settings are checked at log time)", "self", "::", "$", "smsReceivers", "=", "[", "]", ";", "foreach", "(", "explode", "(", "','", ",", "$", "config", "->", "get", "(", "'log.sms.receiver'", ",", "''", ")", ")", "as", "$", "receiver", ")", "{", "if", "(", "$", "receiver", "=", "trim", "(", "$", "receiver", ")", ")", "{", "if", "(", "strStartsWith", "(", "$", "receiver", ",", "'+'", ")", ")", "$", "receiver", "=", "substr", "(", "$", "receiver", ",", "1", ")", ";", "if", "(", "strStartsWith", "(", "$", "receiver", ",", "'00'", ")", ")", "$", "receiver", "=", "substr", "(", "$", "receiver", ",", "2", ")", ";", "if", "(", "!", "ctype_digit", "(", "$", "receiver", ")", ")", "{", "self", "::", "log", "(", "'Invalid SMS receiver configuration: \"'", ".", "$", "receiver", ".", "'\"'", ",", "L_WARN", ",", "[", "'class'", "=>", "__CLASS__", ",", "'file'", "=>", "__FILE__", ",", "'line'", "=>", "__LINE__", "]", ")", ";", "continue", ";", "}", "self", "::", "$", "smsReceivers", "[", "]", "=", "$", "receiver", ";", "}", "}", "$", "logLevel", "=", "$", "config", "->", "get", "(", "'log.sms.level'", ",", "self", "::", "$", "appLogLevel", ")", ";", "if", "(", "is_string", "(", "$", "logLevel", ")", ")", "// a string if configured", "$", "logLevel", "=", "self", "::", "logLevelToId", "(", "$", "logLevel", ")", "?", ":", "self", "::", "$", "appLogLevel", ";", "self", "::", "$", "smsLogLevel", "=", "$", "logLevel", ";", "$", "options", "=", "$", "config", "->", "get", "(", "'sms'", ",", "[", "]", ")", ";", "if", "(", "!", "is_array", "(", "$", "options", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Invalid type of config value \"sms\": '", ".", "gettype", "(", "$", "options", ")", ".", "' (not array)'", ")", ";", "self", "::", "$", "smsOptions", "=", "$", "options", ";", "self", "::", "$", "smsHandler", "=", "self", "::", "$", "smsReceivers", "&&", "self", "::", "$", "smsOptions", ";", "// (6) PHP error_log handler: enabled if the mail handler is disabled", "self", "::", "$", "errorLogHandler", "=", "!", "self", "::", "$", "mailHandler", ";", "$", "initialized", "=", "true", ";", "}" ]
Initialize the Logger configuration.
[ "Initialize", "the", "Logger", "configuration", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L151-L217
29,454
rosasurfer/ministruts
src/log/Logger.php
Logger.logLevelToId
public static function logLevelToId($value) { if (!is_string($value)) throw new IllegalTypeException('Illegal type of parameter $value: '.gettype($value)); switch (strtolower($value)) { case 'debug' : return L_DEBUG; case 'info' : return L_INFO; case 'notice': return L_NOTICE; case 'warn' : return L_WARN; case 'error' : return L_ERROR; case 'fatal' : return L_FATAL; default: return null; } }
php
public static function logLevelToId($value) { if (!is_string($value)) throw new IllegalTypeException('Illegal type of parameter $value: '.gettype($value)); switch (strtolower($value)) { case 'debug' : return L_DEBUG; case 'info' : return L_INFO; case 'notice': return L_NOTICE; case 'warn' : return L_WARN; case 'error' : return L_ERROR; case 'fatal' : return L_FATAL; default: return null; } }
[ "public", "static", "function", "logLevelToId", "(", "$", "value", ")", "{", "if", "(", "!", "is_string", "(", "$", "value", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $value: '", ".", "gettype", "(", "$", "value", ")", ")", ";", "switch", "(", "strtolower", "(", "$", "value", ")", ")", "{", "case", "'debug'", ":", "return", "L_DEBUG", ";", "case", "'info'", ":", "return", "L_INFO", ";", "case", "'notice'", ":", "return", "L_NOTICE", ";", "case", "'warn'", ":", "return", "L_WARN", ";", "case", "'error'", ":", "return", "L_ERROR", ";", "case", "'fatal'", ":", "return", "L_FATAL", ";", "default", ":", "return", "null", ";", "}", "}" ]
Convert a loglevel description to a loglevel constant. @param string $value - loglevel description @return int|null - loglevel constant or NULL, if $value is not a valid loglevel description
[ "Convert", "a", "loglevel", "description", "to", "a", "loglevel", "constant", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L227-L240
29,455
rosasurfer/ministruts
src/log/Logger.php
Logger.getLogLevel
public static function getLogLevel($class = '') { if (!is_string($class)) throw new IllegalTypeException('Illegal type of parameter $class: '.gettype($class)); self::init(); // read the configured class specific loglevels static $logLevels = null; if ($logLevels === null) { /** @var ConfigInterface $config */ $config = self::di('config'); $logLevels = $config->get('log.level', []); if (is_string($logLevels)) $logLevels = ['' => $logLevels]; // only the general application loglevel is configured foreach ($logLevels as $className => $level) { if (!is_string($level)) throw new IllegalTypeException('Illegal configuration value for "log.level.'.$className.'": '.gettype($level)); if ($level == '') { // classes with empty values fall back to the application loglevel unset($logLevels[$className]); } else { $logLevel = self::logLevelToId($level); if (!$logLevel) throw new InvalidArgumentException('Invalid configuration value for "log.level.'.$className.'" = '.$level); $logLevels[$className] = $logLevel; if (strStartsWith($className, '\\')) { // normalize class names: remove leading back slash unset($logLevels[$className]); $className = substr($className, 1); $logLevels[$className] = $logLevel; } } } $logLevels = \array_change_key_case($logLevels, CASE_LOWER); // normalize class names: lower-case for case-insensitive look-up } // look-up the loglevel for the specified class $class = strtolower($class); if (isset($logLevels[$class])) return $logLevels[$class]; // return the general application loglevel if no class specific loglevel is configured return self::$appLogLevel; }
php
public static function getLogLevel($class = '') { if (!is_string($class)) throw new IllegalTypeException('Illegal type of parameter $class: '.gettype($class)); self::init(); // read the configured class specific loglevels static $logLevels = null; if ($logLevels === null) { /** @var ConfigInterface $config */ $config = self::di('config'); $logLevels = $config->get('log.level', []); if (is_string($logLevels)) $logLevels = ['' => $logLevels]; // only the general application loglevel is configured foreach ($logLevels as $className => $level) { if (!is_string($level)) throw new IllegalTypeException('Illegal configuration value for "log.level.'.$className.'": '.gettype($level)); if ($level == '') { // classes with empty values fall back to the application loglevel unset($logLevels[$className]); } else { $logLevel = self::logLevelToId($level); if (!$logLevel) throw new InvalidArgumentException('Invalid configuration value for "log.level.'.$className.'" = '.$level); $logLevels[$className] = $logLevel; if (strStartsWith($className, '\\')) { // normalize class names: remove leading back slash unset($logLevels[$className]); $className = substr($className, 1); $logLevels[$className] = $logLevel; } } } $logLevels = \array_change_key_case($logLevels, CASE_LOWER); // normalize class names: lower-case for case-insensitive look-up } // look-up the loglevel for the specified class $class = strtolower($class); if (isset($logLevels[$class])) return $logLevels[$class]; // return the general application loglevel if no class specific loglevel is configured return self::$appLogLevel; }
[ "public", "static", "function", "getLogLevel", "(", "$", "class", "=", "''", ")", "{", "if", "(", "!", "is_string", "(", "$", "class", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $class: '", ".", "gettype", "(", "$", "class", ")", ")", ";", "self", "::", "init", "(", ")", ";", "// read the configured class specific loglevels", "static", "$", "logLevels", "=", "null", ";", "if", "(", "$", "logLevels", "===", "null", ")", "{", "/** @var ConfigInterface $config */", "$", "config", "=", "self", "::", "di", "(", "'config'", ")", ";", "$", "logLevels", "=", "$", "config", "->", "get", "(", "'log.level'", ",", "[", "]", ")", ";", "if", "(", "is_string", "(", "$", "logLevels", ")", ")", "$", "logLevels", "=", "[", "''", "=>", "$", "logLevels", "]", ";", "// only the general application loglevel is configured", "foreach", "(", "$", "logLevels", "as", "$", "className", "=>", "$", "level", ")", "{", "if", "(", "!", "is_string", "(", "$", "level", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal configuration value for \"log.level.'", ".", "$", "className", ".", "'\": '", ".", "gettype", "(", "$", "level", ")", ")", ";", "if", "(", "$", "level", "==", "''", ")", "{", "// classes with empty values fall back to the application loglevel", "unset", "(", "$", "logLevels", "[", "$", "className", "]", ")", ";", "}", "else", "{", "$", "logLevel", "=", "self", "::", "logLevelToId", "(", "$", "level", ")", ";", "if", "(", "!", "$", "logLevel", ")", "throw", "new", "InvalidArgumentException", "(", "'Invalid configuration value for \"log.level.'", ".", "$", "className", ".", "'\" = '", ".", "$", "level", ")", ";", "$", "logLevels", "[", "$", "className", "]", "=", "$", "logLevel", ";", "if", "(", "strStartsWith", "(", "$", "className", ",", "'\\\\'", ")", ")", "{", "// normalize class names: remove leading back slash", "unset", "(", "$", "logLevels", "[", "$", "className", "]", ")", ";", "$", "className", "=", "substr", "(", "$", "className", ",", "1", ")", ";", "$", "logLevels", "[", "$", "className", "]", "=", "$", "logLevel", ";", "}", "}", "}", "$", "logLevels", "=", "\\", "array_change_key_case", "(", "$", "logLevels", ",", "CASE_LOWER", ")", ";", "// normalize class names: lower-case for case-insensitive look-up", "}", "// look-up the loglevel for the specified class", "$", "class", "=", "strtolower", "(", "$", "class", ")", ";", "if", "(", "isset", "(", "$", "logLevels", "[", "$", "class", "]", ")", ")", "return", "$", "logLevels", "[", "$", "class", "]", ";", "// return the general application loglevel if no class specific loglevel is configured", "return", "self", "::", "$", "appLogLevel", ";", "}" ]
Resolve the loglevel of the specified class. @param string $class [optional] - class name @return int - configured loglevel or the application loglevel if no class specific loglevel is configured
[ "Resolve", "the", "loglevel", "of", "the", "specified", "class", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L250-L292
29,456
rosasurfer/ministruts
src/log/Logger.php
Logger.invokeMailHandler
private static function invokeMailHandler($loggable, $level, array &$context) { if (!key_exists('mailSubject', $context) || !key_exists('mailMessage', $context)) self::composeMailMessage($loggable, $level, $context); $subject = $context['mailSubject']; $message = $context['mailMessage']; /** @var ConfigInterface $config */ $config = self::di('config'); $options = $headers = []; $sender = null; if (strlen($name = $config->get('log.mail.profile', ''))) { $options = $config->get('mail.profile.'.$name, []); $sender = $config->get('mail.profile.'.$name.'.from', null); $headers = $config->get('mail.profile.'.$name.'.headers', []); } static $mailer; !$mailer && $mailer=Mailer::create($options); foreach (self::$mailReceivers as $receiver) { $mailer->sendMail($sender, $receiver, $subject, $message, $headers); } }
php
private static function invokeMailHandler($loggable, $level, array &$context) { if (!key_exists('mailSubject', $context) || !key_exists('mailMessage', $context)) self::composeMailMessage($loggable, $level, $context); $subject = $context['mailSubject']; $message = $context['mailMessage']; /** @var ConfigInterface $config */ $config = self::di('config'); $options = $headers = []; $sender = null; if (strlen($name = $config->get('log.mail.profile', ''))) { $options = $config->get('mail.profile.'.$name, []); $sender = $config->get('mail.profile.'.$name.'.from', null); $headers = $config->get('mail.profile.'.$name.'.headers', []); } static $mailer; !$mailer && $mailer=Mailer::create($options); foreach (self::$mailReceivers as $receiver) { $mailer->sendMail($sender, $receiver, $subject, $message, $headers); } }
[ "private", "static", "function", "invokeMailHandler", "(", "$", "loggable", ",", "$", "level", ",", "array", "&", "$", "context", ")", "{", "if", "(", "!", "key_exists", "(", "'mailSubject'", ",", "$", "context", ")", "||", "!", "key_exists", "(", "'mailMessage'", ",", "$", "context", ")", ")", "self", "::", "composeMailMessage", "(", "$", "loggable", ",", "$", "level", ",", "$", "context", ")", ";", "$", "subject", "=", "$", "context", "[", "'mailSubject'", "]", ";", "$", "message", "=", "$", "context", "[", "'mailMessage'", "]", ";", "/** @var ConfigInterface $config */", "$", "config", "=", "self", "::", "di", "(", "'config'", ")", ";", "$", "options", "=", "$", "headers", "=", "[", "]", ";", "$", "sender", "=", "null", ";", "if", "(", "strlen", "(", "$", "name", "=", "$", "config", "->", "get", "(", "'log.mail.profile'", ",", "''", ")", ")", ")", "{", "$", "options", "=", "$", "config", "->", "get", "(", "'mail.profile.'", ".", "$", "name", ",", "[", "]", ")", ";", "$", "sender", "=", "$", "config", "->", "get", "(", "'mail.profile.'", ".", "$", "name", ".", "'.from'", ",", "null", ")", ";", "$", "headers", "=", "$", "config", "->", "get", "(", "'mail.profile.'", ".", "$", "name", ".", "'.headers'", ",", "[", "]", ")", ";", "}", "static", "$", "mailer", ";", "!", "$", "mailer", "&&", "$", "mailer", "=", "Mailer", "::", "create", "(", "$", "options", ")", ";", "foreach", "(", "self", "::", "$", "mailReceivers", "as", "$", "receiver", ")", "{", "$", "mailer", "->", "sendMail", "(", "$", "sender", ",", "$", "receiver", ",", "$", "subject", ",", "$", "message", ",", "$", "headers", ")", ";", "}", "}" ]
Send the message to the configured mail receivers. @param string|\Exception $loggable - message or exception to log @param int $level - loglevel of the loggable @param array $context - reference to the log context with additional data
[ "Send", "the", "message", "to", "the", "configured", "mail", "receivers", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L404-L426
29,457
rosasurfer/ministruts
src/log/Logger.php
Logger.invokeErrorLogHandler
private static function invokeErrorLogHandler($loggable, $level, array &$context) { if (!key_exists('cliMessage', $context)) self::composeCliMessage($loggable, $level, $context); $msg = 'PHP '.$context['cliMessage']; if (key_exists('cliExtra', $context)) $msg .= $context['cliExtra']; $msg = str_replace(chr(0), '?', $msg); // replace NUL bytes which mess up the logfile if (CLI && empty(ini_get('error_log'))) { // Suppress duplicated output to STDERR, the PrintHandler already wrote to STDOUT. // TODO: Instead of messing around here the PrintHandler must not print to STDOUT if the ErrorLogHandler // is active and prints to STDERR. // TODO: Suppress output to STDERR in interactive terminals only (i.e. not in CRON). } else { error_log(trim($msg), ERROR_LOG_DEFAULT); } }
php
private static function invokeErrorLogHandler($loggable, $level, array &$context) { if (!key_exists('cliMessage', $context)) self::composeCliMessage($loggable, $level, $context); $msg = 'PHP '.$context['cliMessage']; if (key_exists('cliExtra', $context)) $msg .= $context['cliExtra']; $msg = str_replace(chr(0), '?', $msg); // replace NUL bytes which mess up the logfile if (CLI && empty(ini_get('error_log'))) { // Suppress duplicated output to STDERR, the PrintHandler already wrote to STDOUT. // TODO: Instead of messing around here the PrintHandler must not print to STDOUT if the ErrorLogHandler // is active and prints to STDERR. // TODO: Suppress output to STDERR in interactive terminals only (i.e. not in CRON). } else { error_log(trim($msg), ERROR_LOG_DEFAULT); } }
[ "private", "static", "function", "invokeErrorLogHandler", "(", "$", "loggable", ",", "$", "level", ",", "array", "&", "$", "context", ")", "{", "if", "(", "!", "key_exists", "(", "'cliMessage'", ",", "$", "context", ")", ")", "self", "::", "composeCliMessage", "(", "$", "loggable", ",", "$", "level", ",", "$", "context", ")", ";", "$", "msg", "=", "'PHP '", ".", "$", "context", "[", "'cliMessage'", "]", ";", "if", "(", "key_exists", "(", "'cliExtra'", ",", "$", "context", ")", ")", "$", "msg", ".=", "$", "context", "[", "'cliExtra'", "]", ";", "$", "msg", "=", "str_replace", "(", "chr", "(", "0", ")", ",", "'?'", ",", "$", "msg", ")", ";", "// replace NUL bytes which mess up the logfile", "if", "(", "CLI", "&&", "empty", "(", "ini_get", "(", "'error_log'", ")", ")", ")", "{", "// Suppress duplicated output to STDERR, the PrintHandler already wrote to STDOUT.", "// TODO: Instead of messing around here the PrintHandler must not print to STDOUT if the ErrorLogHandler", "// is active and prints to STDERR.", "// TODO: Suppress output to STDERR in interactive terminals only (i.e. not in CRON).", "}", "else", "{", "error_log", "(", "trim", "(", "$", "msg", ")", ",", "ERROR_LOG_DEFAULT", ")", ";", "}", "}" ]
Pass the message to the PHP default error log mechanism as defined by the PHP configuration value "error_log". ini_get('error_log') Name of the file where script errors should be logged. If the special value "syslog" is used, errors are sent to the system logger instead. On Unix, this means syslog(3) and on Windows it means the event log. If this directive is not set, errors are sent to the SAPI error logger. For example, it is an error log in Apache or STDERR in CLI mode. @param string|\Exception $loggable - message or exception to log @param int $level - loglevel of the loggable @param array $context - reference to the log context with additional data
[ "Pass", "the", "message", "to", "the", "PHP", "default", "error", "log", "mechanism", "as", "defined", "by", "the", "PHP", "configuration", "value", "error_log", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L543-L562
29,458
rosasurfer/ministruts
src/log/Logger.php
Logger.composeMailMessage
private static function composeMailMessage($loggable, $level, array &$context) { if (!key_exists('cliMessage', $context)) self::composeCliMessage($loggable, $level, $context); $msg = $context['cliMessage']; if (key_exists('cliExtra', $context)) $msg .= $context['cliExtra']; $location = null; // compose message if (CLI) { $msg .= NL.NL.'Shell:'.NL.'------'.NL.print_r(ksort_r($_SERVER), true).NL; $location = realpath($_SERVER['PHP_SELF']); } else { $request = Request::me(); $location = strLeftTo($request->getUrl(), '?'); $session = null; if (isset($_SESSION)) { $session = $_SESSION; } else if ($request->hasSessionId()) { $request->getSession($suppressHeadersAlreadySentError = true); if (session_id() == $request->getSessionId()) // if both differ the id was regenerated and $session = $_SESSION; // the session is empty } $session = is_null($session) ? null : print_r(ksort_r($session), true); $ip = $_SERVER['REMOTE_ADDR']; $host = NetTools::getHostByAddress($ip); if ($host != $ip) $ip .= ' ('.$host.')'; $msg .= NL.NL.'Request:'.NL.'--------'.NL.$request.NL.NL . 'Session: '.($session ? NL.'--------'.NL.$session : '(none)'.NL.'--------'.NL).NL.NL . 'Server:'.NL.'-------'.NL.print_r(ksort_r($_SERVER), true).NL.NL . 'IP: '.$ip.NL . 'Time: '.date('Y-m-d H:i:s').NL; } $type = ($loggable instanceof \Exception && key_exists('unhandled', $context)) ? 'Unhandled Exception ':''; // store subject and message $context['mailSubject'] = 'PHP ['.self::$logLevels[$level].'] '.$type.(CLI ? 'in ':'at ').$location; $context['mailMessage'] = $msg; }
php
private static function composeMailMessage($loggable, $level, array &$context) { if (!key_exists('cliMessage', $context)) self::composeCliMessage($loggable, $level, $context); $msg = $context['cliMessage']; if (key_exists('cliExtra', $context)) $msg .= $context['cliExtra']; $location = null; // compose message if (CLI) { $msg .= NL.NL.'Shell:'.NL.'------'.NL.print_r(ksort_r($_SERVER), true).NL; $location = realpath($_SERVER['PHP_SELF']); } else { $request = Request::me(); $location = strLeftTo($request->getUrl(), '?'); $session = null; if (isset($_SESSION)) { $session = $_SESSION; } else if ($request->hasSessionId()) { $request->getSession($suppressHeadersAlreadySentError = true); if (session_id() == $request->getSessionId()) // if both differ the id was regenerated and $session = $_SESSION; // the session is empty } $session = is_null($session) ? null : print_r(ksort_r($session), true); $ip = $_SERVER['REMOTE_ADDR']; $host = NetTools::getHostByAddress($ip); if ($host != $ip) $ip .= ' ('.$host.')'; $msg .= NL.NL.'Request:'.NL.'--------'.NL.$request.NL.NL . 'Session: '.($session ? NL.'--------'.NL.$session : '(none)'.NL.'--------'.NL).NL.NL . 'Server:'.NL.'-------'.NL.print_r(ksort_r($_SERVER), true).NL.NL . 'IP: '.$ip.NL . 'Time: '.date('Y-m-d H:i:s').NL; } $type = ($loggable instanceof \Exception && key_exists('unhandled', $context)) ? 'Unhandled Exception ':''; // store subject and message $context['mailSubject'] = 'PHP ['.self::$logLevels[$level].'] '.$type.(CLI ? 'in ':'at ').$location; $context['mailMessage'] = $msg; }
[ "private", "static", "function", "composeMailMessage", "(", "$", "loggable", ",", "$", "level", ",", "array", "&", "$", "context", ")", "{", "if", "(", "!", "key_exists", "(", "'cliMessage'", ",", "$", "context", ")", ")", "self", "::", "composeCliMessage", "(", "$", "loggable", ",", "$", "level", ",", "$", "context", ")", ";", "$", "msg", "=", "$", "context", "[", "'cliMessage'", "]", ";", "if", "(", "key_exists", "(", "'cliExtra'", ",", "$", "context", ")", ")", "$", "msg", ".=", "$", "context", "[", "'cliExtra'", "]", ";", "$", "location", "=", "null", ";", "// compose message", "if", "(", "CLI", ")", "{", "$", "msg", ".=", "NL", ".", "NL", ".", "'Shell:'", ".", "NL", ".", "'------'", ".", "NL", ".", "print_r", "(", "ksort_r", "(", "$", "_SERVER", ")", ",", "true", ")", ".", "NL", ";", "$", "location", "=", "realpath", "(", "$", "_SERVER", "[", "'PHP_SELF'", "]", ")", ";", "}", "else", "{", "$", "request", "=", "Request", "::", "me", "(", ")", ";", "$", "location", "=", "strLeftTo", "(", "$", "request", "->", "getUrl", "(", ")", ",", "'?'", ")", ";", "$", "session", "=", "null", ";", "if", "(", "isset", "(", "$", "_SESSION", ")", ")", "{", "$", "session", "=", "$", "_SESSION", ";", "}", "else", "if", "(", "$", "request", "->", "hasSessionId", "(", ")", ")", "{", "$", "request", "->", "getSession", "(", "$", "suppressHeadersAlreadySentError", "=", "true", ")", ";", "if", "(", "session_id", "(", ")", "==", "$", "request", "->", "getSessionId", "(", ")", ")", "// if both differ the id was regenerated and", "$", "session", "=", "$", "_SESSION", ";", "// the session is empty", "}", "$", "session", "=", "is_null", "(", "$", "session", ")", "?", "null", ":", "print_r", "(", "ksort_r", "(", "$", "session", ")", ",", "true", ")", ";", "$", "ip", "=", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ";", "$", "host", "=", "NetTools", "::", "getHostByAddress", "(", "$", "ip", ")", ";", "if", "(", "$", "host", "!=", "$", "ip", ")", "$", "ip", ".=", "' ('", ".", "$", "host", ".", "')'", ";", "$", "msg", ".=", "NL", ".", "NL", ".", "'Request:'", ".", "NL", ".", "'--------'", ".", "NL", ".", "$", "request", ".", "NL", ".", "NL", ".", "'Session: '", ".", "(", "$", "session", "?", "NL", ".", "'--------'", ".", "NL", ".", "$", "session", ":", "'(none)'", ".", "NL", ".", "'--------'", ".", "NL", ")", ".", "NL", ".", "NL", ".", "'Server:'", ".", "NL", ".", "'-------'", ".", "NL", ".", "print_r", "(", "ksort_r", "(", "$", "_SERVER", ")", ",", "true", ")", ".", "NL", ".", "NL", ".", "'IP: '", ".", "$", "ip", ".", "NL", ".", "'Time: '", ".", "date", "(", "'Y-m-d H:i:s'", ")", ".", "NL", ";", "}", "$", "type", "=", "(", "$", "loggable", "instanceof", "\\", "Exception", "&&", "key_exists", "(", "'unhandled'", ",", "$", "context", ")", ")", "?", "'Unhandled Exception '", ":", "''", ";", "// store subject and message", "$", "context", "[", "'mailSubject'", "]", "=", "'PHP ['", ".", "self", "::", "$", "logLevels", "[", "$", "level", "]", ".", "'] '", ".", "$", "type", ".", "(", "CLI", "?", "'in '", ":", "'at '", ")", ".", "$", "location", ";", "$", "context", "[", "'mailMessage'", "]", "=", "$", "msg", ";", "}" ]
Compose a mail log message and store it in the passed log context under the keys "mailSubject" and "mailMessage". @param string|\Exception $loggable - message or exception to log @param int $level - loglevel of the loggable @param array $context - reference to the log context
[ "Compose", "a", "mail", "log", "message", "and", "store", "it", "in", "the", "passed", "log", "context", "under", "the", "keys", "mailSubject", "and", "mailMessage", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L648-L691
29,459
rosasurfer/ministruts
src/log/Logger.php
Logger.resolveLogLocation
private static function resolveLogLocation(array &$context) { if (!key_exists('trace', $context)) self::generateStackTrace($context); $trace = $context['trace']; foreach ($trace as $i => $frame) { // find the first frame with "file" if (isset($frame['file'])) { // skip internal PHP functions $context['file'] = $frame['file']; $context['line'] = $frame['line']; break; } } if (!key_exists('file', $context)) { $context['file'] = '(unknown)'; $context['line'] = '(?)'; } }
php
private static function resolveLogLocation(array &$context) { if (!key_exists('trace', $context)) self::generateStackTrace($context); $trace = $context['trace']; foreach ($trace as $i => $frame) { // find the first frame with "file" if (isset($frame['file'])) { // skip internal PHP functions $context['file'] = $frame['file']; $context['line'] = $frame['line']; break; } } if (!key_exists('file', $context)) { $context['file'] = '(unknown)'; $context['line'] = '(?)'; } }
[ "private", "static", "function", "resolveLogLocation", "(", "array", "&", "$", "context", ")", "{", "if", "(", "!", "key_exists", "(", "'trace'", ",", "$", "context", ")", ")", "self", "::", "generateStackTrace", "(", "$", "context", ")", ";", "$", "trace", "=", "$", "context", "[", "'trace'", "]", ";", "foreach", "(", "$", "trace", "as", "$", "i", "=>", "$", "frame", ")", "{", "// find the first frame with \"file\"", "if", "(", "isset", "(", "$", "frame", "[", "'file'", "]", ")", ")", "{", "// skip internal PHP functions", "$", "context", "[", "'file'", "]", "=", "$", "frame", "[", "'file'", "]", ";", "$", "context", "[", "'line'", "]", "=", "$", "frame", "[", "'line'", "]", ";", "break", ";", "}", "}", "if", "(", "!", "key_exists", "(", "'file'", ",", "$", "context", ")", ")", "{", "$", "context", "[", "'file'", "]", "=", "'(unknown)'", ";", "$", "context", "[", "'line'", "]", "=", "'(?)'", ";", "}", "}" ]
Resolve the location the logger was called from and store it in the log context under the keys "file" and "line". @param array $context - reference to the log context
[ "Resolve", "the", "location", "the", "logger", "was", "called", "from", "and", "store", "it", "in", "the", "log", "context", "under", "the", "keys", "file", "and", "line", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L783-L800
29,460
rosasurfer/ministruts
src/log/Logger.php
Logger.resolveLogCaller
private static function resolveLogCaller(array &$context) { if (!key_exists('trace', $context)) self::generateStackTrace($context); $trace = $context['trace']; $context['class'] = isset($trace[0]['class']) ? $trace[0]['class'] : ''; }
php
private static function resolveLogCaller(array &$context) { if (!key_exists('trace', $context)) self::generateStackTrace($context); $trace = $context['trace']; $context['class'] = isset($trace[0]['class']) ? $trace[0]['class'] : ''; }
[ "private", "static", "function", "resolveLogCaller", "(", "array", "&", "$", "context", ")", "{", "if", "(", "!", "key_exists", "(", "'trace'", ",", "$", "context", ")", ")", "self", "::", "generateStackTrace", "(", "$", "context", ")", ";", "$", "trace", "=", "$", "context", "[", "'trace'", "]", ";", "$", "context", "[", "'class'", "]", "=", "isset", "(", "$", "trace", "[", "0", "]", "[", "'class'", "]", ")", "?", "$", "trace", "[", "0", "]", "[", "'class'", "]", ":", "''", ";", "}" ]
Resolve the class the logger was called from and store it in the log context under the key "class". @param array $context - reference to the log context TODO: test with Closure and internal PHP functions
[ "Resolve", "the", "class", "the", "logger", "was", "called", "from", "and", "store", "it", "in", "the", "log", "context", "under", "the", "key", "class", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L811-L817
29,461
rosasurfer/ministruts
src/log/Logger.php
Logger.generateStackTrace
private static function generateStackTrace(array &$context) { if (!key_exists('trace', $context)) { $trace = DebugHelper::fixTrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), __FILE__, __LINE__); foreach ($trace as $i => $frame) { if (!isset($frame['class']) || $frame['class']!=__CLASS__) // remove non-logger frames break; unset($trace[$i]); } $context['trace'] = \array_values($trace); } }
php
private static function generateStackTrace(array &$context) { if (!key_exists('trace', $context)) { $trace = DebugHelper::fixTrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), __FILE__, __LINE__); foreach ($trace as $i => $frame) { if (!isset($frame['class']) || $frame['class']!=__CLASS__) // remove non-logger frames break; unset($trace[$i]); } $context['trace'] = \array_values($trace); } }
[ "private", "static", "function", "generateStackTrace", "(", "array", "&", "$", "context", ")", "{", "if", "(", "!", "key_exists", "(", "'trace'", ",", "$", "context", ")", ")", "{", "$", "trace", "=", "DebugHelper", "::", "fixTrace", "(", "debug_backtrace", "(", "DEBUG_BACKTRACE_IGNORE_ARGS", ")", ",", "__FILE__", ",", "__LINE__", ")", ";", "foreach", "(", "$", "trace", "as", "$", "i", "=>", "$", "frame", ")", "{", "if", "(", "!", "isset", "(", "$", "frame", "[", "'class'", "]", ")", "||", "$", "frame", "[", "'class'", "]", "!=", "__CLASS__", ")", "// remove non-logger frames", "break", ";", "unset", "(", "$", "trace", "[", "$", "i", "]", ")", ";", "}", "$", "context", "[", "'trace'", "]", "=", "\\", "array_values", "(", "$", "trace", ")", ";", "}", "}" ]
Generate an internal stacktrace and store it in the log context under the key "trace". @param array $context - reference to the log context
[ "Generate", "an", "internal", "stacktrace", "and", "store", "it", "in", "the", "log", "context", "under", "the", "key", "trace", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L825-L836
29,462
timble/kodekit
code/user/provider/abstract.php
UserProviderAbstract.getUser
public function getUser($identifier) { //Fetch a user from the backend if not loaded yet if(!$this->isLoaded($identifier)) { $this->fetch($identifier); } //Create an anonymous user was not loaded if(!$user = $this->findUser($identifier)) { $user = $this->create(array( 'id' => 0, 'name' => $this->getObject('translator')->translate('Anonymous') )); } return $user; }
php
public function getUser($identifier) { //Fetch a user from the backend if not loaded yet if(!$this->isLoaded($identifier)) { $this->fetch($identifier); } //Create an anonymous user was not loaded if(!$user = $this->findUser($identifier)) { $user = $this->create(array( 'id' => 0, 'name' => $this->getObject('translator')->translate('Anonymous') )); } return $user; }
[ "public", "function", "getUser", "(", "$", "identifier", ")", "{", "//Fetch a user from the backend if not loaded yet", "if", "(", "!", "$", "this", "->", "isLoaded", "(", "$", "identifier", ")", ")", "{", "$", "this", "->", "fetch", "(", "$", "identifier", ")", ";", "}", "//Create an anonymous user was not loaded", "if", "(", "!", "$", "user", "=", "$", "this", "->", "findUser", "(", "$", "identifier", ")", ")", "{", "$", "user", "=", "$", "this", "->", "create", "(", "array", "(", "'id'", "=>", "0", ",", "'name'", "=>", "$", "this", "->", "getObject", "(", "'translator'", ")", "->", "translate", "(", "'Anonymous'", ")", ")", ")", ";", "}", "return", "$", "user", ";", "}" ]
Load the user for the given username or identifier If the user could not be loaded an anonymous user will be returned with a user 'id' off 0. @param string $identifier A unique user identifier, (i.e a username or email address) @return UserInterface Returns a UserInterface object.
[ "Load", "the", "user", "for", "the", "given", "username", "or", "identifier" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/user/provider/abstract.php#L83-L100
29,463
rosasurfer/ministruts
src/console/Command.php
Command.run
public function run() { $this->input = new Input($this->docoptResult); $this->di()->set(Input::class, $this->input); if ($this->validator) $error = $this->validator->__invoke($this->input, $this->output); else $error = $this->validate($this->input, $this->output); if ($error) return $this->status = (int) $error; if ($this->task) $status = $this->task->__invoke($this->input, $this->output); else $status = $this->execute($this->input, $this->output); return $this->status = (int) $status; }
php
public function run() { $this->input = new Input($this->docoptResult); $this->di()->set(Input::class, $this->input); if ($this->validator) $error = $this->validator->__invoke($this->input, $this->output); else $error = $this->validate($this->input, $this->output); if ($error) return $this->status = (int) $error; if ($this->task) $status = $this->task->__invoke($this->input, $this->output); else $status = $this->execute($this->input, $this->output); return $this->status = (int) $status; }
[ "public", "function", "run", "(", ")", "{", "$", "this", "->", "input", "=", "new", "Input", "(", "$", "this", "->", "docoptResult", ")", ";", "$", "this", "->", "di", "(", ")", "->", "set", "(", "Input", "::", "class", ",", "$", "this", "->", "input", ")", ";", "if", "(", "$", "this", "->", "validator", ")", "$", "error", "=", "$", "this", "->", "validator", "->", "__invoke", "(", "$", "this", "->", "input", ",", "$", "this", "->", "output", ")", ";", "else", "$", "error", "=", "$", "this", "->", "validate", "(", "$", "this", "->", "input", ",", "$", "this", "->", "output", ")", ";", "if", "(", "$", "error", ")", "return", "$", "this", "->", "status", "=", "(", "int", ")", "$", "error", ";", "if", "(", "$", "this", "->", "task", ")", "$", "status", "=", "$", "this", "->", "task", "->", "__invoke", "(", "$", "this", "->", "input", ",", "$", "this", "->", "output", ")", ";", "else", "$", "status", "=", "$", "this", "->", "execute", "(", "$", "this", "->", "input", ",", "$", "this", "->", "output", ")", ";", "return", "$", "this", "->", "status", "=", "(", "int", ")", "$", "status", ";", "}" ]
Trigger execution of the command. @return int - execution status (0 for success)
[ "Trigger", "execution", "of", "the", "command", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/console/Command.php#L84-L98
29,464
rosasurfer/ministruts
src/console/Command.php
Command.setAliases
public function setAliases(array $names) { if ($this->frozen) throw new RuntimeException('Configuration of "'.get_class($this).'" is frozen'); if ($this->name === '') throw new IllegalStateException('A default command (name="") cannot have aliases'); foreach ($names as $i => $alias) { $this->validateName($alias); } $this->aliases = array_diff($names, [$this->name]); // remove an overlapping command name return $this; }
php
public function setAliases(array $names) { if ($this->frozen) throw new RuntimeException('Configuration of "'.get_class($this).'" is frozen'); if ($this->name === '') throw new IllegalStateException('A default command (name="") cannot have aliases'); foreach ($names as $i => $alias) { $this->validateName($alias); } $this->aliases = array_diff($names, [$this->name]); // remove an overlapping command name return $this; }
[ "public", "function", "setAliases", "(", "array", "$", "names", ")", "{", "if", "(", "$", "this", "->", "frozen", ")", "throw", "new", "RuntimeException", "(", "'Configuration of \"'", ".", "get_class", "(", "$", "this", ")", ".", "'\" is frozen'", ")", ";", "if", "(", "$", "this", "->", "name", "===", "''", ")", "throw", "new", "IllegalStateException", "(", "'A default command (name=\"\") cannot have aliases'", ")", ";", "foreach", "(", "$", "names", "as", "$", "i", "=>", "$", "alias", ")", "{", "$", "this", "->", "validateName", "(", "$", "alias", ")", ";", "}", "$", "this", "->", "aliases", "=", "array_diff", "(", "$", "names", ",", "[", "$", "this", "->", "name", "]", ")", ";", "// remove an overlapping command name", "return", "$", "this", ";", "}" ]
Set the alias names of the command if the command has a non-empty name. A command with an empty name is considered the default command and cannot have aliases. @param string[] $names @return $this
[ "Set", "the", "alias", "names", "of", "the", "command", "if", "the", "command", "has", "a", "non", "-", "empty", "name", ".", "A", "command", "with", "an", "empty", "name", "is", "considered", "the", "default", "command", "and", "cannot", "have", "aliases", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/console/Command.php#L181-L190
29,465
rosasurfer/ministruts
src/console/Command.php
Command.setDocoptDefinition
public function setDocoptDefinition($doc) { if ($this->frozen) throw new RuntimeException('Configuration of "'.get_class($this).'" is frozen'); if (!is_string($doc)) throw new IllegalTypeException('Illegal type of parameter $doc: '.gettype($doc)); $parser = new DocoptParser(); $this->docoptResult = $parser->parse($doc); $this->docoptDefinition = $doc; return $this; }
php
public function setDocoptDefinition($doc) { if ($this->frozen) throw new RuntimeException('Configuration of "'.get_class($this).'" is frozen'); if (!is_string($doc)) throw new IllegalTypeException('Illegal type of parameter $doc: '.gettype($doc)); $parser = new DocoptParser(); $this->docoptResult = $parser->parse($doc); $this->docoptDefinition = $doc; return $this; }
[ "public", "function", "setDocoptDefinition", "(", "$", "doc", ")", "{", "if", "(", "$", "this", "->", "frozen", ")", "throw", "new", "RuntimeException", "(", "'Configuration of \"'", ".", "get_class", "(", "$", "this", ")", ".", "'\" is frozen'", ")", ";", "if", "(", "!", "is_string", "(", "$", "doc", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $doc: '", ".", "gettype", "(", "$", "doc", ")", ")", ";", "$", "parser", "=", "new", "DocoptParser", "(", ")", ";", "$", "this", "->", "docoptResult", "=", "$", "parser", "->", "parse", "(", "$", "doc", ")", ";", "$", "this", "->", "docoptDefinition", "=", "$", "doc", ";", "return", "$", "this", ";", "}" ]
Set the command's docopt definition. @param string $doc - syntax definition in docopt format @return $this @link http://docopt.org
[ "Set", "the", "command", "s", "docopt", "definition", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/console/Command.php#L212-L221
29,466
rosasurfer/ministruts
src/console/Command.php
Command.validateName
private function validateName($name) { if (!is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name)); if ($name != trim($name)) throw new InvalidArgumentException('Invalid parameter $name: "'.$name.'" (enclosing white space)'); if (strlen($name) && !preg_match('/^[^\s:]+(:[^\s:]+)*$/', $name)) throw new InvalidArgumentException('Invalid parameter $name: "'.$name.'" (not a command name)'); return $this; }
php
private function validateName($name) { if (!is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name)); if ($name != trim($name)) throw new InvalidArgumentException('Invalid parameter $name: "'.$name.'" (enclosing white space)'); if (strlen($name) && !preg_match('/^[^\s:]+(:[^\s:]+)*$/', $name)) throw new InvalidArgumentException('Invalid parameter $name: "'.$name.'" (not a command name)'); return $this; }
[ "private", "function", "validateName", "(", "$", "name", ")", "{", "if", "(", "!", "is_string", "(", "$", "name", ")", ")", "throw", "new", "IllegalTypeException", "(", "'Illegal type of parameter $name: '", ".", "gettype", "(", "$", "name", ")", ")", ";", "if", "(", "$", "name", "!=", "trim", "(", "$", "name", ")", ")", "throw", "new", "InvalidArgumentException", "(", "'Invalid parameter $name: \"'", ".", "$", "name", ".", "'\" (enclosing white space)'", ")", ";", "if", "(", "strlen", "(", "$", "name", ")", "&&", "!", "preg_match", "(", "'/^[^\\s:]+(:[^\\s:]+)*$/'", ",", "$", "name", ")", ")", "throw", "new", "InvalidArgumentException", "(", "'Invalid parameter $name: \"'", ".", "$", "name", ".", "'\" (not a command name)'", ")", ";", "return", "$", "this", ";", "}" ]
Validate a command name. @param string $name @return $this
[ "Validate", "a", "command", "name", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/console/Command.php#L295-L302
29,467
timble/kodekit
code/user/user.php
User.setProperties
public function setProperties($properties) { parent::setProperties($properties); //Set the user data $this->getSession()->set('user', ObjectConfig::unbox($properties)); return $this; }
php
public function setProperties($properties) { parent::setProperties($properties); //Set the user data $this->getSession()->set('user', ObjectConfig::unbox($properties)); return $this; }
[ "public", "function", "setProperties", "(", "$", "properties", ")", "{", "parent", "::", "setProperties", "(", "$", "properties", ")", ";", "//Set the user data", "$", "this", "->", "getSession", "(", ")", "->", "set", "(", "'user'", ",", "ObjectConfig", "::", "unbox", "(", "$", "properties", ")", ")", ";", "return", "$", "this", ";", "}" ]
Set the user properties from an array @param array $properties An associative array @return User
[ "Set", "the", "user", "properties", "from", "an", "array" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/user/user.php#L207-L215
29,468
rosasurfer/ministruts
src/debug/ErrorHandler.php
ErrorHandler.setupErrorHandling
public static function setupErrorHandling($mode) { if ($mode === self::LOG_ERRORS ) self::$errorMode = self::LOG_ERRORS; elseif ($mode === self::THROW_EXCEPTIONS) self::$errorMode = self::THROW_EXCEPTIONS; else return null; return set_error_handler(self::$errorHandler=__CLASS__.'::handleError', error_reporting()); }
php
public static function setupErrorHandling($mode) { if ($mode === self::LOG_ERRORS ) self::$errorMode = self::LOG_ERRORS; elseif ($mode === self::THROW_EXCEPTIONS) self::$errorMode = self::THROW_EXCEPTIONS; else return null; return set_error_handler(self::$errorHandler=__CLASS__.'::handleError', error_reporting()); }
[ "public", "static", "function", "setupErrorHandling", "(", "$", "mode", ")", "{", "if", "(", "$", "mode", "===", "self", "::", "LOG_ERRORS", ")", "self", "::", "$", "errorMode", "=", "self", "::", "LOG_ERRORS", ";", "elseif", "(", "$", "mode", "===", "self", "::", "THROW_EXCEPTIONS", ")", "self", "::", "$", "errorMode", "=", "self", "::", "THROW_EXCEPTIONS", ";", "else", "return", "null", ";", "return", "set_error_handler", "(", "self", "::", "$", "errorHandler", "=", "__CLASS__", ".", "'::handleError'", ",", "error_reporting", "(", ")", ")", ";", "}" ]
Setup global error handling. @param int $mode - mode the error handler to setup for can be either self::LOG_ERRORS or self::THROW_EXCEPTIONS @return mixed - Returns a string containing the previously defined error handler (if any). If the passed $mode parameter is invalid or if the built-in error handler was active NULL is returned. If the previous error handler was a class method an indexed array with the class and the method name is returned.
[ "Setup", "global", "error", "handling", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/debug/ErrorHandler.php#L101-L107
29,469
rosasurfer/ministruts
src/debug/ErrorHandler.php
ErrorHandler.setupExceptionHandling
public static function setupExceptionHandling() { $previous = set_exception_handler(self::$exceptionHandler=__CLASS__.'::handleException'); /** * Detect entering of the script's shutdown phase to be capable of handling destructor exceptions during shutdown * differently and avoid otherwise fatal errors. Should be the very first function on the shutdown function stack. * * @see http://php.net/manual/en/language.oop5.decon.php * @see ErrorHandler::handleDestructorException() */ register_shutdown_function(function() { self::$inShutdown = true; }); return $previous; }
php
public static function setupExceptionHandling() { $previous = set_exception_handler(self::$exceptionHandler=__CLASS__.'::handleException'); /** * Detect entering of the script's shutdown phase to be capable of handling destructor exceptions during shutdown * differently and avoid otherwise fatal errors. Should be the very first function on the shutdown function stack. * * @see http://php.net/manual/en/language.oop5.decon.php * @see ErrorHandler::handleDestructorException() */ register_shutdown_function(function() { self::$inShutdown = true; }); return $previous; }
[ "public", "static", "function", "setupExceptionHandling", "(", ")", "{", "$", "previous", "=", "set_exception_handler", "(", "self", "::", "$", "exceptionHandler", "=", "__CLASS__", ".", "'::handleException'", ")", ";", "/**\n * Detect entering of the script's shutdown phase to be capable of handling destructor exceptions during shutdown\n * differently and avoid otherwise fatal errors. Should be the very first function on the shutdown function stack.\n *\n * @see http://php.net/manual/en/language.oop5.decon.php\n * @see ErrorHandler::handleDestructorException()\n */", "register_shutdown_function", "(", "function", "(", ")", "{", "self", "::", "$", "inShutdown", "=", "true", ";", "}", ")", ";", "return", "$", "previous", ";", "}" ]
Setup global exception handling. @return callable|null - Returns the name of the previously defined exception handler, or NULL if no previous handler was defined or an error occurred.
[ "Setup", "global", "exception", "handling", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/debug/ErrorHandler.php#L116-L130
29,470
rosasurfer/ministruts
src/debug/ErrorHandler.php
ErrorHandler.handleException
public static function handleException(\Exception $exception) { $context = []; $second = null; try { $context['class' ] = __CLASS__; $context['file' ] = $exception->getFile(); // If the location is not preset the logger will resolve the $context['line' ] = $exception->getLine(); // exception handler as the originating location. $context['unhandled'] = true; Logger::log($exception, L_FATAL, $context); // log with the highest level } // Exceptions thrown from within the exception handler will not be passed back to the handler again. Instead the // script terminates with an uncatchable fatal error. catch (\Exception $second) { $indent = ' '; // the application is crashing, last try to log // secondary exception $msg2 = '[FATAL] Unhandled '.trim(DebugHelper::composeBetterMessage($second)).NL; $file = $second->getFile(); $line = $second->getLine(); $msg2 .= $indent.'in '.$file.' on line '.$line.NL.NL; $msg2 .= $indent.'Stacktrace:'.NL.$indent.'-----------'.NL; $msg2 .= DebugHelper::getBetterTraceAsString($second, $indent); // primary (the causing) exception if (isset($context['cliMessage'])) { $msg1 = $context['cliMessage']; if (isset($context['cliExtra'])) $msg1 .= $context['cliExtra']; } else { $msg1 = $indent.'Unhandled '.trim(DebugHelper::composeBetterMessage($exception)).NL; $file = $exception->getFile(); $line = $exception->getLine(); $msg1 .= $indent.'in '.$file.' on line '.$line.NL.NL; $msg1 .= $indent.'Stacktrace:'.NL.$indent.'-----------'.NL; $msg1 .= DebugHelper::getBetterTraceAsString($exception, $indent); } $msg = $msg2.NL; $msg .= $indent.'caused by'.NL; $msg .= $msg1; $msg = str_replace(chr(0), '?', $msg); // replace NUL bytes which mess up the logfile if (CLI) // full second exception echo $msg.NL; error_log(trim($msg), ERROR_LOG_DEFAULT); } // web: prevent an empty page if (!CLI) { try { if (Application::isAdminIP() || ini_get_bool('display_errors')) { if ($second) { // full second exception, full log location echoPre($second); echoPre('error log: '.(strlen($errorLog=ini_get('error_log')) ? $errorLog : 'web server')); } } else echoPre('application error (see error log)'); } catch (\Exception $third) { echoPre('application error (see error log)'); } } }
php
public static function handleException(\Exception $exception) { $context = []; $second = null; try { $context['class' ] = __CLASS__; $context['file' ] = $exception->getFile(); // If the location is not preset the logger will resolve the $context['line' ] = $exception->getLine(); // exception handler as the originating location. $context['unhandled'] = true; Logger::log($exception, L_FATAL, $context); // log with the highest level } // Exceptions thrown from within the exception handler will not be passed back to the handler again. Instead the // script terminates with an uncatchable fatal error. catch (\Exception $second) { $indent = ' '; // the application is crashing, last try to log // secondary exception $msg2 = '[FATAL] Unhandled '.trim(DebugHelper::composeBetterMessage($second)).NL; $file = $second->getFile(); $line = $second->getLine(); $msg2 .= $indent.'in '.$file.' on line '.$line.NL.NL; $msg2 .= $indent.'Stacktrace:'.NL.$indent.'-----------'.NL; $msg2 .= DebugHelper::getBetterTraceAsString($second, $indent); // primary (the causing) exception if (isset($context['cliMessage'])) { $msg1 = $context['cliMessage']; if (isset($context['cliExtra'])) $msg1 .= $context['cliExtra']; } else { $msg1 = $indent.'Unhandled '.trim(DebugHelper::composeBetterMessage($exception)).NL; $file = $exception->getFile(); $line = $exception->getLine(); $msg1 .= $indent.'in '.$file.' on line '.$line.NL.NL; $msg1 .= $indent.'Stacktrace:'.NL.$indent.'-----------'.NL; $msg1 .= DebugHelper::getBetterTraceAsString($exception, $indent); } $msg = $msg2.NL; $msg .= $indent.'caused by'.NL; $msg .= $msg1; $msg = str_replace(chr(0), '?', $msg); // replace NUL bytes which mess up the logfile if (CLI) // full second exception echo $msg.NL; error_log(trim($msg), ERROR_LOG_DEFAULT); } // web: prevent an empty page if (!CLI) { try { if (Application::isAdminIP() || ini_get_bool('display_errors')) { if ($second) { // full second exception, full log location echoPre($second); echoPre('error log: '.(strlen($errorLog=ini_get('error_log')) ? $errorLog : 'web server')); } } else echoPre('application error (see error log)'); } catch (\Exception $third) { echoPre('application error (see error log)'); } } }
[ "public", "static", "function", "handleException", "(", "\\", "Exception", "$", "exception", ")", "{", "$", "context", "=", "[", "]", ";", "$", "second", "=", "null", ";", "try", "{", "$", "context", "[", "'class'", "]", "=", "__CLASS__", ";", "$", "context", "[", "'file'", "]", "=", "$", "exception", "->", "getFile", "(", ")", ";", "// If the location is not preset the logger will resolve the", "$", "context", "[", "'line'", "]", "=", "$", "exception", "->", "getLine", "(", ")", ";", "// exception handler as the originating location.", "$", "context", "[", "'unhandled'", "]", "=", "true", ";", "Logger", "::", "log", "(", "$", "exception", ",", "L_FATAL", ",", "$", "context", ")", ";", "// log with the highest level", "}", "// Exceptions thrown from within the exception handler will not be passed back to the handler again. Instead the", "// script terminates with an uncatchable fatal error.", "catch", "(", "\\", "Exception", "$", "second", ")", "{", "$", "indent", "=", "' '", ";", "// the application is crashing, last try to log", "// secondary exception", "$", "msg2", "=", "'[FATAL] Unhandled '", ".", "trim", "(", "DebugHelper", "::", "composeBetterMessage", "(", "$", "second", ")", ")", ".", "NL", ";", "$", "file", "=", "$", "second", "->", "getFile", "(", ")", ";", "$", "line", "=", "$", "second", "->", "getLine", "(", ")", ";", "$", "msg2", ".=", "$", "indent", ".", "'in '", ".", "$", "file", ".", "' on line '", ".", "$", "line", ".", "NL", ".", "NL", ";", "$", "msg2", ".=", "$", "indent", ".", "'Stacktrace:'", ".", "NL", ".", "$", "indent", ".", "'-----------'", ".", "NL", ";", "$", "msg2", ".=", "DebugHelper", "::", "getBetterTraceAsString", "(", "$", "second", ",", "$", "indent", ")", ";", "// primary (the causing) exception", "if", "(", "isset", "(", "$", "context", "[", "'cliMessage'", "]", ")", ")", "{", "$", "msg1", "=", "$", "context", "[", "'cliMessage'", "]", ";", "if", "(", "isset", "(", "$", "context", "[", "'cliExtra'", "]", ")", ")", "$", "msg1", ".=", "$", "context", "[", "'cliExtra'", "]", ";", "}", "else", "{", "$", "msg1", "=", "$", "indent", ".", "'Unhandled '", ".", "trim", "(", "DebugHelper", "::", "composeBetterMessage", "(", "$", "exception", ")", ")", ".", "NL", ";", "$", "file", "=", "$", "exception", "->", "getFile", "(", ")", ";", "$", "line", "=", "$", "exception", "->", "getLine", "(", ")", ";", "$", "msg1", ".=", "$", "indent", ".", "'in '", ".", "$", "file", ".", "' on line '", ".", "$", "line", ".", "NL", ".", "NL", ";", "$", "msg1", ".=", "$", "indent", ".", "'Stacktrace:'", ".", "NL", ".", "$", "indent", ".", "'-----------'", ".", "NL", ";", "$", "msg1", ".=", "DebugHelper", "::", "getBetterTraceAsString", "(", "$", "exception", ",", "$", "indent", ")", ";", "}", "$", "msg", "=", "$", "msg2", ".", "NL", ";", "$", "msg", ".=", "$", "indent", ".", "'caused by'", ".", "NL", ";", "$", "msg", ".=", "$", "msg1", ";", "$", "msg", "=", "str_replace", "(", "chr", "(", "0", ")", ",", "'?'", ",", "$", "msg", ")", ";", "// replace NUL bytes which mess up the logfile", "if", "(", "CLI", ")", "// full second exception", "echo", "$", "msg", ".", "NL", ";", "error_log", "(", "trim", "(", "$", "msg", ")", ",", "ERROR_LOG_DEFAULT", ")", ";", "}", "// web: prevent an empty page", "if", "(", "!", "CLI", ")", "{", "try", "{", "if", "(", "Application", "::", "isAdminIP", "(", ")", "||", "ini_get_bool", "(", "'display_errors'", ")", ")", "{", "if", "(", "$", "second", ")", "{", "// full second exception, full log location", "echoPre", "(", "$", "second", ")", ";", "echoPre", "(", "'error log: '", ".", "(", "strlen", "(", "$", "errorLog", "=", "ini_get", "(", "'error_log'", ")", ")", "?", "$", "errorLog", ":", "'web server'", ")", ")", ";", "}", "}", "else", "echoPre", "(", "'application error (see error log)'", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "third", ")", "{", "echoPre", "(", "'application error (see error log)'", ")", ";", "}", "}", "}" ]
Global handler for otherwise unhandled exceptions. The exception is sent to the default logger with loglevel L_FATAL. After the handler returns PHP will terminate the script. @param \Exception $exception - the unhandled exception
[ "Global", "handler", "for", "otherwise", "unhandled", "exceptions", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/debug/ErrorHandler.php#L231-L297
29,471
rosasurfer/ministruts
src/debug/ErrorHandler.php
ErrorHandler.handleDestructorException
public static function handleDestructorException(\Exception $exception) { if (self::isInShutdown()) { self::handleException($exception); exit(1); // exit and signal the error // Calling exit() is the only way to prevent the immediately following non-catchable fatal error. // However, calling exit() in a destructor will also prevent any remaining shutdown routines from executing. // @see above link } return $exception; }
php
public static function handleDestructorException(\Exception $exception) { if (self::isInShutdown()) { self::handleException($exception); exit(1); // exit and signal the error // Calling exit() is the only way to prevent the immediately following non-catchable fatal error. // However, calling exit() in a destructor will also prevent any remaining shutdown routines from executing. // @see above link } return $exception; }
[ "public", "static", "function", "handleDestructorException", "(", "\\", "Exception", "$", "exception", ")", "{", "if", "(", "self", "::", "isInShutdown", "(", ")", ")", "{", "self", "::", "handleException", "(", "$", "exception", ")", ";", "exit", "(", "1", ")", ";", "// exit and signal the error", "// Calling exit() is the only way to prevent the immediately following non-catchable fatal error.", "// However, calling exit() in a destructor will also prevent any remaining shutdown routines from executing.", "// @see above link", "}", "return", "$", "exception", ";", "}" ]
Manually called handler for exceptions occurring in object destructors. Attempting to throw an exception from a destructor during script shutdown causes a fatal error. Therefore this method has to be called manually from object destructors if an exception occurred. If the script is in the shutdown phase the exception is passed on to the regular exception handler and the script is terminated. If the script is currently not in the shutdown phase this method ignores the exception. For an example see this package's README. @param \Exception $exception @return \Exception - the same exception @link http://php.net/manual/en/language.oop5.decon.php
[ "Manually", "called", "handler", "for", "exceptions", "occurring", "in", "object", "destructors", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/debug/ErrorHandler.php#L314-L324
29,472
rosasurfer/ministruts
src/net/http/CurlHttpResponse.php
CurlHttpResponse.writeContent
public function writeContent($hCurl, $data) { $this->content .= $data; $obtainedLength = strlen($data); $this->currentContentLength += $obtainedLength; return $obtainedLength; }
php
public function writeContent($hCurl, $data) { $this->content .= $data; $obtainedLength = strlen($data); $this->currentContentLength += $obtainedLength; return $obtainedLength; }
[ "public", "function", "writeContent", "(", "$", "hCurl", ",", "$", "data", ")", "{", "$", "this", "->", "content", ".=", "$", "data", ";", "$", "obtainedLength", "=", "strlen", "(", "$", "data", ")", ";", "$", "this", "->", "currentContentLength", "+=", "$", "obtainedLength", ";", "return", "$", "obtainedLength", ";", "}" ]
Callback fuer CurlHttpClient, dem der empfangene Content des HTTP-Requests chunk-weise uebergeben wird. @param resource $hCurl - das CURL-Handle des aktuellen Requests @param string $data - die empfangenen Daten @return int - Anzahl der bei diesem Methodenaufruf erhaltenen Bytes
[ "Callback", "fuer", "CurlHttpClient", "dem", "der", "empfangene", "Content", "des", "HTTP", "-", "Requests", "chunk", "-", "weise", "uebergeben", "wird", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/net/http/CurlHttpResponse.php#L107-L114
29,473
rosasurfer/ministruts
src/console/docopt/DocoptParser.php
DocoptParser.parseArgs
protected static function parseArgs(TokenIterator $tokens, \ArrayIterator $options, $optionsFirst = false) { $parsed = []; while ($tokens->current() !== null) { if ($tokens->current() == '--') { while ($tokens->current() !== null) { $parsed[] = new Argument(null, $tokens->move()); } return $parsed; } elseif (strStartsWith($tokens->current(), '--')) { $parsed = array_merge($parsed, static::parseLong($tokens, $options)); } elseif (strStartsWith($tokens->current(), '-') && $tokens->current()!='-') { $parsed = array_merge($parsed, static::parseShort($tokens, $options)); } elseif ($optionsFirst) { return array_merge($parsed, array_map(function($value) { return new Argument(null, $value); }, $tokens->left())); } else { $parsed[] = new Argument(null, $tokens->move()); } } return $parsed; }
php
protected static function parseArgs(TokenIterator $tokens, \ArrayIterator $options, $optionsFirst = false) { $parsed = []; while ($tokens->current() !== null) { if ($tokens->current() == '--') { while ($tokens->current() !== null) { $parsed[] = new Argument(null, $tokens->move()); } return $parsed; } elseif (strStartsWith($tokens->current(), '--')) { $parsed = array_merge($parsed, static::parseLong($tokens, $options)); } elseif (strStartsWith($tokens->current(), '-') && $tokens->current()!='-') { $parsed = array_merge($parsed, static::parseShort($tokens, $options)); } elseif ($optionsFirst) { return array_merge($parsed, array_map(function($value) { return new Argument(null, $value); }, $tokens->left())); } else { $parsed[] = new Argument(null, $tokens->move()); } } return $parsed; }
[ "protected", "static", "function", "parseArgs", "(", "TokenIterator", "$", "tokens", ",", "\\", "ArrayIterator", "$", "options", ",", "$", "optionsFirst", "=", "false", ")", "{", "$", "parsed", "=", "[", "]", ";", "while", "(", "$", "tokens", "->", "current", "(", ")", "!==", "null", ")", "{", "if", "(", "$", "tokens", "->", "current", "(", ")", "==", "'--'", ")", "{", "while", "(", "$", "tokens", "->", "current", "(", ")", "!==", "null", ")", "{", "$", "parsed", "[", "]", "=", "new", "Argument", "(", "null", ",", "$", "tokens", "->", "move", "(", ")", ")", ";", "}", "return", "$", "parsed", ";", "}", "elseif", "(", "strStartsWith", "(", "$", "tokens", "->", "current", "(", ")", ",", "'--'", ")", ")", "{", "$", "parsed", "=", "array_merge", "(", "$", "parsed", ",", "static", "::", "parseLong", "(", "$", "tokens", ",", "$", "options", ")", ")", ";", "}", "elseif", "(", "strStartsWith", "(", "$", "tokens", "->", "current", "(", ")", ",", "'-'", ")", "&&", "$", "tokens", "->", "current", "(", ")", "!=", "'-'", ")", "{", "$", "parsed", "=", "array_merge", "(", "$", "parsed", ",", "static", "::", "parseShort", "(", "$", "tokens", ",", "$", "options", ")", ")", ";", "}", "elseif", "(", "$", "optionsFirst", ")", "{", "return", "array_merge", "(", "$", "parsed", ",", "array_map", "(", "function", "(", "$", "value", ")", "{", "return", "new", "Argument", "(", "null", ",", "$", "value", ")", ";", "}", ",", "$", "tokens", "->", "left", "(", ")", ")", ")", ";", "}", "else", "{", "$", "parsed", "[", "]", "=", "new", "Argument", "(", "null", ",", "$", "tokens", "->", "move", "(", ")", ")", ";", "}", "}", "return", "$", "parsed", ";", "}" ]
Parse arguments. If options_first: argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ; else: argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ; @param TokenIterator $tokens @param \ArrayIterator $options @param bool $optionsFirst [optional] @return Pattern[]
[ "Parse", "arguments", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/console/docopt/DocoptParser.php#L191-L217
29,474
timble/kodekit
code/database/row/abstract.php
DatabaseRowAbstract.clear
public function clear() { $this->_data = array(); $this->__modified_properties = array(); $this->setStatus(NULL); if ($this->isConnected()) { $this->_data = $this->getTable()->getDefaults(); } return $this; }
php
public function clear() { $this->_data = array(); $this->__modified_properties = array(); $this->setStatus(NULL); if ($this->isConnected()) { $this->_data = $this->getTable()->getDefaults(); } return $this; }
[ "public", "function", "clear", "(", ")", "{", "$", "this", "->", "_data", "=", "array", "(", ")", ";", "$", "this", "->", "__modified_properties", "=", "array", "(", ")", ";", "$", "this", "->", "setStatus", "(", "NULL", ")", ";", "if", "(", "$", "this", "->", "isConnected", "(", ")", ")", "{", "$", "this", "->", "_data", "=", "$", "this", "->", "getTable", "(", ")", "->", "getDefaults", "(", ")", ";", "}", "return", "$", "this", ";", "}" ]
Clear the row data using the defaults @return DatabaseRowInterface
[ "Clear", "the", "row", "data", "using", "the", "defaults" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/database/row/abstract.php#L182-L193
29,475
rosasurfer/ministruts
src/ministruts/Tile.php
Tile.setNestedTile
public function setNestedTile($name, Tile $tile = null) { if ($this->configured) throw new IllegalStateException('Configuration is frozen'); $this->nestedTiles[$name] = $tile; return $this; }
php
public function setNestedTile($name, Tile $tile = null) { if ($this->configured) throw new IllegalStateException('Configuration is frozen'); $this->nestedTiles[$name] = $tile; return $this; }
[ "public", "function", "setNestedTile", "(", "$", "name", ",", "Tile", "$", "tile", "=", "null", ")", "{", "if", "(", "$", "this", "->", "configured", ")", "throw", "new", "IllegalStateException", "(", "'Configuration is frozen'", ")", ";", "$", "this", "->", "nestedTiles", "[", "$", "name", "]", "=", "$", "tile", ";", "return", "$", "this", ";", "}" ]
Speichert in der Tile unter dem angegebenen Namen eine Child-Tile. @param string $name - Name der Tile @param Tile $tile [optional] - die zu speichernde Tile oder NULL, wenn die Child-Deklaration abstrakt ist @return $this
[ "Speichert", "in", "der", "Tile", "unter", "dem", "angegebenen", "Namen", "eine", "Child", "-", "Tile", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Tile.php#L166-L171
29,476
rosasurfer/ministruts
src/ministruts/Tile.php
Tile.setProperty
public function setProperty($name, $value) { if ($this->configured) throw new IllegalStateException('Configuration is frozen'); $this->properties[$name] = $value; return $this; }
php
public function setProperty($name, $value) { if ($this->configured) throw new IllegalStateException('Configuration is frozen'); $this->properties[$name] = $value; return $this; }
[ "public", "function", "setProperty", "(", "$", "name", ",", "$", "value", ")", "{", "if", "(", "$", "this", "->", "configured", ")", "throw", "new", "IllegalStateException", "(", "'Configuration is frozen'", ")", ";", "$", "this", "->", "properties", "[", "$", "name", "]", "=", "$", "value", ";", "return", "$", "this", ";", "}" ]
Speichert in der Tile unter dem angegebenen Namen eine zusaetzliche Eigenschaft. @param string $name - Name der Eigenschaft @param mixed $value - der zu speichernde Wert @return $this
[ "Speichert", "in", "der", "Tile", "unter", "dem", "angegebenen", "Namen", "eine", "zusaetzliche", "Eigenschaft", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Tile.php#L182-L187
29,477
rosasurfer/ministruts
src/ministruts/Tile.php
Tile.getMergedProperties
protected function getMergedProperties() { $parentProperties = $this->parent ? $this->parent->getMergedProperties() : []; return \array_merge($parentProperties, $this->properties); }
php
protected function getMergedProperties() { $parentProperties = $this->parent ? $this->parent->getMergedProperties() : []; return \array_merge($parentProperties, $this->properties); }
[ "protected", "function", "getMergedProperties", "(", ")", "{", "$", "parentProperties", "=", "$", "this", "->", "parent", "?", "$", "this", "->", "parent", "->", "getMergedProperties", "(", ")", ":", "[", "]", ";", "return", "\\", "array_merge", "(", "$", "parentProperties", ",", "$", "this", "->", "properties", ")", ";", "}" ]
Gibt die eigenen und die Properties der umgebenden Tile zurueck. Eigene Properties ueberschreiben gleichnamige Properties der umgebenden Tile. @return array - Properties
[ "Gibt", "die", "eigenen", "und", "die", "Properties", "der", "umgebenden", "Tile", "zurueck", ".", "Eigene", "Properties", "ueberschreiben", "gleichnamige", "Properties", "der", "umgebenden", "Tile", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Tile.php#L196-L199
29,478
rosasurfer/ministruts
src/ministruts/Tile.php
Tile.freeze
public function freeze() { if (!$this->configured) { if (!$this->fileName) throw new StrutsConfigException('<tile name="'.$this->name.'": No file configured.'); foreach ($this->nestedTiles as $tile) { if ($tile) $tile->freeze(); } $this->configured = true; } return $this; }
php
public function freeze() { if (!$this->configured) { if (!$this->fileName) throw new StrutsConfigException('<tile name="'.$this->name.'": No file configured.'); foreach ($this->nestedTiles as $tile) { if ($tile) $tile->freeze(); } $this->configured = true; } return $this; }
[ "public", "function", "freeze", "(", ")", "{", "if", "(", "!", "$", "this", "->", "configured", ")", "{", "if", "(", "!", "$", "this", "->", "fileName", ")", "throw", "new", "StrutsConfigException", "(", "'<tile name=\"'", ".", "$", "this", "->", "name", ".", "'\": No file configured.'", ")", ";", "foreach", "(", "$", "this", "->", "nestedTiles", "as", "$", "tile", ")", "{", "if", "(", "$", "tile", ")", "$", "tile", "->", "freeze", "(", ")", ";", "}", "$", "this", "->", "configured", "=", "true", ";", "}", "return", "$", "this", ";", "}" ]
Friert die Konfiguration dieser Komponente ein. @return $this @throws StrutsConfigException on configuration errors
[ "Friert", "die", "Konfiguration", "dieser", "Komponente", "ein", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Tile.php#L219-L229
29,479
rosasurfer/ministruts
src/ministruts/Tile.php
Tile.render
public function render() { $request = Request::me(); $namespace = $this->module->getViewNamespace(); $appUri = $request->getApplicationBaseUri(); $nestedTiles = $this->nestedTiles; foreach ($nestedTiles as $tile) { $tile->setParent($this); } $properties = $this->getMergedProperties(); if (!defined($namespace.'APP')) { define($namespace.'APP', strLeft($appUri, -1)); } if (!defined($namespace.'MODULE')) { $moduleUri = $appUri.$this->module->getPrefix(); define($namespace.'MODULE', strLeft($moduleUri, -1)); } $properties['request' ] = $request; $properties['response'] = Response::me(); $properties['session' ] = $request->isSession() ? $request->getSession() : null; $properties['form' ] = $request->getAttribute(ACTION_FORM_KEY); $properties['page' ] = Page::me(); if ($this->isPushModelSupport()) { $pageValues = Page::me()->values(); $properties = \array_merge($properties, $pageValues); } $tileHint = false; if (Application::isAdminIP()) { $rootDir = $this->di('config')['app.dir.root']; $file = $this->fileName; $file = strRightFrom($file, $rootDir.DIRECTORY_SEPARATOR, 1, false, $file); $file = 'file="'.str_replace('\\', '/', $file).'"'; $tile = $this->name==self::GENERIC_NAME ? '':'tile="'.$this->name.'" '; $tileHint = $tile.$file; echo ($this->parent ? NL:'').'<!-- #begin: '.$tileHint.' -->'.NL; } includeFile($this->fileName, $nestedTiles + $properties); if ($tileHint) { echo NL.'<!-- #end: '.$tileHint.' -->'.NL; } return $this; }
php
public function render() { $request = Request::me(); $namespace = $this->module->getViewNamespace(); $appUri = $request->getApplicationBaseUri(); $nestedTiles = $this->nestedTiles; foreach ($nestedTiles as $tile) { $tile->setParent($this); } $properties = $this->getMergedProperties(); if (!defined($namespace.'APP')) { define($namespace.'APP', strLeft($appUri, -1)); } if (!defined($namespace.'MODULE')) { $moduleUri = $appUri.$this->module->getPrefix(); define($namespace.'MODULE', strLeft($moduleUri, -1)); } $properties['request' ] = $request; $properties['response'] = Response::me(); $properties['session' ] = $request->isSession() ? $request->getSession() : null; $properties['form' ] = $request->getAttribute(ACTION_FORM_KEY); $properties['page' ] = Page::me(); if ($this->isPushModelSupport()) { $pageValues = Page::me()->values(); $properties = \array_merge($properties, $pageValues); } $tileHint = false; if (Application::isAdminIP()) { $rootDir = $this->di('config')['app.dir.root']; $file = $this->fileName; $file = strRightFrom($file, $rootDir.DIRECTORY_SEPARATOR, 1, false, $file); $file = 'file="'.str_replace('\\', '/', $file).'"'; $tile = $this->name==self::GENERIC_NAME ? '':'tile="'.$this->name.'" '; $tileHint = $tile.$file; echo ($this->parent ? NL:'').'<!-- #begin: '.$tileHint.' -->'.NL; } includeFile($this->fileName, $nestedTiles + $properties); if ($tileHint) { echo NL.'<!-- #end: '.$tileHint.' -->'.NL; } return $this; }
[ "public", "function", "render", "(", ")", "{", "$", "request", "=", "Request", "::", "me", "(", ")", ";", "$", "namespace", "=", "$", "this", "->", "module", "->", "getViewNamespace", "(", ")", ";", "$", "appUri", "=", "$", "request", "->", "getApplicationBaseUri", "(", ")", ";", "$", "nestedTiles", "=", "$", "this", "->", "nestedTiles", ";", "foreach", "(", "$", "nestedTiles", "as", "$", "tile", ")", "{", "$", "tile", "->", "setParent", "(", "$", "this", ")", ";", "}", "$", "properties", "=", "$", "this", "->", "getMergedProperties", "(", ")", ";", "if", "(", "!", "defined", "(", "$", "namespace", ".", "'APP'", ")", ")", "{", "define", "(", "$", "namespace", ".", "'APP'", ",", "strLeft", "(", "$", "appUri", ",", "-", "1", ")", ")", ";", "}", "if", "(", "!", "defined", "(", "$", "namespace", ".", "'MODULE'", ")", ")", "{", "$", "moduleUri", "=", "$", "appUri", ".", "$", "this", "->", "module", "->", "getPrefix", "(", ")", ";", "define", "(", "$", "namespace", ".", "'MODULE'", ",", "strLeft", "(", "$", "moduleUri", ",", "-", "1", ")", ")", ";", "}", "$", "properties", "[", "'request'", "]", "=", "$", "request", ";", "$", "properties", "[", "'response'", "]", "=", "Response", "::", "me", "(", ")", ";", "$", "properties", "[", "'session'", "]", "=", "$", "request", "->", "isSession", "(", ")", "?", "$", "request", "->", "getSession", "(", ")", ":", "null", ";", "$", "properties", "[", "'form'", "]", "=", "$", "request", "->", "getAttribute", "(", "ACTION_FORM_KEY", ")", ";", "$", "properties", "[", "'page'", "]", "=", "Page", "::", "me", "(", ")", ";", "if", "(", "$", "this", "->", "isPushModelSupport", "(", ")", ")", "{", "$", "pageValues", "=", "Page", "::", "me", "(", ")", "->", "values", "(", ")", ";", "$", "properties", "=", "\\", "array_merge", "(", "$", "properties", ",", "$", "pageValues", ")", ";", "}", "$", "tileHint", "=", "false", ";", "if", "(", "Application", "::", "isAdminIP", "(", ")", ")", "{", "$", "rootDir", "=", "$", "this", "->", "di", "(", "'config'", ")", "[", "'app.dir.root'", "]", ";", "$", "file", "=", "$", "this", "->", "fileName", ";", "$", "file", "=", "strRightFrom", "(", "$", "file", ",", "$", "rootDir", ".", "DIRECTORY_SEPARATOR", ",", "1", ",", "false", ",", "$", "file", ")", ";", "$", "file", "=", "'file=\"'", ".", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "$", "file", ")", ".", "'\"'", ";", "$", "tile", "=", "$", "this", "->", "name", "==", "self", "::", "GENERIC_NAME", "?", "''", ":", "'tile=\"'", ".", "$", "this", "->", "name", ".", "'\" '", ";", "$", "tileHint", "=", "$", "tile", ".", "$", "file", ";", "echo", "(", "$", "this", "->", "parent", "?", "NL", ":", "''", ")", ".", "'<!-- #begin: '", ".", "$", "tileHint", ".", "' -->'", ".", "NL", ";", "}", "includeFile", "(", "$", "this", "->", "fileName", ",", "$", "nestedTiles", "+", "$", "properties", ")", ";", "if", "(", "$", "tileHint", ")", "{", "echo", "NL", ".", "'<!-- #end: '", ".", "$", "tileHint", ".", "' -->'", ".", "NL", ";", "}", "return", "$", "this", ";", "}" ]
Render the Tile. @return $this
[ "Render", "the", "Tile", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Tile.php#L237-L283
29,480
deArcane/framework
src/User28/Utils/Hash.php
Hash.hash
private function hash(int $length):string { $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // strlen($char) = 62 $hash = ''; for( $i=0; $i < $length; $i++ ) $hash .= $char[random_int(0,61)]; return $hash; }
php
private function hash(int $length):string { $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // strlen($char) = 62 $hash = ''; for( $i=0; $i < $length; $i++ ) $hash .= $char[random_int(0,61)]; return $hash; }
[ "private", "function", "hash", "(", "int", "$", "length", ")", ":", "string", "{", "$", "char", "=", "'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'", ";", "// strlen($char) = 62", "$", "hash", "=", "''", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "length", ";", "$", "i", "++", ")", "$", "hash", ".=", "$", "char", "[", "random_int", "(", "0", ",", "61", ")", "]", ";", "return", "$", "hash", ";", "}" ]
Create random hash.
[ "Create", "random", "hash", "." ]
468da43678119f8c9e3f67183b5bec727c436404
https://github.com/deArcane/framework/blob/468da43678119f8c9e3f67183b5bec727c436404/src/User28/Utils/Hash.php#L12-L18
29,481
deArcane/framework
src/User28/Utils/Hash.php
Hash.selector
private function selector():string{ $selector = $this->hash(50); // Check if selector is unique. do{ $isUnique = Input::$token->selectOneBySelector($selector); }while( $isUnique[0] !== null ); return $selector; }
php
private function selector():string{ $selector = $this->hash(50); // Check if selector is unique. do{ $isUnique = Input::$token->selectOneBySelector($selector); }while( $isUnique[0] !== null ); return $selector; }
[ "private", "function", "selector", "(", ")", ":", "string", "{", "$", "selector", "=", "$", "this", "->", "hash", "(", "50", ")", ";", "// Check if selector is unique.", "do", "{", "$", "isUnique", "=", "Input", "::", "$", "token", "->", "selectOneBySelector", "(", "$", "selector", ")", ";", "}", "while", "(", "$", "isUnique", "[", "0", "]", "!==", "null", ")", ";", "return", "$", "selector", ";", "}" ]
Create selector.
[ "Create", "selector", "." ]
468da43678119f8c9e3f67183b5bec727c436404
https://github.com/deArcane/framework/blob/468da43678119f8c9e3f67183b5bec727c436404/src/User28/Utils/Hash.php#L23-L30
29,482
dereuromark/cakephp-feedback
src/Controller/Admin/FeedbackController.php
FeedbackController.index
public function index() { $savepath = Configure::read('Feedback.configuration.Filesystem.location'); //Check dir if (!is_dir($savepath)) { mkdir($savepath, 0770, true); if (!is_dir($savepath)) { throw new NotFoundException('Feedback location not found: ' . $savepath); } } //Creat feedback array in a cake-like way $feedbacks = []; //Loop through files foreach (glob($savepath . '*.feedback') as $feedbackfile) { $feedbackObject = unserialize(file_get_contents($feedbackfile)); $feedbacks[$feedbackObject['time']] = $feedbackObject; } //Sort by time krsort($feedbacks); $this->set('feedbacks', $feedbacks); }
php
public function index() { $savepath = Configure::read('Feedback.configuration.Filesystem.location'); //Check dir if (!is_dir($savepath)) { mkdir($savepath, 0770, true); if (!is_dir($savepath)) { throw new NotFoundException('Feedback location not found: ' . $savepath); } } //Creat feedback array in a cake-like way $feedbacks = []; //Loop through files foreach (glob($savepath . '*.feedback') as $feedbackfile) { $feedbackObject = unserialize(file_get_contents($feedbackfile)); $feedbacks[$feedbackObject['time']] = $feedbackObject; } //Sort by time krsort($feedbacks); $this->set('feedbacks', $feedbacks); }
[ "public", "function", "index", "(", ")", "{", "$", "savepath", "=", "Configure", "::", "read", "(", "'Feedback.configuration.Filesystem.location'", ")", ";", "//Check dir", "if", "(", "!", "is_dir", "(", "$", "savepath", ")", ")", "{", "mkdir", "(", "$", "savepath", ",", "0770", ",", "true", ")", ";", "if", "(", "!", "is_dir", "(", "$", "savepath", ")", ")", "{", "throw", "new", "NotFoundException", "(", "'Feedback location not found: '", ".", "$", "savepath", ")", ";", "}", "}", "//Creat feedback array in a cake-like way", "$", "feedbacks", "=", "[", "]", ";", "//Loop through files", "foreach", "(", "glob", "(", "$", "savepath", ".", "'*.feedback'", ")", "as", "$", "feedbackfile", ")", "{", "$", "feedbackObject", "=", "unserialize", "(", "file_get_contents", "(", "$", "feedbackfile", ")", ")", ";", "$", "feedbacks", "[", "$", "feedbackObject", "[", "'time'", "]", "]", "=", "$", "feedbackObject", ";", "}", "//Sort by time", "krsort", "(", "$", "feedbacks", ")", ";", "$", "this", "->", "set", "(", "'feedbacks'", ",", "$", "feedbacks", ")", ";", "}" ]
Example index function for current save in tmp dir solution @return \Cake\Http\Response|null
[ "Example", "index", "function", "for", "current", "save", "in", "tmp", "dir", "solution" ]
0bd774fda38b3cdd05db8c07a06a526d3ba81879
https://github.com/dereuromark/cakephp-feedback/blob/0bd774fda38b3cdd05db8c07a06a526d3ba81879/src/Controller/Admin/FeedbackController.php#L50-L76
29,483
rosasurfer/ministruts
etc/phpstan/DAO_Find_ReturnType.php
DAO_Find_ReturnType.resolveReturnType
protected function resolveReturnType(Type $type, \Closure $resolver) : Type { if ($type instanceof UnionType) { $old = $type->getTypes(); $new = []; foreach ($old as $subtype) $new[] = $resolver($subtype); return ($old===$new) ? $type : new UnionType($new); } return $resolver($type); }
php
protected function resolveReturnType(Type $type, \Closure $resolver) : Type { if ($type instanceof UnionType) { $old = $type->getTypes(); $new = []; foreach ($old as $subtype) $new[] = $resolver($subtype); return ($old===$new) ? $type : new UnionType($new); } return $resolver($type); }
[ "protected", "function", "resolveReturnType", "(", "Type", "$", "type", ",", "\\", "Closure", "$", "resolver", ")", ":", "Type", "{", "if", "(", "$", "type", "instanceof", "UnionType", ")", "{", "$", "old", "=", "$", "type", "->", "getTypes", "(", ")", ";", "$", "new", "=", "[", "]", ";", "foreach", "(", "$", "old", "as", "$", "subtype", ")", "$", "new", "[", "]", "=", "$", "resolver", "(", "$", "subtype", ")", ";", "return", "(", "$", "old", "===", "$", "new", ")", "?", "$", "type", ":", "new", "UnionType", "(", "$", "new", ")", ";", "}", "return", "$", "resolver", "(", "$", "type", ")", ";", "}" ]
Resolve a return type using a resolver function. @return Type
[ "Resolve", "a", "return", "type", "using", "a", "resolver", "function", "." ]
9d27f93dd53d2d626c75c92cfde9d004bab34d30
https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/etc/phpstan/DAO_Find_ReturnType.php#L128-L137
29,484
timble/kodekit
code/controller/response/response.php
ControllerResponse.addMessage
public function addMessage($message, $type = self::FLASH_SUCCESS) { if (!is_string($message) && !(is_object($message) && method_exists($message, '__toString'))) { throw new \UnexpectedValueException( 'The flash message must be a string or object implementing __toString(), "'.gettype($message).'" given.' ); } if(!isset($this->_messages[$type])) { $this->_messages[$type] = array(); } $this->_messages[$type][] = $message; return $this; }
php
public function addMessage($message, $type = self::FLASH_SUCCESS) { if (!is_string($message) && !(is_object($message) && method_exists($message, '__toString'))) { throw new \UnexpectedValueException( 'The flash message must be a string or object implementing __toString(), "'.gettype($message).'" given.' ); } if(!isset($this->_messages[$type])) { $this->_messages[$type] = array(); } $this->_messages[$type][] = $message; return $this; }
[ "public", "function", "addMessage", "(", "$", "message", ",", "$", "type", "=", "self", "::", "FLASH_SUCCESS", ")", "{", "if", "(", "!", "is_string", "(", "$", "message", ")", "&&", "!", "(", "is_object", "(", "$", "message", ")", "&&", "method_exists", "(", "$", "message", ",", "'__toString'", ")", ")", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "'The flash message must be a string or object implementing __toString(), \"'", ".", "gettype", "(", "$", "message", ")", ".", "'\" given.'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "_messages", "[", "$", "type", "]", ")", ")", "{", "$", "this", "->", "_messages", "[", "$", "type", "]", "=", "array", "(", ")", ";", "}", "$", "this", "->", "_messages", "[", "$", "type", "]", "[", "]", "=", "$", "message", ";", "return", "$", "this", ";", "}" ]
Add a response message Flash messages are self-expiring messages that are meant to live for exactly one request. They can be used across redirects, or flushed at the end of the request. @param string $message The flash message @param string $type Message category type. Default is 'success'. @throws \UnexpectedValueException @return ControllerResponse
[ "Add", "a", "response", "message" ]
4c376f8873f8d10c55e3d290616ff622605cd246
https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/controller/response/response.php#L182-L197
29,485
symbiote/silverstripe-content-services
code/content/ContentService.php
ContentService.getWriterFor
public function getWriterFor(DataObject $object = null, $field = 'FilePointer', $type = null) { if ($object && $field && $object->hasField($field)) { $val = $object->$field; if (strlen($val)) { $reader = $this->getReader($val); if ($reader && $reader->isReadable()) { return $reader->getWriter(); } } } if (!$type) { // specifically expecting to be handling File objects, but allows other // objects to play too if ($object && $object->hasMethod('getEffectiveContentStore')) { $type = $object->getEffectiveContentStore(); } else { $type = $this->defaultStore; } } // looks like we're getting a writer with no underlying file (as yet) return $this->getWriter($type); }
php
public function getWriterFor(DataObject $object = null, $field = 'FilePointer', $type = null) { if ($object && $field && $object->hasField($field)) { $val = $object->$field; if (strlen($val)) { $reader = $this->getReader($val); if ($reader && $reader->isReadable()) { return $reader->getWriter(); } } } if (!$type) { // specifically expecting to be handling File objects, but allows other // objects to play too if ($object && $object->hasMethod('getEffectiveContentStore')) { $type = $object->getEffectiveContentStore(); } else { $type = $this->defaultStore; } } // looks like we're getting a writer with no underlying file (as yet) return $this->getWriter($type); }
[ "public", "function", "getWriterFor", "(", "DataObject", "$", "object", "=", "null", ",", "$", "field", "=", "'FilePointer'", ",", "$", "type", "=", "null", ")", "{", "if", "(", "$", "object", "&&", "$", "field", "&&", "$", "object", "->", "hasField", "(", "$", "field", ")", ")", "{", "$", "val", "=", "$", "object", "->", "$", "field", ";", "if", "(", "strlen", "(", "$", "val", ")", ")", "{", "$", "reader", "=", "$", "this", "->", "getReader", "(", "$", "val", ")", ";", "if", "(", "$", "reader", "&&", "$", "reader", "->", "isReadable", "(", ")", ")", "{", "return", "$", "reader", "->", "getWriter", "(", ")", ";", "}", "}", "}", "if", "(", "!", "$", "type", ")", "{", "// specifically expecting to be handling File objects, but allows other ", "// objects to play too", "if", "(", "$", "object", "&&", "$", "object", "->", "hasMethod", "(", "'getEffectiveContentStore'", ")", ")", "{", "$", "type", "=", "$", "object", "->", "getEffectiveContentStore", "(", ")", ";", "}", "else", "{", "$", "type", "=", "$", "this", "->", "defaultStore", ";", "}", "}", "// looks like we're getting a writer with no underlying file (as yet)", "return", "$", "this", "->", "getWriter", "(", "$", "type", ")", ";", "}" ]
Gets a writer for a DataObject If the field already has a value, a writer is created matching that identifier. Otherwise, a new writer is created based on either - The $type passed in - whether the $object class specifies a prefered storage type via getEffectiveContentStore - what the `defaultStore` is set to for the content service @param DataObject $object The object to get a writer for @param String $field The field being written to @param String $type Explicitly state what the content store type will be @return ContentWriter
[ "Gets", "a", "writer", "for", "a", "DataObject" ]
d6dec8da12208d876051aa4329a9b76032172bfa
https://github.com/symbiote/silverstripe-content-services/blob/d6dec8da12208d876051aa4329a9b76032172bfa/code/content/ContentService.php#L68-L91
29,486
symbiote/silverstripe-content-services
code/content/ContentService.php
ContentService.findReaderFor
public function findReaderFor($storeType, $assetName, $remapToId = true) { $writer = $this->getWriter($storeType); $contentId = $storeType . self::SEPARATOR . ($remapToId ? $writer->nameToId($assetName) : $assetName); $reader = $this->getReader($contentId); return $reader ? ($reader->isReadable() ? $reader : null) : null; }
php
public function findReaderFor($storeType, $assetName, $remapToId = true) { $writer = $this->getWriter($storeType); $contentId = $storeType . self::SEPARATOR . ($remapToId ? $writer->nameToId($assetName) : $assetName); $reader = $this->getReader($contentId); return $reader ? ($reader->isReadable() ? $reader : null) : null; }
[ "public", "function", "findReaderFor", "(", "$", "storeType", ",", "$", "assetName", ",", "$", "remapToId", "=", "true", ")", "{", "$", "writer", "=", "$", "this", "->", "getWriter", "(", "$", "storeType", ")", ";", "$", "contentId", "=", "$", "storeType", ".", "self", "::", "SEPARATOR", ".", "(", "$", "remapToId", "?", "$", "writer", "->", "nameToId", "(", "$", "assetName", ")", ":", "$", "assetName", ")", ";", "$", "reader", "=", "$", "this", "->", "getReader", "(", "$", "contentId", ")", ";", "return", "$", "reader", "?", "(", "$", "reader", "->", "isReadable", "(", ")", "?", "$", "reader", ":", "null", ")", ":", "null", ";", "}" ]
Gets a content reader for the given store type over the asset given in assetName. This is used for finding if an asset is stored remotely or not Returns NULL if that asset doesn't exist. @param string $storeType The named store we're looking into @param string $assetName The name of the asset to look up @param boolean $remapToId Do we let the reader remap the name to how it represents asset paths? Or are we looking up an already-mapped path name? @return ContentReader
[ "Gets", "a", "content", "reader", "for", "the", "given", "store", "type", "over", "the", "asset", "given", "in", "assetName", ".", "This", "is", "used", "for", "finding", "if", "an", "asset", "is", "stored", "remotely", "or", "not" ]
d6dec8da12208d876051aa4329a9b76032172bfa
https://github.com/symbiote/silverstripe-content-services/blob/d6dec8da12208d876051aa4329a9b76032172bfa/code/content/ContentService.php#L161-L166
29,487
Innmind/Immutable
src/Str.php
Str.split
public function split(string $delimiter = null): StreamInterface { if (\is_null($delimiter) || $delimiter === '') { return $this->chunk(); } $parts = \explode($delimiter, $this->value); $stream = new Stream(self::class); foreach ($parts as $part) { $stream = $stream->add(new self($part, $this->encoding)); } return $stream; }
php
public function split(string $delimiter = null): StreamInterface { if (\is_null($delimiter) || $delimiter === '') { return $this->chunk(); } $parts = \explode($delimiter, $this->value); $stream = new Stream(self::class); foreach ($parts as $part) { $stream = $stream->add(new self($part, $this->encoding)); } return $stream; }
[ "public", "function", "split", "(", "string", "$", "delimiter", "=", "null", ")", ":", "StreamInterface", "{", "if", "(", "\\", "is_null", "(", "$", "delimiter", ")", "||", "$", "delimiter", "===", "''", ")", "{", "return", "$", "this", "->", "chunk", "(", ")", ";", "}", "$", "parts", "=", "\\", "explode", "(", "$", "delimiter", ",", "$", "this", "->", "value", ")", ";", "$", "stream", "=", "new", "Stream", "(", "self", "::", "class", ")", ";", "foreach", "(", "$", "parts", "as", "$", "part", ")", "{", "$", "stream", "=", "$", "stream", "->", "add", "(", "new", "self", "(", "$", "part", ",", "$", "this", "->", "encoding", ")", ")", ";", "}", "return", "$", "stream", ";", "}" ]
Split the string into a collection of ones @param string $delimiter @return StreamInterface<self>
[ "Split", "the", "string", "into", "a", "collection", "of", "ones" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L74-L88
29,488
Innmind/Immutable
src/Str.php
Str.chunk
public function chunk(int $size = 1): StreamInterface { $stream = new Stream(self::class); $string = $this; while ($string->length() > 0) { $stream = $stream->add($string->substring(0, $size)); $string = $string->substring($size); } return $stream; }
php
public function chunk(int $size = 1): StreamInterface { $stream = new Stream(self::class); $string = $this; while ($string->length() > 0) { $stream = $stream->add($string->substring(0, $size)); $string = $string->substring($size); } return $stream; }
[ "public", "function", "chunk", "(", "int", "$", "size", "=", "1", ")", ":", "StreamInterface", "{", "$", "stream", "=", "new", "Stream", "(", "self", "::", "class", ")", ";", "$", "string", "=", "$", "this", ";", "while", "(", "$", "string", "->", "length", "(", ")", ">", "0", ")", "{", "$", "stream", "=", "$", "stream", "->", "add", "(", "$", "string", "->", "substring", "(", "0", ",", "$", "size", ")", ")", ";", "$", "string", "=", "$", "string", "->", "substring", "(", "$", "size", ")", ";", "}", "return", "$", "stream", ";", "}" ]
Returns a collection of the string splitted by the given chunk size @param int $size @return StreamInterface<self>
[ "Returns", "a", "collection", "of", "the", "string", "splitted", "by", "the", "given", "chunk", "size" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L97-L108
29,489
Innmind/Immutable
src/Str.php
Str.position
public function position(string $needle, int $offset = 0): int { $position = \mb_strpos($this->value, $needle, $offset, (string) $this->encoding()); if ($position === false) { throw new SubstringException(\sprintf( 'Substring "%s" not found', $needle )); } return (int) $position; }
php
public function position(string $needle, int $offset = 0): int { $position = \mb_strpos($this->value, $needle, $offset, (string) $this->encoding()); if ($position === false) { throw new SubstringException(\sprintf( 'Substring "%s" not found', $needle )); } return (int) $position; }
[ "public", "function", "position", "(", "string", "$", "needle", ",", "int", "$", "offset", "=", "0", ")", ":", "int", "{", "$", "position", "=", "\\", "mb_strpos", "(", "$", "this", "->", "value", ",", "$", "needle", ",", "$", "offset", ",", "(", "string", ")", "$", "this", "->", "encoding", "(", ")", ")", ";", "if", "(", "$", "position", "===", "false", ")", "{", "throw", "new", "SubstringException", "(", "\\", "sprintf", "(", "'Substring \"%s\" not found'", ",", "$", "needle", ")", ")", ";", "}", "return", "(", "int", ")", "$", "position", ";", "}" ]
Returns the position of the first occurence of the string @param string $needle @param int $offset @throws SubstringException If the string is not found @return int
[ "Returns", "the", "position", "of", "the", "first", "occurence", "of", "the", "string" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L120-L132
29,490
Innmind/Immutable
src/Str.php
Str.replace
public function replace(string $search, string $replacement): self { if (!$this->contains($search)) { return $this; } return $this ->split($search) ->join($replacement); }
php
public function replace(string $search, string $replacement): self { if (!$this->contains($search)) { return $this; } return $this ->split($search) ->join($replacement); }
[ "public", "function", "replace", "(", "string", "$", "search", ",", "string", "$", "replacement", ")", ":", "self", "{", "if", "(", "!", "$", "this", "->", "contains", "(", "$", "search", ")", ")", "{", "return", "$", "this", ";", "}", "return", "$", "this", "->", "split", "(", "$", "search", ")", "->", "join", "(", "$", "replacement", ")", ";", "}" ]
Replace all occurences of the search string with the replacement one @param string $search @param string $replacement @return self
[ "Replace", "all", "occurences", "of", "the", "search", "string", "with", "the", "replacement", "one" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L142-L151
29,491
Innmind/Immutable
src/Str.php
Str.str
public function str(string $delimiter): self { $sub = \mb_strstr($this->value, $delimiter, false, (string) $this->encoding()); if ($sub === false) { throw new SubstringException(\sprintf( 'Substring "%s" not found', $delimiter )); } return new self($sub, $this->encoding); }
php
public function str(string $delimiter): self { $sub = \mb_strstr($this->value, $delimiter, false, (string) $this->encoding()); if ($sub === false) { throw new SubstringException(\sprintf( 'Substring "%s" not found', $delimiter )); } return new self($sub, $this->encoding); }
[ "public", "function", "str", "(", "string", "$", "delimiter", ")", ":", "self", "{", "$", "sub", "=", "\\", "mb_strstr", "(", "$", "this", "->", "value", ",", "$", "delimiter", ",", "false", ",", "(", "string", ")", "$", "this", "->", "encoding", "(", ")", ")", ";", "if", "(", "$", "sub", "===", "false", ")", "{", "throw", "new", "SubstringException", "(", "\\", "sprintf", "(", "'Substring \"%s\" not found'", ",", "$", "delimiter", ")", ")", ";", "}", "return", "new", "self", "(", "$", "sub", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Returns the string following the given delimiter @param string $delimiter @throws SubstringException If the string is not found @return self
[ "Returns", "the", "string", "following", "the", "given", "delimiter" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L162-L174
29,492
Innmind/Immutable
src/Str.php
Str.rightPad
public function rightPad(int $length, string $character = ' '): self { return $this->pad($length, $character, self::PAD_RIGHT); }
php
public function rightPad(int $length, string $character = ' '): self { return $this->pad($length, $character, self::PAD_RIGHT); }
[ "public", "function", "rightPad", "(", "int", "$", "length", ",", "string", "$", "character", "=", "' '", ")", ":", "self", "{", "return", "$", "this", "->", "pad", "(", "$", "length", ",", "$", "character", ",", "self", "::", "PAD_RIGHT", ")", ";", "}" ]
Pad to the right @param int $length @param string $character @return self
[ "Pad", "to", "the", "right" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L232-L235
29,493
Innmind/Immutable
src/Str.php
Str.leftPad
public function leftPad(int $length, string $character = ' '): self { return $this->pad($length, $character, self::PAD_LEFT); }
php
public function leftPad(int $length, string $character = ' '): self { return $this->pad($length, $character, self::PAD_LEFT); }
[ "public", "function", "leftPad", "(", "int", "$", "length", ",", "string", "$", "character", "=", "' '", ")", ":", "self", "{", "return", "$", "this", "->", "pad", "(", "$", "length", ",", "$", "character", ",", "self", "::", "PAD_LEFT", ")", ";", "}" ]
Pad to the left @param int $length @param string $character @return self
[ "Pad", "to", "the", "left" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L245-L248
29,494
Innmind/Immutable
src/Str.php
Str.uniPad
public function uniPad(int $length, string $character = ' '): self { return $this->pad($length, $character, self::PAD_BOTH); }
php
public function uniPad(int $length, string $character = ' '): self { return $this->pad($length, $character, self::PAD_BOTH); }
[ "public", "function", "uniPad", "(", "int", "$", "length", ",", "string", "$", "character", "=", "' '", ")", ":", "self", "{", "return", "$", "this", "->", "pad", "(", "$", "length", ",", "$", "character", ",", "self", "::", "PAD_BOTH", ")", ";", "}" ]
Pad both sides @param int $length @param string $character @return self
[ "Pad", "both", "sides" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L258-L261
29,495
Innmind/Immutable
src/Str.php
Str.cspn
public function cspn(string $mask, int $start = 0, int $length = null): int { if ($length === null) { $value = \strcspn($this->value, $mask, $start); } else { $value = \strcspn( $this->value, $mask, $start, $length ); } return (int) $value; }
php
public function cspn(string $mask, int $start = 0, int $length = null): int { if ($length === null) { $value = \strcspn($this->value, $mask, $start); } else { $value = \strcspn( $this->value, $mask, $start, $length ); } return (int) $value; }
[ "public", "function", "cspn", "(", "string", "$", "mask", ",", "int", "$", "start", "=", "0", ",", "int", "$", "length", "=", "null", ")", ":", "int", "{", "if", "(", "$", "length", "===", "null", ")", "{", "$", "value", "=", "\\", "strcspn", "(", "$", "this", "->", "value", ",", "$", "mask", ",", "$", "start", ")", ";", "}", "else", "{", "$", "value", "=", "\\", "strcspn", "(", "$", "this", "->", "value", ",", "$", "mask", ",", "$", "start", ",", "$", "length", ")", ";", "}", "return", "(", "int", ")", "$", "value", ";", "}" ]
Find length of initial segment not matching mask @param string $mask @param int $start @param int $length @return int
[ "Find", "length", "of", "initial", "segment", "not", "matching", "mask" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L272-L286
29,496
Innmind/Immutable
src/Str.php
Str.repeat
public function repeat(int $repeat): self { return new self(\str_repeat($this->value, $repeat), $this->encoding); }
php
public function repeat(int $repeat): self { return new self(\str_repeat($this->value, $repeat), $this->encoding); }
[ "public", "function", "repeat", "(", "int", "$", "repeat", ")", ":", "self", "{", "return", "new", "self", "(", "\\", "str_repeat", "(", "$", "this", "->", "value", ",", "$", "repeat", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Repeat the string n times @param int $repeat @return self
[ "Repeat", "the", "string", "n", "times" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L295-L298
29,497
Innmind/Immutable
src/Str.php
Str.shuffle
public function shuffle(): self { $parts = $this->chunk()->toPrimitive(); \shuffle($parts); return new self(\implode('', $parts), $this->encoding); }
php
public function shuffle(): self { $parts = $this->chunk()->toPrimitive(); \shuffle($parts); return new self(\implode('', $parts), $this->encoding); }
[ "public", "function", "shuffle", "(", ")", ":", "self", "{", "$", "parts", "=", "$", "this", "->", "chunk", "(", ")", "->", "toPrimitive", "(", ")", ";", "\\", "shuffle", "(", "$", "parts", ")", ";", "return", "new", "self", "(", "\\", "implode", "(", "''", ",", "$", "parts", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Shuffle the string @return self
[ "Shuffle", "the", "string" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L305-L311
29,498
Innmind/Immutable
src/Str.php
Str.words
public function words(string $charlist = ''): MapInterface { $words = \str_word_count($this->value, 2, $charlist); $map = new Map('int', self::class); foreach ($words as $position => $word) { $map = $map->put($position, new self($word, $this->encoding)); } return $map; }
php
public function words(string $charlist = ''): MapInterface { $words = \str_word_count($this->value, 2, $charlist); $map = new Map('int', self::class); foreach ($words as $position => $word) { $map = $map->put($position, new self($word, $this->encoding)); } return $map; }
[ "public", "function", "words", "(", "string", "$", "charlist", "=", "''", ")", ":", "MapInterface", "{", "$", "words", "=", "\\", "str_word_count", "(", "$", "this", "->", "value", ",", "2", ",", "$", "charlist", ")", ";", "$", "map", "=", "new", "Map", "(", "'int'", ",", "self", "::", "class", ")", ";", "foreach", "(", "$", "words", "as", "$", "position", "=>", "$", "word", ")", "{", "$", "map", "=", "$", "map", "->", "put", "(", "$", "position", ",", "new", "self", "(", "$", "word", ",", "$", "this", "->", "encoding", ")", ")", ";", "}", "return", "$", "map", ";", "}" ]
Return the collection of words @param string $charlist @return MapInterface<int, self>
[ "Return", "the", "collection", "of", "words" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L356-L366
29,499
Innmind/Immutable
src/Str.php
Str.pregSplit
public function pregSplit(string $regex, int $limit = -1): StreamInterface { $strings = \preg_split($regex, $this->value, $limit); $stream = new Stream(self::class); foreach ($strings as $string) { $stream = $stream->add(new self($string, $this->encoding)); } return $stream; }
php
public function pregSplit(string $regex, int $limit = -1): StreamInterface { $strings = \preg_split($regex, $this->value, $limit); $stream = new Stream(self::class); foreach ($strings as $string) { $stream = $stream->add(new self($string, $this->encoding)); } return $stream; }
[ "public", "function", "pregSplit", "(", "string", "$", "regex", ",", "int", "$", "limit", "=", "-", "1", ")", ":", "StreamInterface", "{", "$", "strings", "=", "\\", "preg_split", "(", "$", "regex", ",", "$", "this", "->", "value", ",", "$", "limit", ")", ";", "$", "stream", "=", "new", "Stream", "(", "self", "::", "class", ")", ";", "foreach", "(", "$", "strings", "as", "$", "string", ")", "{", "$", "stream", "=", "$", "stream", "->", "add", "(", "new", "self", "(", "$", "string", ",", "$", "this", "->", "encoding", ")", ")", ";", "}", "return", "$", "stream", ";", "}" ]
Split the string using a regular expression @param string $regex @param int $limit @return StreamInterface<self>
[ "Split", "the", "string", "using", "a", "regular", "expression" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L376-L386