repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
rosasurfer/ministruts | src/monitor/FileDependency.php | FileDependency.isValid | public function isValid() {
// TODO: stat-Cache bei wiederholten Aufrufen loeschen, siehe clearstatcache()
if (file_exists($this->fileName)) {
if ($this->lastModified !== filemtime($this->fileName))
return false;
}
elseif ($this->lastModified !== null) {
return false;
}
return true;
} | php | public function isValid() {
// TODO: stat-Cache bei wiederholten Aufrufen loeschen, siehe clearstatcache()
if (file_exists($this->fileName)) {
if ($this->lastModified !== filemtime($this->fileName))
return false;
}
elseif ($this->lastModified !== null) {
return false;
}
return true;
} | [
"public",
"function",
"isValid",
"(",
")",
"{",
"// TODO: stat-Cache bei wiederholten Aufrufen loeschen, siehe clearstatcache()",
"if",
"(",
"file_exists",
"(",
"$",
"this",
"->",
"fileName",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"lastModified",
"!==",
"filem... | Ob die der Abhaengigkeit zugrunde liegende Datei weiterhin unveraendert ist.
@return bool - TRUE, wenn die Datei sich nicht geaendert hat.
FALSE, wenn die Datei sich geaendert hat. | [
"Ob",
"die",
"der",
"Abhaengigkeit",
"zugrunde",
"liegende",
"Datei",
"weiterhin",
"unveraendert",
"ist",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/monitor/FileDependency.php#L101-L113 | train |
timble/kodekit | code/template/helper/select.php | TemplateHelperSelect.options | public function options( $config = array() )
{
$config = new ObjectConfig($config);
$config->append(array(
'entity' => array(),
'name' => 'id',
'value' => 'id',
'label' => 'id',
'disabled' => null,
'attribs' => array(),
));
$options = array();
foreach($config->entity as $entity)
{
$option = array(
'id' => isset($entity->{$config->name}) ? $entity->{$config->name} : null,
'name' => $config->name,
'disabled' => $config->disabled,
'attribs' => ObjectConfig::unbox($config->attribs),
'value' => $entity->{$config->value},
'label' => $entity->{$config->label},
);
if($config->entity instanceof \RecursiveIteratorIterator) {
$option['level'] = $config->entity->getDepth() + 1;
}
$options[] = $this->option($option);
}
return $options;
} | php | public function options( $config = array() )
{
$config = new ObjectConfig($config);
$config->append(array(
'entity' => array(),
'name' => 'id',
'value' => 'id',
'label' => 'id',
'disabled' => null,
'attribs' => array(),
));
$options = array();
foreach($config->entity as $entity)
{
$option = array(
'id' => isset($entity->{$config->name}) ? $entity->{$config->name} : null,
'name' => $config->name,
'disabled' => $config->disabled,
'attribs' => ObjectConfig::unbox($config->attribs),
'value' => $entity->{$config->value},
'label' => $entity->{$config->label},
);
if($config->entity instanceof \RecursiveIteratorIterator) {
$option['level'] = $config->entity->getDepth() + 1;
}
$options[] = $this->option($option);
}
return $options;
} | [
"public",
"function",
"options",
"(",
"$",
"config",
"=",
"array",
"(",
")",
")",
"{",
"$",
"config",
"=",
"new",
"ObjectConfig",
"(",
"$",
"config",
")",
";",
"$",
"config",
"->",
"append",
"(",
"array",
"(",
"'entity'",
"=>",
"array",
"(",
")",
"... | Generates a select option list
@param array $config An optional array with configuration options
@return array An array of objects containing the option attributes | [
"Generates",
"a",
"select",
"option",
"list"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/template/helper/select.php#L65-L93 | train |
timble/kodekit | code/template/helper/select.php | TemplateHelperSelect.radiolist | public function radiolist($config = array())
{
$config = new ObjectConfigJson($config);
$config->append(array(
'options' => array(),
'legend' => null,
'name' => 'id',
'selected' => null,
'translate' => false,
'attribs' => array(),
));
$translator = $this->getObject('translator');
$attribs = $this->buildAttributes($config->attribs);
$html = array();
$html[] = '<fieldset name="'. $config->name .'" '. $attribs .'>';
if(isset($config->legend)) {
$html[] = '<legend>'.$config->translate ? $translator->translate( $config->legend ) : $config->legend.'</legend>';
}
foreach($config->options as $option)
{
$value = $option->value;
$label = $config->translate ? $translator->translate( $option->label ) : $option->label;
$extra = ($value == $config->selected ? 'checked="checked"' : '');
if(isset($option->disabled) && $option->disabled) {
$extra .= 'disabled="disabled"';
}
if(isset($option->attribs)) {
$attribs = $this->buildAttributes($option->attribs);
}
$html[] = '<label class="radio" for="'.$config->name.$option->id.'">';
$html[] = '<input type="radio" name="'.$config->name.'" id="'.$config->name.$option->id.'" value="'.$value.'" '.$extra.' '.$attribs.' />';
$html[] = $label;
$html[] = '</label>';
}
$html[] = '</fieldset>';
return implode(PHP_EOL, $html);
} | php | public function radiolist($config = array())
{
$config = new ObjectConfigJson($config);
$config->append(array(
'options' => array(),
'legend' => null,
'name' => 'id',
'selected' => null,
'translate' => false,
'attribs' => array(),
));
$translator = $this->getObject('translator');
$attribs = $this->buildAttributes($config->attribs);
$html = array();
$html[] = '<fieldset name="'. $config->name .'" '. $attribs .'>';
if(isset($config->legend)) {
$html[] = '<legend>'.$config->translate ? $translator->translate( $config->legend ) : $config->legend.'</legend>';
}
foreach($config->options as $option)
{
$value = $option->value;
$label = $config->translate ? $translator->translate( $option->label ) : $option->label;
$extra = ($value == $config->selected ? 'checked="checked"' : '');
if(isset($option->disabled) && $option->disabled) {
$extra .= 'disabled="disabled"';
}
if(isset($option->attribs)) {
$attribs = $this->buildAttributes($option->attribs);
}
$html[] = '<label class="radio" for="'.$config->name.$option->id.'">';
$html[] = '<input type="radio" name="'.$config->name.'" id="'.$config->name.$option->id.'" value="'.$value.'" '.$extra.' '.$attribs.' />';
$html[] = $label;
$html[] = '</label>';
}
$html[] = '</fieldset>';
return implode(PHP_EOL, $html);
} | [
"public",
"function",
"radiolist",
"(",
"$",
"config",
"=",
"array",
"(",
")",
")",
"{",
"$",
"config",
"=",
"new",
"ObjectConfigJson",
"(",
"$",
"config",
")",
";",
"$",
"config",
"->",
"append",
"(",
"array",
"(",
"'options'",
"=>",
"array",
"(",
"... | Generates an HTML radio list
@param array|ObjectConfig $config An optional array with configuration options
@return string Html | [
"Generates",
"an",
"HTML",
"radio",
"list"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/template/helper/select.php#L175-L221 | train |
timble/kodekit | code/view/json.php | ViewJson._createResource | protected function _createResource(ModelEntityInterface $entity, array $config = array())
{
$config = array_merge(array(
'links' => true,
'relationships' => true
), $config);
$data = array(
'type' => $this->_callCustomMethod($entity, 'type') ?: StringInflector::pluralize($entity->getIdentifier()->name),
'id' => $this->_callCustomMethod($entity, 'id') ?: $entity->{$entity->getIdentityKey()},
'attributes' => $this->_callCustomMethod($entity, 'attributes') ?: $entity->toArray()
);
if (isset($this->_fields[$data['type']]))
{
$fields = array_flip($this->_fields[$data['type']]);
$data['attributes'] = array_intersect_key($data['attributes'], $fields);
}
if ($config['links'])
{
$links = $this->_callCustomMethod($entity, 'links') ?: array('self' => (string)$this->_getEntityRoute($entity));
if ($links) {
$data['links'] = $links;
}
}
if ($config['relationships'])
{
$relationships = $this->_callCustomMethod($entity, 'relationships');
if ($relationships) {
$data['relationships'] = $relationships;
}
}
return $data;
} | php | protected function _createResource(ModelEntityInterface $entity, array $config = array())
{
$config = array_merge(array(
'links' => true,
'relationships' => true
), $config);
$data = array(
'type' => $this->_callCustomMethod($entity, 'type') ?: StringInflector::pluralize($entity->getIdentifier()->name),
'id' => $this->_callCustomMethod($entity, 'id') ?: $entity->{$entity->getIdentityKey()},
'attributes' => $this->_callCustomMethod($entity, 'attributes') ?: $entity->toArray()
);
if (isset($this->_fields[$data['type']]))
{
$fields = array_flip($this->_fields[$data['type']]);
$data['attributes'] = array_intersect_key($data['attributes'], $fields);
}
if ($config['links'])
{
$links = $this->_callCustomMethod($entity, 'links') ?: array('self' => (string)$this->_getEntityRoute($entity));
if ($links) {
$data['links'] = $links;
}
}
if ($config['relationships'])
{
$relationships = $this->_callCustomMethod($entity, 'relationships');
if ($relationships) {
$data['relationships'] = $relationships;
}
}
return $data;
} | [
"protected",
"function",
"_createResource",
"(",
"ModelEntityInterface",
"$",
"entity",
",",
"array",
"$",
"config",
"=",
"array",
"(",
")",
")",
"{",
"$",
"config",
"=",
"array_merge",
"(",
"array",
"(",
"'links'",
"=>",
"true",
",",
"'relationships'",
"=>"... | Creates a resource object specified by JSON API
@see http://jsonapi.org/format/#document-resource-objects
@param ModelEntityInterface $entity Document row
@param array $config Resource configuration.
@return array The array with data to be encoded to json | [
"Creates",
"a",
"resource",
"object",
"specified",
"by",
"JSON",
"API"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/view/json.php#L189-L225 | train |
timble/kodekit | code/view/json.php | ViewJson._includeResource | protected function _includeResource(ModelEntityInterface $entity)
{
$cache = $entity->getIdentifier()->name.'-'.$entity->getHandle();
if (!isset($this->_included_resources[$cache])) {
$this->_included_resources[$cache] = $this->_createResource($entity, array('relationships' => false));
}
$resource = $this->_included_resources[$cache];
return array(
'data' => array(
'type' => $resource['type'],
'id' => $resource['id']
)
);
} | php | protected function _includeResource(ModelEntityInterface $entity)
{
$cache = $entity->getIdentifier()->name.'-'.$entity->getHandle();
if (!isset($this->_included_resources[$cache])) {
$this->_included_resources[$cache] = $this->_createResource($entity, array('relationships' => false));
}
$resource = $this->_included_resources[$cache];
return array(
'data' => array(
'type' => $resource['type'],
'id' => $resource['id']
)
);
} | [
"protected",
"function",
"_includeResource",
"(",
"ModelEntityInterface",
"$",
"entity",
")",
"{",
"$",
"cache",
"=",
"$",
"entity",
"->",
"getIdentifier",
"(",
")",
"->",
"name",
".",
"'-'",
".",
"$",
"entity",
"->",
"getHandle",
"(",
")",
";",
"if",
"(... | Creates a resource object and returns a resource identifier object specified by JSON API
@see http://jsonapi.org/format/#document-resource-identifier-objects
@param ModelEntityInterface $entity
@return array | [
"Creates",
"a",
"resource",
"object",
"and",
"returns",
"a",
"resource",
"identifier",
"object",
"specified",
"by",
"JSON",
"API"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/view/json.php#L234-L250 | train |
timble/kodekit | code/view/json.php | ViewJson._includeCollection | protected function _includeCollection(ModelEntityInterface $entities)
{
$result = array('data' => array());
foreach ($entities as $entity)
{
$relation = $this->_includeResource($entity);
$result['data'][] = $relation['data'];
}
return $result;
} | php | protected function _includeCollection(ModelEntityInterface $entities)
{
$result = array('data' => array());
foreach ($entities as $entity)
{
$relation = $this->_includeResource($entity);
$result['data'][] = $relation['data'];
}
return $result;
} | [
"protected",
"function",
"_includeCollection",
"(",
"ModelEntityInterface",
"$",
"entities",
")",
"{",
"$",
"result",
"=",
"array",
"(",
"'data'",
"=>",
"array",
"(",
")",
")",
";",
"foreach",
"(",
"$",
"entities",
"as",
"$",
"entity",
")",
"{",
"$",
"re... | Creates resource objects and returns an array of resource identifier objects specified by JSON API
@see http://jsonapi.org/format/#document-resource-identifier-objects
@param ModelEntityInterface $entities
@return array | [
"Creates",
"resource",
"objects",
"and",
"returns",
"an",
"array",
"of",
"resource",
"identifier",
"objects",
"specified",
"by",
"JSON",
"API"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/view/json.php#L259-L270 | train |
timble/kodekit | code/view/json.php | ViewJson._callCustomMethod | protected function _callCustomMethod(ModelEntityInterface $entity, $method)
{
$result = false;
$name = StringInflector::singularize($entity->getIdentifier()->name);
$method = '_get'.ucfirst($name).ucfirst($method);
if ($method !== '_getEntity'.ucfirst($method) && method_exists($this, $method)) {
$result = $this->$method($entity);
}
return $result;
} | php | protected function _callCustomMethod(ModelEntityInterface $entity, $method)
{
$result = false;
$name = StringInflector::singularize($entity->getIdentifier()->name);
$method = '_get'.ucfirst($name).ucfirst($method);
if ($method !== '_getEntity'.ucfirst($method) && method_exists($this, $method)) {
$result = $this->$method($entity);
}
return $result;
} | [
"protected",
"function",
"_callCustomMethod",
"(",
"ModelEntityInterface",
"$",
"entity",
",",
"$",
"method",
")",
"{",
"$",
"result",
"=",
"false",
";",
"$",
"name",
"=",
"StringInflector",
"::",
"singularize",
"(",
"$",
"entity",
"->",
"getIdentifier",
"(",
... | Calls a custom method per entity name to modify resource objects
If the entity is of type foo and the method is links, this method will return the results of
_getFooLinks method if possible
@param ModelEntityInterface $entity
@param string $method
@return mixed Method results or false if the method not exists | [
"Calls",
"a",
"custom",
"method",
"per",
"entity",
"name",
"to",
"modify",
"resource",
"objects"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/view/json.php#L282-L293 | train |
timble/kodekit | code/view/json.php | ViewJson._getEntityRoute | protected function _getEntityRoute(ModelEntityInterface $entity)
{
$package = $this->getIdentifier()->package;
$view = $entity->getIdentifier()->name;
return $this->getRoute(sprintf('component=%s&view=%s&slug=%s&format=json', $package, $view, $entity->slug));
} | php | protected function _getEntityRoute(ModelEntityInterface $entity)
{
$package = $this->getIdentifier()->package;
$view = $entity->getIdentifier()->name;
return $this->getRoute(sprintf('component=%s&view=%s&slug=%s&format=json', $package, $view, $entity->slug));
} | [
"protected",
"function",
"_getEntityRoute",
"(",
"ModelEntityInterface",
"$",
"entity",
")",
"{",
"$",
"package",
"=",
"$",
"this",
"->",
"getIdentifier",
"(",
")",
"->",
"package",
";",
"$",
"view",
"=",
"$",
"entity",
"->",
"getIdentifier",
"(",
")",
"->... | Provides a default entity link
It can be overridden by creating a _getFooLinks method where foo is the entity type
@param ModelEntityInterface $entity
@return string | [
"Provides",
"a",
"default",
"entity",
"link"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/view/json.php#L303-L309 | train |
timble/kodekit | code/view/json.php | ViewJson._convertRelativeLinks | protected function _convertRelativeLinks(ViewContextInterface $context)
{
if (is_array($context->content) || $context->content instanceof \Traversable) {
$this->_processLinks($context->content);
}
} | php | protected function _convertRelativeLinks(ViewContextInterface $context)
{
if (is_array($context->content) || $context->content instanceof \Traversable) {
$this->_processLinks($context->content);
}
} | [
"protected",
"function",
"_convertRelativeLinks",
"(",
"ViewContextInterface",
"$",
"context",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"context",
"->",
"content",
")",
"||",
"$",
"context",
"->",
"content",
"instanceof",
"\\",
"Traversable",
")",
"{",
"$",
... | Converts links in the content from relative to absolute
@param ViewContextInterface $context | [
"Converts",
"links",
"in",
"the",
"content",
"from",
"relative",
"to",
"absolute"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/view/json.php#L316-L321 | train |
timble/kodekit | code/view/json.php | ViewJson._processLinks | protected function _processLinks(&$array)
{
$base = $this->getUrl()->toString(HttpUrl::AUTHORITY);
foreach ($array as $key => &$value)
{
if ($key === 'links')
{
foreach ($array['links'] as $k => $v)
{
if (strpos($v, ':/') === false) {
$array['links'][$k] = $base.$v;
}
}
}
elseif (is_array($value)) {
$this->_processLinks($value);
}
elseif (in_array($key, $this->_text_fields, true)) {
$array[$key] = $this->_processText($value);
}
}
} | php | protected function _processLinks(&$array)
{
$base = $this->getUrl()->toString(HttpUrl::AUTHORITY);
foreach ($array as $key => &$value)
{
if ($key === 'links')
{
foreach ($array['links'] as $k => $v)
{
if (strpos($v, ':/') === false) {
$array['links'][$k] = $base.$v;
}
}
}
elseif (is_array($value)) {
$this->_processLinks($value);
}
elseif (in_array($key, $this->_text_fields, true)) {
$array[$key] = $this->_processText($value);
}
}
} | [
"protected",
"function",
"_processLinks",
"(",
"&",
"$",
"array",
")",
"{",
"$",
"base",
"=",
"$",
"this",
"->",
"getUrl",
"(",
")",
"->",
"toString",
"(",
"HttpUrl",
"::",
"AUTHORITY",
")",
";",
"foreach",
"(",
"$",
"array",
"as",
"$",
"key",
"=>",
... | Converts links in the content array from relative to absolute
@param \Traversable|array $array | [
"Converts",
"links",
"in",
"the",
"content",
"array",
"from",
"relative",
"to",
"absolute"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/view/json.php#L328-L350 | train |
timble/kodekit | code/object/manager/manager.php | ObjectManager.isMultiton | public function isMultiton($identifier)
{
$result = false;
$class = $this->getClass($identifier);
if($class) {
$result = array_key_exists(__NAMESPACE__.'\ObjectMultiton', class_implements($class));
}
return $result;
} | php | public function isMultiton($identifier)
{
$result = false;
$class = $this->getClass($identifier);
if($class) {
$result = array_key_exists(__NAMESPACE__.'\ObjectMultiton', class_implements($class));
}
return $result;
} | [
"public",
"function",
"isMultiton",
"(",
"$",
"identifier",
")",
"{",
"$",
"result",
"=",
"false",
";",
"$",
"class",
"=",
"$",
"this",
"->",
"getClass",
"(",
"$",
"identifier",
")",
";",
"if",
"(",
"$",
"class",
")",
"{",
"$",
"result",
"=",
"arra... | Check if the object is a multiton
@param mixed $identifier An object that implements the ObjectInterface, an ObjectIdentifier or valid identifier string
@return boolean Returns TRUE if the object is a singleton, FALSE otherwise. | [
"Check",
"if",
"the",
"object",
"is",
"a",
"multiton"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/object/manager/manager.php#L474-L485 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.getFiles | public function getFiles() {
static $files;
if (!isset($files)) {
$normalizeLevel = function(array $file) use (&$normalizeLevel) {
if (isset($file['name']) && is_array($file['name'])) {
$properties = \array_keys($file);
$normalized = [];
foreach (\array_keys($file['name']) as $name) {
foreach ($properties as $property) {
$normalized[$name][$property] = $file[$property][$name];
}
$normalized[$name] = $normalizeLevel($normalized[$name]);
}
$file = $normalized;
}
return $file;
};
$files = [];
if (isset($_FILES)) {
foreach ($_FILES as $key => $file) {
$files[$key] = $normalizeLevel($file);
}
}
}
return $files;
} | php | public function getFiles() {
static $files;
if (!isset($files)) {
$normalizeLevel = function(array $file) use (&$normalizeLevel) {
if (isset($file['name']) && is_array($file['name'])) {
$properties = \array_keys($file);
$normalized = [];
foreach (\array_keys($file['name']) as $name) {
foreach ($properties as $property) {
$normalized[$name][$property] = $file[$property][$name];
}
$normalized[$name] = $normalizeLevel($normalized[$name]);
}
$file = $normalized;
}
return $file;
};
$files = [];
if (isset($_FILES)) {
foreach ($_FILES as $key => $file) {
$files[$key] = $normalizeLevel($file);
}
}
}
return $files;
} | [
"public",
"function",
"getFiles",
"(",
")",
"{",
"static",
"$",
"files",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"files",
")",
")",
"{",
"$",
"normalizeLevel",
"=",
"function",
"(",
"array",
"$",
"file",
")",
"use",
"(",
"&",
"$",
"normalizeLevel",
... | Return an object-oriented representation of the uploaded files. The broken PHP array structure of uploaded files is
converted to regular file arrays.
@TODO: convert file data to {@link UploadedFile} instances
@return array - associative array of files | [
"Return",
"an",
"object",
"-",
"oriented",
"representation",
"of",
"the",
"uploaded",
"files",
".",
"The",
"broken",
"PHP",
"array",
"structure",
"of",
"uploaded",
"files",
"is",
"converted",
"to",
"regular",
"file",
"arrays",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L272-L297 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.getHostname | public function getHostname() {
if (!empty($_SERVER['HTTP_HOST'])) {
$httpHost = strtolower(trim($_SERVER['HTTP_HOST'])); // nginx doesn't set $_SERVER[SERVER_NAME]
if (strlen($httpHost)) // automatically to $_SERVER[HTTP_HOST]
return $httpHost;
}
return $_SERVER['SERVER_NAME'];
} | php | public function getHostname() {
if (!empty($_SERVER['HTTP_HOST'])) {
$httpHost = strtolower(trim($_SERVER['HTTP_HOST'])); // nginx doesn't set $_SERVER[SERVER_NAME]
if (strlen($httpHost)) // automatically to $_SERVER[HTTP_HOST]
return $httpHost;
}
return $_SERVER['SERVER_NAME'];
} | [
"public",
"function",
"getHostname",
"(",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"_SERVER",
"[",
"'HTTP_HOST'",
"]",
")",
")",
"{",
"$",
"httpHost",
"=",
"strtolower",
"(",
"trim",
"(",
"$",
"_SERVER",
"[",
"'HTTP_HOST'",
"]",
")",
")",
";",
... | Return the host name the request was made to.
@return string - host name
@example
<pre>
$request->getUrl(): "http://a.domain.tld/path/application/module/foo/bar.html?key=value"
$request->getHostname(): "a.domain.tld"
</pre> | [
"Return",
"the",
"host",
"name",
"the",
"request",
"was",
"made",
"to",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L311-L318 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.resolveBaseUriVar | private function resolveBaseUriVar() {
$envName = 'APP_BASE_URI';
$envValue = null;
if (!isset($_SERVER[$envName]))
$envName = 'REDIRECT_'.$envName;
while (isset($_SERVER[$envName])) {
$envValue = $_SERVER[$envName];
$envName = 'REDIRECT_'.$envName;
}
return $envValue;
} | php | private function resolveBaseUriVar() {
$envName = 'APP_BASE_URI';
$envValue = null;
if (!isset($_SERVER[$envName]))
$envName = 'REDIRECT_'.$envName;
while (isset($_SERVER[$envName])) {
$envValue = $_SERVER[$envName];
$envName = 'REDIRECT_'.$envName;
}
return $envValue;
} | [
"private",
"function",
"resolveBaseUriVar",
"(",
")",
"{",
"$",
"envName",
"=",
"'APP_BASE_URI'",
";",
"$",
"envValue",
"=",
"null",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"_SERVER",
"[",
"$",
"envName",
"]",
")",
")",
"$",
"envName",
"=",
"'REDIRECT_... | Resolve the value of an existing APP_BASE_URI server variable. Considers existing redirection values.
@return string|null - value or NULL if the variable is not defined | [
"Resolve",
"the",
"value",
"of",
"an",
"existing",
"APP_BASE_URI",
"server",
"variable",
".",
"Considers",
"existing",
"redirection",
"values",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L487-L499 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.getQueryString | public function getQueryString() {
// The variable $_SERVER['QUERY_STRING'] is set by the server and can differ from the transmitted query string.
// It might hold additional parameters added by the server or it might be empty (e.g. on a mis-configured nginx).
if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING'])) {
$query = $_SERVER['QUERY_STRING'];
}
else {
$query = strRightFrom($_SERVER['REQUEST_URI'], '?');
}
return $query;
} | php | public function getQueryString() {
// The variable $_SERVER['QUERY_STRING'] is set by the server and can differ from the transmitted query string.
// It might hold additional parameters added by the server or it might be empty (e.g. on a mis-configured nginx).
if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING'])) {
$query = $_SERVER['QUERY_STRING'];
}
else {
$query = strRightFrom($_SERVER['REQUEST_URI'], '?');
}
return $query;
} | [
"public",
"function",
"getQueryString",
"(",
")",
"{",
"// The variable $_SERVER['QUERY_STRING'] is set by the server and can differ from the transmitted query string.",
"// It might hold additional parameters added by the server or it might be empty (e.g. on a mis-configured nginx).",
"if",
"(",
... | Return the query string of the request's URL.
@return string
@example
<pre>
$request->getUrl(): "http://a.domain.tld/path/application/module/foo/bar.html?key=value"
$request->getQueryString(): "key=value"
</pre> | [
"Return",
"the",
"query",
"string",
"of",
"the",
"request",
"s",
"URL",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L513-L524 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.getRemoteHostname | public function getRemoteHostname() {
static $hostname = null;
if (!$hostname) {
/** @var string $hostname */
$hostname = NetTools::getHostByAddress($this->getRemoteAddress());
}
return $hostname;
} | php | public function getRemoteHostname() {
static $hostname = null;
if (!$hostname) {
/** @var string $hostname */
$hostname = NetTools::getHostByAddress($this->getRemoteAddress());
}
return $hostname;
} | [
"public",
"function",
"getRemoteHostname",
"(",
")",
"{",
"static",
"$",
"hostname",
"=",
"null",
";",
"if",
"(",
"!",
"$",
"hostname",
")",
"{",
"/** @var string $hostname */",
"$",
"hostname",
"=",
"NetTools",
"::",
"getHostByAddress",
"(",
"$",
"this",
"-... | Return the name of the host the request was made from.
@return string - host name | [
"Return",
"the",
"name",
"of",
"the",
"host",
"the",
"request",
"was",
"made",
"from",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L542-L549 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.getContentType | public function getContentType() {
$contentType = $this->getHeaderValue('Content-Type');
if ($contentType) {
$headers = explode(',', $contentType, 2);
$contentType = \array_shift($headers);
$values = explode(';', $contentType, 2);
$contentType = trim(\array_shift($values));
}
return $contentType;
} | php | public function getContentType() {
$contentType = $this->getHeaderValue('Content-Type');
if ($contentType) {
$headers = explode(',', $contentType, 2);
$contentType = \array_shift($headers);
$values = explode(';', $contentType, 2);
$contentType = trim(\array_shift($values));
}
return $contentType;
} | [
"public",
"function",
"getContentType",
"(",
")",
"{",
"$",
"contentType",
"=",
"$",
"this",
"->",
"getHeaderValue",
"(",
"'Content-Type'",
")",
";",
"if",
"(",
"$",
"contentType",
")",
"{",
"$",
"headers",
"=",
"explode",
"(",
"','",
",",
"$",
"contentT... | Return the "Content-Type" header of the request. If multiple "Content-Type" headers have been transmitted the first
one is returned.
@return string|null - "Content-Type" header or NULL if no "Content-Type" header was transmitted. | [
"Return",
"the",
"Content",
"-",
"Type",
"header",
"of",
"the",
"request",
".",
"If",
"multiple",
"Content",
"-",
"Type",
"headers",
"have",
"been",
"transmitted",
"the",
"first",
"one",
"is",
"returned",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L597-L608 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.isSessionAttribute | public function isSessionAttribute($key) {
if ($this->isSession() || $this->hasSessionId())
return $this->getSession()->isAttribute($key);
return false;
} | php | public function isSessionAttribute($key) {
if ($this->isSession() || $this->hasSessionId())
return $this->getSession()->isAttribute($key);
return false;
} | [
"public",
"function",
"isSessionAttribute",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isSession",
"(",
")",
"||",
"$",
"this",
"->",
"hasSessionId",
"(",
")",
")",
"return",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"isAttribute"... | Whether a session attribute of the specified name exists. If no session exists none is started.
@param string $key - key
@return bool | [
"Whether",
"a",
"session",
"attribute",
"of",
"the",
"specified",
"name",
"exists",
".",
"If",
"no",
"session",
"exists",
"none",
"is",
"started",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L640-L644 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.hasSessionId | public function hasSessionId() {
$name = session_name();
if (ini_get_bool('session.use_cookies'))
if (isset($_COOKIE[$name]))
return true;
if (!ini_get_bool('session.use_only_cookies'))
if (isset($_REQUEST[$name]))
return true;
return false;
} | php | public function hasSessionId() {
$name = session_name();
if (ini_get_bool('session.use_cookies'))
if (isset($_COOKIE[$name]))
return true;
if (!ini_get_bool('session.use_only_cookies'))
if (isset($_REQUEST[$name]))
return true;
return false;
} | [
"public",
"function",
"hasSessionId",
"(",
")",
"{",
"$",
"name",
"=",
"session_name",
"(",
")",
";",
"if",
"(",
"ini_get_bool",
"(",
"'session.use_cookies'",
")",
")",
"if",
"(",
"isset",
"(",
"$",
"_COOKIE",
"[",
"$",
"name",
"]",
")",
")",
"return",... | Whether a valid session id was transmitted with the request. An invalid id is a URL based session id when the php.ini
setting 'session.use_only_cookies' is enabled.
@return bool | [
"Whether",
"a",
"valid",
"session",
"id",
"was",
"transmitted",
"with",
"the",
"request",
".",
"An",
"invalid",
"id",
"is",
"a",
"URL",
"based",
"session",
"id",
"when",
"the",
"php",
".",
"ini",
"setting",
"session",
".",
"use_only_cookies",
"is",
"enable... | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L673-L685 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.destroySession | public function destroySession() {
if (session_status() == PHP_SESSION_ACTIVE) {
// unset all session variables
$_SESSION = [];
// delete the session cookie
if (ini_get_bool('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie($name=session_name(), $value='', $expire=time()-1*DAY, $params['path' ],
$params['domain' ],
$params['secure' ],
$params['httponly']);
}
session_destroy(); // TODO: check if SID is reset
}
} | php | public function destroySession() {
if (session_status() == PHP_SESSION_ACTIVE) {
// unset all session variables
$_SESSION = [];
// delete the session cookie
if (ini_get_bool('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie($name=session_name(), $value='', $expire=time()-1*DAY, $params['path' ],
$params['domain' ],
$params['secure' ],
$params['httponly']);
}
session_destroy(); // TODO: check if SID is reset
}
} | [
"public",
"function",
"destroySession",
"(",
")",
"{",
"if",
"(",
"session_status",
"(",
")",
"==",
"PHP_SESSION_ACTIVE",
")",
"{",
"// unset all session variables",
"$",
"_SESSION",
"=",
"[",
"]",
";",
"// delete the session cookie",
"if",
"(",
"ini_get_bool",
"(... | Destroy the current session and it's data. | [
"Destroy",
"the",
"current",
"session",
"and",
"it",
"s",
"data",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L691-L706 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.getHeader | public function getHeader($name) {
if (!is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name));
$headers = $this->getHeaders($name);
return \array_shift($headers);
} | php | public function getHeader($name) {
if (!is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name));
$headers = $this->getHeaders($name);
return \array_shift($headers);
} | [
"public",
"function",
"getHeader",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"name",
")",
")",
"throw",
"new",
"IllegalTypeException",
"(",
"'Illegal type of parameter $name: '",
".",
"gettype",
"(",
"$",
"name",
")",
")",
";",
"$"... | Gibt den Wert des angegebenen Headers zurueck. Wurden mehrere Header dieses Namens uebertragen,
wird der Wert des ersten uebertragenen Headers zurueckgegeben.
@param string $name - Name des Headers
@return string|null - Wert oder NULL, wenn kein Header dieses Namens uebertragen wurde | [
"Gibt",
"den",
"Wert",
"des",
"angegebenen",
"Headers",
"zurueck",
".",
"Wurden",
"mehrere",
"Header",
"dieses",
"Namens",
"uebertragen",
"wird",
"der",
"Wert",
"des",
"ersten",
"uebertragenen",
"Headers",
"zurueckgegeben",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L717-L722 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.getAttribute | public function getAttribute($key) {
if (key_exists($key, $this->attributes))
return $this->attributes[$key];
return null;
} | php | public function getAttribute($key) {
if (key_exists($key, $this->attributes))
return $this->attributes[$key];
return null;
} | [
"public",
"function",
"getAttribute",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"attributes",
")",
")",
"return",
"$",
"this",
"->",
"attributes",
"[",
"$",
"key",
"]",
";",
"return",
"null",
";",
... | Gibt den im Request-Context unter dem angegebenen Schluessel gespeicherten Wert zurueck oder NULL,
wenn unter diesem Schluessel kein Wert existiert.
@param string $key - Schluessel, unter dem der Wert im Context gespeichert ist
@return mixed - der gespeicherte Wert oder NULL | [
"Gibt",
"den",
"im",
"Request",
"-",
"Context",
"unter",
"dem",
"angegebenen",
"Schluessel",
"gespeicherten",
"Wert",
"zurueck",
"oder",
"NULL",
"wenn",
"unter",
"diesem",
"Schluessel",
"kein",
"Wert",
"existiert",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L842-L846 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.setCookie | public function setCookie($name, $value, $expires = 0, $path = null) {
if (!is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name));
if (!is_int($expires)) throw new IllegalTypeException('Illegal type of parameter $expires: '.gettype($expires));
if ($expires < 0) throw new InvalidArgumentException('Invalid argument $expires: '.$expires);
$value = (string)$value;
if ($path === null)
$path = $this->getApplicationBaseUri();
if (!is_string($path)) throw new IllegalTypeException('Illegal type of parameter $path: '.gettype($path));
\setcookie($name, $value, $expires, $path);
} | php | public function setCookie($name, $value, $expires = 0, $path = null) {
if (!is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name));
if (!is_int($expires)) throw new IllegalTypeException('Illegal type of parameter $expires: '.gettype($expires));
if ($expires < 0) throw new InvalidArgumentException('Invalid argument $expires: '.$expires);
$value = (string)$value;
if ($path === null)
$path = $this->getApplicationBaseUri();
if (!is_string($path)) throw new IllegalTypeException('Illegal type of parameter $path: '.gettype($path));
\setcookie($name, $value, $expires, $path);
} | [
"public",
"function",
"setCookie",
"(",
"$",
"name",
",",
"$",
"value",
",",
"$",
"expires",
"=",
"0",
",",
"$",
"path",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"name",
")",
")",
"throw",
"new",
"IllegalTypeException",
"(",
"'... | Setzt einen Cookie mit den angegebenen Daten.
@param string $name - Name des Cookies
@param mixed $value - der zu speichernde Wert (wird zu String gecastet)
@param int $expires - Lebenszeit des Cookies (0: bis zum Schliessen des Browsers)
@param string $path [optional] - Pfad, fuer den der Cookie gueltig sein soll (default: whole domain) | [
"Setzt",
"einen",
"Cookie",
"mit",
"den",
"angegebenen",
"Daten",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L891-L904 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.getActionMessage | public function getActionMessage($key = null) {
$messages = $this->getAttribute(ACTION_MESSAGES_KEY);
if ($key === null) { // return the first one
if ($messages) {
foreach ($messages as $message) return $message;
}
}
elseif (key_exists($key, $messages)) { // return the specified one
return $messages[$key];
}
return $this->getActionError($key); // look-up separately stored ActionErrors
} | php | public function getActionMessage($key = null) {
$messages = $this->getAttribute(ACTION_MESSAGES_KEY);
if ($key === null) { // return the first one
if ($messages) {
foreach ($messages as $message) return $message;
}
}
elseif (key_exists($key, $messages)) { // return the specified one
return $messages[$key];
}
return $this->getActionError($key); // look-up separately stored ActionErrors
} | [
"public",
"function",
"getActionMessage",
"(",
"$",
"key",
"=",
"null",
")",
"{",
"$",
"messages",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"ACTION_MESSAGES_KEY",
")",
";",
"if",
"(",
"$",
"key",
"===",
"null",
")",
"{",
"// return the first one",
"if"... | Return the ActionMessage for the specified key or the first ActionMessage if no key was given.
@param string $key [optional]
@return string|null - ActionMessage | [
"Return",
"the",
"ActionMessage",
"for",
"the",
"specified",
"key",
"or",
"the",
"first",
"ActionMessage",
"if",
"no",
"key",
"was",
"given",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L937-L949 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.getActionMessages | public function getActionMessages() {
$messages = $this->getAttribute(ACTION_MESSAGES_KEY);
if ($messages === null)
$messages = [];
$errors = $this->getActionErrors();
return \array_merge($messages, $errors);
} | php | public function getActionMessages() {
$messages = $this->getAttribute(ACTION_MESSAGES_KEY);
if ($messages === null)
$messages = [];
$errors = $this->getActionErrors();
return \array_merge($messages, $errors);
} | [
"public",
"function",
"getActionMessages",
"(",
")",
"{",
"$",
"messages",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"ACTION_MESSAGES_KEY",
")",
";",
"if",
"(",
"$",
"messages",
"===",
"null",
")",
"$",
"messages",
"=",
"[",
"]",
";",
"$",
"errors",
... | Return all existing ActionMessages, including ActionErrors.
@return array | [
"Return",
"all",
"existing",
"ActionMessages",
"including",
"ActionErrors",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L957-L964 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.isActionMessage | public function isActionMessage($keys = null) {
$messages = $this->getAttribute(ACTION_MESSAGES_KEY);
if (!$messages)
return $this->isActionError($keys);
if (is_string($keys))
$keys = [$keys];
if (is_array($keys)) {
foreach ($keys as $key) {
if (key_exists($key, $messages)) return true;
}
if ($keys)
return $this->isActionError($keys);
$keys = null;
}
if (is_null($keys))
return true;
throw new IllegalTypeException('Illegal type of parameter $keys: '.gettype($keys));
} | php | public function isActionMessage($keys = null) {
$messages = $this->getAttribute(ACTION_MESSAGES_KEY);
if (!$messages)
return $this->isActionError($keys);
if (is_string($keys))
$keys = [$keys];
if (is_array($keys)) {
foreach ($keys as $key) {
if (key_exists($key, $messages)) return true;
}
if ($keys)
return $this->isActionError($keys);
$keys = null;
}
if (is_null($keys))
return true;
throw new IllegalTypeException('Illegal type of parameter $keys: '.gettype($keys));
} | [
"public",
"function",
"isActionMessage",
"(",
"$",
"keys",
"=",
"null",
")",
"{",
"$",
"messages",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"ACTION_MESSAGES_KEY",
")",
";",
"if",
"(",
"!",
"$",
"messages",
")",
"return",
"$",
"this",
"->",
"isActionE... | Whether an ActionMessage exists for one of the specified keys, or for any key if no key was given.
@param string|string[] $keys [optional] - message keys
@return bool | [
"Whether",
"an",
"ActionMessage",
"exists",
"for",
"one",
"of",
"the",
"specified",
"keys",
"or",
"for",
"any",
"key",
"if",
"no",
"key",
"was",
"given",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L974-L994 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.setActionMessage | public function setActionMessage($key, $message) {
if (!isset($message)) {
unset($this->attributes[ACTION_MESSAGES_KEY][$key]);
}
elseif (is_string($message)) {
$this->attributes[ACTION_MESSAGES_KEY][$key] = $message;
}
else throw new IllegalTypeException('Illegal type of parameter $message: '.gettype($message));
} | php | public function setActionMessage($key, $message) {
if (!isset($message)) {
unset($this->attributes[ACTION_MESSAGES_KEY][$key]);
}
elseif (is_string($message)) {
$this->attributes[ACTION_MESSAGES_KEY][$key] = $message;
}
else throw new IllegalTypeException('Illegal type of parameter $message: '.gettype($message));
} | [
"public",
"function",
"setActionMessage",
"(",
"$",
"key",
",",
"$",
"message",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"message",
")",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"attributes",
"[",
"ACTION_MESSAGES_KEY",
"]",
"[",
"$",
"key",
"]... | Store or delete an ActionMessage for the specified key.
@param string $key - message key
@param string $message - message; if NULL the message for the specified key is deleted
(an ActionError with the same key is not deleted) | [
"Store",
"or",
"delete",
"an",
"ActionMessage",
"for",
"the",
"specified",
"key",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L1004-L1012 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.removeActionMessages | public function removeActionMessages(...$keys) {
$messages = $this->getAttribute(ACTION_MESSAGES_KEY);
$dropped = [];
foreach ($keys as $key) {
if (isset($messages[$key]))
$dropped[$key] = $messages[$key];
unset($this->attributes[ACTION_MESSAGES_KEY][$key]);
}
if ($keys)
return $dropped;
unset($this->attributes[ACTION_MESSAGES_KEY]);
return $messages;
} | php | public function removeActionMessages(...$keys) {
$messages = $this->getAttribute(ACTION_MESSAGES_KEY);
$dropped = [];
foreach ($keys as $key) {
if (isset($messages[$key]))
$dropped[$key] = $messages[$key];
unset($this->attributes[ACTION_MESSAGES_KEY][$key]);
}
if ($keys)
return $dropped;
unset($this->attributes[ACTION_MESSAGES_KEY]);
return $messages;
} | [
"public",
"function",
"removeActionMessages",
"(",
"...",
"$",
"keys",
")",
"{",
"$",
"messages",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"ACTION_MESSAGES_KEY",
")",
";",
"$",
"dropped",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
... | Delete the ActionMessages with the specified keys.
@param string[] ...$keys - zero or more message keys to delete; without a key all ActionMessages are deleted
(ActionErrors with the same keys are not deleted
@return array - the deleted ActionMessages | [
"Delete",
"the",
"ActionMessages",
"with",
"the",
"specified",
"keys",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L1023-L1037 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.getActionError | public function getActionError($key = null) {
$errors = $this->getAttribute(ACTION_ERRORS_KEY);
if ($key === null) { // return the first one
if ($errors) {
foreach ($errors as $error) return $error;
}
}
elseif (key_exists($key, $errors)) { // return the specified one
return $errors[$key];
}
return null;
} | php | public function getActionError($key = null) {
$errors = $this->getAttribute(ACTION_ERRORS_KEY);
if ($key === null) { // return the first one
if ($errors) {
foreach ($errors as $error) return $error;
}
}
elseif (key_exists($key, $errors)) { // return the specified one
return $errors[$key];
}
return null;
} | [
"public",
"function",
"getActionError",
"(",
"$",
"key",
"=",
"null",
")",
"{",
"$",
"errors",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"ACTION_ERRORS_KEY",
")",
";",
"if",
"(",
"$",
"key",
"===",
"null",
")",
"{",
"// return the first one",
"if",
"(... | Return the ActionError for the specified key or the first ActionError if no key was given.
@param string $key [optional]
@return string|null - ActionError | [
"Return",
"the",
"ActionError",
"for",
"the",
"specified",
"key",
"or",
"the",
"first",
"ActionError",
"if",
"no",
"key",
"was",
"given",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L1047-L1059 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.isActionError | public function isActionError($keys = null) {
$errors = $this->getAttribute(ACTION_ERRORS_KEY);
if (!$errors)
return false;
if (is_string($keys))
$keys = [$keys];
if (is_array($keys)) {
foreach ($keys as $key) {
if (key_exists($key, $errors)) return true;
}
if ($keys)
return false;
$keys = null;
}
if (is_null($keys))
return true;
throw new IllegalTypeException('Illegal type of parameter $keys: '.gettype($keys));
} | php | public function isActionError($keys = null) {
$errors = $this->getAttribute(ACTION_ERRORS_KEY);
if (!$errors)
return false;
if (is_string($keys))
$keys = [$keys];
if (is_array($keys)) {
foreach ($keys as $key) {
if (key_exists($key, $errors)) return true;
}
if ($keys)
return false;
$keys = null;
}
if (is_null($keys))
return true;
throw new IllegalTypeException('Illegal type of parameter $keys: '.gettype($keys));
} | [
"public",
"function",
"isActionError",
"(",
"$",
"keys",
"=",
"null",
")",
"{",
"$",
"errors",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"ACTION_ERRORS_KEY",
")",
";",
"if",
"(",
"!",
"$",
"errors",
")",
"return",
"false",
";",
"if",
"(",
"is_string... | Whether an ActionError exists for one of the specified keys or for any key if no key was given.
@param string|string[] $keys [optional] - error keys
@return bool | [
"Whether",
"an",
"ActionError",
"exists",
"for",
"one",
"of",
"the",
"specified",
"keys",
"or",
"for",
"any",
"key",
"if",
"no",
"key",
"was",
"given",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L1082-L1102 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.setActionError | public function setActionError($key, $message) {
if (!isset($message)) {
unset($this->attributes[ACTION_ERRORS_KEY][$key]);
}
elseif (is_string($message)) {
$this->attributes[ACTION_ERRORS_KEY][$key] = $message;
}
else throw new IllegalTypeException('Illegal type of parameter $message: '.gettype($message));
} | php | public function setActionError($key, $message) {
if (!isset($message)) {
unset($this->attributes[ACTION_ERRORS_KEY][$key]);
}
elseif (is_string($message)) {
$this->attributes[ACTION_ERRORS_KEY][$key] = $message;
}
else throw new IllegalTypeException('Illegal type of parameter $message: '.gettype($message));
} | [
"public",
"function",
"setActionError",
"(",
"$",
"key",
",",
"$",
"message",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"message",
")",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"attributes",
"[",
"ACTION_ERRORS_KEY",
"]",
"[",
"$",
"key",
"]",
... | Store or delete an ActionError for the specified key.
@param string $key - error key
@param string $message - error message; if NULL the error for the specified key is deleted | [
"Store",
"or",
"delete",
"an",
"ActionError",
"for",
"the",
"specified",
"key",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L1111-L1119 | train |
rosasurfer/ministruts | src/ministruts/Request.php | Request.removeActionErrors | public function removeActionErrors(...$keys) {
$errors = $this->getAttribute(ACTION_ERRORS_KEY);
$dropped = [];
foreach ($keys as $key) {
if (isset($errors[$key]))
$dropped[$key] = $errors[$key];
unset($this->attributes[ACTION_ERRORS_KEY][$key]);
}
if ($keys)
return $dropped;
unset($this->attributes[ACTION_ERRORS_KEY]);
return $errors;
} | php | public function removeActionErrors(...$keys) {
$errors = $this->getAttribute(ACTION_ERRORS_KEY);
$dropped = [];
foreach ($keys as $key) {
if (isset($errors[$key]))
$dropped[$key] = $errors[$key];
unset($this->attributes[ACTION_ERRORS_KEY][$key]);
}
if ($keys)
return $dropped;
unset($this->attributes[ACTION_ERRORS_KEY]);
return $errors;
} | [
"public",
"function",
"removeActionErrors",
"(",
"...",
"$",
"keys",
")",
"{",
"$",
"errors",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"ACTION_ERRORS_KEY",
")",
";",
"$",
"dropped",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"key",... | Delete the ActionErrors with the specified keys.
@param string[] ...$keys - zero or more error keys to delete; without a key all ActionErrors are deleted
@return array - the deleted ActionErrors | [
"Delete",
"the",
"ActionErrors",
"with",
"the",
"specified",
"keys",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Request.php#L1129-L1143 | train |
timble/kodekit | code/controller/toolbar/actionbar.php | ControllerToolbarActionbar._afterRead | protected function _afterRead(ControllerContext $context)
{
$controller = $this->getController();
if($controller->isEditable() && $controller->canSave()) {
$this->addCommand('save');
}
if($controller->isEditable() && $controller->canApply()) {
$this->addCommand('apply');
}
if($controller->isEditable() && $controller->canCancel()) {
$this->addCommand('cancel', array('attribs' => array('data-novalidate' => 'novalidate')));
}
} | php | protected function _afterRead(ControllerContext $context)
{
$controller = $this->getController();
if($controller->isEditable() && $controller->canSave()) {
$this->addCommand('save');
}
if($controller->isEditable() && $controller->canApply()) {
$this->addCommand('apply');
}
if($controller->isEditable() && $controller->canCancel()) {
$this->addCommand('cancel', array('attribs' => array('data-novalidate' => 'novalidate')));
}
} | [
"protected",
"function",
"_afterRead",
"(",
"ControllerContext",
"$",
"context",
")",
"{",
"$",
"controller",
"=",
"$",
"this",
"->",
"getController",
"(",
")",
";",
"if",
"(",
"$",
"controller",
"->",
"isEditable",
"(",
")",
"&&",
"$",
"controller",
"->",... | Add default toolbar commands and set the toolbar title
.
@param ControllerContext $context A controller context object | [
"Add",
"default",
"toolbar",
"commands",
"and",
"set",
"the",
"toolbar",
"title",
"."
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/controller/toolbar/actionbar.php#L42-L57 | train |
timble/kodekit | code/model/database.php | ModelDatabase.setTable | public function setTable($table)
{
if(!($table instanceof DatabaseTableInterface))
{
if(is_string($table) && strpos($table, '.') === false )
{
$identifier = $this->getIdentifier()->toArray();
$identifier['path'] = array('database', 'table');
$identifier['name'] = StringInflector::pluralize(StringInflector::underscore($table));
$identifier = $this->getIdentifier($identifier);
}
else $identifier = $this->getIdentifier($table);
if($identifier->path[1] != 'table') {
throw new \UnexpectedValueException('Identifier: '.$identifier.' is not a table identifier');
}
$table = $identifier;
}
$this->_table = $table;
return $this;
} | php | public function setTable($table)
{
if(!($table instanceof DatabaseTableInterface))
{
if(is_string($table) && strpos($table, '.') === false )
{
$identifier = $this->getIdentifier()->toArray();
$identifier['path'] = array('database', 'table');
$identifier['name'] = StringInflector::pluralize(StringInflector::underscore($table));
$identifier = $this->getIdentifier($identifier);
}
else $identifier = $this->getIdentifier($table);
if($identifier->path[1] != 'table') {
throw new \UnexpectedValueException('Identifier: '.$identifier.' is not a table identifier');
}
$table = $identifier;
}
$this->_table = $table;
return $this;
} | [
"public",
"function",
"setTable",
"(",
"$",
"table",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"table",
"instanceof",
"DatabaseTableInterface",
")",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"table",
")",
"&&",
"strpos",
"(",
"$",
"table",
",",
"'.'",
")... | Method to set a table object attached to the model
@param mixed $table An object that implements ObjectInterface, ObjectIdentifier object
or valid identifier string
@throws \UnexpectedValueException If the identifier is not a table identifier
@return ModelDatabase | [
"Method",
"to",
"set",
"a",
"table",
"object",
"attached",
"to",
"the",
"model"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/model/database.php#L168-L192 | train |
timble/kodekit | code/dispatcher/request/transport/data.php | DispatcherRequestTransportData.receive | public function receive(DispatcherRequestInterface $request)
{
if($request->getContentType() == 'application/x-www-form-urlencoded')
{
if (in_array($request->getMethod(), array('PUT', 'DELETE', 'PATCH')))
{
parse_str($request->getContent(), $data);
$request->getData()->add($data);
}
}
if(in_array($request->getContentType(), array('application/json', 'application/x-json', 'application/vnd.api+json')))
{
if(in_array($request->getMethod(), array('POST', 'PUT', 'DELETE', 'PATCH')))
{
$data = array();
if ($content = $request->getContent()) {
$data = json_decode($content, true);
}
if ($data) {
$request->getData()->add($data);
}
// Transform the JSON API request payloads
if($request->getContentType() == 'application/vnd.api+json')
{
if (is_array($request->data->data))
{
$data = $request->data->data;
if (isset($data['attributes']) && is_array($data['attributes'])) {
$request->data->add($data['attributes']);
}
}
}
}
}
} | php | public function receive(DispatcherRequestInterface $request)
{
if($request->getContentType() == 'application/x-www-form-urlencoded')
{
if (in_array($request->getMethod(), array('PUT', 'DELETE', 'PATCH')))
{
parse_str($request->getContent(), $data);
$request->getData()->add($data);
}
}
if(in_array($request->getContentType(), array('application/json', 'application/x-json', 'application/vnd.api+json')))
{
if(in_array($request->getMethod(), array('POST', 'PUT', 'DELETE', 'PATCH')))
{
$data = array();
if ($content = $request->getContent()) {
$data = json_decode($content, true);
}
if ($data) {
$request->getData()->add($data);
}
// Transform the JSON API request payloads
if($request->getContentType() == 'application/vnd.api+json')
{
if (is_array($request->data->data))
{
$data = $request->data->data;
if (isset($data['attributes']) && is_array($data['attributes'])) {
$request->data->add($data['attributes']);
}
}
}
}
}
} | [
"public",
"function",
"receive",
"(",
"DispatcherRequestInterface",
"$",
"request",
")",
"{",
"if",
"(",
"$",
"request",
"->",
"getContentType",
"(",
")",
"==",
"'application/x-www-form-urlencoded'",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"request",
"->",
... | Set the request data
@param DispatcherRequestInterface $request | [
"Set",
"the",
"request",
"data"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/dispatcher/request/transport/data.php#L27-L66 | train |
rosasurfer/ministruts | src/db/ConnectionPool.php | ConnectionPool.getConnector | public static function getConnector($id = null) {
$me = self::me();
if ($id === null) { // a single db project
if (!$me->default) throw new IllegalStateException('Invalid default database configuration: null');
$connector = $me->default;
}
elseif (isset($me->pool[$id])) { // is the connection already known?
$connector = $me->pool[$id];
}
else { // no, get the connection's config
/** @var ConfigInterface $config */
$config = self::di('config');
$options = $config->get('db.'.$id, []);
if (!is_array($options)) throw new IllegalTypeException('Invalid config value "db.'.$id.'": '.gettype($options).' (not array)');
if (!$options) throw new IllegalStateException('No configuration found for database alias "'.$id.'"');
// resolve the class name to use for the connector
$className = $options['connector']; unset($options['connector']);
$className = str_replace('/', '\\', $className);
if ($className[0]=='\\') $className = substr($className, 1);
// check known aliases for a match
$lName = strtolower($className);
if (isset(self::$aliases[$lName]))
$className = self::$aliases[$lName];
// instantiate and save a new connector
$me->pool[$id] = $connector = Connector::create($className, $options);
}
return $connector;
} | php | public static function getConnector($id = null) {
$me = self::me();
if ($id === null) { // a single db project
if (!$me->default) throw new IllegalStateException('Invalid default database configuration: null');
$connector = $me->default;
}
elseif (isset($me->pool[$id])) { // is the connection already known?
$connector = $me->pool[$id];
}
else { // no, get the connection's config
/** @var ConfigInterface $config */
$config = self::di('config');
$options = $config->get('db.'.$id, []);
if (!is_array($options)) throw new IllegalTypeException('Invalid config value "db.'.$id.'": '.gettype($options).' (not array)');
if (!$options) throw new IllegalStateException('No configuration found for database alias "'.$id.'"');
// resolve the class name to use for the connector
$className = $options['connector']; unset($options['connector']);
$className = str_replace('/', '\\', $className);
if ($className[0]=='\\') $className = substr($className, 1);
// check known aliases for a match
$lName = strtolower($className);
if (isset(self::$aliases[$lName]))
$className = self::$aliases[$lName];
// instantiate and save a new connector
$me->pool[$id] = $connector = Connector::create($className, $options);
}
return $connector;
} | [
"public",
"static",
"function",
"getConnector",
"(",
"$",
"id",
"=",
"null",
")",
"{",
"$",
"me",
"=",
"self",
"::",
"me",
"(",
")",
";",
"if",
"(",
"$",
"id",
"===",
"null",
")",
"{",
"// a single db project",
"if",
"(",
"!",
"$",
"me",
"->",
"d... | Return the connector instance for the specified connection identifier.
@param string $id [optional] - connection identifier
@return IConnector - database adapter for the specified identifier | [
"Return",
"the",
"connector",
"instance",
"for",
"the",
"specified",
"connection",
"identifier",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/ConnectionPool.php#L64-L95 | train |
locomotivemtl/charcoal-core | src/Charcoal/Loader/CollectionLoaderFactoryTrait.php | CollectionLoaderFactoryTrait.collectionLoaderFactory | public function collectionLoaderFactory()
{
if (!isset($this->collectionLoaderFactory)) {
throw new RuntimeException(sprintf(
'Collection Loader Factory is not defined for [%s]',
get_class($this)
));
}
return $this->collectionLoaderFactory;
} | php | public function collectionLoaderFactory()
{
if (!isset($this->collectionLoaderFactory)) {
throw new RuntimeException(sprintf(
'Collection Loader Factory is not defined for [%s]',
get_class($this)
));
}
return $this->collectionLoaderFactory;
} | [
"public",
"function",
"collectionLoaderFactory",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"collectionLoaderFactory",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"sprintf",
"(",
"'Collection Loader Factory is not defined for [%s]'",
... | Retrieve the collection loader factory.
@throws RuntimeException If the collection loader factory is missing.
@return FactoryInterface | [
"Retrieve",
"the",
"collection",
"loader",
"factory",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Loader/CollectionLoaderFactoryTrait.php#L40-L50 | train |
locomotivemtl/charcoal-core | src/Charcoal/Loader/CollectionLoaderFactoryTrait.php | CollectionLoaderFactoryTrait.createCollectionLoaderWith | public function createCollectionLoaderWith(array $args = null, callable $callback = null)
{
$factory = $this->collectionLoaderFactory();
return $factory->create($factory->defaultClass(), $args, $callback);
} | php | public function createCollectionLoaderWith(array $args = null, callable $callback = null)
{
$factory = $this->collectionLoaderFactory();
return $factory->create($factory->defaultClass(), $args, $callback);
} | [
"public",
"function",
"createCollectionLoaderWith",
"(",
"array",
"$",
"args",
"=",
"null",
",",
"callable",
"$",
"callback",
"=",
"null",
")",
"{",
"$",
"factory",
"=",
"$",
"this",
"->",
"collectionLoaderFactory",
"(",
")",
";",
"return",
"$",
"factory",
... | Create a model collection loader with optional constructor arguments and a post-creation callback.
@param array|null $args Optional. Constructor arguments.
@param callable|null $callback Optional. Called at creation.
@return CollectionLoader | [
"Create",
"a",
"model",
"collection",
"loader",
"with",
"optional",
"constructor",
"arguments",
"and",
"a",
"post",
"-",
"creation",
"callback",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Loader/CollectionLoaderFactoryTrait.php#L59-L64 | train |
timble/kodekit | code/manifest/manifest.php | Manifest.getAuthors | public function getAuthors()
{
$result = false;
if($this->__manifest !== false)
{
$authors = $this->__manifest->get('authors', array());
$result = ObjectConfig::unbox($authors);
}
return $result;
} | php | public function getAuthors()
{
$result = false;
if($this->__manifest !== false)
{
$authors = $this->__manifest->get('authors', array());
$result = ObjectConfig::unbox($authors);
}
return $result;
} | [
"public",
"function",
"getAuthors",
"(",
")",
"{",
"$",
"result",
"=",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"__manifest",
"!==",
"false",
")",
"{",
"$",
"authors",
"=",
"$",
"this",
"->",
"__manifest",
"->",
"get",
"(",
"'authors'",
",",
"arra... | Get the homepage
@return array|false Returns FALSE if the manifest doesn't exist | [
"Get",
"the",
"homepage"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/manifest/manifest.php#L112-L122 | train |
timble/kodekit | code/manifest/manifest.php | Manifest.__isset | final public function __isset($name)
{
$result = false;
if($this->__manifest !== false) {
$result = $this->__manifest->has($name);
}
return $result;
} | php | final public function __isset($name)
{
$result = false;
if($this->__manifest !== false) {
$result = $this->__manifest->has($name);
}
return $result;
} | [
"final",
"public",
"function",
"__isset",
"(",
"$",
"name",
")",
"{",
"$",
"result",
"=",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"__manifest",
"!==",
"false",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"__manifest",
"->",
"has",
"(",
"$"... | Test existence of a manifest option
@param string $name
@return bool | [
"Test",
"existence",
"of",
"a",
"manifest",
"option"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/manifest/manifest.php#L146-L154 | train |
locomotivemtl/charcoal-core | src/Charcoal/Model/Service/ModelLoader.php | ModelLoader.load | public function load($ident, $useCache = true, $reloadObj = false)
{
if (!$useCache) {
return $this->loadFromSource($ident);
}
$cacheKey = $this->cacheKey($ident);
$cacheItem = $this->cachePool->getItem($cacheKey);
if (!$reloadObj) {
if ($cacheItem->isHit()) {
$data = $cacheItem->get();
$obj = $this->factory->create($this->objType);
$obj->setData($data);
return $obj;
}
}
$obj = $this->loadFromSource($ident);
$data = ($obj->id() ? $obj->data() : []);
$cacheItem->set($data);
$this->cachePool->save($cacheItem);
return $obj;
} | php | public function load($ident, $useCache = true, $reloadObj = false)
{
if (!$useCache) {
return $this->loadFromSource($ident);
}
$cacheKey = $this->cacheKey($ident);
$cacheItem = $this->cachePool->getItem($cacheKey);
if (!$reloadObj) {
if ($cacheItem->isHit()) {
$data = $cacheItem->get();
$obj = $this->factory->create($this->objType);
$obj->setData($data);
return $obj;
}
}
$obj = $this->loadFromSource($ident);
$data = ($obj->id() ? $obj->data() : []);
$cacheItem->set($data);
$this->cachePool->save($cacheItem);
return $obj;
} | [
"public",
"function",
"load",
"(",
"$",
"ident",
",",
"$",
"useCache",
"=",
"true",
",",
"$",
"reloadObj",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"useCache",
")",
"{",
"return",
"$",
"this",
"->",
"loadFromSource",
"(",
"$",
"ident",
")",
";"... | Retrieve an object, by its key, from its source or from the cache.
When the cache is enabled, only the object's _data_ is stored. This prevents issues
when unserializing a class that might have dependencies.
@param string|integer $ident The object identifier to load.
@param boolean $useCache If FALSE, ignore the cached object. Defaults to TRUE.
@param boolean $reloadObj If TRUE, refresh the cached object. Defaults to FALSE.
@return ModelInterface | [
"Retrieve",
"an",
"object",
"by",
"its",
"key",
"from",
"its",
"source",
"or",
"from",
"the",
"cache",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/ModelLoader.php#L212-L237 | train |
locomotivemtl/charcoal-core | src/Charcoal/Model/Service/ModelLoader.php | ModelLoader.loadFromSource | private function loadFromSource($ident)
{
$obj = $this->factory->create($this->objType);
if ($this->objKey) {
$obj->loadFrom($this->objKey, $ident);
} else {
$obj->load($ident);
}
return $obj;
} | php | private function loadFromSource($ident)
{
$obj = $this->factory->create($this->objType);
if ($this->objKey) {
$obj->loadFrom($this->objKey, $ident);
} else {
$obj->load($ident);
}
return $obj;
} | [
"private",
"function",
"loadFromSource",
"(",
"$",
"ident",
")",
"{",
"$",
"obj",
"=",
"$",
"this",
"->",
"factory",
"->",
"create",
"(",
"$",
"this",
"->",
"objType",
")",
";",
"if",
"(",
"$",
"this",
"->",
"objKey",
")",
"{",
"$",
"obj",
"->",
... | Load an objet from its soure.
@param string|integer $ident The object identifier to load.
@return ModelInterface | [
"Load",
"an",
"objet",
"from",
"its",
"soure",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/ModelLoader.php#L245-L255 | train |
locomotivemtl/charcoal-core | src/Charcoal/Model/Service/ModelLoader.php | ModelLoader.cacheKey | private function cacheKey($ident)
{
if ($this->objKey === null) {
$model = $this->factory->get($this->objType);
$this->setObjKey($model->key());
}
$cacheKey = 'object/'.str_replace('/', '.', $this->objType.'.'.$this->objKey.'.'.$ident);
return $cacheKey;
} | php | private function cacheKey($ident)
{
if ($this->objKey === null) {
$model = $this->factory->get($this->objType);
$this->setObjKey($model->key());
}
$cacheKey = 'object/'.str_replace('/', '.', $this->objType.'.'.$this->objKey.'.'.$ident);
return $cacheKey;
} | [
"private",
"function",
"cacheKey",
"(",
"$",
"ident",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"objKey",
"===",
"null",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"factory",
"->",
"get",
"(",
"$",
"this",
"->",
"objType",
")",
";",
"$",
"this... | Generate a cache key.
@param string|integer $ident The object identifier to load.
@return string | [
"Generate",
"a",
"cache",
"key",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/ModelLoader.php#L263-L273 | train |
locomotivemtl/charcoal-core | src/Charcoal/Model/Service/ModelLoader.php | ModelLoader.setObjKey | private function setObjKey($objKey)
{
if (empty($objKey) && !is_numeric($objKey)) {
$this->objKey = null;
return $this;
}
if (!is_string($objKey)) {
throw new InvalidArgumentException(
'Can not set model loader object type: not a string'
);
}
$this->objKey = $objKey;
return $this;
} | php | private function setObjKey($objKey)
{
if (empty($objKey) && !is_numeric($objKey)) {
$this->objKey = null;
return $this;
}
if (!is_string($objKey)) {
throw new InvalidArgumentException(
'Can not set model loader object type: not a string'
);
}
$this->objKey = $objKey;
return $this;
} | [
"private",
"function",
"setObjKey",
"(",
"$",
"objKey",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"objKey",
")",
"&&",
"!",
"is_numeric",
"(",
"$",
"objKey",
")",
")",
"{",
"$",
"this",
"->",
"objKey",
"=",
"null",
";",
"return",
"$",
"this",
";",
... | Set the object key.
@param string $objKey The object key to use for laoding.
@throws InvalidArgumentException If the object key is not a string.
@return ModelLoader Chainable | [
"Set",
"the",
"object",
"key",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/ModelLoader.php#L306-L321 | train |
nicebooks-com/isbn | src/Isbn.php | Isbn.to10 | public function to10() : Isbn
{
if (! $this->is13) {
return $this;
}
return new Isbn(Internal\Converter::convertIsbn13to10($this->isbn), false);
} | php | public function to10() : Isbn
{
if (! $this->is13) {
return $this;
}
return new Isbn(Internal\Converter::convertIsbn13to10($this->isbn), false);
} | [
"public",
"function",
"to10",
"(",
")",
":",
"Isbn",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"is13",
")",
"{",
"return",
"$",
"this",
";",
"}",
"return",
"new",
"Isbn",
"(",
"Internal",
"\\",
"Converter",
"::",
"convertIsbn13to10",
"(",
"$",
"this",
... | Returns a copy of this Isbn, converted to ISBN-10.
@return Isbn The ISBN-10.
@throws Exception\IsbnNotConvertibleException If this is an ISBN-13 not starting with 978. | [
"Returns",
"a",
"copy",
"of",
"this",
"Isbn",
"converted",
"to",
"ISBN",
"-",
"10",
"."
] | f5ceb662e517b21e30c9dfa53c4d74823849232d | https://github.com/nicebooks-com/isbn/blob/f5ceb662e517b21e30c9dfa53c4d74823849232d/src/Isbn.php#L114-L121 | train |
nicebooks-com/isbn | src/Isbn.php | Isbn.to13 | public function to13() : Isbn
{
if ($this->is13) {
return $this;
}
return new Isbn(Internal\Converter::convertIsbn10to13($this->isbn), true);
} | php | public function to13() : Isbn
{
if ($this->is13) {
return $this;
}
return new Isbn(Internal\Converter::convertIsbn10to13($this->isbn), true);
} | [
"public",
"function",
"to13",
"(",
")",
":",
"Isbn",
"{",
"if",
"(",
"$",
"this",
"->",
"is13",
")",
"{",
"return",
"$",
"this",
";",
"}",
"return",
"new",
"Isbn",
"(",
"Internal",
"\\",
"Converter",
"::",
"convertIsbn10to13",
"(",
"$",
"this",
"->",... | Returns a copy of this Isbn, converted to ISBN-13.
@return Isbn The ISBN-13. | [
"Returns",
"a",
"copy",
"of",
"this",
"Isbn",
"converted",
"to",
"ISBN",
"-",
"13",
"."
] | f5ceb662e517b21e30c9dfa53c4d74823849232d | https://github.com/nicebooks-com/isbn/blob/f5ceb662e517b21e30c9dfa53c4d74823849232d/src/Isbn.php#L128-L135 | train |
nicebooks-com/isbn | src/Isbn.php | Isbn.getGroupIdentifier | public function getGroupIdentifier() : string
{
if ($this->rangeInfo === null) {
throw IsbnException::unknownGroup($this->isbn);
}
return $this->rangeInfo->groupIdentifier;
} | php | public function getGroupIdentifier() : string
{
if ($this->rangeInfo === null) {
throw IsbnException::unknownGroup($this->isbn);
}
return $this->rangeInfo->groupIdentifier;
} | [
"public",
"function",
"getGroupIdentifier",
"(",
")",
":",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"rangeInfo",
"===",
"null",
")",
"{",
"throw",
"IsbnException",
"::",
"unknownGroup",
"(",
"$",
"this",
"->",
"isbn",
")",
";",
"}",
"return",
"$",
... | Returns the group identifier.
The group or country identifier identifies a national or geographic grouping of publishers.
For ISBN-13, the identifier includes the GS1 (EAN) prefix, for example "978-2".
For the equivalent ISBN-10, the identifier would be "2".
@return string
@throws IsbnException If this ISBN is not in a recognized group. | [
"Returns",
"the",
"group",
"identifier",
"."
] | f5ceb662e517b21e30c9dfa53c4d74823849232d | https://github.com/nicebooks-com/isbn/blob/f5ceb662e517b21e30c9dfa53c4d74823849232d/src/Isbn.php#L190-L197 | train |
nicebooks-com/isbn | src/Isbn.php | Isbn.getGroupName | public function getGroupName() : string
{
if ($this->rangeInfo === null) {
throw IsbnException::unknownGroup($this->isbn);
}
return $this->rangeInfo->groupName;
} | php | public function getGroupName() : string
{
if ($this->rangeInfo === null) {
throw IsbnException::unknownGroup($this->isbn);
}
return $this->rangeInfo->groupName;
} | [
"public",
"function",
"getGroupName",
"(",
")",
":",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"rangeInfo",
"===",
"null",
")",
"{",
"throw",
"IsbnException",
"::",
"unknownGroup",
"(",
"$",
"this",
"->",
"isbn",
")",
";",
"}",
"return",
"$",
"this"... | Returns the group name.
@return string
@throws IsbnException If this ISBN is not in a recognized group. | [
"Returns",
"the",
"group",
"name",
"."
] | f5ceb662e517b21e30c9dfa53c4d74823849232d | https://github.com/nicebooks-com/isbn/blob/f5ceb662e517b21e30c9dfa53c4d74823849232d/src/Isbn.php#L206-L213 | train |
nicebooks-com/isbn | src/Isbn.php | Isbn.getPublisherIdentifier | public function getPublisherIdentifier() : string
{
if ($this->rangeInfo === null) {
throw IsbnException::unknownGroup($this->isbn);
}
if ($this->rangeInfo->parts === null) {
throw IsbnException::unknownRange($this->isbn);
}
return $this->rangeInfo->parts[$this->is13 ? 2 : 1];
} | php | public function getPublisherIdentifier() : string
{
if ($this->rangeInfo === null) {
throw IsbnException::unknownGroup($this->isbn);
}
if ($this->rangeInfo->parts === null) {
throw IsbnException::unknownRange($this->isbn);
}
return $this->rangeInfo->parts[$this->is13 ? 2 : 1];
} | [
"public",
"function",
"getPublisherIdentifier",
"(",
")",
":",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"rangeInfo",
"===",
"null",
")",
"{",
"throw",
"IsbnException",
"::",
"unknownGroup",
"(",
"$",
"this",
"->",
"isbn",
")",
";",
"}",
"if",
"(",
... | Returns the publisher identifier.
The publisher identifier identifies a particular publisher within a group.
@return string
@throws IsbnException If this ISBN is not in a recognized group or range. | [
"Returns",
"the",
"publisher",
"identifier",
"."
] | f5ceb662e517b21e30c9dfa53c4d74823849232d | https://github.com/nicebooks-com/isbn/blob/f5ceb662e517b21e30c9dfa53c4d74823849232d/src/Isbn.php#L224-L235 | train |
timble/kodekit | code/filter/abstract.php | FilterAbstract.getInstance | public static function getInstance(ObjectConfigInterface $config, ObjectManagerInterface $manager)
{
//Create the singleton
$class = $manager->getClass($config->object_identifier);
$instance = new $class($config);
if($instance instanceof FilterTraversable) {
$instance = $instance->decorate('lib:filter.iterator');
}
return $instance;
} | php | public static function getInstance(ObjectConfigInterface $config, ObjectManagerInterface $manager)
{
//Create the singleton
$class = $manager->getClass($config->object_identifier);
$instance = new $class($config);
if($instance instanceof FilterTraversable) {
$instance = $instance->decorate('lib:filter.iterator');
}
return $instance;
} | [
"public",
"static",
"function",
"getInstance",
"(",
"ObjectConfigInterface",
"$",
"config",
",",
"ObjectManagerInterface",
"$",
"manager",
")",
"{",
"//Create the singleton",
"$",
"class",
"=",
"$",
"manager",
"->",
"getClass",
"(",
"$",
"config",
"->",
"object_id... | Create filter and decorate it with FilterIterator if the filter implements FilterTraversable
@param ObjectConfigInterface $config Configuration options
@param ObjectManagerInterface $manager A ObjectManagerInterface object
@return FilterInterface
@see FilterTraversable | [
"Create",
"filter",
"and",
"decorate",
"it",
"with",
"FilterIterator",
"if",
"the",
"filter",
"implements",
"FilterTraversable"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/filter/abstract.php#L82-L93 | train |
timble/kodekit | code/database/query/abstract.php | DatabaseQueryAbstract.getDriver | public function getDriver()
{
if(!$this->__driver instanceof DatabaseDriverInterface)
{
$this->__driver = $this->getObject($this->__driver);
if(!$this->__driver instanceof DatabaseDriverInterface)
{
throw new \UnexpectedValueException(
'Driver: '.get_class($this->__driver).' does not implement DatabaseDriverInterface'
);
}
}
return $this->__driver;
} | php | public function getDriver()
{
if(!$this->__driver instanceof DatabaseDriverInterface)
{
$this->__driver = $this->getObject($this->__driver);
if(!$this->__driver instanceof DatabaseDriverInterface)
{
throw new \UnexpectedValueException(
'Driver: '.get_class($this->__driver).' does not implement DatabaseDriverInterface'
);
}
}
return $this->__driver;
} | [
"public",
"function",
"getDriver",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"__driver",
"instanceof",
"DatabaseDriverInterface",
")",
"{",
"$",
"this",
"->",
"__driver",
"=",
"$",
"this",
"->",
"getObject",
"(",
"$",
"this",
"->",
"__driver",
")... | Gets the database driver
@throws \\UnexpectedValueException If the driver doesn't implement DatabaseDriverInterface
@return DatabaseDriverInterface | [
"Gets",
"the",
"database",
"driver"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/database/query/abstract.php#L106-L121 | train |
rosasurfer/ministruts | src/ministruts/Page.php | Page.get | public static function get($name, $altValue = null) {
$page = self::me();
if (\key_exists($name, $page->properties))
return $page->properties[$name];
return $altValue;
} | php | public static function get($name, $altValue = null) {
$page = self::me();
if (\key_exists($name, $page->properties))
return $page->properties[$name];
return $altValue;
} | [
"public",
"static",
"function",
"get",
"(",
"$",
"name",
",",
"$",
"altValue",
"=",
"null",
")",
"{",
"$",
"page",
"=",
"self",
"::",
"me",
"(",
")",
";",
"if",
"(",
"\\",
"key_exists",
"(",
"$",
"name",
",",
"$",
"page",
"->",
"properties",
")",... | Lookup and return a property stored in the instance.
@param string $name - property name
@param mixed $altValue [optional] - value to return if no such property exists
@return mixed - value | [
"Lookup",
"and",
"return",
"a",
"property",
"stored",
"in",
"the",
"instance",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Page.php#L51-L58 | train |
timble/kodekit | code/template/engine/abstract.php | TemplateEngineAbstract.renderPartial | public function renderPartial($url, array $data = array())
{
//Qualify relative template url
if(!parse_url($url, PHP_URL_SCHEME))
{
if(!$template = end($this->__stack)) {
throw new \RuntimeException('Cannot qualify partial template url');
}
$basepath = dirname($template);
//Resolve relative path
if($path = trim('.', dirname($url)))
{
$count = 0;
$total = count(explode('/', $path));
while ($count++ < $total) {
$basepath = dirname($basepath);
}
$basename = $url;
}
else $basename = basename($url);
$url = $basepath. '/' .$basename;
}
if(array_search($url, $this->__stack))
{
throw new \RuntimeException(sprintf(
'Template recursion detected while importing "%s" in "%s"', $url
));
}
$type = pathinfo( $this->locateSource($url), PATHINFO_EXTENSION);
$data = array_merge((array) $this->getData(), $data);
//If the partial requires a different engine create it and delegate
if(!in_array($type, $this->getFileTypes()))
{
$result = $this->getObject('template.engine.factory')
->createEngine($type, array('functions' => $this->getFunctions()))
->render($url, $data);
}
else $result = $this->render($url, $data);
//Remove the template from the stack
array_pop($this->__stack);
return $result;
} | php | public function renderPartial($url, array $data = array())
{
//Qualify relative template url
if(!parse_url($url, PHP_URL_SCHEME))
{
if(!$template = end($this->__stack)) {
throw new \RuntimeException('Cannot qualify partial template url');
}
$basepath = dirname($template);
//Resolve relative path
if($path = trim('.', dirname($url)))
{
$count = 0;
$total = count(explode('/', $path));
while ($count++ < $total) {
$basepath = dirname($basepath);
}
$basename = $url;
}
else $basename = basename($url);
$url = $basepath. '/' .$basename;
}
if(array_search($url, $this->__stack))
{
throw new \RuntimeException(sprintf(
'Template recursion detected while importing "%s" in "%s"', $url
));
}
$type = pathinfo( $this->locateSource($url), PATHINFO_EXTENSION);
$data = array_merge((array) $this->getData(), $data);
//If the partial requires a different engine create it and delegate
if(!in_array($type, $this->getFileTypes()))
{
$result = $this->getObject('template.engine.factory')
->createEngine($type, array('functions' => $this->getFunctions()))
->render($url, $data);
}
else $result = $this->render($url, $data);
//Remove the template from the stack
array_pop($this->__stack);
return $result;
} | [
"public",
"function",
"renderPartial",
"(",
"$",
"url",
",",
"array",
"$",
"data",
"=",
"array",
"(",
")",
")",
"{",
"//Qualify relative template url",
"if",
"(",
"!",
"parse_url",
"(",
"$",
"url",
",",
"PHP_URL_SCHEME",
")",
")",
"{",
"if",
"(",
"!",
... | Render a partial template
This method merges the data passed in with the data from the parent template. If the partial template
has different file type the method will try to allocate it by jumping out of the local template scope.
@param string $url The template url
@param array $data The data to pass to the template
@throws \RuntimeException If a partial template url could not be fully qualified
@return string The rendered template content | [
"Render",
"a",
"partial",
"template"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/template/engine/abstract.php#L139-L190 | train |
timble/kodekit | code/template/engine/abstract.php | TemplateEngineAbstract.renderDebug | public function renderDebug($source)
{
$template = end($this->__stack);
if($this->getObject('filter.path')->validate($template)) {
$path = $this->locateSource($template);
} else {
$path = '';
}
//Render debug comments
if($this->isDebug())
{
$type = $this->getIdentifier()->getName();
$path = str_replace(rtrim(\Kodekit::getInstance()->getRootPath(), '/').'/', '', $path);
$format = PHP_EOL.'<!--BEGIN '.$type.':render '.$path.' -->'.PHP_EOL;
$format .= '%s';
$format .= PHP_EOL.'<!--END '.$type.':render '.$path.' -->'.PHP_EOL;
$source = sprintf($format, trim($source));
}
return $source;
} | php | public function renderDebug($source)
{
$template = end($this->__stack);
if($this->getObject('filter.path')->validate($template)) {
$path = $this->locateSource($template);
} else {
$path = '';
}
//Render debug comments
if($this->isDebug())
{
$type = $this->getIdentifier()->getName();
$path = str_replace(rtrim(\Kodekit::getInstance()->getRootPath(), '/').'/', '', $path);
$format = PHP_EOL.'<!--BEGIN '.$type.':render '.$path.' -->'.PHP_EOL;
$format .= '%s';
$format .= PHP_EOL.'<!--END '.$type.':render '.$path.' -->'.PHP_EOL;
$source = sprintf($format, trim($source));
}
return $source;
} | [
"public",
"function",
"renderDebug",
"(",
"$",
"source",
")",
"{",
"$",
"template",
"=",
"end",
"(",
"$",
"this",
"->",
"__stack",
")",
";",
"if",
"(",
"$",
"this",
"->",
"getObject",
"(",
"'filter.path'",
")",
"->",
"validate",
"(",
"$",
"template",
... | Render debug information
@param string $source The template source
@return string The rendered template source | [
"Render",
"debug",
"information"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/template/engine/abstract.php#L198-L222 | train |
timble/kodekit | code/template/engine/abstract.php | TemplateEngineAbstract.locateSource | public function locateSource($url)
{
if (!$file = $this->getObject('template.locator.factory')->locate($url)) {
throw new \InvalidArgumentException(sprintf('The template "%s" cannot be located.', $url));
}
return $file;
} | php | public function locateSource($url)
{
if (!$file = $this->getObject('template.locator.factory')->locate($url)) {
throw new \InvalidArgumentException(sprintf('The template "%s" cannot be located.', $url));
}
return $file;
} | [
"public",
"function",
"locateSource",
"(",
"$",
"url",
")",
"{",
"if",
"(",
"!",
"$",
"file",
"=",
"$",
"this",
"->",
"getObject",
"(",
"'template.locator.factory'",
")",
"->",
"locate",
"(",
"$",
"url",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArg... | Locate a template file, given it's url.
@param string $url The template url
@throws \InvalidArgumentException If the template could not be located
@throws \RuntimeException If a partial template url could not be fully qualified
@return string The template real path | [
"Locate",
"a",
"template",
"file",
"given",
"it",
"s",
"url",
"."
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/template/engine/abstract.php#L232-L239 | train |
rosasurfer/ministruts | src/exception/RosasurferExceptionTrait.php | RosasurferExceptionTrait.addMessage | public function addMessage($message) {
$this->message = trim(trim($this->message).NL.$message);
return $this;
} | php | public function addMessage($message) {
$this->message = trim(trim($this->message).NL.$message);
return $this;
} | [
"public",
"function",
"addMessage",
"(",
"$",
"message",
")",
"{",
"$",
"this",
"->",
"message",
"=",
"trim",
"(",
"trim",
"(",
"$",
"this",
"->",
"message",
")",
".",
"NL",
".",
"$",
"message",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Add a message to the exception's existing message. Used to add additional information to an existing message.
@param string $message
@return $this | [
"Add",
"a",
"message",
"to",
"the",
"exception",
"s",
"existing",
"message",
".",
"Used",
"to",
"add",
"additional",
"information",
"to",
"an",
"existing",
"message",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/exception/RosasurferExceptionTrait.php#L32-L35 | train |
rosasurfer/ministruts | src/exception/RosasurferExceptionTrait.php | RosasurferExceptionTrait.getBetterMessage | public function getBetterMessage() {
if (!$this->betterMessage)
$this->betterMessage = DebugHelper::composeBetterMessage($this);
return $this->betterMessage;
} | php | public function getBetterMessage() {
if (!$this->betterMessage)
$this->betterMessage = DebugHelper::composeBetterMessage($this);
return $this->betterMessage;
} | [
"public",
"function",
"getBetterMessage",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"betterMessage",
")",
"$",
"this",
"->",
"betterMessage",
"=",
"DebugHelper",
"::",
"composeBetterMessage",
"(",
"$",
"this",
")",
";",
"return",
"$",
"this",
"->",... | Return the exception's message in a more readable way.
@return string - message | [
"Return",
"the",
"exception",
"s",
"message",
"in",
"a",
"more",
"readable",
"way",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/exception/RosasurferExceptionTrait.php#L59-L63 | train |
timble/kodekit | code/dispatcher/authenticator/csrf.php | DispatcherAuthenticatorCsrf.getToken | public function getToken()
{
if(!isset($this->__token))
{
$token = false;
$request = $this->getObject('request');
if($request->headers->has('X-XSRF-Token')) {
$token = $request->headers->get('X-XSRF-Token');
}
if($request->headers->has('X-CSRF-Token')) {
$token = $request->headers->get('X-CSRF-Token');
}
if($request->data->has('csrf_token')) {
$token = $request->data->get('csrf_token', 'sha1');
}
$this->__token = $token;
}
return $this->__token;
} | php | public function getToken()
{
if(!isset($this->__token))
{
$token = false;
$request = $this->getObject('request');
if($request->headers->has('X-XSRF-Token')) {
$token = $request->headers->get('X-XSRF-Token');
}
if($request->headers->has('X-CSRF-Token')) {
$token = $request->headers->get('X-CSRF-Token');
}
if($request->data->has('csrf_token')) {
$token = $request->data->get('csrf_token', 'sha1');
}
$this->__token = $token;
}
return $this->__token;
} | [
"public",
"function",
"getToken",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"__token",
")",
")",
"{",
"$",
"token",
"=",
"false",
";",
"$",
"request",
"=",
"$",
"this",
"->",
"getObject",
"(",
"'request'",
")",
";",
"if",
"(... | Return the CSRF request token
@return string The CSRF token or NULL if no token could be found | [
"Return",
"the",
"CSRF",
"request",
"token"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/dispatcher/authenticator/csrf.php#L51-L74 | train |
locomotivemtl/charcoal-core | src/Charcoal/Model/Service/ModelBuilder.php | ModelBuilder.build | public function build($objType, $metadataIdent = null, $sourceIdent = null)
{
$metadata = $this->createMetadata($objType, $metadataIdent);
$source = $this->createSource($metadata, $sourceIdent);
$args = array_merge($this->factory->arguments(), [
'metadata' => $metadata,
'source' => $source
]);
$model = $this->factory->create($objType, $args);
$model->source()->setModel($model);
return $model;
} | php | public function build($objType, $metadataIdent = null, $sourceIdent = null)
{
$metadata = $this->createMetadata($objType, $metadataIdent);
$source = $this->createSource($metadata, $sourceIdent);
$args = array_merge($this->factory->arguments(), [
'metadata' => $metadata,
'source' => $source
]);
$model = $this->factory->create($objType, $args);
$model->source()->setModel($model);
return $model;
} | [
"public",
"function",
"build",
"(",
"$",
"objType",
",",
"$",
"metadataIdent",
"=",
"null",
",",
"$",
"sourceIdent",
"=",
"null",
")",
"{",
"$",
"metadata",
"=",
"$",
"this",
"->",
"createMetadata",
"(",
"$",
"objType",
",",
"$",
"metadataIdent",
")",
... | Build a model, pre-initializing its metadata and its source.
By default, the name of the "obj type" (the model class name) is used to determine the metadata ident to load.
To load a custom metadata for the object, use the `$metadataIdent` argument.
By default, the object's _default_ source (from its metadata) is used as source.
To load a custom source for the object, use the `$sourceIdent` argument.
@param string $objType The object type of the Model.
@param string|null $metadataIdent Optional. The metadata ident of the object.
@param string|null $sourceIdent Optional. The custom source ident to load as source.
@return \Charcoal\Model\ModelInterface | [
"Build",
"a",
"model",
"pre",
"-",
"initializing",
"its",
"metadata",
"and",
"its",
"source",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/Service/ModelBuilder.php#L60-L71 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/StorableTrait.php | StorableTrait.setId | public function setId($id)
{
if (!is_scalar($id)) {
throw new InvalidArgumentException(sprintf(
'ID for "%s" must be a scalar (integer, float, string, or boolean); received %s',
get_class($this),
(is_object($id) ? get_class($id) : gettype($id))
));
}
$key = $this->key();
if ($key === 'id') {
$this->id = $id;
} else {
$this[$key] = $id;
}
return $this;
} | php | public function setId($id)
{
if (!is_scalar($id)) {
throw new InvalidArgumentException(sprintf(
'ID for "%s" must be a scalar (integer, float, string, or boolean); received %s',
get_class($this),
(is_object($id) ? get_class($id) : gettype($id))
));
}
$key = $this->key();
if ($key === 'id') {
$this->id = $id;
} else {
$this[$key] = $id;
}
return $this;
} | [
"public",
"function",
"setId",
"(",
"$",
"id",
")",
"{",
"if",
"(",
"!",
"is_scalar",
"(",
"$",
"id",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'ID for \"%s\" must be a scalar (integer, float, string, or boolean); received %s'",
... | Set the object's unique ID.
The actual property set depends on `key()`.
@param mixed $id The object's ID.
@throws InvalidArgumentException If the argument is not scalar.
@return self | [
"Set",
"the",
"object",
"s",
"unique",
"ID",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L57-L75 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/StorableTrait.php | StorableTrait.setKey | public function setKey($key)
{
if (!is_string($key)) {
throw new InvalidArgumentException(sprintf(
'Key must be a string; received %s',
(is_object($key) ? get_class($key) : gettype($key))
));
}
if (!preg_match_all('/^[A-Za-z0-9_]+$/', $key)) {
throw new InvalidArgumentException(
sprintf('Key "%s" is invalid: must be alphanumeric / underscore.', $key)
);
}
$this->key = $key;
return $this;
} | php | public function setKey($key)
{
if (!is_string($key)) {
throw new InvalidArgumentException(sprintf(
'Key must be a string; received %s',
(is_object($key) ? get_class($key) : gettype($key))
));
}
if (!preg_match_all('/^[A-Za-z0-9_]+$/', $key)) {
throw new InvalidArgumentException(
sprintf('Key "%s" is invalid: must be alphanumeric / underscore.', $key)
);
}
$this->key = $key;
return $this;
} | [
"public",
"function",
"setKey",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"key",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Key must be a string; received %s'",
",",
"(",
"is_object",
"(",
"$",
... | Set the primary property key.
For uniquely identifying this object in storage.
Note: For security reason, only alphanumeric characters (and underscores)
are valid key names. Although SQL can support more, there's really no reason to.
@param string $key The object's primary key.
@throws InvalidArgumentException If the argument is not scalar.
@return self | [
"Set",
"the",
"primary",
"property",
"key",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L106-L123 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/StorableTrait.php | StorableTrait.source | public function source()
{
if ($this->source === null) {
$this->source = $this->createSource();
}
return $this->source;
} | php | public function source()
{
if ($this->source === null) {
$this->source = $this->createSource();
}
return $this->source;
} | [
"public",
"function",
"source",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"source",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"source",
"=",
"$",
"this",
"->",
"createSource",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"source",
";",
"... | Get the object's datasource repository.
@return SourceInterface | [
"Get",
"the",
"object",
"s",
"datasource",
"repository",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L153-L159 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/StorableTrait.php | StorableTrait.load | final public function load($id = null)
{
if ($id === null) {
$id = $this->id();
}
$this->source()->loadItem($id, $this);
return $this;
} | php | final public function load($id = null)
{
if ($id === null) {
$id = $this->id();
}
$this->source()->loadItem($id, $this);
return $this;
} | [
"final",
"public",
"function",
"load",
"(",
"$",
"id",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"id",
"===",
"null",
")",
"{",
"$",
"id",
"=",
"$",
"this",
"->",
"id",
"(",
")",
";",
"}",
"$",
"this",
"->",
"source",
"(",
")",
"->",
"loadItem",... | Load an object from the database from its ID.
@param mixed $id The identifier to load.
@return self | [
"Load",
"an",
"object",
"from",
"the",
"database",
"from",
"its",
"ID",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L175-L182 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/StorableTrait.php | StorableTrait.loadFromQuery | final public function loadFromQuery($query, array $binds = [])
{
$this->source()->loadItemFromQuery($query, $binds, $this);
return $this;
} | php | final public function loadFromQuery($query, array $binds = [])
{
$this->source()->loadItemFromQuery($query, $binds, $this);
return $this;
} | [
"final",
"public",
"function",
"loadFromQuery",
"(",
"$",
"query",
",",
"array",
"$",
"binds",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"source",
"(",
")",
"->",
"loadItemFromQuery",
"(",
"$",
"query",
",",
"$",
"binds",
",",
"$",
"this",
")",
"... | Load an object from the repository from a custom SQL query.
@param string $query The SQL query.
@param array $binds Optional. The SQL query parameters.
@return self | [
"Load",
"an",
"object",
"from",
"the",
"repository",
"from",
"a",
"custom",
"SQL",
"query",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L204-L208 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/StorableTrait.php | StorableTrait.save | final public function save()
{
$pre = $this->preSave();
if ($pre === false) {
$this->logger->error(sprintf(
'Can not save object "%s:%s"; cancelled by %s::preSave()',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
}
$ret = $this->source()->saveItem($this);
if ($ret === false) {
$this->logger->error(sprintf(
'Can not save object "%s:%s"; repository failed for %s',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
} else {
$this->setId($ret);
}
$post = $this->postSave();
if ($post === false) {
$this->logger->error(sprintf(
'Saved object "%s:%s" but %s::postSave() failed',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
}
return true;
} | php | final public function save()
{
$pre = $this->preSave();
if ($pre === false) {
$this->logger->error(sprintf(
'Can not save object "%s:%s"; cancelled by %s::preSave()',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
}
$ret = $this->source()->saveItem($this);
if ($ret === false) {
$this->logger->error(sprintf(
'Can not save object "%s:%s"; repository failed for %s',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
} else {
$this->setId($ret);
}
$post = $this->postSave();
if ($post === false) {
$this->logger->error(sprintf(
'Saved object "%s:%s" but %s::postSave() failed',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
}
return true;
} | [
"final",
"public",
"function",
"save",
"(",
")",
"{",
"$",
"pre",
"=",
"$",
"this",
"->",
"preSave",
"(",
")",
";",
"if",
"(",
"$",
"pre",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"sprintf",
"(",
"'Can not save obj... | Insert the object's current state in storage.
@return boolean TRUE on success. | [
"Insert",
"the",
"object",
"s",
"current",
"state",
"in",
"storage",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L215-L253 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/StorableTrait.php | StorableTrait.update | final public function update(array $keys = null)
{
$pre = $this->preUpdate($keys);
if ($pre === false) {
$this->logger->error(sprintf(
'Can not update object "%s:%s"; cancelled by %s::preUpdate()',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
}
$ret = $this->source()->updateItem($this, $keys);
if ($ret === false) {
$this->logger->error(sprintf(
'Can not update object "%s:%s"; repository failed for %s',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
}
$post = $this->postUpdate($keys);
if ($post === false) {
$this->logger->warning(sprintf(
'Updated object "%s:%s" but %s::postUpdate() failed',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
}
return true;
} | php | final public function update(array $keys = null)
{
$pre = $this->preUpdate($keys);
if ($pre === false) {
$this->logger->error(sprintf(
'Can not update object "%s:%s"; cancelled by %s::preUpdate()',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
}
$ret = $this->source()->updateItem($this, $keys);
if ($ret === false) {
$this->logger->error(sprintf(
'Can not update object "%s:%s"; repository failed for %s',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
}
$post = $this->postUpdate($keys);
if ($post === false) {
$this->logger->warning(sprintf(
'Updated object "%s:%s" but %s::postUpdate() failed',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
}
return true;
} | [
"final",
"public",
"function",
"update",
"(",
"array",
"$",
"keys",
"=",
"null",
")",
"{",
"$",
"pre",
"=",
"$",
"this",
"->",
"preUpdate",
"(",
"$",
"keys",
")",
";",
"if",
"(",
"$",
"pre",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"logger",
... | Update the object in storage with the current state.
@param string[] $keys If provided, only update the properties specified.
@return boolean TRUE on success. | [
"Update",
"the",
"object",
"in",
"storage",
"with",
"the",
"current",
"state",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L261-L297 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/StorableTrait.php | StorableTrait.delete | final public function delete()
{
$pre = $this->preDelete();
if ($pre === false) {
$this->logger->error(sprintf(
'Can not delete object "%s:%s"; cancelled by %s::preDelete()',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
}
$ret = $this->source()->deleteItem($this);
if ($ret === false) {
$this->logger->error(sprintf(
'Can not delete object "%s:%s"; repository failed for %s',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
}
$del = $this->postDelete();
if ($del === false) {
$this->logger->warning(sprintf(
'Deleted object "%s:%s" but %s::postDelete() failed',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
}
return true;
} | php | final public function delete()
{
$pre = $this->preDelete();
if ($pre === false) {
$this->logger->error(sprintf(
'Can not delete object "%s:%s"; cancelled by %s::preDelete()',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
}
$ret = $this->source()->deleteItem($this);
if ($ret === false) {
$this->logger->error(sprintf(
'Can not delete object "%s:%s"; repository failed for %s',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
}
$del = $this->postDelete();
if ($del === false) {
$this->logger->warning(sprintf(
'Deleted object "%s:%s" but %s::postDelete() failed',
$this->objType(),
$this->id(),
get_called_class()
));
return false;
}
return true;
} | [
"final",
"public",
"function",
"delete",
"(",
")",
"{",
"$",
"pre",
"=",
"$",
"this",
"->",
"preDelete",
"(",
")",
";",
"if",
"(",
"$",
"pre",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"sprintf",
"(",
"'Can not dele... | Delete an object from storage.
@return boolean TRUE on success. | [
"Delete",
"an",
"object",
"from",
"storage",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L304-L340 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/StorableTrait.php | StorableTrait.sourceFactory | protected function sourceFactory()
{
if (!isset($this->sourceFactory)) {
throw new RuntimeException(
sprintf('Source factory is not set for "%s"', get_class($this))
);
}
return $this->sourceFactory;
} | php | protected function sourceFactory()
{
if (!isset($this->sourceFactory)) {
throw new RuntimeException(
sprintf('Source factory is not set for "%s"', get_class($this))
);
}
return $this->sourceFactory;
} | [
"protected",
"function",
"sourceFactory",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"sourceFactory",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"sprintf",
"(",
"'Source factory is not set for \"%s\"'",
",",
"get_class",
"(",
... | Get the datasource repository factory.
@throws RuntimeException If the source factory was not previously set.
@return FactoryInterface | [
"Get",
"the",
"datasource",
"repository",
"factory",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/StorableTrait.php#L360-L368 | train |
timble/kodekit | code/template/helper/listbox.php | TemplateHelperListbox.optionlist | public function optionlist($config = array())
{
$translator = $this->getObject('translator');
$config = new ObjectConfigJson($config);
$config->append(array(
'prompt' => '- '.$translator->translate('Select').' -',
'deselect' => false,
'options' => array(),
'select2' => true,
'attribs' => array(),
));
if ($config->deselect && !$config->attribs->multiple)
{
$deselect = $this->option(array('value' => '', 'label' => $config->prompt));
$options = $config->options->toArray();
array_unshift($options, $deselect);
$config->options = $options;
}
if ($config->attribs->multiple && $config->name && substr($config->name, -2) !== '[]') {
$config->name .= '[]';
}
$html = '';
if ($config->select2)
{
if (!$config->name) {
$config->attribs->append(array(
'id' => 'select2-element-'.mt_rand(1000, 100000)
));
}
if ($config->deselect) {
$config->attribs->append(array(
'data-placeholder' => $config->prompt
));
}
$config->append(array(
'select2_options' => array(
'element' => $config->attribs->id ? '#'.$config->attribs->id : 'select[name=\"'.$config->name.'\"]',
'options' => array(
'allowClear' => $config->deselect
)
)
));
$html .= $this->createHelper('behavior')->select2($config->select2_options);
}
$html .= parent::optionlist($config);
return $html;
} | php | public function optionlist($config = array())
{
$translator = $this->getObject('translator');
$config = new ObjectConfigJson($config);
$config->append(array(
'prompt' => '- '.$translator->translate('Select').' -',
'deselect' => false,
'options' => array(),
'select2' => true,
'attribs' => array(),
));
if ($config->deselect && !$config->attribs->multiple)
{
$deselect = $this->option(array('value' => '', 'label' => $config->prompt));
$options = $config->options->toArray();
array_unshift($options, $deselect);
$config->options = $options;
}
if ($config->attribs->multiple && $config->name && substr($config->name, -2) !== '[]') {
$config->name .= '[]';
}
$html = '';
if ($config->select2)
{
if (!$config->name) {
$config->attribs->append(array(
'id' => 'select2-element-'.mt_rand(1000, 100000)
));
}
if ($config->deselect) {
$config->attribs->append(array(
'data-placeholder' => $config->prompt
));
}
$config->append(array(
'select2_options' => array(
'element' => $config->attribs->id ? '#'.$config->attribs->id : 'select[name=\"'.$config->name.'\"]',
'options' => array(
'allowClear' => $config->deselect
)
)
));
$html .= $this->createHelper('behavior')->select2($config->select2_options);
}
$html .= parent::optionlist($config);
return $html;
} | [
"public",
"function",
"optionlist",
"(",
"$",
"config",
"=",
"array",
"(",
")",
")",
"{",
"$",
"translator",
"=",
"$",
"this",
"->",
"getObject",
"(",
"'translator'",
")",
";",
"$",
"config",
"=",
"new",
"ObjectConfigJson",
"(",
"$",
"config",
")",
";"... | Adds the option to enhance the select box using Select2
@param array|ObjectConfig $config
@return string | [
"Adds",
"the",
"option",
"to",
"enhance",
"the",
"select",
"box",
"using",
"Select2"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/template/helper/listbox.php#L79-L136 | train |
timble/kodekit | code/template/helper/listbox.php | TemplateHelperListbox.enabled | public function enabled( $config = array())
{
$config = new ObjectConfigJson($config);
$config->append(array(
'name' => 'enabled',
'attribs' => array(),
'deselect' => true,
))->append(array(
'selected' => $config->{$config->name}
));
$translator = $this->getObject('translator');
$options = array();
$options[] = $this->option(array('label' => $translator->translate( 'Enabled' ) , 'value' => 1 ));
$options[] = $this->option(array('label' => $translator->translate( 'Disabled' ), 'value' => 0 ));
//Add the options to the config object
$config->options = $options;
return $this->optionlist($config);
} | php | public function enabled( $config = array())
{
$config = new ObjectConfigJson($config);
$config->append(array(
'name' => 'enabled',
'attribs' => array(),
'deselect' => true,
))->append(array(
'selected' => $config->{$config->name}
));
$translator = $this->getObject('translator');
$options = array();
$options[] = $this->option(array('label' => $translator->translate( 'Enabled' ) , 'value' => 1 ));
$options[] = $this->option(array('label' => $translator->translate( 'Disabled' ), 'value' => 0 ));
//Add the options to the config object
$config->options = $options;
return $this->optionlist($config);
} | [
"public",
"function",
"enabled",
"(",
"$",
"config",
"=",
"array",
"(",
")",
")",
"{",
"$",
"config",
"=",
"new",
"ObjectConfigJson",
"(",
"$",
"config",
")",
";",
"$",
"config",
"->",
"append",
"(",
"array",
"(",
"'name'",
"=>",
"'enabled'",
",",
"'... | Generates an HTML enabled listbox
@param array $config An optional array with configuration options
@return string Html | [
"Generates",
"an",
"HTML",
"enabled",
"listbox"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/template/helper/listbox.php#L144-L165 | train |
timble/kodekit | code/template/helper/listbox.php | TemplateHelperListbox.timezones | public function timezones($config = array())
{
$config = new ObjectConfig($config);
$config->append(array(
'name' => 'timezone',
'attribs' => array(),
'deselect' => true,
'prompt' => '- '.$this->getObject('translator')->translate('Select Time Zone').' -',
));
if ($config->deselect) {
$options[] = $this->option(array('label' => $config->prompt, 'value' => ''));
}
foreach (\DateTimeZone::listIdentifiers() as $identifier)
{
if (strpos($identifier, '/'))
{
list($group, $locale) = explode('/', $identifier, 2);
$groups[$group][] = str_replace('_', ' ', $locale);
}
}
$options[] = $this->option(array('label' => 'Coordinated Universal Time', 'value' => 'UTC'));
foreach ($groups as $group => $locales)
{
foreach ($locales as $locale) {
$options[$group][] = $this->option(array('label' => $locale, 'value' => str_replace(' ', '_', $group.'/'.$locale)));
}
}
$list = $this->optionlist(array(
'options' => $options,
'name' => $config->name,
'selected' => $config->selected,
'attribs' => $config->attribs
));
return $list;
} | php | public function timezones($config = array())
{
$config = new ObjectConfig($config);
$config->append(array(
'name' => 'timezone',
'attribs' => array(),
'deselect' => true,
'prompt' => '- '.$this->getObject('translator')->translate('Select Time Zone').' -',
));
if ($config->deselect) {
$options[] = $this->option(array('label' => $config->prompt, 'value' => ''));
}
foreach (\DateTimeZone::listIdentifiers() as $identifier)
{
if (strpos($identifier, '/'))
{
list($group, $locale) = explode('/', $identifier, 2);
$groups[$group][] = str_replace('_', ' ', $locale);
}
}
$options[] = $this->option(array('label' => 'Coordinated Universal Time', 'value' => 'UTC'));
foreach ($groups as $group => $locales)
{
foreach ($locales as $locale) {
$options[$group][] = $this->option(array('label' => $locale, 'value' => str_replace(' ', '_', $group.'/'.$locale)));
}
}
$list = $this->optionlist(array(
'options' => $options,
'name' => $config->name,
'selected' => $config->selected,
'attribs' => $config->attribs
));
return $list;
} | [
"public",
"function",
"timezones",
"(",
"$",
"config",
"=",
"array",
"(",
")",
")",
"{",
"$",
"config",
"=",
"new",
"ObjectConfig",
"(",
"$",
"config",
")",
";",
"$",
"config",
"->",
"append",
"(",
"array",
"(",
"'name'",
"=>",
"'timezone'",
",",
"'a... | Generates an HTML timezones listbox
@param array $config An optional array with configuration options
@return string Html | [
"Generates",
"an",
"HTML",
"timezones",
"listbox"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/template/helper/listbox.php#L202-L241 | train |
rosasurfer/ministruts | src/loader/ClassLoader.php | ClassLoader.register | public function register() {
if (!$this->registered) {
spl_autoload_register([$this, 'autoLoad'], $throw=true, $prepend=false);
$this->registered = true;
}
return $this;
} | php | public function register() {
if (!$this->registered) {
spl_autoload_register([$this, 'autoLoad'], $throw=true, $prepend=false);
$this->registered = true;
}
return $this;
} | [
"public",
"function",
"register",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"registered",
")",
"{",
"spl_autoload_register",
"(",
"[",
"$",
"this",
",",
"'autoLoad'",
"]",
",",
"$",
"throw",
"=",
"true",
",",
"$",
"prepend",
"=",
"false",
")"... | Register this instance.
@return $this | [
"Register",
"this",
"instance",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/loader/ClassLoader.php#L37-L43 | train |
rosasurfer/ministruts | src/loader/ClassLoader.php | ClassLoader.autoLoad | public function autoLoad($class) {
$lowerClass = strtolower($class);
if (isset($this->classMap[$lowerClass])) {
include($this->classMap[$lowerClass]);
}
} | php | public function autoLoad($class) {
$lowerClass = strtolower($class);
if (isset($this->classMap[$lowerClass])) {
include($this->classMap[$lowerClass]);
}
} | [
"public",
"function",
"autoLoad",
"(",
"$",
"class",
")",
"{",
"$",
"lowerClass",
"=",
"strtolower",
"(",
"$",
"class",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"classMap",
"[",
"$",
"lowerClass",
"]",
")",
")",
"{",
"include",
"(",
"$... | Load the specified class.
@param string $class | [
"Load",
"the",
"specified",
"class",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/loader/ClassLoader.php#L65-L71 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/AbstractExpression.php | AbstractExpression.quoteValue | public static function quoteValue($value)
{
$value = static::parseValue($value);
if (!is_scalar($value)) {
return $value;
}
if (is_bool($value)) {
return (int)$value;
}
if (!is_numeric($value)) {
$value = htmlspecialchars($value, ENT_QUOTES);
$value = sprintf('"%s"', $value);
}
return $value;
} | php | public static function quoteValue($value)
{
$value = static::parseValue($value);
if (!is_scalar($value)) {
return $value;
}
if (is_bool($value)) {
return (int)$value;
}
if (!is_numeric($value)) {
$value = htmlspecialchars($value, ENT_QUOTES);
$value = sprintf('"%s"', $value);
}
return $value;
} | [
"public",
"static",
"function",
"quoteValue",
"(",
"$",
"value",
")",
"{",
"$",
"value",
"=",
"static",
"::",
"parseValue",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"is_scalar",
"(",
"$",
"value",
")",
")",
"{",
"return",
"$",
"value",
";",
"}"... | Quote the given scalar value.
@param mixed $value The value to be quoted.
@return mixed Returns:
- If $value is not a scalar value, the value is returned intact.
- if $value is a boolean, the value is cast to an integer.
- If $value is not a number, the value is stringified
and wrapped in double quotes. | [
"Quote",
"the",
"given",
"scalar",
"value",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/AbstractExpression.php#L151-L169 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/AbstractExpression.php | AbstractExpression.quoteIdentifier | public static function quoteIdentifier($identifier, $tableName = null)
{
if ($identifier === null || $identifier === '') {
return '';
}
if (!is_string($identifier)) {
throw new InvalidArgumentException(sprintf(
'Field Name must be a string, received %s',
is_object($identifier) ? get_class($identifier) : gettype($identifier)
));
}
if ($tableName !== null) {
if (!is_string($tableName)) {
throw new InvalidArgumentException(sprintf(
'Table Name must be a string, received %s',
is_object($tableName) ? get_class($tableName) : gettype($tableName)
));
}
if ($tableName === '') {
throw new InvalidArgumentException(
'Table Name can not be empty.'
);
}
if ($identifier === '*') {
$template = '%1$s.*';
} else {
$template = '%1$s.`%2$s`';
}
return sprintf($template, $tableName, $identifier);
}
if ($identifier === '*') {
return $identifier;
} else {
return sprintf('`%1$s`', $identifier);
}
} | php | public static function quoteIdentifier($identifier, $tableName = null)
{
if ($identifier === null || $identifier === '') {
return '';
}
if (!is_string($identifier)) {
throw new InvalidArgumentException(sprintf(
'Field Name must be a string, received %s',
is_object($identifier) ? get_class($identifier) : gettype($identifier)
));
}
if ($tableName !== null) {
if (!is_string($tableName)) {
throw new InvalidArgumentException(sprintf(
'Table Name must be a string, received %s',
is_object($tableName) ? get_class($tableName) : gettype($tableName)
));
}
if ($tableName === '') {
throw new InvalidArgumentException(
'Table Name can not be empty.'
);
}
if ($identifier === '*') {
$template = '%1$s.*';
} else {
$template = '%1$s.`%2$s`';
}
return sprintf($template, $tableName, $identifier);
}
if ($identifier === '*') {
return $identifier;
} else {
return sprintf('`%1$s`', $identifier);
}
} | [
"public",
"static",
"function",
"quoteIdentifier",
"(",
"$",
"identifier",
",",
"$",
"tableName",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"identifier",
"===",
"null",
"||",
"$",
"identifier",
"===",
"''",
")",
"{",
"return",
"''",
";",
"}",
"if",
"(",
... | Quote the given field name.
@param string $identifier The field name.
@param string|null $tableName If provided, the table name is prepended to the $identifier.
@throws InvalidArgumentException If the parameters are not string.
@return string | [
"Quote",
"the",
"given",
"field",
"name",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/AbstractExpression.php#L179-L220 | train |
sroze/ChainOfResponsibility | ChainBuilder.php | ChainBuilder.getOrderedProcesses | public function getOrderedProcesses()
{
$graph = new DependencyGraph();
$root = new DependencyGraphNode(self::ROOT_NODE_NAME);
$graph->addRoot($root);
$processes = $this->getProcesses();
$nodes = [];
foreach ($processes as $process) {
$processName = $this->getProcessName($process);
$node = new DependencyGraphNode($processName);
$graph->addDependency($root, $node);
$nodes[$processName] = [$process, $node];
}
foreach ($nodes as $processName => $nodeDescription) {
list($process, $node) = $nodeDescription;
if (!$process instanceof DependentChainProcessInterface) {
$graph->addDependency($root, $node);
continue;
}
foreach ($process->dependsOn() as $dependencyName) {
if (!array_key_exists($dependencyName, $nodes)) {
throw new UnresolvedDependencyException(sprintf(
'Process "%s" is dependent of "%s" which is not found',
$processName,
$dependencyName
));
}
if ($graph->addDependency($node, $nodes[$dependencyName][1]) instanceof Left) {
throw new CircularDependencyException(sprintf(
'Circular dependency found: %s already depends on %s',
$dependencyName, $processName
));
}
}
}
return array_map(function ($nodeName) use ($nodes) {
return $nodes[$nodeName][0];
}, array_filter($graph->flatten(), function ($nodeName) {
return $nodeName !== self::ROOT_NODE_NAME;
}));
} | php | public function getOrderedProcesses()
{
$graph = new DependencyGraph();
$root = new DependencyGraphNode(self::ROOT_NODE_NAME);
$graph->addRoot($root);
$processes = $this->getProcesses();
$nodes = [];
foreach ($processes as $process) {
$processName = $this->getProcessName($process);
$node = new DependencyGraphNode($processName);
$graph->addDependency($root, $node);
$nodes[$processName] = [$process, $node];
}
foreach ($nodes as $processName => $nodeDescription) {
list($process, $node) = $nodeDescription;
if (!$process instanceof DependentChainProcessInterface) {
$graph->addDependency($root, $node);
continue;
}
foreach ($process->dependsOn() as $dependencyName) {
if (!array_key_exists($dependencyName, $nodes)) {
throw new UnresolvedDependencyException(sprintf(
'Process "%s" is dependent of "%s" which is not found',
$processName,
$dependencyName
));
}
if ($graph->addDependency($node, $nodes[$dependencyName][1]) instanceof Left) {
throw new CircularDependencyException(sprintf(
'Circular dependency found: %s already depends on %s',
$dependencyName, $processName
));
}
}
}
return array_map(function ($nodeName) use ($nodes) {
return $nodes[$nodeName][0];
}, array_filter($graph->flatten(), function ($nodeName) {
return $nodeName !== self::ROOT_NODE_NAME;
}));
} | [
"public",
"function",
"getOrderedProcesses",
"(",
")",
"{",
"$",
"graph",
"=",
"new",
"DependencyGraph",
"(",
")",
";",
"$",
"root",
"=",
"new",
"DependencyGraphNode",
"(",
"self",
"::",
"ROOT_NODE_NAME",
")",
";",
"$",
"graph",
"->",
"addRoot",
"(",
"$",
... | Get processes ordered based on their dependencies.
@return array
@throws CircularDependencyException
@throws UnresolvedDependencyException | [
"Get",
"processes",
"ordered",
"based",
"on",
"their",
"dependencies",
"."
] | d1c9743a4a7e5e63004be41d89175a05b3ea81b0 | https://github.com/sroze/ChainOfResponsibility/blob/d1c9743a4a7e5e63004be41d89175a05b3ea81b0/ChainBuilder.php#L48-L93 | train |
timble/kodekit | code/database/query/insert.php | DatabaseQueryInsert.type | public function type($type)
{
$type = strtoupper($type);
if (!in_array($type, ['INSERT', 'INSERT IGNORE', 'REPLACE'])) {
throw new \UnexpectedValueException('Invalid insert type');
}
$this->type = $type;
return $this;
} | php | public function type($type)
{
$type = strtoupper($type);
if (!in_array($type, ['INSERT', 'INSERT IGNORE', 'REPLACE'])) {
throw new \UnexpectedValueException('Invalid insert type');
}
$this->type = $type;
return $this;
} | [
"public",
"function",
"type",
"(",
"$",
"type",
")",
"{",
"$",
"type",
"=",
"strtoupper",
"(",
"$",
"type",
")",
";",
"if",
"(",
"!",
"in_array",
"(",
"$",
"type",
",",
"[",
"'INSERT'",
",",
"'INSERT IGNORE'",
",",
"'REPLACE'",
"]",
")",
")",
"{",
... | Sets insert operation type
Possible values are INSERT|REPLACE|INSERT IGNORE
@param string $type
@return $this | [
"Sets",
"insert",
"operation",
"type"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/database/query/insert.php#L65-L76 | train |
timble/kodekit | code/string/escaper/escaper.php | StringEscaper.escape | public static function escape($string, $context = 'html')
{
$method = 'escape'.ucfirst($context);
if(!method_exists(__CLASS__, $method)) {
throw new \InvalidArgumentException(sprintf('Cannot escape to: %s. Unknow context.', $context));
}
return static::$method($string);
} | php | public static function escape($string, $context = 'html')
{
$method = 'escape'.ucfirst($context);
if(!method_exists(__CLASS__, $method)) {
throw new \InvalidArgumentException(sprintf('Cannot escape to: %s. Unknow context.', $context));
}
return static::$method($string);
} | [
"public",
"static",
"function",
"escape",
"(",
"$",
"string",
",",
"$",
"context",
"=",
"'html'",
")",
"{",
"$",
"method",
"=",
"'escape'",
".",
"ucfirst",
"(",
"$",
"context",
")",
";",
"if",
"(",
"!",
"method_exists",
"(",
"__CLASS__",
",",
"$",
"m... | Escapde a string for a specific context
@param string $string The string to escape
@param string $context The context. Default HTML
@throws \InvalidArgumentException If the context is not recognised
@return string | [
"Escapde",
"a",
"string",
"for",
"a",
"specific",
"context"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/string/escaper/escaper.php#L47-L56 | train |
timble/kodekit | code/string/escaper/escaper.php | StringEscaper.escapeAttr | public static function escapeAttr($string)
{
if ($string !== '' && !ctype_digit($string))
{
$matcher = function($matches)
{
$chr = $matches[0];
$ord = ord($chr);
/**
* Replace undefined characters
*
* Replace characters undefined in HTML with the hex entity for the Unicode
* replacement character.
*/
if (($ord <= 0x1f && $chr != "\t" && $chr != "\n" && $chr != "\r")
|| ($ord >= 0x7f && $ord <= 0x9f)
) {
return '�';
}
/**
* Replace name entities
*
* If the current character to escape has a name entity replace it with while
* grabbing the integer value of the character.
*/
if (strlen($chr) > 1) {
$chr = static::convertEncoding($chr, 'UTF-16BE', 'UTF-8');
}
$hex = bin2hex($chr);
$ord = hexdec($hex);
if (isset(static::$_entity_map[$ord])) {
return '&' . static::$_entity_map[$ord] . ';';
}
/**
* Per OWASP recommendation
*
* Use upper hex entities for any other characters where a named entity does
* not exist.
*/
if ($ord > 255) {
return sprintf('&#x%04X;', $ord);
}
return sprintf('&#x%02X;', $ord);
};
$string = preg_replace_callback('/[^a-z0-9,\.\-_]/iSu', $matcher, $string);
}
return $string;
} | php | public static function escapeAttr($string)
{
if ($string !== '' && !ctype_digit($string))
{
$matcher = function($matches)
{
$chr = $matches[0];
$ord = ord($chr);
/**
* Replace undefined characters
*
* Replace characters undefined in HTML with the hex entity for the Unicode
* replacement character.
*/
if (($ord <= 0x1f && $chr != "\t" && $chr != "\n" && $chr != "\r")
|| ($ord >= 0x7f && $ord <= 0x9f)
) {
return '�';
}
/**
* Replace name entities
*
* If the current character to escape has a name entity replace it with while
* grabbing the integer value of the character.
*/
if (strlen($chr) > 1) {
$chr = static::convertEncoding($chr, 'UTF-16BE', 'UTF-8');
}
$hex = bin2hex($chr);
$ord = hexdec($hex);
if (isset(static::$_entity_map[$ord])) {
return '&' . static::$_entity_map[$ord] . ';';
}
/**
* Per OWASP recommendation
*
* Use upper hex entities for any other characters where a named entity does
* not exist.
*/
if ($ord > 255) {
return sprintf('&#x%04X;', $ord);
}
return sprintf('&#x%02X;', $ord);
};
$string = preg_replace_callback('/[^a-z0-9,\.\-_]/iSu', $matcher, $string);
}
return $string;
} | [
"public",
"static",
"function",
"escapeAttr",
"(",
"$",
"string",
")",
"{",
"if",
"(",
"$",
"string",
"!==",
"''",
"&&",
"!",
"ctype_digit",
"(",
"$",
"string",
")",
")",
"{",
"$",
"matcher",
"=",
"function",
"(",
"$",
"matches",
")",
"{",
"$",
"ch... | Escape Html Attribute
This method uses an extended set of characters o escape that are not covered by htmlspecialchars() to cover
cases where an attribute might be unquoted or quoted illegally (e.g. backticks are valid quotes for IE).
@param string $string
@return string | [
"Escape",
"Html",
"Attribute"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/string/escaper/escaper.php#L81-L135 | train |
timble/kodekit | code/controller/behavior/permissible.php | ControllerBehaviorPermissible.canExecute | public function canExecute($action)
{
$method = 'can'.ucfirst($action);
$methods = $this->getMixer()->getMethods();
if (!isset($methods[$method]))
{
$actions = $this->getActions();
$actions = array_flip($actions);
$result = isset($actions[$action]);
}
else $result = $this->$method();
return $result;
} | php | public function canExecute($action)
{
$method = 'can'.ucfirst($action);
$methods = $this->getMixer()->getMethods();
if (!isset($methods[$method]))
{
$actions = $this->getActions();
$actions = array_flip($actions);
$result = isset($actions[$action]);
}
else $result = $this->$method();
return $result;
} | [
"public",
"function",
"canExecute",
"(",
"$",
"action",
")",
"{",
"$",
"method",
"=",
"'can'",
".",
"ucfirst",
"(",
"$",
"action",
")",
";",
"$",
"methods",
"=",
"$",
"this",
"->",
"getMixer",
"(",
")",
"->",
"getMethods",
"(",
")",
";",
"if",
"(",... | Check if an action can be executed
@param string $action Action name
@return boolean True if the action can be executed, otherwise FALSE. | [
"Check",
"if",
"an",
"action",
"can",
"be",
"executed"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/controller/behavior/permissible.php#L122-L137 | train |
timble/kodekit | code/database/behavior/orderable.php | DatabaseBehaviorOrderable.order | public function order($change)
{
//force to integer
settype($change, 'int');
if($change !== 0)
{
$old = (int) $this->ordering;
$new = $this->ordering + $change;
$new = $new <= 0 ? 1 : $new;
$table = $this->getTable();
$query = $this->getObject('lib:database.query.update')
->table($table->getBase());
//Build the where query
$this->_buildQueryWhere($query);
if($change < 0)
{
$query->values('ordering = ordering + 1')
->where('ordering >= :new')
->where('ordering < :old')
->bind(array('new' => $new, 'old' => $old));
}
else
{
$query->values('ordering = ordering - 1')
->where('ordering <= :new')
->where('ordering > :old')
->bind(array('new' => $new, 'old' => $old));
}
$table->getDriver()->update($query);
$this->ordering = $new;
$this->save();
$this->reorder();
}
return $this->getMixer();
} | php | public function order($change)
{
//force to integer
settype($change, 'int');
if($change !== 0)
{
$old = (int) $this->ordering;
$new = $this->ordering + $change;
$new = $new <= 0 ? 1 : $new;
$table = $this->getTable();
$query = $this->getObject('lib:database.query.update')
->table($table->getBase());
//Build the where query
$this->_buildQueryWhere($query);
if($change < 0)
{
$query->values('ordering = ordering + 1')
->where('ordering >= :new')
->where('ordering < :old')
->bind(array('new' => $new, 'old' => $old));
}
else
{
$query->values('ordering = ordering - 1')
->where('ordering <= :new')
->where('ordering > :old')
->bind(array('new' => $new, 'old' => $old));
}
$table->getDriver()->update($query);
$this->ordering = $new;
$this->save();
$this->reorder();
}
return $this->getMixer();
} | [
"public",
"function",
"order",
"(",
"$",
"change",
")",
"{",
"//force to integer",
"settype",
"(",
"$",
"change",
",",
"'int'",
")",
";",
"if",
"(",
"$",
"change",
"!==",
"0",
")",
"{",
"$",
"old",
"=",
"(",
"int",
")",
"$",
"this",
"->",
"ordering... | Move the row up or down in the ordering
Requires an 'ordering' column
@param integer $change Amount to move up or down
@return DatabaseRowAbstract | [
"Move",
"the",
"row",
"up",
"or",
"down",
"in",
"the",
"ordering"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/database/behavior/orderable.php#L72-L113 | train |
timble/kodekit | code/database/behavior/orderable.php | DatabaseBehaviorOrderable.reorder | public function reorder($base = 0)
{
//force to integer
settype($base, 'int');
$table = $this->getTable();
$db = $table->getDriver();
$db->execute('SET @order = '.$base);
$query = $this->getObject('lib:database.query.update')
->table($table->getBase())
->values('ordering = (@order := @order + 1)')
->order('ordering', 'ASC');
//Build the where query
$this->_buildQueryWhere($query);
if ($base) {
$query->where('ordering >= :ordering')->bind(array(':ordering' => $base));
}
$db->update($query);
return $this;
} | php | public function reorder($base = 0)
{
//force to integer
settype($base, 'int');
$table = $this->getTable();
$db = $table->getDriver();
$db->execute('SET @order = '.$base);
$query = $this->getObject('lib:database.query.update')
->table($table->getBase())
->values('ordering = (@order := @order + 1)')
->order('ordering', 'ASC');
//Build the where query
$this->_buildQueryWhere($query);
if ($base) {
$query->where('ordering >= :ordering')->bind(array(':ordering' => $base));
}
$db->update($query);
return $this;
} | [
"public",
"function",
"reorder",
"(",
"$",
"base",
"=",
"0",
")",
"{",
"//force to integer",
"settype",
"(",
"$",
"base",
",",
"'int'",
")",
";",
"$",
"table",
"=",
"$",
"this",
"->",
"getTable",
"(",
")",
";",
"$",
"db",
"=",
"$",
"table",
"->",
... | Resets the order of all rows
Resetting starts at $base to allow creating space in sequence for later record insertion.
@param integer $base Order at which to start resetting.
@return DatabaseBehaviorOrderable | [
"Resets",
"the",
"order",
"of",
"all",
"rows"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/database/behavior/orderable.php#L123-L147 | train |
timble/kodekit | code/view/template.php | ViewTemplate.qualifyLayout | public function qualifyLayout($layout, $type = 'com')
{
$layout = (string) $layout;
//Handle partial layout paths
if(!parse_url($layout, PHP_URL_SCHEME))
{
$package = $this->getIdentifier()->package;
$domain = $this->getIdentifier()->domain;
$format = $this->getFormat();
$path = $this->getIdentifier()->getPath();
array_shift($path); //remove 'view'
$path[] = basename($layout);
$path = implode('/', $path);
if($domain) {
$layout = $type.'://'.$domain .'/' . $package . '/' .$path;
} else {
$layout = $type.':' . $package . '/' .$path;
}
$layout = $layout.'.'.$format;
}
return $layout;
} | php | public function qualifyLayout($layout, $type = 'com')
{
$layout = (string) $layout;
//Handle partial layout paths
if(!parse_url($layout, PHP_URL_SCHEME))
{
$package = $this->getIdentifier()->package;
$domain = $this->getIdentifier()->domain;
$format = $this->getFormat();
$path = $this->getIdentifier()->getPath();
array_shift($path); //remove 'view'
$path[] = basename($layout);
$path = implode('/', $path);
if($domain) {
$layout = $type.'://'.$domain .'/' . $package . '/' .$path;
} else {
$layout = $type.':' . $package . '/' .$path;
}
$layout = $layout.'.'.$format;
}
return $layout;
} | [
"public",
"function",
"qualifyLayout",
"(",
"$",
"layout",
",",
"$",
"type",
"=",
"'com'",
")",
"{",
"$",
"layout",
"=",
"(",
"string",
")",
"$",
"layout",
";",
"//Handle partial layout paths",
"if",
"(",
"!",
"parse_url",
"(",
"$",
"layout",
",",
"PHP_U... | Qualify the layout
Convert a relative layout URL into an absolute layout URL
@param string $layout The view layout name
@param string $type The filesystem locator type
@return string The fully qualified template url | [
"Qualify",
"the",
"layout"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/view/template.php#L225-L252 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.setTable | public function setTable($table)
{
if (!is_string($table)) {
throw new InvalidArgumentException(sprintf(
'DatabaseSource::setTable() expects a string as table. (%s given). [%s]',
gettype($table),
get_class($this->model())
));
}
/**
* For security reason, only alphanumeric characters (+ underscores)
* are valid table names; Although SQL can support more,
* there's really no reason to.
*/
if (!preg_match('/[A-Za-z0-9_]/', $table)) {
throw new InvalidArgumentException(sprintf(
'Table name "%s" is invalid: must be alphanumeric / underscore.',
$table
));
}
$this->table = $table;
return $this;
} | php | public function setTable($table)
{
if (!is_string($table)) {
throw new InvalidArgumentException(sprintf(
'DatabaseSource::setTable() expects a string as table. (%s given). [%s]',
gettype($table),
get_class($this->model())
));
}
/**
* For security reason, only alphanumeric characters (+ underscores)
* are valid table names; Although SQL can support more,
* there's really no reason to.
*/
if (!preg_match('/[A-Za-z0-9_]/', $table)) {
throw new InvalidArgumentException(sprintf(
'Table name "%s" is invalid: must be alphanumeric / underscore.',
$table
));
}
$this->table = $table;
return $this;
} | [
"public",
"function",
"setTable",
"(",
"$",
"table",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"table",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'DatabaseSource::setTable() expects a string as table. (%s given). [%s]'",
... | Set the database's table to use.
@param string $table The source table.
@throws InvalidArgumentException If argument is not a string or alphanumeric/underscore.
@return self | [
"Set",
"the",
"database",
"s",
"table",
"to",
"use",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L86-L110 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.createTable | public function createTable()
{
if ($this->tableExists() === true) {
return true;
}
$dbh = $this->db();
$driver = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME);
$model = $this->model();
$metadata = $model->metadata();
$table = $this->table();
$fields = $this->getModelFields($model);
$columns = [];
foreach ($fields as $field) {
$columns[] = $field->sql();
}
$query = 'CREATE TABLE `'.$table.'` ('."\n";
$query .= implode(',', $columns);
$key = $model->key();
if ($key) {
$query .= ', PRIMARY KEY (`'.$key.'`) '."\n";
}
/** @todo Add indexes for all defined list constraints (yea... tough job...) */
if ($driver === self::MYSQL_DRIVER_NAME) {
$engine = 'InnoDB';
$query .= ') ENGINE='.$engine.' DEFAULT CHARSET=utf8 COMMENT="'.addslashes($metadata['name']).'";';
} else {
$query .= ');';
}
$this->logger->debug($query);
$dbh->query($query);
return true;
} | php | public function createTable()
{
if ($this->tableExists() === true) {
return true;
}
$dbh = $this->db();
$driver = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME);
$model = $this->model();
$metadata = $model->metadata();
$table = $this->table();
$fields = $this->getModelFields($model);
$columns = [];
foreach ($fields as $field) {
$columns[] = $field->sql();
}
$query = 'CREATE TABLE `'.$table.'` ('."\n";
$query .= implode(',', $columns);
$key = $model->key();
if ($key) {
$query .= ', PRIMARY KEY (`'.$key.'`) '."\n";
}
/** @todo Add indexes for all defined list constraints (yea... tough job...) */
if ($driver === self::MYSQL_DRIVER_NAME) {
$engine = 'InnoDB';
$query .= ') ENGINE='.$engine.' DEFAULT CHARSET=utf8 COMMENT="'.addslashes($metadata['name']).'";';
} else {
$query .= ');';
}
$this->logger->debug($query);
$dbh->query($query);
return true;
} | [
"public",
"function",
"createTable",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"tableExists",
"(",
")",
"===",
"true",
")",
"{",
"return",
"true",
";",
"}",
"$",
"dbh",
"=",
"$",
"this",
"->",
"db",
"(",
")",
";",
"$",
"driver",
"=",
"$",
"d... | Create a table from a model's metadata.
@return boolean TRUE if the table was created, otherwise FALSE. | [
"Create",
"a",
"table",
"from",
"a",
"model",
"s",
"metadata",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L143-L181 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.alterTable | public function alterTable()
{
if ($this->tableExists() === false) {
return false;
}
$dbh = $this->db();
$table = $this->table();
$fields = $this->getModelFields($this->model());
$cols = $this->tableStructure();
foreach ($fields as $field) {
$ident = $field->ident();
if (!array_key_exists($ident, $cols)) {
// The key does not exist at all.
$query = 'ALTER TABLE `'.$table.'` ADD '.$field->sql();
$this->logger->debug($query);
$dbh->query($query);
} else {
// The key exists. Validate.
$col = $cols[$ident];
$alter = true;
if (strtolower($col['Type']) !== strtolower($field->sqlType())) {
$alter = true;
}
if ((strtolower($col['Null']) === 'no') && !$field->allowNull()) {
$alter = true;
}
if ((strtolower($col['Null']) !== 'no') && $field->allowNull()) {
$alter = true;
}
if ($col['Default'] !== $field->defaultVal()) {
$alter = true;
}
if ($alter === true) {
$query = 'ALTER TABLE `'.$table.'` CHANGE `'.$ident.'` '.$field->sql();
$this->logger->debug($query);
$dbh->query($query);
}
}
}
return true;
} | php | public function alterTable()
{
if ($this->tableExists() === false) {
return false;
}
$dbh = $this->db();
$table = $this->table();
$fields = $this->getModelFields($this->model());
$cols = $this->tableStructure();
foreach ($fields as $field) {
$ident = $field->ident();
if (!array_key_exists($ident, $cols)) {
// The key does not exist at all.
$query = 'ALTER TABLE `'.$table.'` ADD '.$field->sql();
$this->logger->debug($query);
$dbh->query($query);
} else {
// The key exists. Validate.
$col = $cols[$ident];
$alter = true;
if (strtolower($col['Type']) !== strtolower($field->sqlType())) {
$alter = true;
}
if ((strtolower($col['Null']) === 'no') && !$field->allowNull()) {
$alter = true;
}
if ((strtolower($col['Null']) !== 'no') && $field->allowNull()) {
$alter = true;
}
if ($col['Default'] !== $field->defaultVal()) {
$alter = true;
}
if ($alter === true) {
$query = 'ALTER TABLE `'.$table.'` CHANGE `'.$ident.'` '.$field->sql();
$this->logger->debug($query);
$dbh->query($query);
}
}
}
return true;
} | [
"public",
"function",
"alterTable",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"tableExists",
"(",
")",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"$",
"dbh",
"=",
"$",
"this",
"->",
"db",
"(",
")",
";",
"$",
"table",
"=",
"$",
"t... | Alter an existing table to match the model's metadata.
@return boolean TRUE if the table was altered, otherwise FALSE. | [
"Alter",
"an",
"existing",
"table",
"to",
"match",
"the",
"model",
"s",
"metadata",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L188-L235 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.tableExists | public function tableExists()
{
$dbh = $this->db();
$table = $this->table();
$driver = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($driver === self::SQLITE_DRIVER_NAME) {
$query = sprintf('SELECT name FROM sqlite_master WHERE type = "table" AND name = "%s";', $table);
} else {
$query = sprintf('SHOW TABLES LIKE "%s"', $table);
}
$this->logger->debug($query);
$sth = $dbh->query($query);
$exists = $sth->fetchColumn(0);
return !!$exists;
} | php | public function tableExists()
{
$dbh = $this->db();
$table = $this->table();
$driver = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($driver === self::SQLITE_DRIVER_NAME) {
$query = sprintf('SELECT name FROM sqlite_master WHERE type = "table" AND name = "%s";', $table);
} else {
$query = sprintf('SHOW TABLES LIKE "%s"', $table);
}
$this->logger->debug($query);
$sth = $dbh->query($query);
$exists = $sth->fetchColumn(0);
return !!$exists;
} | [
"public",
"function",
"tableExists",
"(",
")",
"{",
"$",
"dbh",
"=",
"$",
"this",
"->",
"db",
"(",
")",
";",
"$",
"table",
"=",
"$",
"this",
"->",
"table",
"(",
")",
";",
"$",
"driver",
"=",
"$",
"dbh",
"->",
"getAttribute",
"(",
"PDO",
"::",
"... | Determine if the source table exists.
@return boolean TRUE if the table exists, otherwise FALSE. | [
"Determine",
"if",
"the",
"source",
"table",
"exists",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L242-L258 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.tableStructure | public function tableStructure()
{
$dbh = $this->db();
$table = $this->table();
$driver = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($driver === self::SQLITE_DRIVER_NAME) {
$query = sprintf('PRAGMA table_info("%s") ', $table);
} else {
$query = sprintf('SHOW COLUMNS FROM `%s`', $table);
}
$this->logger->debug($query);
$sth = $dbh->query($query);
$cols = $sth->fetchAll((PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC));
if ($driver === self::SQLITE_DRIVER_NAME) {
$struct = [];
foreach ($cols as $col) {
// Normalize SQLite's result (PRAGMA) with mysql's (SHOW COLUMNS)
$struct[$col['name']] = [
'Type' => $col['type'],
'Null' => !!$col['notnull'] ? 'NO' : 'YES',
'Default' => $col['dflt_value'],
'Key' => !!$col['pk'] ? 'PRI' : '',
'Extra' => ''
];
}
return $struct;
} else {
return $cols;
}
} | php | public function tableStructure()
{
$dbh = $this->db();
$table = $this->table();
$driver = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($driver === self::SQLITE_DRIVER_NAME) {
$query = sprintf('PRAGMA table_info("%s") ', $table);
} else {
$query = sprintf('SHOW COLUMNS FROM `%s`', $table);
}
$this->logger->debug($query);
$sth = $dbh->query($query);
$cols = $sth->fetchAll((PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC));
if ($driver === self::SQLITE_DRIVER_NAME) {
$struct = [];
foreach ($cols as $col) {
// Normalize SQLite's result (PRAGMA) with mysql's (SHOW COLUMNS)
$struct[$col['name']] = [
'Type' => $col['type'],
'Null' => !!$col['notnull'] ? 'NO' : 'YES',
'Default' => $col['dflt_value'],
'Key' => !!$col['pk'] ? 'PRI' : '',
'Extra' => ''
];
}
return $struct;
} else {
return $cols;
}
} | [
"public",
"function",
"tableStructure",
"(",
")",
"{",
"$",
"dbh",
"=",
"$",
"this",
"->",
"db",
"(",
")",
";",
"$",
"table",
"=",
"$",
"this",
"->",
"table",
"(",
")",
";",
"$",
"driver",
"=",
"$",
"dbh",
"->",
"getAttribute",
"(",
"PDO",
"::",
... | Get the table columns information.
@return array An associative array. | [
"Get",
"the",
"table",
"columns",
"information",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L265-L296 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.tableIsEmpty | public function tableIsEmpty()
{
$table = $this->table();
$query = sprintf('SELECT NULL FROM `%s` LIMIT 1', $table);
$this->logger->debug($query);
$sth = $this->db()->query($query);
return ($sth->rowCount() === 0);
} | php | public function tableIsEmpty()
{
$table = $this->table();
$query = sprintf('SELECT NULL FROM `%s` LIMIT 1', $table);
$this->logger->debug($query);
$sth = $this->db()->query($query);
return ($sth->rowCount() === 0);
} | [
"public",
"function",
"tableIsEmpty",
"(",
")",
"{",
"$",
"table",
"=",
"$",
"this",
"->",
"table",
"(",
")",
";",
"$",
"query",
"=",
"sprintf",
"(",
"'SELECT NULL FROM `%s` LIMIT 1'",
",",
"$",
"table",
")",
";",
"$",
"this",
"->",
"logger",
"->",
"de... | Determine if the source table is empty or not.
@return boolean TRUE if the table has no data, otherwise FALSE. | [
"Determine",
"if",
"the",
"source",
"table",
"is",
"empty",
"or",
"not",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L303-L310 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.getModelFields | private function getModelFields(ModelInterface $model, $properties = null)
{
if ($properties === null) {
// No custom properties; use all (from model metadata)
$properties = array_keys($model->metadata()->properties());
} else {
// Ensure the key is always in the required fields.
$properties = array_unique(array_merge([ $model->key() ], $properties));
}
$fields = [];
foreach ($properties as $propertyIdent) {
$prop = $model->property($propertyIdent);
if (!$prop || !$prop->active() || !$prop->storable()) {
continue;
}
$val = $model->propertyValue($propertyIdent);
foreach ($prop->fields($val) as $fieldIdent => $field) {
$fields[$field->ident()] = $field;
}
}
return $fields;
} | php | private function getModelFields(ModelInterface $model, $properties = null)
{
if ($properties === null) {
// No custom properties; use all (from model metadata)
$properties = array_keys($model->metadata()->properties());
} else {
// Ensure the key is always in the required fields.
$properties = array_unique(array_merge([ $model->key() ], $properties));
}
$fields = [];
foreach ($properties as $propertyIdent) {
$prop = $model->property($propertyIdent);
if (!$prop || !$prop->active() || !$prop->storable()) {
continue;
}
$val = $model->propertyValue($propertyIdent);
foreach ($prop->fields($val) as $fieldIdent => $field) {
$fields[$field->ident()] = $field;
}
}
return $fields;
} | [
"private",
"function",
"getModelFields",
"(",
"ModelInterface",
"$",
"model",
",",
"$",
"properties",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"properties",
"===",
"null",
")",
"{",
"// No custom properties; use all (from model metadata)",
"$",
"properties",
"=",
"a... | Retrieve all fields from a model.
@todo Move this method in StorableTrait or AbstractModel
@param ModelInterface $model The model to get fields from.
@param array|null $properties Optional list of properties to get.
If NULL, retrieve all (from metadata).
@return PropertyField[] | [
"Retrieve",
"all",
"fields",
"from",
"a",
"model",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L321-L345 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.loadItem | public function loadItem($ident, StorableInterface $item = null)
{
$key = $this->model()->key();
return $this->loadItemFromKey($key, $ident, $item);
} | php | public function loadItem($ident, StorableInterface $item = null)
{
$key = $this->model()->key();
return $this->loadItemFromKey($key, $ident, $item);
} | [
"public",
"function",
"loadItem",
"(",
"$",
"ident",
",",
"StorableInterface",
"$",
"item",
"=",
"null",
")",
"{",
"$",
"key",
"=",
"$",
"this",
"->",
"model",
"(",
")",
"->",
"key",
"(",
")",
";",
"return",
"$",
"this",
"->",
"loadItemFromKey",
"(",... | Load item by the primary column.
@param mixed $ident Ident can be any scalar value.
@param StorableInterface $item Optional item to load into.
@return StorableInterface | [
"Load",
"item",
"by",
"the",
"primary",
"column",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L354-L359 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.loadItemFromKey | public function loadItemFromKey($key, $ident, StorableInterface $item = null)
{
if ($item !== null) {
$this->setModel($item);
} else {
$class = get_class($this->model());
$item = new $class;
}
$key = preg_replace('/[^\w-]+/', '', $key);
// Missing parameters
if (!$key || !$ident) {
return $item;
}
$table = $this->table();
$query = sprintf('
SELECT
*
FROM
`%s`
WHERE
`%s` = :ident
LIMIT
1', $table, $key);
$binds = [
'ident' => $ident
];
return $this->loadItemFromQuery($query, $binds, $item);
} | php | public function loadItemFromKey($key, $ident, StorableInterface $item = null)
{
if ($item !== null) {
$this->setModel($item);
} else {
$class = get_class($this->model());
$item = new $class;
}
$key = preg_replace('/[^\w-]+/', '', $key);
// Missing parameters
if (!$key || !$ident) {
return $item;
}
$table = $this->table();
$query = sprintf('
SELECT
*
FROM
`%s`
WHERE
`%s` = :ident
LIMIT
1', $table, $key);
$binds = [
'ident' => $ident
];
return $this->loadItemFromQuery($query, $binds, $item);
} | [
"public",
"function",
"loadItemFromKey",
"(",
"$",
"key",
",",
"$",
"ident",
",",
"StorableInterface",
"$",
"item",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"item",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"setModel",
"(",
"$",
"item",
")",
";",
"... | Load item by the given column.
@param string $key Column name.
@param mixed $ident Value of said column.
@param StorableInterface|null $item Optional. Item (storable object) to load into.
@throws \Exception If the query fails.
@return StorableInterface | [
"Load",
"item",
"by",
"the",
"given",
"column",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L370-L401 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.loadItemFromQuery | public function loadItemFromQuery($query, array $binds = [], StorableInterface $item = null)
{
if ($item !== null) {
$this->setModel($item);
} else {
$class = get_class($this->model());
$item = new $class;
}
// Missing parameters
if (!$query) {
return $item;
}
$sth = $this->dbQuery($query, $binds);
if ($sth === false) {
throw new PDOException('Could not load item.');
}
$data = $sth->fetch(PDO::FETCH_ASSOC);
if ($data) {
$item->setFlatData($data);
}
return $item;
} | php | public function loadItemFromQuery($query, array $binds = [], StorableInterface $item = null)
{
if ($item !== null) {
$this->setModel($item);
} else {
$class = get_class($this->model());
$item = new $class;
}
// Missing parameters
if (!$query) {
return $item;
}
$sth = $this->dbQuery($query, $binds);
if ($sth === false) {
throw new PDOException('Could not load item.');
}
$data = $sth->fetch(PDO::FETCH_ASSOC);
if ($data) {
$item->setFlatData($data);
}
return $item;
} | [
"public",
"function",
"loadItemFromQuery",
"(",
"$",
"query",
",",
"array",
"$",
"binds",
"=",
"[",
"]",
",",
"StorableInterface",
"$",
"item",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"item",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"setModel",
"("... | Load item by the given query statement.
@param string $query The SQL SELECT statement.
@param array $binds Optional. The query parameters.
@param StorableInterface $item Optional. Item (storable object) to load into.
@throws PDOException If there is a query error.
@return StorableInterface | [
"Load",
"item",
"by",
"the",
"given",
"query",
"statement",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L412-L437 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.loadItems | public function loadItems(StorableInterface $item = null)
{
if ($item !== null) {
$this->setModel($item);
}
$query = $this->sqlLoad();
return $this->loadItemsFromQuery($query, [], $item);
} | php | public function loadItems(StorableInterface $item = null)
{
if ($item !== null) {
$this->setModel($item);
}
$query = $this->sqlLoad();
return $this->loadItemsFromQuery($query, [], $item);
} | [
"public",
"function",
"loadItems",
"(",
"StorableInterface",
"$",
"item",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"item",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"setModel",
"(",
"$",
"item",
")",
";",
"}",
"$",
"query",
"=",
"$",
"this",
"->",
... | Load items for the given model.
@param StorableInterface|null $item Optional model.
@return StorableInterface[] | [
"Load",
"items",
"for",
"the",
"given",
"model",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L445-L453 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.loadItemsFromQuery | public function loadItemsFromQuery($query, array $binds = [], StorableInterface $item = null)
{
if ($item !== null) {
$this->setModel($item);
}
$items = [];
$model = $this->model();
$dbh = $this->db();
$this->logger->debug($query);
$sth = $dbh->prepare($query);
// @todo Binds
if (!empty($binds)) {
unset($binds);
}
$sth->execute();
$sth->setFetchMode(PDO::FETCH_ASSOC);
$className = get_class($model);
while ($objData = $sth->fetch()) {
$obj = new $className;
$obj->setFlatData($objData);
$items[] = $obj;
}
return $items;
} | php | public function loadItemsFromQuery($query, array $binds = [], StorableInterface $item = null)
{
if ($item !== null) {
$this->setModel($item);
}
$items = [];
$model = $this->model();
$dbh = $this->db();
$this->logger->debug($query);
$sth = $dbh->prepare($query);
// @todo Binds
if (!empty($binds)) {
unset($binds);
}
$sth->execute();
$sth->setFetchMode(PDO::FETCH_ASSOC);
$className = get_class($model);
while ($objData = $sth->fetch()) {
$obj = new $className;
$obj->setFlatData($objData);
$items[] = $obj;
}
return $items;
} | [
"public",
"function",
"loadItemsFromQuery",
"(",
"$",
"query",
",",
"array",
"$",
"binds",
"=",
"[",
"]",
",",
"StorableInterface",
"$",
"item",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"item",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"setModel",
"(... | Load items for the given query statement.
@param string $query The SQL SELECT statement.
@param array $binds This has to be done.
@param StorableInterface|null $item Model Item.
@return StorableInterface[] | [
"Load",
"items",
"for",
"the",
"given",
"query",
"statement",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L463-L493 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.updateItem | public function updateItem(StorableInterface $item, array $properties = null)
{
if ($item !== null) {
$this->setModel($item);
}
$model = $this->model();
$table = $this->table();
$struct = array_keys($this->tableStructure());
$fields = $this->getModelFields($model, $properties);
$updates = [];
$binds = [];
$types = [];
foreach ($fields as $field) {
$key = $field->ident();
if (in_array($key, $struct)) {
if ($key !== $model->key()) {
$param = ':'.$key;
$updates[] = '`'.$key.'` = '.$param;
}
$binds[$key] = $field->val();
$types[$key] = $field->sqlPdoType();
} else {
$this->logger->debug(
sprintf('Field "%s" not in table structure', $key)
);
}
}
if (empty($updates)) {
$this->logger->warning(
'Could not update items. No valid fields were set / available in database table.',
[
'properties' => $properties,
'structure' => $struct
]
);
return false;
}
$binds[$model->key()] = $model->id();
$types[$model->key()] = PDO::PARAM_STR;
$query = '
UPDATE
`'.$table.'`
SET
'.implode(", \n\t", $updates).'
WHERE
`'.$model->key().'`=:'.$model->key().'';
$driver = $this->db()->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($driver == self::MYSQL_DRIVER_NAME) {
$query .= "\n".'LIMIT 1';
}
$result = $this->dbQuery($query, $binds, $types);
if ($result === false) {
return false;
} else {
return true;
}
} | php | public function updateItem(StorableInterface $item, array $properties = null)
{
if ($item !== null) {
$this->setModel($item);
}
$model = $this->model();
$table = $this->table();
$struct = array_keys($this->tableStructure());
$fields = $this->getModelFields($model, $properties);
$updates = [];
$binds = [];
$types = [];
foreach ($fields as $field) {
$key = $field->ident();
if (in_array($key, $struct)) {
if ($key !== $model->key()) {
$param = ':'.$key;
$updates[] = '`'.$key.'` = '.$param;
}
$binds[$key] = $field->val();
$types[$key] = $field->sqlPdoType();
} else {
$this->logger->debug(
sprintf('Field "%s" not in table structure', $key)
);
}
}
if (empty($updates)) {
$this->logger->warning(
'Could not update items. No valid fields were set / available in database table.',
[
'properties' => $properties,
'structure' => $struct
]
);
return false;
}
$binds[$model->key()] = $model->id();
$types[$model->key()] = PDO::PARAM_STR;
$query = '
UPDATE
`'.$table.'`
SET
'.implode(", \n\t", $updates).'
WHERE
`'.$model->key().'`=:'.$model->key().'';
$driver = $this->db()->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($driver == self::MYSQL_DRIVER_NAME) {
$query .= "\n".'LIMIT 1';
}
$result = $this->dbQuery($query, $binds, $types);
if ($result === false) {
return false;
} else {
return true;
}
} | [
"public",
"function",
"updateItem",
"(",
"StorableInterface",
"$",
"item",
",",
"array",
"$",
"properties",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"item",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"setModel",
"(",
"$",
"item",
")",
";",
"}",
"$",
... | Update an item in storage.
@param StorableInterface $item The object to update.
@param array $properties The list of properties to update, if not all.
@return boolean TRUE if the item was updated, otherwise FALSE. | [
"Update",
"an",
"item",
"in",
"storage",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L559-L621 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.deleteItem | public function deleteItem(StorableInterface $item = null)
{
if ($item !== null) {
$this->setModel($item);
}
$model = $this->model();
if (!$model->id()) {
throw new UnexpectedValueException(
sprintf('Can not delete "%s" item. No ID.', get_class($this))
);
}
$key = $model->key();
$table = $this->table();
$query = '
DELETE FROM
`'.$table.'`
WHERE
`'.$key.'` = :id';
$driver = $this->db()->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($driver == self::MYSQL_DRIVER_NAME) {
$query .= "\n".'LIMIT 1';
}
$binds = [
'id' => $model->id()
];
$result = $this->dbQuery($query, $binds);
if ($result === false) {
return false;
} else {
return true;
}
} | php | public function deleteItem(StorableInterface $item = null)
{
if ($item !== null) {
$this->setModel($item);
}
$model = $this->model();
if (!$model->id()) {
throw new UnexpectedValueException(
sprintf('Can not delete "%s" item. No ID.', get_class($this))
);
}
$key = $model->key();
$table = $this->table();
$query = '
DELETE FROM
`'.$table.'`
WHERE
`'.$key.'` = :id';
$driver = $this->db()->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($driver == self::MYSQL_DRIVER_NAME) {
$query .= "\n".'LIMIT 1';
}
$binds = [
'id' => $model->id()
];
$result = $this->dbQuery($query, $binds);
if ($result === false) {
return false;
} else {
return true;
}
} | [
"public",
"function",
"deleteItem",
"(",
"StorableInterface",
"$",
"item",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"item",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"setModel",
"(",
"$",
"item",
")",
";",
"}",
"$",
"model",
"=",
"$",
"this",
"->",... | Delete an item from storage.
@param StorableInterface $item Optional item to delete. If none, the current model object will be used.
@throws UnexpectedValueException If the item does not have an ID.
@return boolean TRUE if the item was deleted, otherwise FALSE. | [
"Delete",
"an",
"item",
"from",
"storage",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L630-L668 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.dbQuery | public function dbQuery($query, array $binds = [], array $types = [])
{
$this->logger->debug($query, $binds);
$sth = $this->db()->prepare($query);
if (!$sth) {
return false;
}
if (!empty($binds)) {
foreach ($binds as $key => $val) {
if ($binds[$key] === null) {
$types[$key] = PDO::PARAM_NULL;
} elseif (!is_scalar($binds[$key])) {
$binds[$key] = json_encode($binds[$key]);
}
$type = (isset($types[$key]) ? $types[$key] : PDO::PARAM_STR);
$param = ':'.$key;
$sth->bindParam($param, $binds[$key], $type);
}
}
$result = $sth->execute();
if ($result === false) {
return false;
}
return $sth;
} | php | public function dbQuery($query, array $binds = [], array $types = [])
{
$this->logger->debug($query, $binds);
$sth = $this->db()->prepare($query);
if (!$sth) {
return false;
}
if (!empty($binds)) {
foreach ($binds as $key => $val) {
if ($binds[$key] === null) {
$types[$key] = PDO::PARAM_NULL;
} elseif (!is_scalar($binds[$key])) {
$binds[$key] = json_encode($binds[$key]);
}
$type = (isset($types[$key]) ? $types[$key] : PDO::PARAM_STR);
$param = ':'.$key;
$sth->bindParam($param, $binds[$key], $type);
}
}
$result = $sth->execute();
if ($result === false) {
return false;
}
return $sth;
} | [
"public",
"function",
"dbQuery",
"(",
"$",
"query",
",",
"array",
"$",
"binds",
"=",
"[",
"]",
",",
"array",
"$",
"types",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"$",
"query",
",",
"$",
"binds",
")",
";",
"$",... | Execute a SQL query, with PDO, and returns the PDOStatement.
If the query fails, this method will return false.
@param string $query The SQL query to executed.
@param array $binds Optional. Query parameter binds.
@param array $types Optional. Types of parameter bindings.
@return \PDOStatement|false The PDOStatement, otherwise FALSE. | [
"Execute",
"a",
"SQL",
"query",
"with",
"PDO",
"and",
"returns",
"the",
"PDOStatement",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L680-L707 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.sqlLoad | public function sqlLoad()
{
if (!$this->hasTable()) {
throw new UnexpectedValueException(
'Can not get SQL SELECT clause. No table defined.'
);
}
$selects = $this->sqlSelect();
$tables = $this->sqlFrom();
$filters = $this->sqlFilters();
$orders = $this->sqlOrders();
$limits = $this->sqlPagination();
$query = 'SELECT '.$selects.' FROM '.$tables.$filters.$orders.$limits;
return $query;
} | php | public function sqlLoad()
{
if (!$this->hasTable()) {
throw new UnexpectedValueException(
'Can not get SQL SELECT clause. No table defined.'
);
}
$selects = $this->sqlSelect();
$tables = $this->sqlFrom();
$filters = $this->sqlFilters();
$orders = $this->sqlOrders();
$limits = $this->sqlPagination();
$query = 'SELECT '.$selects.' FROM '.$tables.$filters.$orders.$limits;
return $query;
} | [
"public",
"function",
"sqlLoad",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasTable",
"(",
")",
")",
"{",
"throw",
"new",
"UnexpectedValueException",
"(",
"'Can not get SQL SELECT clause. No table defined.'",
")",
";",
"}",
"$",
"selects",
"=",
"$",
... | Compile the SELECT statement for fetching one or more objects.
@throws UnexpectedValueException If the source does not have a table defined.
@return string | [
"Compile",
"the",
"SELECT",
"statement",
"for",
"fetching",
"one",
"or",
"more",
"objects",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L715-L731 | train |
locomotivemtl/charcoal-core | src/Charcoal/Source/DatabaseSource.php | DatabaseSource.sqlLoadCount | public function sqlLoadCount()
{
if (!$this->hasTable()) {
throw new UnexpectedValueException(
'Can not get SQL count. No table defined.'
);
}
$tables = $this->sqlFrom();
$filters = $this->sqlFilters();
$query = 'SELECT COUNT(*) FROM '.$tables.$filters;
return $query;
} | php | public function sqlLoadCount()
{
if (!$this->hasTable()) {
throw new UnexpectedValueException(
'Can not get SQL count. No table defined.'
);
}
$tables = $this->sqlFrom();
$filters = $this->sqlFilters();
$query = 'SELECT COUNT(*) FROM '.$tables.$filters;
return $query;
} | [
"public",
"function",
"sqlLoadCount",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasTable",
"(",
")",
")",
"{",
"throw",
"new",
"UnexpectedValueException",
"(",
"'Can not get SQL count. No table defined.'",
")",
";",
"}",
"$",
"tables",
"=",
"$",
"th... | Compile the SELECT statement for fetching the number of objects.
@throws UnexpectedValueException If the source does not have a table defined.
@return string | [
"Compile",
"the",
"SELECT",
"statement",
"for",
"fetching",
"the",
"number",
"of",
"objects",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Source/DatabaseSource.php#L739-L752 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.