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
bound1ess/essence
src/Essence/Essence.php
Essence.go
public function go($verbose = false) { $this->builder->setLinks($this->configuration["links"]); $this->builder->setMatchers($this->configuration["matchers"]); if ( ! $this->builder->validate()) { // @codeCoverageIgnoreStart if ($verbose) { $this->dumpValueAndArguments($this->builder->getLastMatcher()); } $this->throwOnFailure($this->builder->getMessage()); } // @codeCoverageIgnoreEnd return true; }
php
public function go($verbose = false) { $this->builder->setLinks($this->configuration["links"]); $this->builder->setMatchers($this->configuration["matchers"]); if ( ! $this->builder->validate()) { // @codeCoverageIgnoreStart if ($verbose) { $this->dumpValueAndArguments($this->builder->getLastMatcher()); } $this->throwOnFailure($this->builder->getMessage()); } // @codeCoverageIgnoreEnd return true; }
[ "public", "function", "go", "(", "$", "verbose", "=", "false", ")", "{", "$", "this", "->", "builder", "->", "setLinks", "(", "$", "this", "->", "configuration", "[", "\"links\"", "]", ")", ";", "$", "this", "->", "builder", "->", "setMatchers", "(", "$", "this", "->", "configuration", "[", "\"matchers\"", "]", ")", ";", "if", "(", "!", "$", "this", "->", "builder", "->", "validate", "(", ")", ")", "{", "// @codeCoverageIgnoreStart", "if", "(", "$", "verbose", ")", "{", "$", "this", "->", "dumpValueAndArguments", "(", "$", "this", "->", "builder", "->", "getLastMatcher", "(", ")", ")", ";", "}", "$", "this", "->", "throwOnFailure", "(", "$", "this", "->", "builder", "->", "getMessage", "(", ")", ")", ";", "}", "// @codeCoverageIgnoreEnd", "return", "true", ";", "}" ]
Explicitly performs the validation. @throws Essence\Exceptions\AssertionException|object @param boolean $verbose @return boolean
[ "Explicitly", "performs", "the", "validation", "." ]
b773d3f17e192d7c7184ffd3640c668e7d74f69b
https://github.com/bound1ess/essence/blob/b773d3f17e192d7c7184ffd3640c668e7d74f69b/src/Essence/Essence.php#L246-L262
train
bound1ess/essence
src/Essence/Essence.php
Essence.dumpValueAndArguments
protected function dumpValueAndArguments(Matchers\AbstractMatcher $matcher) { printf("Value: %s" . PHP_EOL, $matcher->getDumper()->dump($matcher->getValue())); print ("Arguments:" . PHP_EOL); foreach ($matcher->getArguments() as $key => $argument) { printf(" #%s: %s" . PHP_EOL, $key + 1, $matcher->getDumper()->dump($argument)); } exit; }
php
protected function dumpValueAndArguments(Matchers\AbstractMatcher $matcher) { printf("Value: %s" . PHP_EOL, $matcher->getDumper()->dump($matcher->getValue())); print ("Arguments:" . PHP_EOL); foreach ($matcher->getArguments() as $key => $argument) { printf(" #%s: %s" . PHP_EOL, $key + 1, $matcher->getDumper()->dump($argument)); } exit; }
[ "protected", "function", "dumpValueAndArguments", "(", "Matchers", "\\", "AbstractMatcher", "$", "matcher", ")", "{", "printf", "(", "\"Value: %s\"", ".", "PHP_EOL", ",", "$", "matcher", "->", "getDumper", "(", ")", "->", "dump", "(", "$", "matcher", "->", "getValue", "(", ")", ")", ")", ";", "print", "(", "\"Arguments:\"", ".", "PHP_EOL", ")", ";", "foreach", "(", "$", "matcher", "->", "getArguments", "(", ")", "as", "$", "key", "=>", "$", "argument", ")", "{", "printf", "(", "\" #%s: %s\"", ".", "PHP_EOL", ",", "$", "key", "+", "1", ",", "$", "matcher", "->", "getDumper", "(", ")", "->", "dump", "(", "$", "argument", ")", ")", ";", "}", "exit", ";", "}" ]
"Dumps" given matcher's value and its arguments. @codeCoverageIgnore @param Essence\Matchers\AbstractMatcher @return void
[ "Dumps", "given", "matcher", "s", "value", "and", "its", "arguments", "." ]
b773d3f17e192d7c7184ffd3640c668e7d74f69b
https://github.com/bound1ess/essence/blob/b773d3f17e192d7c7184ffd3640c668e7d74f69b/src/Essence/Essence.php#L303-L313
train
RocketPropelledTortoise/Core
src/Entities/Entity.php
Entity.initialize
protected function initialize(array $fields) { $this->content = new Content; $this->revision = new Revision; foreach ($fields as $field => $settings) { $this->data[$field] = $this->initializeField($field, $settings); } }
php
protected function initialize(array $fields) { $this->content = new Content; $this->revision = new Revision; foreach ($fields as $field => $settings) { $this->data[$field] = $this->initializeField($field, $settings); } }
[ "protected", "function", "initialize", "(", "array", "$", "fields", ")", "{", "$", "this", "->", "content", "=", "new", "Content", ";", "$", "this", "->", "revision", "=", "new", "Revision", ";", "foreach", "(", "$", "fields", "as", "$", "field", "=>", "$", "settings", ")", "{", "$", "this", "->", "data", "[", "$", "field", "]", "=", "$", "this", "->", "initializeField", "(", "$", "field", ",", "$", "settings", ")", ";", "}", "}" ]
Creates the Content, Revision and FieldCollections @param array $fields The fields and their configurations @throws InvalidFieldTypeException @throws ReservedFieldNameException
[ "Creates", "the", "Content", "Revision", "and", "FieldCollections" ]
78b65663fc463e21e494257140ddbed0a9ccb3c3
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Entities/Entity.php#L90-L98
train
RocketPropelledTortoise/Core
src/Entities/Entity.php
Entity.initializeField
protected function initializeField($field, $settings) { if ($this->isContentField($field) || $this->isRevisionField($field)) { throw new ReservedFieldNameException( "The field '$field' cannot be used in '" . get_class($this) . "' as it is a reserved name" ); } $type = $settings['type']; if (!array_key_exists($type, self::$types)) { throw new InvalidFieldTypeException("Unkown type '$type' in '" . get_class($this) . "'"); } $settings['type'] = self::$types[$settings['type']]; return FieldCollection::initField($settings); }
php
protected function initializeField($field, $settings) { if ($this->isContentField($field) || $this->isRevisionField($field)) { throw new ReservedFieldNameException( "The field '$field' cannot be used in '" . get_class($this) . "' as it is a reserved name" ); } $type = $settings['type']; if (!array_key_exists($type, self::$types)) { throw new InvalidFieldTypeException("Unkown type '$type' in '" . get_class($this) . "'"); } $settings['type'] = self::$types[$settings['type']]; return FieldCollection::initField($settings); }
[ "protected", "function", "initializeField", "(", "$", "field", ",", "$", "settings", ")", "{", "if", "(", "$", "this", "->", "isContentField", "(", "$", "field", ")", "||", "$", "this", "->", "isRevisionField", "(", "$", "field", ")", ")", "{", "throw", "new", "ReservedFieldNameException", "(", "\"The field '$field' cannot be used in '\"", ".", "get_class", "(", "$", "this", ")", ".", "\"' as it is a reserved name\"", ")", ";", "}", "$", "type", "=", "$", "settings", "[", "'type'", "]", ";", "if", "(", "!", "array_key_exists", "(", "$", "type", ",", "self", "::", "$", "types", ")", ")", "{", "throw", "new", "InvalidFieldTypeException", "(", "\"Unkown type '$type' in '\"", ".", "get_class", "(", "$", "this", ")", ".", "\"'\"", ")", ";", "}", "$", "settings", "[", "'type'", "]", "=", "self", "::", "$", "types", "[", "$", "settings", "[", "'type'", "]", "]", ";", "return", "FieldCollection", "::", "initField", "(", "$", "settings", ")", ";", "}" ]
Validate configuration and prepare a FieldCollection @param string $field @param array $settings @throws InvalidFieldTypeException @throws ReservedFieldNameException @return FieldCollection
[ "Validate", "configuration", "and", "prepare", "a", "FieldCollection" ]
78b65663fc463e21e494257140ddbed0a9ccb3c3
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Entities/Entity.php#L109-L126
train
RocketPropelledTortoise/Core
src/Entities/Entity.php
Entity.newRevision
public function newRevision($language_id = null) { $created = new static($language_id ?: $this->language_id); $created->content = $this->content; return $created; }
php
public function newRevision($language_id = null) { $created = new static($language_id ?: $this->language_id); $created->content = $this->content; return $created; }
[ "public", "function", "newRevision", "(", "$", "language_id", "=", "null", ")", "{", "$", "created", "=", "new", "static", "(", "$", "language_id", "?", ":", "$", "this", "->", "language_id", ")", ";", "$", "created", "->", "content", "=", "$", "this", "->", "content", ";", "return", "$", "created", ";", "}" ]
Create a new revision based on the same content ID but without the content. Very useful if you want to add a new language @param int $language_id @return static
[ "Create", "a", "new", "revision", "based", "on", "the", "same", "content", "ID", "but", "without", "the", "content", ".", "Very", "useful", "if", "you", "want", "to", "add", "a", "new", "language" ]
78b65663fc463e21e494257140ddbed0a9ccb3c3
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Entities/Entity.php#L152-L158
train
RocketPropelledTortoise/Core
src/Entities/Entity.php
Entity.setOnField
protected function setOnField(FieldCollection $field, $value) { if (!is_array($value)) { if ($field->getMaxItems() != 1) { throw new MultipleFieldAssignmentException('You cannot assign a value to replace a multiple field'); } $field->offsetSet(static::$SINGLE_ITEM_KEY, $value); return; } $field->clear(); // This happens when the array is // replaced completely by another array if (count($value)) { foreach ($value as $k => $v) { $field->offsetSet($k, $v); } } }
php
protected function setOnField(FieldCollection $field, $value) { if (!is_array($value)) { if ($field->getMaxItems() != 1) { throw new MultipleFieldAssignmentException('You cannot assign a value to replace a multiple field'); } $field->offsetSet(static::$SINGLE_ITEM_KEY, $value); return; } $field->clear(); // This happens when the array is // replaced completely by another array if (count($value)) { foreach ($value as $k => $v) { $field->offsetSet($k, $v); } } }
[ "protected", "function", "setOnField", "(", "FieldCollection", "$", "field", ",", "$", "value", ")", "{", "if", "(", "!", "is_array", "(", "$", "value", ")", ")", "{", "if", "(", "$", "field", "->", "getMaxItems", "(", ")", "!=", "1", ")", "{", "throw", "new", "MultipleFieldAssignmentException", "(", "'You cannot assign a value to replace a multiple field'", ")", ";", "}", "$", "field", "->", "offsetSet", "(", "static", "::", "$", "SINGLE_ITEM_KEY", ",", "$", "value", ")", ";", "return", ";", "}", "$", "field", "->", "clear", "(", ")", ";", "// This happens when the array is", "// replaced completely by another array", "if", "(", "count", "(", "$", "value", ")", ")", "{", "foreach", "(", "$", "value", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "field", "->", "offsetSet", "(", "$", "k", ",", "$", "v", ")", ";", "}", "}", "}" ]
Set values on a field @param FieldCollection $field @param $value @throws MultipleFieldAssignmentException
[ "Set", "values", "on", "a", "field" ]
78b65663fc463e21e494257140ddbed0a9ccb3c3
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Entities/Entity.php#L289-L310
train
RocketPropelledTortoise/Core
src/Entities/Entity.php
Entity.getFieldTypes
protected function getFieldTypes() { return (new Collection($this->getFields())) ->map(function ($options) { return $options['type']; }) ->values() ->unique() ->map(function ($type) { return self::$types[$type]; }); }
php
protected function getFieldTypes() { return (new Collection($this->getFields())) ->map(function ($options) { return $options['type']; }) ->values() ->unique() ->map(function ($type) { return self::$types[$type]; }); }
[ "protected", "function", "getFieldTypes", "(", ")", "{", "return", "(", "new", "Collection", "(", "$", "this", "->", "getFields", "(", ")", ")", ")", "->", "map", "(", "function", "(", "$", "options", ")", "{", "return", "$", "options", "[", "'type'", "]", ";", "}", ")", "->", "values", "(", ")", "->", "unique", "(", ")", "->", "map", "(", "function", "(", "$", "type", ")", "{", "return", "self", "::", "$", "types", "[", "$", "type", "]", ";", "}", ")", ";", "}" ]
Get all field types in this Entity. @return Collection
[ "Get", "all", "field", "types", "in", "this", "Entity", "." ]
78b65663fc463e21e494257140ddbed0a9ccb3c3
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Entities/Entity.php#L317-L328
train
RocketPropelledTortoise/Core
src/Entities/Entity.php
Entity.findRevision
protected static function findRevision($id, $language_id, $revision_id = null) { try { if (is_numeric($revision_id) && $revision_id != 0) { $revision = Revision::findOrFail($revision_id); if ($revision->content_id != $id) { throw new RevisionEntityMismatchException("This revision doesn't belong to this entity"); } if ($revision->language_id != $language_id) { //TODO :: throw an exception in this case as well } return $revision; } return Revision::where('content_id', $id) ->where('language_id', $language_id) ->where('published', true) ->firstOrFail(); } catch (ModelNotFoundException $e) { if (is_numeric($revision_id) && $revision_id != 0) { throw new RevisionNotFoundException("This revision doesn't exist", 0, $e); } $count = Revision::where('content_id', $id)->where('language_id', $language_id)->count(); if ($count) { $message = "There are revisions in language_id='$language_id' for Entity '$id' but none is published"; throw new NoPublishedRevisionForLanguageException($message, 0, $e); } else { $message = "There no revisions in language_id='$language_id' for Entity '$id' but none is published"; throw new NoRevisionForLanguageException($message, 0, $e); } } }
php
protected static function findRevision($id, $language_id, $revision_id = null) { try { if (is_numeric($revision_id) && $revision_id != 0) { $revision = Revision::findOrFail($revision_id); if ($revision->content_id != $id) { throw new RevisionEntityMismatchException("This revision doesn't belong to this entity"); } if ($revision->language_id != $language_id) { //TODO :: throw an exception in this case as well } return $revision; } return Revision::where('content_id', $id) ->where('language_id', $language_id) ->where('published', true) ->firstOrFail(); } catch (ModelNotFoundException $e) { if (is_numeric($revision_id) && $revision_id != 0) { throw new RevisionNotFoundException("This revision doesn't exist", 0, $e); } $count = Revision::where('content_id', $id)->where('language_id', $language_id)->count(); if ($count) { $message = "There are revisions in language_id='$language_id' for Entity '$id' but none is published"; throw new NoPublishedRevisionForLanguageException($message, 0, $e); } else { $message = "There no revisions in language_id='$language_id' for Entity '$id' but none is published"; throw new NoRevisionForLanguageException($message, 0, $e); } } }
[ "protected", "static", "function", "findRevision", "(", "$", "id", ",", "$", "language_id", ",", "$", "revision_id", "=", "null", ")", "{", "try", "{", "if", "(", "is_numeric", "(", "$", "revision_id", ")", "&&", "$", "revision_id", "!=", "0", ")", "{", "$", "revision", "=", "Revision", "::", "findOrFail", "(", "$", "revision_id", ")", ";", "if", "(", "$", "revision", "->", "content_id", "!=", "$", "id", ")", "{", "throw", "new", "RevisionEntityMismatchException", "(", "\"This revision doesn't belong to this entity\"", ")", ";", "}", "if", "(", "$", "revision", "->", "language_id", "!=", "$", "language_id", ")", "{", "//TODO :: throw an exception in this case as well", "}", "return", "$", "revision", ";", "}", "return", "Revision", "::", "where", "(", "'content_id'", ",", "$", "id", ")", "->", "where", "(", "'language_id'", ",", "$", "language_id", ")", "->", "where", "(", "'published'", ",", "true", ")", "->", "firstOrFail", "(", ")", ";", "}", "catch", "(", "ModelNotFoundException", "$", "e", ")", "{", "if", "(", "is_numeric", "(", "$", "revision_id", ")", "&&", "$", "revision_id", "!=", "0", ")", "{", "throw", "new", "RevisionNotFoundException", "(", "\"This revision doesn't exist\"", ",", "0", ",", "$", "e", ")", ";", "}", "$", "count", "=", "Revision", "::", "where", "(", "'content_id'", ",", "$", "id", ")", "->", "where", "(", "'language_id'", ",", "$", "language_id", ")", "->", "count", "(", ")", ";", "if", "(", "$", "count", ")", "{", "$", "message", "=", "\"There are revisions in language_id='$language_id' for Entity '$id' but none is published\"", ";", "throw", "new", "NoPublishedRevisionForLanguageException", "(", "$", "message", ",", "0", ",", "$", "e", ")", ";", "}", "else", "{", "$", "message", "=", "\"There no revisions in language_id='$language_id' for Entity '$id' but none is published\"", ";", "throw", "new", "NoRevisionForLanguageException", "(", "$", "message", ",", "0", ",", "$", "e", ")", ";", "}", "}", "}" ]
Find the requested Revision. If a revision_id it will be requested against the requested ID and Language. If none is requested, it will find the revision that is published in that language. @param int $id The content ID @param int $language_id The language ID @param int $revision_id The revision ID which you want to load, this is optional @throws NoPublishedRevisionForLanguageException @throws NoRevisionForLanguageException @throws RevisionEntityMismatchException @throws RevisionNotFoundException @return Revision
[ "Find", "the", "requested", "Revision", "." ]
78b65663fc463e21e494257140ddbed0a9ccb3c3
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Entities/Entity.php#L346-L382
train
RocketPropelledTortoise/Core
src/Entities/Entity.php
Entity.find
public static function find($id, $language_id, $revision_id = null) { $instance = new static($language_id); try { $instance->content = Content::findOrFail($id); } catch (ModelNotFoundException $e) { throw new EntityNotFoundException("The entity with id '$id' doesn't exist", 0, $e); } $instance->revision = static::findRevision($id, $language_id, $revision_id); $instance->getFieldTypes() ->each(function ($type) use ($instance) { $type::where('revision_id', $instance->revision->id) ->get() ->each(function (Field $value) use ($instance) { $instance->data[$value->name][$value->weight] = $value; }); }); return $instance; }
php
public static function find($id, $language_id, $revision_id = null) { $instance = new static($language_id); try { $instance->content = Content::findOrFail($id); } catch (ModelNotFoundException $e) { throw new EntityNotFoundException("The entity with id '$id' doesn't exist", 0, $e); } $instance->revision = static::findRevision($id, $language_id, $revision_id); $instance->getFieldTypes() ->each(function ($type) use ($instance) { $type::where('revision_id', $instance->revision->id) ->get() ->each(function (Field $value) use ($instance) { $instance->data[$value->name][$value->weight] = $value; }); }); return $instance; }
[ "public", "static", "function", "find", "(", "$", "id", ",", "$", "language_id", ",", "$", "revision_id", "=", "null", ")", "{", "$", "instance", "=", "new", "static", "(", "$", "language_id", ")", ";", "try", "{", "$", "instance", "->", "content", "=", "Content", "::", "findOrFail", "(", "$", "id", ")", ";", "}", "catch", "(", "ModelNotFoundException", "$", "e", ")", "{", "throw", "new", "EntityNotFoundException", "(", "\"The entity with id '$id' doesn't exist\"", ",", "0", ",", "$", "e", ")", ";", "}", "$", "instance", "->", "revision", "=", "static", "::", "findRevision", "(", "$", "id", ",", "$", "language_id", ",", "$", "revision_id", ")", ";", "$", "instance", "->", "getFieldTypes", "(", ")", "->", "each", "(", "function", "(", "$", "type", ")", "use", "(", "$", "instance", ")", "{", "$", "type", "::", "where", "(", "'revision_id'", ",", "$", "instance", "->", "revision", "->", "id", ")", "->", "get", "(", ")", "->", "each", "(", "function", "(", "Field", "$", "value", ")", "use", "(", "$", "instance", ")", "{", "$", "instance", "->", "data", "[", "$", "value", "->", "name", "]", "[", "$", "value", "->", "weight", "]", "=", "$", "value", ";", "}", ")", ";", "}", ")", ";", "return", "$", "instance", ";", "}" ]
Find the latest valid revision for this entity @param int $id The content ID @param int $language_id The language ID @param int $revision_id The revision ID which you want to load, this is optional @throws EntityNotFoundException @throws NoPublishedRevisionForLanguageException @throws NoRevisionForLanguageException @throws RevisionEntityMismatchException @throws RevisionNotFoundException @return static
[ "Find", "the", "latest", "valid", "revision", "for", "this", "entity" ]
78b65663fc463e21e494257140ddbed0a9ccb3c3
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Entities/Entity.php#L397-L419
train
RocketPropelledTortoise/Core
src/Entities/Entity.php
Entity.save
public function save($newRevision = false, $publishRevision = true) { if ($newRevision) { $revision = new Revision; $revision->language_id = $this->revision->language_id; $this->revision = $revision; } DB::transaction( function () use ($newRevision, $publishRevision) { $this->saveContent(); $this->saveRevision($publishRevision); // Prepare and save fields foreach (array_keys($this->data) as $fieldName) { /** @var FieldCollection $field */ $field = $this->data[$fieldName]; if (!$newRevision) { $field->deleted()->each(function (Field $value) { $value->delete(); }); } $field->each(function (Field $value, $key) use ($newRevision, $fieldName) { $value->weight = $key; $value->name = $fieldName; $this->saveField($value, $newRevision); }); $field->syncOriginal(); } } ); }
php
public function save($newRevision = false, $publishRevision = true) { if ($newRevision) { $revision = new Revision; $revision->language_id = $this->revision->language_id; $this->revision = $revision; } DB::transaction( function () use ($newRevision, $publishRevision) { $this->saveContent(); $this->saveRevision($publishRevision); // Prepare and save fields foreach (array_keys($this->data) as $fieldName) { /** @var FieldCollection $field */ $field = $this->data[$fieldName]; if (!$newRevision) { $field->deleted()->each(function (Field $value) { $value->delete(); }); } $field->each(function (Field $value, $key) use ($newRevision, $fieldName) { $value->weight = $key; $value->name = $fieldName; $this->saveField($value, $newRevision); }); $field->syncOriginal(); } } ); }
[ "public", "function", "save", "(", "$", "newRevision", "=", "false", ",", "$", "publishRevision", "=", "true", ")", "{", "if", "(", "$", "newRevision", ")", "{", "$", "revision", "=", "new", "Revision", ";", "$", "revision", "->", "language_id", "=", "$", "this", "->", "revision", "->", "language_id", ";", "$", "this", "->", "revision", "=", "$", "revision", ";", "}", "DB", "::", "transaction", "(", "function", "(", ")", "use", "(", "$", "newRevision", ",", "$", "publishRevision", ")", "{", "$", "this", "->", "saveContent", "(", ")", ";", "$", "this", "->", "saveRevision", "(", "$", "publishRevision", ")", ";", "// Prepare and save fields", "foreach", "(", "array_keys", "(", "$", "this", "->", "data", ")", "as", "$", "fieldName", ")", "{", "/** @var FieldCollection $field */", "$", "field", "=", "$", "this", "->", "data", "[", "$", "fieldName", "]", ";", "if", "(", "!", "$", "newRevision", ")", "{", "$", "field", "->", "deleted", "(", ")", "->", "each", "(", "function", "(", "Field", "$", "value", ")", "{", "$", "value", "->", "delete", "(", ")", ";", "}", ")", ";", "}", "$", "field", "->", "each", "(", "function", "(", "Field", "$", "value", ",", "$", "key", ")", "use", "(", "$", "newRevision", ",", "$", "fieldName", ")", "{", "$", "value", "->", "weight", "=", "$", "key", ";", "$", "value", "->", "name", "=", "$", "fieldName", ";", "$", "this", "->", "saveField", "(", "$", "value", ",", "$", "newRevision", ")", ";", "}", ")", ";", "$", "field", "->", "syncOriginal", "(", ")", ";", "}", "}", ")", ";", "}" ]
Save a revision @param bool $newRevision Should we create a new revision, false by default @param bool $publishRevision Should we immediately publish this revision, true by default
[ "Save", "a", "revision" ]
78b65663fc463e21e494257140ddbed0a9ccb3c3
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Entities/Entity.php#L427-L463
train
RocketPropelledTortoise/Core
src/Entities/Entity.php
Entity.saveRevision
protected function saveRevision($publishRevision) { if (!$this->revision->exists && !$publishRevision) { $this->revision->published = $publishRevision; } $this->revision->content_id = $this->content->id; $this->revision->save(); if ($publishRevision) { $this->unpublishOtherRevisions(); } }
php
protected function saveRevision($publishRevision) { if (!$this->revision->exists && !$publishRevision) { $this->revision->published = $publishRevision; } $this->revision->content_id = $this->content->id; $this->revision->save(); if ($publishRevision) { $this->unpublishOtherRevisions(); } }
[ "protected", "function", "saveRevision", "(", "$", "publishRevision", ")", "{", "if", "(", "!", "$", "this", "->", "revision", "->", "exists", "&&", "!", "$", "publishRevision", ")", "{", "$", "this", "->", "revision", "->", "published", "=", "$", "publishRevision", ";", "}", "$", "this", "->", "revision", "->", "content_id", "=", "$", "this", "->", "content", "->", "id", ";", "$", "this", "->", "revision", "->", "save", "(", ")", ";", "if", "(", "$", "publishRevision", ")", "{", "$", "this", "->", "unpublishOtherRevisions", "(", ")", ";", "}", "}" ]
Save the revision @param bool $publishRevision Should we immediately publish this revision, true by default
[ "Save", "the", "revision" ]
78b65663fc463e21e494257140ddbed0a9ccb3c3
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Entities/Entity.php#L478-L490
train
RocketPropelledTortoise/Core
src/Entities/Entity.php
Entity.unpublishOtherRevisions
protected function unpublishOtherRevisions() { if ($this->content->wasRecentlyCreated) { return; } // Unpublish all other revisions Revision::where('content_id', $this->content->id) ->where('language_id', $this->revision->language_id) ->where('id', '!=', $this->revision->id) ->update(['published' => false]); }
php
protected function unpublishOtherRevisions() { if ($this->content->wasRecentlyCreated) { return; } // Unpublish all other revisions Revision::where('content_id', $this->content->id) ->where('language_id', $this->revision->language_id) ->where('id', '!=', $this->revision->id) ->update(['published' => false]); }
[ "protected", "function", "unpublishOtherRevisions", "(", ")", "{", "if", "(", "$", "this", "->", "content", "->", "wasRecentlyCreated", ")", "{", "return", ";", "}", "// Unpublish all other revisions", "Revision", "::", "where", "(", "'content_id'", ",", "$", "this", "->", "content", "->", "id", ")", "->", "where", "(", "'language_id'", ",", "$", "this", "->", "revision", "->", "language_id", ")", "->", "where", "(", "'id'", ",", "'!='", ",", "$", "this", "->", "revision", "->", "id", ")", "->", "update", "(", "[", "'published'", "=>", "false", "]", ")", ";", "}" ]
Unpublish the revisions other than this one. Only for the same content_id and language_id
[ "Unpublish", "the", "revisions", "other", "than", "this", "one", ".", "Only", "for", "the", "same", "content_id", "and", "language_id" ]
78b65663fc463e21e494257140ddbed0a9ccb3c3
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Entities/Entity.php#L496-L507
train
RocketPropelledTortoise/Core
src/Entities/Entity.php
Entity.saveField
protected function saveField(Field $field, $newRevision) { // If we create a new revision, this will // reinit the field to a non-saved field // and create a new row in the database if ($newRevision) { $field->id = null; $field->exists = false; } $field->revision_id = $this->revision->id; $field->save(); }
php
protected function saveField(Field $field, $newRevision) { // If we create a new revision, this will // reinit the field to a non-saved field // and create a new row in the database if ($newRevision) { $field->id = null; $field->exists = false; } $field->revision_id = $this->revision->id; $field->save(); }
[ "protected", "function", "saveField", "(", "Field", "$", "field", ",", "$", "newRevision", ")", "{", "// If we create a new revision, this will", "// reinit the field to a non-saved field", "// and create a new row in the database", "if", "(", "$", "newRevision", ")", "{", "$", "field", "->", "id", "=", "null", ";", "$", "field", "->", "exists", "=", "false", ";", "}", "$", "field", "->", "revision_id", "=", "$", "this", "->", "revision", "->", "id", ";", "$", "field", "->", "save", "(", ")", ";", "}" ]
Save a single field instance @param Field $field The field instance to save @param bool $newRevision Should we create a new revision?
[ "Save", "a", "single", "field", "instance" ]
78b65663fc463e21e494257140ddbed0a9ccb3c3
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Entities/Entity.php#L515-L528
train
RocketPropelledTortoise/Core
src/Entities/Entity.php
Entity.toArray
public function toArray() { $content = [ 'id' => $this->content->id, '_content' => $this->content->toArray(), '_revision' => $this->revision->toArray(), ]; foreach ($this->data as $field => $data) { $content[$field] = $data->toArray(); } return $content; }
php
public function toArray() { $content = [ 'id' => $this->content->id, '_content' => $this->content->toArray(), '_revision' => $this->revision->toArray(), ]; foreach ($this->data as $field => $data) { $content[$field] = $data->toArray(); } return $content; }
[ "public", "function", "toArray", "(", ")", "{", "$", "content", "=", "[", "'id'", "=>", "$", "this", "->", "content", "->", "id", ",", "'_content'", "=>", "$", "this", "->", "content", "->", "toArray", "(", ")", ",", "'_revision'", "=>", "$", "this", "->", "revision", "->", "toArray", "(", ")", ",", "]", ";", "foreach", "(", "$", "this", "->", "data", "as", "$", "field", "=>", "$", "data", ")", "{", "$", "content", "[", "$", "field", "]", "=", "$", "data", "->", "toArray", "(", ")", ";", "}", "return", "$", "content", ";", "}" ]
Convert the Entity to an array. @return array
[ "Convert", "the", "Entity", "to", "an", "array", "." ]
78b65663fc463e21e494257140ddbed0a9ccb3c3
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Entities/Entity.php#L535-L548
train
RocketPropelledTortoise/Core
src/Entities/Entity.php
Entity.delete
public function delete($clear = true) { $revisions = Revision::where('content_id', $this->content->id)->get(); $ids = $revisions->pluck('id'); $this->getFieldTypes()->each(function ($type) use ($ids) { $type::whereIn('revision_id', $ids)->delete(); }); Revision::whereIn('id', $ids)->delete(); $this->revision->exists = false; // TODO :: add an event system to be able to remove this content from entity fields $this->content->delete(); if ($clear) { $this->revision->id = null; $this->content->id = null; $this->clearFields(); } }
php
public function delete($clear = true) { $revisions = Revision::where('content_id', $this->content->id)->get(); $ids = $revisions->pluck('id'); $this->getFieldTypes()->each(function ($type) use ($ids) { $type::whereIn('revision_id', $ids)->delete(); }); Revision::whereIn('id', $ids)->delete(); $this->revision->exists = false; // TODO :: add an event system to be able to remove this content from entity fields $this->content->delete(); if ($clear) { $this->revision->id = null; $this->content->id = null; $this->clearFields(); } }
[ "public", "function", "delete", "(", "$", "clear", "=", "true", ")", "{", "$", "revisions", "=", "Revision", "::", "where", "(", "'content_id'", ",", "$", "this", "->", "content", "->", "id", ")", "->", "get", "(", ")", ";", "$", "ids", "=", "$", "revisions", "->", "pluck", "(", "'id'", ")", ";", "$", "this", "->", "getFieldTypes", "(", ")", "->", "each", "(", "function", "(", "$", "type", ")", "use", "(", "$", "ids", ")", "{", "$", "type", "::", "whereIn", "(", "'revision_id'", ",", "$", "ids", ")", "->", "delete", "(", ")", ";", "}", ")", ";", "Revision", "::", "whereIn", "(", "'id'", ",", "$", "ids", ")", "->", "delete", "(", ")", ";", "$", "this", "->", "revision", "->", "exists", "=", "false", ";", "// TODO :: add an event system to be able to remove this content from entity fields", "$", "this", "->", "content", "->", "delete", "(", ")", ";", "if", "(", "$", "clear", ")", "{", "$", "this", "->", "revision", "->", "id", "=", "null", ";", "$", "this", "->", "content", "->", "id", "=", "null", ";", "$", "this", "->", "clearFields", "(", ")", ";", "}", "}" ]
Delete this entity and all the underlying Revisions. @param bool $clear Should we clear the fields after deleting the revision ?
[ "Delete", "this", "entity", "and", "all", "the", "underlying", "Revisions", "." ]
78b65663fc463e21e494257140ddbed0a9ccb3c3
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Entities/Entity.php#L555-L577
train
RocketPropelledTortoise/Core
src/Entities/Entity.php
Entity.deleteRevision
public function deleteRevision($clear = true) { $this->getFieldTypes()->each(function ($type) { $type::where('revision_id', $this->revision->id)->delete(); }); // If this revision is currently // published, we need to publish // another revision in place. if ($this->revision->published && $this->revision->exists) { //TODO :: improve this logic Revision::where('content_id', $this->content->id) ->where('id', '!=', $this->revision->id) ->take(1) ->update(['published' => true]); } $this->revision->delete(); if ($clear) { $this->clearFields(); } }
php
public function deleteRevision($clear = true) { $this->getFieldTypes()->each(function ($type) { $type::where('revision_id', $this->revision->id)->delete(); }); // If this revision is currently // published, we need to publish // another revision in place. if ($this->revision->published && $this->revision->exists) { //TODO :: improve this logic Revision::where('content_id', $this->content->id) ->where('id', '!=', $this->revision->id) ->take(1) ->update(['published' => true]); } $this->revision->delete(); if ($clear) { $this->clearFields(); } }
[ "public", "function", "deleteRevision", "(", "$", "clear", "=", "true", ")", "{", "$", "this", "->", "getFieldTypes", "(", ")", "->", "each", "(", "function", "(", "$", "type", ")", "{", "$", "type", "::", "where", "(", "'revision_id'", ",", "$", "this", "->", "revision", "->", "id", ")", "->", "delete", "(", ")", ";", "}", ")", ";", "// If this revision is currently", "// published, we need to publish", "// another revision in place.", "if", "(", "$", "this", "->", "revision", "->", "published", "&&", "$", "this", "->", "revision", "->", "exists", ")", "{", "//TODO :: improve this logic", "Revision", "::", "where", "(", "'content_id'", ",", "$", "this", "->", "content", "->", "id", ")", "->", "where", "(", "'id'", ",", "'!='", ",", "$", "this", "->", "revision", "->", "id", ")", "->", "take", "(", "1", ")", "->", "update", "(", "[", "'published'", "=>", "true", "]", ")", ";", "}", "$", "this", "->", "revision", "->", "delete", "(", ")", ";", "if", "(", "$", "clear", ")", "{", "$", "this", "->", "clearFields", "(", ")", ";", "}", "}" ]
Delete the current revision. @param bool $clear Should we clear the fields after deleting the revision ?
[ "Delete", "the", "current", "revision", "." ]
78b65663fc463e21e494257140ddbed0a9ccb3c3
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Entities/Entity.php#L584-L606
train
RocketPropelledTortoise/Core
src/Entities/Entity.php
Entity.clearFields
protected function clearFields() { // Void all the fields foreach (array_keys($this->data) as $fieldName) { /** @var FieldCollection $field */ $field = $this->data[$fieldName]; $field->clear(); $field->syncOriginal(); } }
php
protected function clearFields() { // Void all the fields foreach (array_keys($this->data) as $fieldName) { /** @var FieldCollection $field */ $field = $this->data[$fieldName]; $field->clear(); $field->syncOriginal(); } }
[ "protected", "function", "clearFields", "(", ")", "{", "// Void all the fields", "foreach", "(", "array_keys", "(", "$", "this", "->", "data", ")", "as", "$", "fieldName", ")", "{", "/** @var FieldCollection $field */", "$", "field", "=", "$", "this", "->", "data", "[", "$", "fieldName", "]", ";", "$", "field", "->", "clear", "(", ")", ";", "$", "field", "->", "syncOriginal", "(", ")", ";", "}", "}" ]
Clear all the fields from their content
[ "Clear", "all", "the", "fields", "from", "their", "content" ]
78b65663fc463e21e494257140ddbed0a9ccb3c3
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Entities/Entity.php#L611-L621
train
RocketPropelledTortoise/Core
src/Entities/Entity.php
Entity.publishRevision
public function publishRevision() { $this->revision->published = true; $this->revision->save(); $this->unpublishOtherRevisions(); }
php
public function publishRevision() { $this->revision->published = true; $this->revision->save(); $this->unpublishOtherRevisions(); }
[ "public", "function", "publishRevision", "(", ")", "{", "$", "this", "->", "revision", "->", "published", "=", "true", ";", "$", "this", "->", "revision", "->", "save", "(", ")", ";", "$", "this", "->", "unpublishOtherRevisions", "(", ")", ";", "}" ]
Publish the current revision and unpublish the other revisions of the same language.
[ "Publish", "the", "current", "revision", "and", "unpublish", "the", "other", "revisions", "of", "the", "same", "language", "." ]
78b65663fc463e21e494257140ddbed0a9ccb3c3
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Entities/Entity.php#L626-L632
train
Kris-Kuiper/sFire-Framework
src/MVC/Mapper.php
Mapper.dbtable
public function dbtable($dbtable = null) { if(true === isset($this -> dbtable) && null === $dbtable) { $dbtable = $this -> dbtable; } if($dbtable !== null && false === is_string($dbtable)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($dbtable)), E_USER_ERROR); } if($dbtable === null) { return trigger_error('Table name can not be empty. Set the table name with the "setTable" method in the mapper', E_USER_ERROR); } if(false === isset($this -> dbtables[$dbtable])) { $folders = explode('.', $dbtable); //Convert dots to directory separators $amount = count($folders) - 1; $namespace = ''; foreach($folders as $index => $folder) { if($amount === $index) { $class = Application :: get(['prefix', 'dbtable']) . NameConvert :: toCamelCase($folder, true); $namespace .= $class; break; } $namespace .= $folder . DIRECTORY_SEPARATOR; } $path = $this -> getNamespace($this, ['directory', 'mapper'], ['directory', 'dbtable']); $namespace = str_replace(DIRECTORY_SEPARATOR, '\\', $path . $namespace); if(false === class_exists($namespace)) { return trigger_error(sprintf('"%s" class does not exists in "%s"', $class, $path), E_USER_ERROR); } $this -> dbtables[$dbtable] = new $namespace; //Set the tablename if class isn't already populated with the table property $cl = new \ReflectionClass($this -> dbtables[$dbtable]); foreach($cl -> getProperties() as $prop) { if('table' === $prop -> name) { goto output; } } $table = $this -> dbtables[$dbtable] -> getTable(); if(null === $table) { $this -> dbtables[$dbtable] -> setTable($dbtable); } } output: return $this -> dbtables[$dbtable]; }
php
public function dbtable($dbtable = null) { if(true === isset($this -> dbtable) && null === $dbtable) { $dbtable = $this -> dbtable; } if($dbtable !== null && false === is_string($dbtable)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($dbtable)), E_USER_ERROR); } if($dbtable === null) { return trigger_error('Table name can not be empty. Set the table name with the "setTable" method in the mapper', E_USER_ERROR); } if(false === isset($this -> dbtables[$dbtable])) { $folders = explode('.', $dbtable); //Convert dots to directory separators $amount = count($folders) - 1; $namespace = ''; foreach($folders as $index => $folder) { if($amount === $index) { $class = Application :: get(['prefix', 'dbtable']) . NameConvert :: toCamelCase($folder, true); $namespace .= $class; break; } $namespace .= $folder . DIRECTORY_SEPARATOR; } $path = $this -> getNamespace($this, ['directory', 'mapper'], ['directory', 'dbtable']); $namespace = str_replace(DIRECTORY_SEPARATOR, '\\', $path . $namespace); if(false === class_exists($namespace)) { return trigger_error(sprintf('"%s" class does not exists in "%s"', $class, $path), E_USER_ERROR); } $this -> dbtables[$dbtable] = new $namespace; //Set the tablename if class isn't already populated with the table property $cl = new \ReflectionClass($this -> dbtables[$dbtable]); foreach($cl -> getProperties() as $prop) { if('table' === $prop -> name) { goto output; } } $table = $this -> dbtables[$dbtable] -> getTable(); if(null === $table) { $this -> dbtables[$dbtable] -> setTable($dbtable); } } output: return $this -> dbtables[$dbtable]; }
[ "public", "function", "dbtable", "(", "$", "dbtable", "=", "null", ")", "{", "if", "(", "true", "===", "isset", "(", "$", "this", "->", "dbtable", ")", "&&", "null", "===", "$", "dbtable", ")", "{", "$", "dbtable", "=", "$", "this", "->", "dbtable", ";", "}", "if", "(", "$", "dbtable", "!==", "null", "&&", "false", "===", "is_string", "(", "$", "dbtable", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "dbtable", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "$", "dbtable", "===", "null", ")", "{", "return", "trigger_error", "(", "'Table name can not be empty. Set the table name with the \"setTable\" method in the mapper'", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "false", "===", "isset", "(", "$", "this", "->", "dbtables", "[", "$", "dbtable", "]", ")", ")", "{", "$", "folders", "=", "explode", "(", "'.'", ",", "$", "dbtable", ")", ";", "//Convert dots to directory separators\r", "$", "amount", "=", "count", "(", "$", "folders", ")", "-", "1", ";", "$", "namespace", "=", "''", ";", "foreach", "(", "$", "folders", "as", "$", "index", "=>", "$", "folder", ")", "{", "if", "(", "$", "amount", "===", "$", "index", ")", "{", "$", "class", "=", "Application", "::", "get", "(", "[", "'prefix'", ",", "'dbtable'", "]", ")", ".", "NameConvert", "::", "toCamelCase", "(", "$", "folder", ",", "true", ")", ";", "$", "namespace", ".=", "$", "class", ";", "break", ";", "}", "$", "namespace", ".=", "$", "folder", ".", "DIRECTORY_SEPARATOR", ";", "}", "$", "path", "=", "$", "this", "->", "getNamespace", "(", "$", "this", ",", "[", "'directory'", ",", "'mapper'", "]", ",", "[", "'directory'", ",", "'dbtable'", "]", ")", ";", "$", "namespace", "=", "str_replace", "(", "DIRECTORY_SEPARATOR", ",", "'\\\\'", ",", "$", "path", ".", "$", "namespace", ")", ";", "if", "(", "false", "===", "class_exists", "(", "$", "namespace", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'\"%s\" class does not exists in \"%s\"'", ",", "$", "class", ",", "$", "path", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "this", "->", "dbtables", "[", "$", "dbtable", "]", "=", "new", "$", "namespace", ";", "//Set the tablename if class isn't already populated with the table property\r", "$", "cl", "=", "new", "\\", "ReflectionClass", "(", "$", "this", "->", "dbtables", "[", "$", "dbtable", "]", ")", ";", "foreach", "(", "$", "cl", "->", "getProperties", "(", ")", "as", "$", "prop", ")", "{", "if", "(", "'table'", "===", "$", "prop", "->", "name", ")", "{", "goto", "output", ";", "}", "}", "$", "table", "=", "$", "this", "->", "dbtables", "[", "$", "dbtable", "]", "->", "getTable", "(", ")", ";", "if", "(", "null", "===", "$", "table", ")", "{", "$", "this", "->", "dbtables", "[", "$", "dbtable", "]", "->", "setTable", "(", "$", "dbtable", ")", ";", "}", "}", "output", ":", "return", "$", "this", "->", "dbtables", "[", "$", "dbtable", "]", ";", "}" ]
Loads and stores a new DBTable and returns it @param string $dbtable @return mixed
[ "Loads", "and", "stores", "a", "new", "DBTable", "and", "returns", "it" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/MVC/Mapper.php#L40-L101
train
Kris-Kuiper/sFire-Framework
src/MVC/Mapper.php
Mapper.setDBTable
protected function setDBTable($dbtable) { if(false === is_string($dbtable)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($dbtable)), E_USER_ERROR); } $this -> dbtable = $dbtable; }
php
protected function setDBTable($dbtable) { if(false === is_string($dbtable)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($dbtable)), E_USER_ERROR); } $this -> dbtable = $dbtable; }
[ "protected", "function", "setDBTable", "(", "$", "dbtable", ")", "{", "if", "(", "false", "===", "is_string", "(", "$", "dbtable", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "dbtable", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "this", "->", "dbtable", "=", "$", "dbtable", ";", "}" ]
Set the dbtable @param string $dbtable
[ "Set", "the", "dbtable" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/MVC/Mapper.php#L108-L115
train
miaoxing/plugin
src/Service/Migration.php
Migration.status
public function status() { $status = $this->getStatus(); if (!$status) { $this->writeln('No migrations found.'); return; } $this->writeln(' Ran? Name '); $this->writeln('--------------'); foreach ($status as $row) { if ($row['migrated']) { $mark = $this->cli->success('Y'); } else { $mark = $this->cli->error('N'); } $this->writeln(' ' . $mark . ' ' . $row['id']); } }
php
public function status() { $status = $this->getStatus(); if (!$status) { $this->writeln('No migrations found.'); return; } $this->writeln(' Ran? Name '); $this->writeln('--------------'); foreach ($status as $row) { if ($row['migrated']) { $mark = $this->cli->success('Y'); } else { $mark = $this->cli->error('N'); } $this->writeln(' ' . $mark . ' ' . $row['id']); } }
[ "public", "function", "status", "(", ")", "{", "$", "status", "=", "$", "this", "->", "getStatus", "(", ")", ";", "if", "(", "!", "$", "status", ")", "{", "$", "this", "->", "writeln", "(", "'No migrations found.'", ")", ";", "return", ";", "}", "$", "this", "->", "writeln", "(", "' Ran? Name '", ")", ";", "$", "this", "->", "writeln", "(", "'--------------'", ")", ";", "foreach", "(", "$", "status", "as", "$", "row", ")", "{", "if", "(", "$", "row", "[", "'migrated'", "]", ")", "{", "$", "mark", "=", "$", "this", "->", "cli", "->", "success", "(", "'Y'", ")", ";", "}", "else", "{", "$", "mark", "=", "$", "this", "->", "cli", "->", "error", "(", "'N'", ")", ";", "}", "$", "this", "->", "writeln", "(", "' '", ".", "$", "mark", ".", "' '", ".", "$", "row", "[", "'id'", "]", ")", ";", "}", "}" ]
Output the migration status table
[ "Output", "the", "migration", "status", "table" ]
f287a1e6c97abba6f06906255b8c26e8ab0afe61
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/Service/Migration.php#L161-L181
train
nails/module-blog
admin/controllers/Post.php
Post.delete
public function delete() { if (!userHasPermission('admin:blog:post:' . $this->blog->id . ':delete')) { unauthorised(); } // -------------------------------------------------------------------------- // Fetch and check post $iPostId = (int) $this->uri->segment(6); $oPost = $this->blog_post_model->getById($iPostId); if (!$oPost || $oPost->blog->id != $this->blog->id) { $this->session->set_flashdata('error', 'I could\'t find a post by that ID.'); redirect('admin/blog/post/index/' . $this->blog->id); } // -------------------------------------------------------------------------- if ($this->blog_post_model->delete($iPostId)) { $sStatus = 'success'; $sMessage = ucfirst($this->data['postName']) . ' was deleted successfully. '; if (userHasPermission('admin:blog:post:' . $this->blog->id . ':restore')) { $sMessage .= anchor('admin/blog/post/restore/' . $this->blog->id . '/' . $iPostId, 'Undo?'); } // Update admin changelog $this->oChangeLogModel->add('deleted', 'a', 'blog post', $iPostId, $oPost->title); } else { $sStatus = 'error'; $sMessage = 'I failed to delete that post. ' . $this->blog_post_model->lastError(); } $this->session->set_flashdata($sStatus, $sMessage); redirect('admin/blog/post/index/' . $this->blog->id); }
php
public function delete() { if (!userHasPermission('admin:blog:post:' . $this->blog->id . ':delete')) { unauthorised(); } // -------------------------------------------------------------------------- // Fetch and check post $iPostId = (int) $this->uri->segment(6); $oPost = $this->blog_post_model->getById($iPostId); if (!$oPost || $oPost->blog->id != $this->blog->id) { $this->session->set_flashdata('error', 'I could\'t find a post by that ID.'); redirect('admin/blog/post/index/' . $this->blog->id); } // -------------------------------------------------------------------------- if ($this->blog_post_model->delete($iPostId)) { $sStatus = 'success'; $sMessage = ucfirst($this->data['postName']) . ' was deleted successfully. '; if (userHasPermission('admin:blog:post:' . $this->blog->id . ':restore')) { $sMessage .= anchor('admin/blog/post/restore/' . $this->blog->id . '/' . $iPostId, 'Undo?'); } // Update admin changelog $this->oChangeLogModel->add('deleted', 'a', 'blog post', $iPostId, $oPost->title); } else { $sStatus = 'error'; $sMessage = 'I failed to delete that post. ' . $this->blog_post_model->lastError(); } $this->session->set_flashdata($sStatus, $sMessage); redirect('admin/blog/post/index/' . $this->blog->id); }
[ "public", "function", "delete", "(", ")", "{", "if", "(", "!", "userHasPermission", "(", "'admin:blog:post:'", ".", "$", "this", "->", "blog", "->", "id", ".", "':delete'", ")", ")", "{", "unauthorised", "(", ")", ";", "}", "// --------------------------------------------------------------------------", "// Fetch and check post", "$", "iPostId", "=", "(", "int", ")", "$", "this", "->", "uri", "->", "segment", "(", "6", ")", ";", "$", "oPost", "=", "$", "this", "->", "blog_post_model", "->", "getById", "(", "$", "iPostId", ")", ";", "if", "(", "!", "$", "oPost", "||", "$", "oPost", "->", "blog", "->", "id", "!=", "$", "this", "->", "blog", "->", "id", ")", "{", "$", "this", "->", "session", "->", "set_flashdata", "(", "'error'", ",", "'I could\\'t find a post by that ID.'", ")", ";", "redirect", "(", "'admin/blog/post/index/'", ".", "$", "this", "->", "blog", "->", "id", ")", ";", "}", "// --------------------------------------------------------------------------", "if", "(", "$", "this", "->", "blog_post_model", "->", "delete", "(", "$", "iPostId", ")", ")", "{", "$", "sStatus", "=", "'success'", ";", "$", "sMessage", "=", "ucfirst", "(", "$", "this", "->", "data", "[", "'postName'", "]", ")", ".", "' was deleted successfully. '", ";", "if", "(", "userHasPermission", "(", "'admin:blog:post:'", ".", "$", "this", "->", "blog", "->", "id", ".", "':restore'", ")", ")", "{", "$", "sMessage", ".=", "anchor", "(", "'admin/blog/post/restore/'", ".", "$", "this", "->", "blog", "->", "id", ".", "'/'", ".", "$", "iPostId", ",", "'Undo?'", ")", ";", "}", "// Update admin changelog", "$", "this", "->", "oChangeLogModel", "->", "add", "(", "'deleted'", ",", "'a'", ",", "'blog post'", ",", "$", "iPostId", ",", "$", "oPost", "->", "title", ")", ";", "}", "else", "{", "$", "sStatus", "=", "'error'", ";", "$", "sMessage", "=", "'I failed to delete that post. '", ".", "$", "this", "->", "blog_post_model", "->", "lastError", "(", ")", ";", "}", "$", "this", "->", "session", "->", "set_flashdata", "(", "$", "sStatus", ",", "$", "sMessage", ")", ";", "redirect", "(", "'admin/blog/post/index/'", ".", "$", "this", "->", "blog", "->", "id", ")", ";", "}" ]
Delete a blog post @return void
[ "Delete", "a", "blog", "post" ]
7b369c5209f4343fff7c7e2a22c237d5a95c8c24
https://github.com/nails/module-blog/blob/7b369c5209f4343fff7c7e2a22c237d5a95c8c24/admin/controllers/Post.php#L814-L855
train
nails/module-blog
admin/controllers/Post.php
Post.restore
public function restore() { if (!userHasPermission('admin:blog:post:' . $this->blog->id . ':restore')) { unauthorised(); } // -------------------------------------------------------------------------- // Fetch and check post $iPostId = (int) $this->uri->segment(6); // -------------------------------------------------------------------------- if ($this->blog_post_model->restore($iPostId)) { $oPost = $this->blog_post_model->getById($iPostId); $this->session->set_flashdata('success', ucfirst($this->data['postName']) . ' was restored successfully.'); // Update admin changelog $this->oChangeLogModel->add( 'restored', 'a', 'blog post', $iPostId, $oPost->title, 'admin/blog/post/create/' . $this->blog->id . '/' . $iPostId ); } else { $sStatus = 'error'; $sMessage = 'I failed to restore that ' . $this->data['postName'] . '. '; $sMessage .= $this->blog_post_model->lastError(); $this->session->set_flashdata($sStatus, $sMessage); } redirect('admin/blog/post/index/' . $this->blog->id); }
php
public function restore() { if (!userHasPermission('admin:blog:post:' . $this->blog->id . ':restore')) { unauthorised(); } // -------------------------------------------------------------------------- // Fetch and check post $iPostId = (int) $this->uri->segment(6); // -------------------------------------------------------------------------- if ($this->blog_post_model->restore($iPostId)) { $oPost = $this->blog_post_model->getById($iPostId); $this->session->set_flashdata('success', ucfirst($this->data['postName']) . ' was restored successfully.'); // Update admin changelog $this->oChangeLogModel->add( 'restored', 'a', 'blog post', $iPostId, $oPost->title, 'admin/blog/post/create/' . $this->blog->id . '/' . $iPostId ); } else { $sStatus = 'error'; $sMessage = 'I failed to restore that ' . $this->data['postName'] . '. '; $sMessage .= $this->blog_post_model->lastError(); $this->session->set_flashdata($sStatus, $sMessage); } redirect('admin/blog/post/index/' . $this->blog->id); }
[ "public", "function", "restore", "(", ")", "{", "if", "(", "!", "userHasPermission", "(", "'admin:blog:post:'", ".", "$", "this", "->", "blog", "->", "id", ".", "':restore'", ")", ")", "{", "unauthorised", "(", ")", ";", "}", "// --------------------------------------------------------------------------", "// Fetch and check post", "$", "iPostId", "=", "(", "int", ")", "$", "this", "->", "uri", "->", "segment", "(", "6", ")", ";", "// --------------------------------------------------------------------------", "if", "(", "$", "this", "->", "blog_post_model", "->", "restore", "(", "$", "iPostId", ")", ")", "{", "$", "oPost", "=", "$", "this", "->", "blog_post_model", "->", "getById", "(", "$", "iPostId", ")", ";", "$", "this", "->", "session", "->", "set_flashdata", "(", "'success'", ",", "ucfirst", "(", "$", "this", "->", "data", "[", "'postName'", "]", ")", ".", "' was restored successfully.'", ")", ";", "// Update admin changelog", "$", "this", "->", "oChangeLogModel", "->", "add", "(", "'restored'", ",", "'a'", ",", "'blog post'", ",", "$", "iPostId", ",", "$", "oPost", "->", "title", ",", "'admin/blog/post/create/'", ".", "$", "this", "->", "blog", "->", "id", ".", "'/'", ".", "$", "iPostId", ")", ";", "}", "else", "{", "$", "sStatus", "=", "'error'", ";", "$", "sMessage", "=", "'I failed to restore that '", ".", "$", "this", "->", "data", "[", "'postName'", "]", ".", "'. '", ";", "$", "sMessage", ".=", "$", "this", "->", "blog_post_model", "->", "lastError", "(", ")", ";", "$", "this", "->", "session", "->", "set_flashdata", "(", "$", "sStatus", ",", "$", "sMessage", ")", ";", "}", "redirect", "(", "'admin/blog/post/index/'", ".", "$", "this", "->", "blog", "->", "id", ")", ";", "}" ]
Restore a blog post @return void
[ "Restore", "a", "blog", "post" ]
7b369c5209f4343fff7c7e2a22c237d5a95c8c24
https://github.com/nails/module-blog/blob/7b369c5209f4343fff7c7e2a22c237d5a95c8c24/admin/controllers/Post.php#L863-L902
train
nails/module-blog
admin/controllers/Post.php
Post.callbackValidAudioUrl
public function callbackValidAudioUrl($sUrl) { $sId = $this->blog_post_model->extractSpotifyId($sUrl); if (!empty($sId)) { return true; } else { $oFormValidation = Factory::service('FormValidation'); $oFormValidation->set_message('callbackValidAudioUrl', 'Not a valid Spotify Track URL.'); return false; } }
php
public function callbackValidAudioUrl($sUrl) { $sId = $this->blog_post_model->extractSpotifyId($sUrl); if (!empty($sId)) { return true; } else { $oFormValidation = Factory::service('FormValidation'); $oFormValidation->set_message('callbackValidAudioUrl', 'Not a valid Spotify Track URL.'); return false; } }
[ "public", "function", "callbackValidAudioUrl", "(", "$", "sUrl", ")", "{", "$", "sId", "=", "$", "this", "->", "blog_post_model", "->", "extractSpotifyId", "(", "$", "sUrl", ")", ";", "if", "(", "!", "empty", "(", "$", "sId", ")", ")", "{", "return", "true", ";", "}", "else", "{", "$", "oFormValidation", "=", "Factory", "::", "service", "(", "'FormValidation'", ")", ";", "$", "oFormValidation", "->", "set_message", "(", "'callbackValidAudioUrl'", ",", "'Not a valid Spotify Track URL.'", ")", ";", "return", "false", ";", "}", "}" ]
Form Validation callback, checks that a Spotify ID can be extracted from the string @param string $sUrl The URL to check @return boolean
[ "Form", "Validation", "callback", "checks", "that", "a", "Spotify", "ID", "can", "be", "extracted", "from", "the", "string" ]
7b369c5209f4343fff7c7e2a22c237d5a95c8c24
https://github.com/nails/module-blog/blob/7b369c5209f4343fff7c7e2a22c237d5a95c8c24/admin/controllers/Post.php#L922-L936
train
nails/module-blog
admin/controllers/Post.php
Post.callbackValidVideoUrl
public function callbackValidVideoUrl($sUrl) { $sId = $this->blog_post_model->extractYoutubeId($sUrl); if (!empty($sId)) { return true; } else { $sId = $this->blog_post_model->extractVimeoId($sUrl); if (!empty($sId)) { return true; } else { $oFormValidation = Factory::service('FormValidation'); $oFormValidation->set_message('_callbackValidVideoUrl', 'Not a valid YouTube or Vimeo URL.'); return false; } } }
php
public function callbackValidVideoUrl($sUrl) { $sId = $this->blog_post_model->extractYoutubeId($sUrl); if (!empty($sId)) { return true; } else { $sId = $this->blog_post_model->extractVimeoId($sUrl); if (!empty($sId)) { return true; } else { $oFormValidation = Factory::service('FormValidation'); $oFormValidation->set_message('_callbackValidVideoUrl', 'Not a valid YouTube or Vimeo URL.'); return false; } } }
[ "public", "function", "callbackValidVideoUrl", "(", "$", "sUrl", ")", "{", "$", "sId", "=", "$", "this", "->", "blog_post_model", "->", "extractYoutubeId", "(", "$", "sUrl", ")", ";", "if", "(", "!", "empty", "(", "$", "sId", ")", ")", "{", "return", "true", ";", "}", "else", "{", "$", "sId", "=", "$", "this", "->", "blog_post_model", "->", "extractVimeoId", "(", "$", "sUrl", ")", ";", "if", "(", "!", "empty", "(", "$", "sId", ")", ")", "{", "return", "true", ";", "}", "else", "{", "$", "oFormValidation", "=", "Factory", "::", "service", "(", "'FormValidation'", ")", ";", "$", "oFormValidation", "->", "set_message", "(", "'_callbackValidVideoUrl'", ",", "'Not a valid YouTube or Vimeo URL.'", ")", ";", "return", "false", ";", "}", "}", "}" ]
Form Validation callback, checks that a YouTube or Vimeo ID can be extracted from the string @param string $sUrl The URL to check @return boolean
[ "Form", "Validation", "callback", "checks", "that", "a", "YouTube", "or", "Vimeo", "ID", "can", "be", "extracted", "from", "the", "string" ]
7b369c5209f4343fff7c7e2a22c237d5a95c8c24
https://github.com/nails/module-blog/blob/7b369c5209f4343fff7c7e2a22c237d5a95c8c24/admin/controllers/Post.php#L945-L968
train
zhaoxianfang/tools
src/Symfony/Component/Config/Definition/ArrayNode.php
ArrayNode.validateType
protected function validateType($value) { if (!is_array($value) && (!$this->allowFalse || false !== $value)) { $ex = new InvalidTypeException(sprintf( 'Invalid type for path "%s". Expected array, but got %s', $this->getPath(), gettype($value) )); if ($hint = $this->getInfo()) { $ex->addHint($hint); } $ex->setPath($this->getPath()); throw $ex; } }
php
protected function validateType($value) { if (!is_array($value) && (!$this->allowFalse || false !== $value)) { $ex = new InvalidTypeException(sprintf( 'Invalid type for path "%s". Expected array, but got %s', $this->getPath(), gettype($value) )); if ($hint = $this->getInfo()) { $ex->addHint($hint); } $ex->setPath($this->getPath()); throw $ex; } }
[ "protected", "function", "validateType", "(", "$", "value", ")", "{", "if", "(", "!", "is_array", "(", "$", "value", ")", "&&", "(", "!", "$", "this", "->", "allowFalse", "||", "false", "!==", "$", "value", ")", ")", "{", "$", "ex", "=", "new", "InvalidTypeException", "(", "sprintf", "(", "'Invalid type for path \"%s\". Expected array, but got %s'", ",", "$", "this", "->", "getPath", "(", ")", ",", "gettype", "(", "$", "value", ")", ")", ")", ";", "if", "(", "$", "hint", "=", "$", "this", "->", "getInfo", "(", ")", ")", "{", "$", "ex", "->", "addHint", "(", "$", "hint", ")", ";", "}", "$", "ex", "->", "setPath", "(", "$", "this", "->", "getPath", "(", ")", ")", ";", "throw", "$", "ex", ";", "}", "}" ]
Validates the type of the value. @param mixed $value @throws InvalidTypeException
[ "Validates", "the", "type", "of", "the", "value", "." ]
d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7
https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/Config/Definition/ArrayNode.php#L264-L279
train
ekyna/Resource
Dispatcher/ResourceEventDispatcherTrait.php
ResourceEventDispatcherTrait.getResourceEventName
public function getResourceEventName(ResourceInterface $resource, $suffix) { if (null !== $configuration = $this->registry->findConfiguration($resource, false)) { return sprintf('%s.%s', $configuration->getResourceId(), $suffix); } // TODO throw exception ? return null; }
php
public function getResourceEventName(ResourceInterface $resource, $suffix) { if (null !== $configuration = $this->registry->findConfiguration($resource, false)) { return sprintf('%s.%s', $configuration->getResourceId(), $suffix); } // TODO throw exception ? return null; }
[ "public", "function", "getResourceEventName", "(", "ResourceInterface", "$", "resource", ",", "$", "suffix", ")", "{", "if", "(", "null", "!==", "$", "configuration", "=", "$", "this", "->", "registry", "->", "findConfiguration", "(", "$", "resource", ",", "false", ")", ")", "{", "return", "sprintf", "(", "'%s.%s'", ",", "$", "configuration", "->", "getResourceId", "(", ")", ",", "$", "suffix", ")", ";", "}", "// TODO throw exception ?", "return", "null", ";", "}" ]
Returns the resource event name. @param ResourceInterface $resource @param string $suffix @return string|null
[ "Returns", "the", "resource", "event", "name", "." ]
96ee3d28e02bd9513705408e3bb7f88a76e52f56
https://github.com/ekyna/Resource/blob/96ee3d28e02bd9513705408e3bb7f88a76e52f56/Dispatcher/ResourceEventDispatcherTrait.php#L92-L101
train
ptlis/grep-db
src/Metadata/MySQL/ServerMetadata.php
ServerMetadata.getDatabaseMetadata
public function getDatabaseMetadata(string $databaseName): DatabaseMetadata { if (!array_key_exists($databaseName, $this->databaseMetadataList)) { throw new \RuntimeException('Server "' . $this->host . '" doesn\'t contain database "' . $databaseName . '"'); } return $this->databaseMetadataList[$databaseName]; }
php
public function getDatabaseMetadata(string $databaseName): DatabaseMetadata { if (!array_key_exists($databaseName, $this->databaseMetadataList)) { throw new \RuntimeException('Server "' . $this->host . '" doesn\'t contain database "' . $databaseName . '"'); } return $this->databaseMetadataList[$databaseName]; }
[ "public", "function", "getDatabaseMetadata", "(", "string", "$", "databaseName", ")", ":", "DatabaseMetadata", "{", "if", "(", "!", "array_key_exists", "(", "$", "databaseName", ",", "$", "this", "->", "databaseMetadataList", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Server \"'", ".", "$", "this", "->", "host", ".", "'\" doesn\\'t contain database \"'", ".", "$", "databaseName", ".", "'\"'", ")", ";", "}", "return", "$", "this", "->", "databaseMetadataList", "[", "$", "databaseName", "]", ";", "}" ]
Returns database metadata for the specified database.
[ "Returns", "database", "metadata", "for", "the", "specified", "database", "." ]
7abff68982d426690d0515ccd7adc7a2e3d72a3f
https://github.com/ptlis/grep-db/blob/7abff68982d426690d0515ccd7adc7a2e3d72a3f/src/Metadata/MySQL/ServerMetadata.php#L56-L63
train
ytake/ConsoleKernel
src/Command.php
Command.configure
public function configure() { $this->setName($this->command); $this->setDescription($this->description); $this->arguments(); }
php
public function configure() { $this->setName($this->command); $this->setDescription($this->description); $this->arguments(); }
[ "public", "function", "configure", "(", ")", "{", "$", "this", "->", "setName", "(", "$", "this", "->", "command", ")", ";", "$", "this", "->", "setDescription", "(", "$", "this", "->", "description", ")", ";", "$", "this", "->", "arguments", "(", ")", ";", "}" ]
command interface configure @return void
[ "command", "interface", "configure" ]
605e6421f968c744c3ffaa07cba3ade1a7a6e623
https://github.com/ytake/ConsoleKernel/blob/605e6421f968c744c3ffaa07cba3ade1a7a6e623/src/Command.php#L55-L60
train
rzajac/phptools
src/Date/DateTime.php
DateTime.toMySQLDate
public function toMySQLDate($withTime = true) { if ($this->isHollow()) { return $withTime ? '0000-00-00 00:00:00' : '0000-00-00'; } $format = $withTime ? 'Y-m-d H:i:s' : 'Y-m-d'; return $this->format($format); }
php
public function toMySQLDate($withTime = true) { if ($this->isHollow()) { return $withTime ? '0000-00-00 00:00:00' : '0000-00-00'; } $format = $withTime ? 'Y-m-d H:i:s' : 'Y-m-d'; return $this->format($format); }
[ "public", "function", "toMySQLDate", "(", "$", "withTime", "=", "true", ")", "{", "if", "(", "$", "this", "->", "isHollow", "(", ")", ")", "{", "return", "$", "withTime", "?", "'0000-00-00 00:00:00'", ":", "'0000-00-00'", ";", "}", "$", "format", "=", "$", "withTime", "?", "'Y-m-d H:i:s'", ":", "'Y-m-d'", ";", "return", "$", "this", "->", "format", "(", "$", "format", ")", ";", "}" ]
Returns date in MySQL format. NOTE: It returns 0000-00-00 00:00:00 for hollow dates @param bool $withTime @return string
[ "Returns", "date", "in", "MySQL", "format", "." ]
3cbece7645942d244603c14ba897d8a676ee3088
https://github.com/rzajac/phptools/blob/3cbece7645942d244603c14ba897d8a676ee3088/src/Date/DateTime.php#L238-L247
train
rzajac/phptools
src/Date/DateTime.php
DateTime.addMonths
public function addMonths($delta) { $interval = new DateInterval('P'.abs($delta).'M'); if ($delta > 0) { $this->add($interval); } elseif ($delta < 0) { $this->sub($interval); } return $this; }
php
public function addMonths($delta) { $interval = new DateInterval('P'.abs($delta).'M'); if ($delta > 0) { $this->add($interval); } elseif ($delta < 0) { $this->sub($interval); } return $this; }
[ "public", "function", "addMonths", "(", "$", "delta", ")", "{", "$", "interval", "=", "new", "DateInterval", "(", "'P'", ".", "abs", "(", "$", "delta", ")", ".", "'M'", ")", ";", "if", "(", "$", "delta", ">", "0", ")", "{", "$", "this", "->", "add", "(", "$", "interval", ")", ";", "}", "elseif", "(", "$", "delta", "<", "0", ")", "{", "$", "this", "->", "sub", "(", "$", "interval", ")", ";", "}", "return", "$", "this", ";", "}" ]
Go x months before or ahead. @param int $delta The number of months to add or subtract @return static
[ "Go", "x", "months", "before", "or", "ahead", "." ]
3cbece7645942d244603c14ba897d8a676ee3088
https://github.com/rzajac/phptools/blob/3cbece7645942d244603c14ba897d8a676ee3088/src/Date/DateTime.php#L386-L397
train
rzajac/phptools
src/Date/DateTime.php
DateTime.getCurrentYear
public static function getCurrentYear($inUTC = false, $format = self::YEAR_FORMAT_LONG) { $tz = $inUTC ? 'UTC' : null; return (int) static::now($tz)->format($format); }
php
public static function getCurrentYear($inUTC = false, $format = self::YEAR_FORMAT_LONG) { $tz = $inUTC ? 'UTC' : null; return (int) static::now($tz)->format($format); }
[ "public", "static", "function", "getCurrentYear", "(", "$", "inUTC", "=", "false", ",", "$", "format", "=", "self", "::", "YEAR_FORMAT_LONG", ")", "{", "$", "tz", "=", "$", "inUTC", "?", "'UTC'", ":", "null", ";", "return", "(", "int", ")", "static", "::", "now", "(", "$", "tz", ")", "->", "format", "(", "$", "format", ")", ";", "}" ]
Get current year. @param bool $inUTC @param string $format @return int
[ "Get", "current", "year", "." ]
3cbece7645942d244603c14ba897d8a676ee3088
https://github.com/rzajac/phptools/blob/3cbece7645942d244603c14ba897d8a676ee3088/src/Date/DateTime.php#L420-L425
train
rzajac/phptools
src/Date/DateTime.php
DateTime.getCurrentMonth
public static function getCurrentMonth($inUTC = false) { $tz = $inUTC ? 'UTC' : null; return (int) static::now($tz)->format('n'); }
php
public static function getCurrentMonth($inUTC = false) { $tz = $inUTC ? 'UTC' : null; return (int) static::now($tz)->format('n'); }
[ "public", "static", "function", "getCurrentMonth", "(", "$", "inUTC", "=", "false", ")", "{", "$", "tz", "=", "$", "inUTC", "?", "'UTC'", ":", "null", ";", "return", "(", "int", ")", "static", "::", "now", "(", "$", "tz", ")", "->", "format", "(", "'n'", ")", ";", "}" ]
Get current month. @param bool $inUTC @return int
[ "Get", "current", "month", "." ]
3cbece7645942d244603c14ba897d8a676ee3088
https://github.com/rzajac/phptools/blob/3cbece7645942d244603c14ba897d8a676ee3088/src/Date/DateTime.php#L434-L439
train
rzajac/phptools
src/Date/DateTime.php
DateTime.getCurrentHour
public static function getCurrentHour($inUTC = false) { $tz = $inUTC ? 'UTC' : null; return (int) static::now($tz)->format('G'); }
php
public static function getCurrentHour($inUTC = false) { $tz = $inUTC ? 'UTC' : null; return (int) static::now($tz)->format('G'); }
[ "public", "static", "function", "getCurrentHour", "(", "$", "inUTC", "=", "false", ")", "{", "$", "tz", "=", "$", "inUTC", "?", "'UTC'", ":", "null", ";", "return", "(", "int", ")", "static", "::", "now", "(", "$", "tz", ")", "->", "format", "(", "'G'", ")", ";", "}" ]
Get current hour. @param bool $inUTC @return int
[ "Get", "current", "hour", "." ]
3cbece7645942d244603c14ba897d8a676ee3088
https://github.com/rzajac/phptools/blob/3cbece7645942d244603c14ba897d8a676ee3088/src/Date/DateTime.php#L448-L453
train
rzajac/phptools
src/Date/DateTime.php
DateTime.getCurrentMinutes
public static function getCurrentMinutes($inUTC = false) { $tz = $inUTC ? 'UTC' : null; return (int) static::now($tz)->format('i'); }
php
public static function getCurrentMinutes($inUTC = false) { $tz = $inUTC ? 'UTC' : null; return (int) static::now($tz)->format('i'); }
[ "public", "static", "function", "getCurrentMinutes", "(", "$", "inUTC", "=", "false", ")", "{", "$", "tz", "=", "$", "inUTC", "?", "'UTC'", ":", "null", ";", "return", "(", "int", ")", "static", "::", "now", "(", "$", "tz", ")", "->", "format", "(", "'i'", ")", ";", "}" ]
Get current minutes. @param bool $inUTC @return int
[ "Get", "current", "minutes", "." ]
3cbece7645942d244603c14ba897d8a676ee3088
https://github.com/rzajac/phptools/blob/3cbece7645942d244603c14ba897d8a676ee3088/src/Date/DateTime.php#L462-L467
train
rzajac/phptools
src/Date/DateTime.php
DateTime.targetSerialize
public function targetSerialize($target = self::SER_DEFAULT, $params = null) { return $this->format($this->format); }
php
public function targetSerialize($target = self::SER_DEFAULT, $params = null) { return $this->format($this->format); }
[ "public", "function", "targetSerialize", "(", "$", "target", "=", "self", "::", "SER_DEFAULT", ",", "$", "params", "=", "null", ")", "{", "return", "$", "this", "->", "format", "(", "$", "this", "->", "format", ")", ";", "}" ]
Serialize object for given target. @param string $target The serialization target (one of the TSer constants) @param mixed $params The additional parameters that serializer might need @throws \Exception @return \stdClass|string|array|NULL
[ "Serialize", "object", "for", "given", "target", "." ]
3cbece7645942d244603c14ba897d8a676ee3088
https://github.com/rzajac/phptools/blob/3cbece7645942d244603c14ba897d8a676ee3088/src/Date/DateTime.php#L517-L520
train
Dhii/stringable-helper-base
src/StringableReplaceCapableTrait.php
StringableReplaceCapableTrait._stringableReplace
public function _stringableReplace($search, $replace, $subject) { $search = $this->_normalizeString($search); $replace = $this->_normalizeString($replace); $subject = $this->_normalizeString($subject); return str_replace($search, $replace, $subject); }
php
public function _stringableReplace($search, $replace, $subject) { $search = $this->_normalizeString($search); $replace = $this->_normalizeString($replace); $subject = $this->_normalizeString($subject); return str_replace($search, $replace, $subject); }
[ "public", "function", "_stringableReplace", "(", "$", "search", ",", "$", "replace", ",", "$", "subject", ")", "{", "$", "search", "=", "$", "this", "->", "_normalizeString", "(", "$", "search", ")", ";", "$", "replace", "=", "$", "this", "->", "_normalizeString", "(", "$", "replace", ")", ";", "$", "subject", "=", "$", "this", "->", "_normalizeString", "(", "$", "subject", ")", ";", "return", "str_replace", "(", "$", "search", ",", "$", "replace", ",", "$", "subject", ")", ";", "}" ]
Replaces occurrences of needle in haystack. @since [*next-version*] @see str_replace() @param string|Stringable $search The string to look for. @param string|Stringable $replace The string to replace with. @param string|Stringable $subject The string look in. @throw InvalidArgumentException If the needle, replacement, or haystack is invalid. @throw RuntimeException If problem replacing. @return string The haystack with all occurrences of needle replaced.
[ "Replaces", "occurrences", "of", "needle", "in", "haystack", "." ]
904254409800710665135a751659b59d140a2b40
https://github.com/Dhii/stringable-helper-base/blob/904254409800710665135a751659b59d140a2b40/src/StringableReplaceCapableTrait.php#L30-L37
train
the-eater/odango.php
src/NyaaUser.php
NyaaUser.construct
static function construct($name, $id, $aliases = []) { $user = new NyaaUser(); $user->name = $name; $user->id = $id; $user->aliases = $aliases; return $user; }
php
static function construct($name, $id, $aliases = []) { $user = new NyaaUser(); $user->name = $name; $user->id = $id; $user->aliases = $aliases; return $user; }
[ "static", "function", "construct", "(", "$", "name", ",", "$", "id", ",", "$", "aliases", "=", "[", "]", ")", "{", "$", "user", "=", "new", "NyaaUser", "(", ")", ";", "$", "user", "->", "name", "=", "$", "name", ";", "$", "user", "->", "id", "=", "$", "id", ";", "$", "user", "->", "aliases", "=", "$", "aliases", ";", "return", "$", "user", ";", "}" ]
Constructs a new NyaaUser @param string $name The name this NyaaUser works under @param int $id The id of the user @param array $aliases Array with aliases this NyaaUser works under @return NyaaUser
[ "Constructs", "a", "new", "NyaaUser" ]
6c78f983e7b3c49ff2f8a10ce7299747d3c82e3f
https://github.com/the-eater/odango.php/blob/6c78f983e7b3c49ff2f8a10ce7299747d3c82e3f/src/NyaaUser.php#L18-L26
train
the-eater/odango.php
src/NyaaUser.php
NyaaUser.getKnown
static function getKnown() { return [ NyaaUser::construct('HorribleSubs', 64513), NyaaUser::construct('Commie', 76430), NyaaUser::construct('Cthuko', 227226, ['Cthune']), NyaaUser::construct('DeadFish', 169660), NyaaUser::construct('Coalgirls', 62260) ]; }
php
static function getKnown() { return [ NyaaUser::construct('HorribleSubs', 64513), NyaaUser::construct('Commie', 76430), NyaaUser::construct('Cthuko', 227226, ['Cthune']), NyaaUser::construct('DeadFish', 169660), NyaaUser::construct('Coalgirls', 62260) ]; }
[ "static", "function", "getKnown", "(", ")", "{", "return", "[", "NyaaUser", "::", "construct", "(", "'HorribleSubs'", ",", "64513", ")", ",", "NyaaUser", "::", "construct", "(", "'Commie'", ",", "76430", ")", ",", "NyaaUser", "::", "construct", "(", "'Cthuko'", ",", "227226", ",", "[", "'Cthune'", "]", ")", ",", "NyaaUser", "::", "construct", "(", "'DeadFish'", ",", "169660", ")", ",", "NyaaUser", "::", "construct", "(", "'Coalgirls'", ",", "62260", ")", "]", ";", "}" ]
Gets a list of known NyaaUsers @return NyaaUser[]
[ "Gets", "a", "list", "of", "known", "NyaaUsers" ]
6c78f983e7b3c49ff2f8a10ce7299747d3c82e3f
https://github.com/the-eater/odango.php/blob/6c78f983e7b3c49ff2f8a10ce7299747d3c82e3f/src/NyaaUser.php#L32-L41
train
wb-crowdfusion/crowdfusion
system/core/classes/mvc/filters/CondFilterer.php
CondFilterer.inArray
public function inArray() { $needle = $this->getParameter('value'); $haystack = $this->getParameter('array'); if($haystack instanceof Meta){ $haystack = $haystack->getMetaValue(); } if(is_string($haystack)) $haystack = StringUtils::smartExplode($haystack); return in_array($needle, (array)$haystack); }
php
public function inArray() { $needle = $this->getParameter('value'); $haystack = $this->getParameter('array'); if($haystack instanceof Meta){ $haystack = $haystack->getMetaValue(); } if(is_string($haystack)) $haystack = StringUtils::smartExplode($haystack); return in_array($needle, (array)$haystack); }
[ "public", "function", "inArray", "(", ")", "{", "$", "needle", "=", "$", "this", "->", "getParameter", "(", "'value'", ")", ";", "$", "haystack", "=", "$", "this", "->", "getParameter", "(", "'array'", ")", ";", "if", "(", "$", "haystack", "instanceof", "Meta", ")", "{", "$", "haystack", "=", "$", "haystack", "->", "getMetaValue", "(", ")", ";", "}", "if", "(", "is_string", "(", "$", "haystack", ")", ")", "$", "haystack", "=", "StringUtils", "::", "smartExplode", "(", "$", "haystack", ")", ";", "return", "in_array", "(", "$", "needle", ",", "(", "array", ")", "$", "haystack", ")", ";", "}" ]
Returns true if 'value' is found in array 'array' Expected Params: value string The item to search for in the array array array The array to search @return boolean true if value is in array
[ "Returns", "true", "if", "value", "is", "found", "in", "array", "array" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/filters/CondFilterer.php#L43-L56
train
wb-crowdfusion/crowdfusion
system/core/classes/mvc/filters/CondFilterer.php
CondFilterer.isItTimeYet
public function isItTimeYet() { $now = $this->DateFactory->newLocalDate(); $today = strtolower($now->format("D")); $days = $this->getParameter('days'); //sun,mon,tue,wed,thu,fri,sat $date = $this->getParameter('date'); //Y-m-d $startTime = $this->getParameter('startTime'); //H:i:s $endTime = $this->getParameter('endTime'); //H:i:s or +3 hours if($days != null && !in_array($today,explode(',',strtolower($days)))) { return false; } if($date != null && $now->format('Y-m-d') != $date) { return false; } if($startTime != null) { if($now < $this->DateFactory->newLocalDate($now->format('Y-m-d').' '.$startTime)) { return false; } if($endTime != null) { if(substr($endTime,0,1) == '+') $endTime = $startTime.' '.$endTime; if($now > $this->DateFactory->newLocalDate($now->format('Y-m-d').' '.$endTime)) { return false; } } } return true; }
php
public function isItTimeYet() { $now = $this->DateFactory->newLocalDate(); $today = strtolower($now->format("D")); $days = $this->getParameter('days'); //sun,mon,tue,wed,thu,fri,sat $date = $this->getParameter('date'); //Y-m-d $startTime = $this->getParameter('startTime'); //H:i:s $endTime = $this->getParameter('endTime'); //H:i:s or +3 hours if($days != null && !in_array($today,explode(',',strtolower($days)))) { return false; } if($date != null && $now->format('Y-m-d') != $date) { return false; } if($startTime != null) { if($now < $this->DateFactory->newLocalDate($now->format('Y-m-d').' '.$startTime)) { return false; } if($endTime != null) { if(substr($endTime,0,1) == '+') $endTime = $startTime.' '.$endTime; if($now > $this->DateFactory->newLocalDate($now->format('Y-m-d').' '.$endTime)) { return false; } } } return true; }
[ "public", "function", "isItTimeYet", "(", ")", "{", "$", "now", "=", "$", "this", "->", "DateFactory", "->", "newLocalDate", "(", ")", ";", "$", "today", "=", "strtolower", "(", "$", "now", "->", "format", "(", "\"D\"", ")", ")", ";", "$", "days", "=", "$", "this", "->", "getParameter", "(", "'days'", ")", ";", "//sun,mon,tue,wed,thu,fri,sat", "$", "date", "=", "$", "this", "->", "getParameter", "(", "'date'", ")", ";", "//Y-m-d", "$", "startTime", "=", "$", "this", "->", "getParameter", "(", "'startTime'", ")", ";", "//H:i:s", "$", "endTime", "=", "$", "this", "->", "getParameter", "(", "'endTime'", ")", ";", "//H:i:s or +3 hours", "if", "(", "$", "days", "!=", "null", "&&", "!", "in_array", "(", "$", "today", ",", "explode", "(", "','", ",", "strtolower", "(", "$", "days", ")", ")", ")", ")", "{", "return", "false", ";", "}", "if", "(", "$", "date", "!=", "null", "&&", "$", "now", "->", "format", "(", "'Y-m-d'", ")", "!=", "$", "date", ")", "{", "return", "false", ";", "}", "if", "(", "$", "startTime", "!=", "null", ")", "{", "if", "(", "$", "now", "<", "$", "this", "->", "DateFactory", "->", "newLocalDate", "(", "$", "now", "->", "format", "(", "'Y-m-d'", ")", ".", "' '", ".", "$", "startTime", ")", ")", "{", "return", "false", ";", "}", "if", "(", "$", "endTime", "!=", "null", ")", "{", "if", "(", "substr", "(", "$", "endTime", ",", "0", ",", "1", ")", "==", "'+'", ")", "$", "endTime", "=", "$", "startTime", ".", "' '", ".", "$", "endTime", ";", "if", "(", "$", "now", ">", "$", "this", "->", "DateFactory", "->", "newLocalDate", "(", "$", "now", "->", "format", "(", "'Y-m-d'", ")", ".", "' '", ".", "$", "endTime", ")", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
Returns true if now is within the specified date criteria; false otherwise. The server timezone is used for all dates. Expected Params: days string A comma-separated list of lowercase 3-character day abbreviations; today must match at least one of these days; optional date string A string in the format of Y-m-d; today must match this date; optional startTime string A string in the format of H:i:s; now must be equal to or after this time; optional endTime string A string in the format of H:i:s or '+X unit' (i.e. +3 hours); now must be before this time; optional @return boolean
[ "Returns", "true", "if", "now", "is", "within", "the", "specified", "date", "criteria", ";", "false", "otherwise", ".", "The", "server", "timezone", "is", "used", "for", "all", "dates", "." ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/filters/CondFilterer.php#L70-L106
train
field-interactive/cito-bundle
Cito/Pagelist.php
Pagelist.applySorting
public static function applySorting($pagelist, $sortOrder = null, $sortBy = null) { // sort order if (isset($sortOrder)) { switch ($sortOrder) { case 'asc': $sortOrder = 1; break; case 'desc': $sortOrder = -1; break; default: $sortOrder = 1; break; } } if (!isset($sortBy)) { $sortBy = 'name'; } // sort key usort( $pagelist, function ($a, $b) use ($sortBy, $sortOrder) { if (isset($sortBy)) { if (is_array($sortBy)) { $key = key($sortBy); $value = reset($sortBy); if (isset($a->$key)) { $temp = $a->$key; if (isset($temp[$value])) { $a = $temp[$value]; } } else { $a = 0; } if (isset($b->$key)) { $temp = $b->$key; if (isset($temp[$value])) { $b = $temp[$value]; } } else { $b = 0; } } else { $a = $a->{$sortBy}; $b = $b->{$sortBy}; } } if ($a == $b) { return 0; } $compareResult = ($a < $b) ? 1 : -1; return $sortOrder * $compareResult; } ); return $pagelist; }
php
public static function applySorting($pagelist, $sortOrder = null, $sortBy = null) { // sort order if (isset($sortOrder)) { switch ($sortOrder) { case 'asc': $sortOrder = 1; break; case 'desc': $sortOrder = -1; break; default: $sortOrder = 1; break; } } if (!isset($sortBy)) { $sortBy = 'name'; } // sort key usort( $pagelist, function ($a, $b) use ($sortBy, $sortOrder) { if (isset($sortBy)) { if (is_array($sortBy)) { $key = key($sortBy); $value = reset($sortBy); if (isset($a->$key)) { $temp = $a->$key; if (isset($temp[$value])) { $a = $temp[$value]; } } else { $a = 0; } if (isset($b->$key)) { $temp = $b->$key; if (isset($temp[$value])) { $b = $temp[$value]; } } else { $b = 0; } } else { $a = $a->{$sortBy}; $b = $b->{$sortBy}; } } if ($a == $b) { return 0; } $compareResult = ($a < $b) ? 1 : -1; return $sortOrder * $compareResult; } ); return $pagelist; }
[ "public", "static", "function", "applySorting", "(", "$", "pagelist", ",", "$", "sortOrder", "=", "null", ",", "$", "sortBy", "=", "null", ")", "{", "// sort order", "if", "(", "isset", "(", "$", "sortOrder", ")", ")", "{", "switch", "(", "$", "sortOrder", ")", "{", "case", "'asc'", ":", "$", "sortOrder", "=", "1", ";", "break", ";", "case", "'desc'", ":", "$", "sortOrder", "=", "-", "1", ";", "break", ";", "default", ":", "$", "sortOrder", "=", "1", ";", "break", ";", "}", "}", "if", "(", "!", "isset", "(", "$", "sortBy", ")", ")", "{", "$", "sortBy", "=", "'name'", ";", "}", "// sort key", "usort", "(", "$", "pagelist", ",", "function", "(", "$", "a", ",", "$", "b", ")", "use", "(", "$", "sortBy", ",", "$", "sortOrder", ")", "{", "if", "(", "isset", "(", "$", "sortBy", ")", ")", "{", "if", "(", "is_array", "(", "$", "sortBy", ")", ")", "{", "$", "key", "=", "key", "(", "$", "sortBy", ")", ";", "$", "value", "=", "reset", "(", "$", "sortBy", ")", ";", "if", "(", "isset", "(", "$", "a", "->", "$", "key", ")", ")", "{", "$", "temp", "=", "$", "a", "->", "$", "key", ";", "if", "(", "isset", "(", "$", "temp", "[", "$", "value", "]", ")", ")", "{", "$", "a", "=", "$", "temp", "[", "$", "value", "]", ";", "}", "}", "else", "{", "$", "a", "=", "0", ";", "}", "if", "(", "isset", "(", "$", "b", "->", "$", "key", ")", ")", "{", "$", "temp", "=", "$", "b", "->", "$", "key", ";", "if", "(", "isset", "(", "$", "temp", "[", "$", "value", "]", ")", ")", "{", "$", "b", "=", "$", "temp", "[", "$", "value", "]", ";", "}", "}", "else", "{", "$", "b", "=", "0", ";", "}", "}", "else", "{", "$", "a", "=", "$", "a", "->", "{", "$", "sortBy", "}", ";", "$", "b", "=", "$", "b", "->", "{", "$", "sortBy", "}", ";", "}", "}", "if", "(", "$", "a", "==", "$", "b", ")", "{", "return", "0", ";", "}", "$", "compareResult", "=", "(", "$", "a", "<", "$", "b", ")", "?", "1", ":", "-", "1", ";", "return", "$", "sortOrder", "*", "$", "compareResult", ";", "}", ")", ";", "return", "$", "pagelist", ";", "}" ]
Sorting method. @param array $pagelist Pagelist array @param string $sortOrder Sort order @param string $sortBy Sort key @return array $pagelist
[ "Sorting", "method", "." ]
41cab570f960d964916e278c616720b17de258c1
https://github.com/field-interactive/cito-bundle/blob/41cab570f960d964916e278c616720b17de258c1/Cito/Pagelist.php#L29-L92
train
field-interactive/cito-bundle
Cito/Pagelist.php
Pagelist.applyFilter
public static function applyFilter($pageList, $filterFunction = null) { if (isset($filterFunction)) { $pageList = array_filter($pageList, $filterFunction); } return $pageList; }
php
public static function applyFilter($pageList, $filterFunction = null) { if (isset($filterFunction)) { $pageList = array_filter($pageList, $filterFunction); } return $pageList; }
[ "public", "static", "function", "applyFilter", "(", "$", "pageList", ",", "$", "filterFunction", "=", "null", ")", "{", "if", "(", "isset", "(", "$", "filterFunction", ")", ")", "{", "$", "pageList", "=", "array_filter", "(", "$", "pageList", ",", "$", "filterFunction", ")", ";", "}", "return", "$", "pageList", ";", "}" ]
Filter method. @param array $pagelist Pagelist array @param $filterFunction Callback function @return array $pagelist
[ "Filter", "method", "." ]
41cab570f960d964916e278c616720b17de258c1
https://github.com/field-interactive/cito-bundle/blob/41cab570f960d964916e278c616720b17de258c1/Cito/Pagelist.php#L102-L109
train
field-interactive/cito-bundle
Cito/Pagelist.php
Pagelist.applyLimit
public static function applyLimit($pageList, $limit = null) { if (isset($limit)) { $pageList = array_slice($pageList, 0, $limit); } return $pageList; }
php
public static function applyLimit($pageList, $limit = null) { if (isset($limit)) { $pageList = array_slice($pageList, 0, $limit); } return $pageList; }
[ "public", "static", "function", "applyLimit", "(", "$", "pageList", ",", "$", "limit", "=", "null", ")", "{", "if", "(", "isset", "(", "$", "limit", ")", ")", "{", "$", "pageList", "=", "array_slice", "(", "$", "pageList", ",", "0", ",", "$", "limit", ")", ";", "}", "return", "$", "pageList", ";", "}" ]
Limit method. @param string $pagelist Pagelist array @param int $limit Limit entries @return array $pagelist
[ "Limit", "method", "." ]
41cab570f960d964916e278c616720b17de258c1
https://github.com/field-interactive/cito-bundle/blob/41cab570f960d964916e278c616720b17de258c1/Cito/Pagelist.php#L119-L126
train
field-interactive/cito-bundle
Cito/Pagelist.php
Pagelist.dir
public static function dir(\Twig_Environment $environment, $dir, $current, $sortOrder = null, $sortBy = 'link', $filter = null, $limit = null, $userAgentEnabled = false) { $pagelist = []; // create new instance $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($dir), \RecursiveIteratorIterator::SELF_FIRST ); foreach ($iterator as $item) { if (!strpos(str_replace('\\', '/', $item->getPathname()), $current) && $item->isFile()) { $fullPath = $item->getPathname(); $relativePath = Page::generateRelativePath($fullPath); $template = $environment->load($relativePath); $page = new Page($template, [], $userAgentEnabled); $pagelist[] = $page; } } // apply filter // $pagelist = self::applyFilter( $pagelist, $filter ); // apply sorting $pagelist = self::applySorting($pagelist, $sortOrder, $sortBy); // apply limit $pagelist = self::applyLimit($pagelist, $limit); return new ArrayIterator($pagelist); }
php
public static function dir(\Twig_Environment $environment, $dir, $current, $sortOrder = null, $sortBy = 'link', $filter = null, $limit = null, $userAgentEnabled = false) { $pagelist = []; // create new instance $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($dir), \RecursiveIteratorIterator::SELF_FIRST ); foreach ($iterator as $item) { if (!strpos(str_replace('\\', '/', $item->getPathname()), $current) && $item->isFile()) { $fullPath = $item->getPathname(); $relativePath = Page::generateRelativePath($fullPath); $template = $environment->load($relativePath); $page = new Page($template, [], $userAgentEnabled); $pagelist[] = $page; } } // apply filter // $pagelist = self::applyFilter( $pagelist, $filter ); // apply sorting $pagelist = self::applySorting($pagelist, $sortOrder, $sortBy); // apply limit $pagelist = self::applyLimit($pagelist, $limit); return new ArrayIterator($pagelist); }
[ "public", "static", "function", "dir", "(", "\\", "Twig_Environment", "$", "environment", ",", "$", "dir", ",", "$", "current", ",", "$", "sortOrder", "=", "null", ",", "$", "sortBy", "=", "'link'", ",", "$", "filter", "=", "null", ",", "$", "limit", "=", "null", ",", "$", "userAgentEnabled", "=", "false", ")", "{", "$", "pagelist", "=", "[", "]", ";", "// create new instance", "$", "iterator", "=", "new", "\\", "RecursiveIteratorIterator", "(", "new", "\\", "RecursiveDirectoryIterator", "(", "$", "dir", ")", ",", "\\", "RecursiveIteratorIterator", "::", "SELF_FIRST", ")", ";", "foreach", "(", "$", "iterator", "as", "$", "item", ")", "{", "if", "(", "!", "strpos", "(", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "$", "item", "->", "getPathname", "(", ")", ")", ",", "$", "current", ")", "&&", "$", "item", "->", "isFile", "(", ")", ")", "{", "$", "fullPath", "=", "$", "item", "->", "getPathname", "(", ")", ";", "$", "relativePath", "=", "Page", "::", "generateRelativePath", "(", "$", "fullPath", ")", ";", "$", "template", "=", "$", "environment", "->", "load", "(", "$", "relativePath", ")", ";", "$", "page", "=", "new", "Page", "(", "$", "template", ",", "[", "]", ",", "$", "userAgentEnabled", ")", ";", "$", "pagelist", "[", "]", "=", "$", "page", ";", "}", "}", "// apply filter", "// $pagelist = self::applyFilter( $pagelist, $filter );", "// apply sorting", "$", "pagelist", "=", "self", "::", "applySorting", "(", "$", "pagelist", ",", "$", "sortOrder", ",", "$", "sortBy", ")", ";", "// apply limit", "$", "pagelist", "=", "self", "::", "applyLimit", "(", "$", "pagelist", ",", "$", "limit", ")", ";", "return", "new", "ArrayIterator", "(", "$", "pagelist", ")", ";", "}" ]
Static helper method for directory listings. @param \Twig_Environment $environment @param string $dir Path to list @param string $current @param string $sortOrder @param string $sortBy @param string $filter @param int $limit @return ArrayIterator @throws \Twig_Error_Loader @throws \Twig_Error_Runtime @throws \Twig_Error_Syntax
[ "Static", "helper", "method", "for", "directory", "listings", "." ]
41cab570f960d964916e278c616720b17de258c1
https://github.com/field-interactive/cito-bundle/blob/41cab570f960d964916e278c616720b17de258c1/Cito/Pagelist.php#L145-L175
train
field-interactive/cito-bundle
Cito/Pagelist.php
Pagelist.files
public static function files(\Twig_Environment $environment, $files, $current, $sortOrder = null, $sortBy = null, $filter = null, $userAgentEnabled = false) { $pagelist = []; foreach ($files as $file) { if (!strpos($file, $current)) { $relativePath = Page::generateRelativePath($file); $template = $environment->load($relativePath); $page = new Page($template, [], $userAgentEnabled); $pagelist[] = $page; } } // apply filter // $pagelist = self::applyFilter( $pagelist, $filter ); if (isset($sortBy)) { $pagelist = self::applySorting($pagelist, $sortOrder, $sortBy); } return new ArrayIterator($pagelist); }
php
public static function files(\Twig_Environment $environment, $files, $current, $sortOrder = null, $sortBy = null, $filter = null, $userAgentEnabled = false) { $pagelist = []; foreach ($files as $file) { if (!strpos($file, $current)) { $relativePath = Page::generateRelativePath($file); $template = $environment->load($relativePath); $page = new Page($template, [], $userAgentEnabled); $pagelist[] = $page; } } // apply filter // $pagelist = self::applyFilter( $pagelist, $filter ); if (isset($sortBy)) { $pagelist = self::applySorting($pagelist, $sortOrder, $sortBy); } return new ArrayIterator($pagelist); }
[ "public", "static", "function", "files", "(", "\\", "Twig_Environment", "$", "environment", ",", "$", "files", ",", "$", "current", ",", "$", "sortOrder", "=", "null", ",", "$", "sortBy", "=", "null", ",", "$", "filter", "=", "null", ",", "$", "userAgentEnabled", "=", "false", ")", "{", "$", "pagelist", "=", "[", "]", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "if", "(", "!", "strpos", "(", "$", "file", ",", "$", "current", ")", ")", "{", "$", "relativePath", "=", "Page", "::", "generateRelativePath", "(", "$", "file", ")", ";", "$", "template", "=", "$", "environment", "->", "load", "(", "$", "relativePath", ")", ";", "$", "page", "=", "new", "Page", "(", "$", "template", ",", "[", "]", ",", "$", "userAgentEnabled", ")", ";", "$", "pagelist", "[", "]", "=", "$", "page", ";", "}", "}", "// apply filter", "// $pagelist = self::applyFilter( $pagelist, $filter );", "if", "(", "isset", "(", "$", "sortBy", ")", ")", "{", "$", "pagelist", "=", "self", "::", "applySorting", "(", "$", "pagelist", ",", "$", "sortOrder", ",", "$", "sortBy", ")", ";", "}", "return", "new", "ArrayIterator", "(", "$", "pagelist", ")", ";", "}" ]
Static helper method for file listings. @param \Twig_Environment $environment @param array $files Files to list @param $current @param null $sortOrder @param string $sortBy @param null $filter @return ArrayIterator @throws \Twig_Error_Loader @throws \Twig_Error_Runtime @throws \Twig_Error_Syntax
[ "Static", "helper", "method", "for", "file", "listings", "." ]
41cab570f960d964916e278c616720b17de258c1
https://github.com/field-interactive/cito-bundle/blob/41cab570f960d964916e278c616720b17de258c1/Cito/Pagelist.php#L193-L213
train
EdwinDayot/shorty-framework
src/Framework/Routing/Router.php
Router.build
public function build() { $uri = $this->trimTrailingSlashes($this->request->getUri()->getPath()); $method = mb_strtoupper($this->request->getMethod()); foreach ($this->routes[$method] as $routeUri => $action) { $arguments = $this->match($uri, $routeUri); if (!is_null($arguments)) { return $this->constructAction($action, $arguments); } } throw new HTTPException('Not found', 404); }
php
public function build() { $uri = $this->trimTrailingSlashes($this->request->getUri()->getPath()); $method = mb_strtoupper($this->request->getMethod()); foreach ($this->routes[$method] as $routeUri => $action) { $arguments = $this->match($uri, $routeUri); if (!is_null($arguments)) { return $this->constructAction($action, $arguments); } } throw new HTTPException('Not found', 404); }
[ "public", "function", "build", "(", ")", "{", "$", "uri", "=", "$", "this", "->", "trimTrailingSlashes", "(", "$", "this", "->", "request", "->", "getUri", "(", ")", "->", "getPath", "(", ")", ")", ";", "$", "method", "=", "mb_strtoupper", "(", "$", "this", "->", "request", "->", "getMethod", "(", ")", ")", ";", "foreach", "(", "$", "this", "->", "routes", "[", "$", "method", "]", "as", "$", "routeUri", "=>", "$", "action", ")", "{", "$", "arguments", "=", "$", "this", "->", "match", "(", "$", "uri", ",", "$", "routeUri", ")", ";", "if", "(", "!", "is_null", "(", "$", "arguments", ")", ")", "{", "return", "$", "this", "->", "constructAction", "(", "$", "action", ",", "$", "arguments", ")", ";", "}", "}", "throw", "new", "HTTPException", "(", "'Not found'", ",", "404", ")", ";", "}" ]
Handle the route. @throws \Shorty\Framework\Routing\Exceptions\HTTPException @return bool
[ "Handle", "the", "route", "." ]
e03c991ea86aedbd87674d1ee2f9041b55b5e578
https://github.com/EdwinDayot/shorty-framework/blob/e03c991ea86aedbd87674d1ee2f9041b55b5e578/src/Framework/Routing/Router.php#L68-L82
train
EdwinDayot/shorty-framework
src/Framework/Routing/Router.php
Router.triggerAction
private function triggerAction($action): Response { if (is_callable($action)) { return $this->returnResponse( $this->container->call($action) ); } elseif (is_array($action)) { return $this->returnResponse( $this->container->call( [ $action['controller'], $action['method'], ], $action['arguments'] ) ); } throw new \InvalidArgumentException('Route\'s action could not be handled.'); }
php
private function triggerAction($action): Response { if (is_callable($action)) { return $this->returnResponse( $this->container->call($action) ); } elseif (is_array($action)) { return $this->returnResponse( $this->container->call( [ $action['controller'], $action['method'], ], $action['arguments'] ) ); } throw new \InvalidArgumentException('Route\'s action could not be handled.'); }
[ "private", "function", "triggerAction", "(", "$", "action", ")", ":", "Response", "{", "if", "(", "is_callable", "(", "$", "action", ")", ")", "{", "return", "$", "this", "->", "returnResponse", "(", "$", "this", "->", "container", "->", "call", "(", "$", "action", ")", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "action", ")", ")", "{", "return", "$", "this", "->", "returnResponse", "(", "$", "this", "->", "container", "->", "call", "(", "[", "$", "action", "[", "'controller'", "]", ",", "$", "action", "[", "'method'", "]", ",", "]", ",", "$", "action", "[", "'arguments'", "]", ")", ")", ";", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "'Route\\'s action could not be handled.'", ")", ";", "}" ]
Triggers an action. @param $action @throws \Shorty\Framework\Routing\Exceptions\HTTPException @return \GuzzleHttp\Psr7\Response
[ "Triggers", "an", "action", "." ]
e03c991ea86aedbd87674d1ee2f9041b55b5e578
https://github.com/EdwinDayot/shorty-framework/blob/e03c991ea86aedbd87674d1ee2f9041b55b5e578/src/Framework/Routing/Router.php#L149-L168
train
EdwinDayot/shorty-framework
src/Framework/Routing/Router.php
Router.returnResponse
private function returnResponse($result): Response { if ($result instanceof Response) { return $result; } if (is_array($result)) { $result = json_encode($result); } return new Response(200, [], $result); }
php
private function returnResponse($result): Response { if ($result instanceof Response) { return $result; } if (is_array($result)) { $result = json_encode($result); } return new Response(200, [], $result); }
[ "private", "function", "returnResponse", "(", "$", "result", ")", ":", "Response", "{", "if", "(", "$", "result", "instanceof", "Response", ")", "{", "return", "$", "result", ";", "}", "if", "(", "is_array", "(", "$", "result", ")", ")", "{", "$", "result", "=", "json_encode", "(", "$", "result", ")", ";", "}", "return", "new", "Response", "(", "200", ",", "[", "]", ",", "$", "result", ")", ";", "}" ]
Returns a Response object. @param mixed $result @return \GuzzleHttp\Psr7\Response|string
[ "Returns", "a", "Response", "object", "." ]
e03c991ea86aedbd87674d1ee2f9041b55b5e578
https://github.com/EdwinDayot/shorty-framework/blob/e03c991ea86aedbd87674d1ee2f9041b55b5e578/src/Framework/Routing/Router.php#L177-L188
train
EdwinDayot/shorty-framework
src/Framework/Routing/Router.php
Router.match
private function match(string $uri, string $routeUri): ?array { if ($uri === $routeUri) { return []; } return $this->getArguments($uri, $routeUri); }
php
private function match(string $uri, string $routeUri): ?array { if ($uri === $routeUri) { return []; } return $this->getArguments($uri, $routeUri); }
[ "private", "function", "match", "(", "string", "$", "uri", ",", "string", "$", "routeUri", ")", ":", "?", "array", "{", "if", "(", "$", "uri", "===", "$", "routeUri", ")", "{", "return", "[", "]", ";", "}", "return", "$", "this", "->", "getArguments", "(", "$", "uri", ",", "$", "routeUri", ")", ";", "}" ]
Matches the URI and route. @param string $uri @param string $routeUri @return array|null
[ "Matches", "the", "URI", "and", "route", "." ]
e03c991ea86aedbd87674d1ee2f9041b55b5e578
https://github.com/EdwinDayot/shorty-framework/blob/e03c991ea86aedbd87674d1ee2f9041b55b5e578/src/Framework/Routing/Router.php#L198-L205
train
EdwinDayot/shorty-framework
src/Framework/Routing/Router.php
Router.constructAction
private function constructAction($action, array $arguments = []): bool { if (is_callable($action)) { $this->pendingAction = $action; return true; } elseif (is_string($action)) { $actionParts = explode('@', $action); $controllerName = 'App\\Http\\Controllers\\' . $actionParts[0]; $methodName = $actionParts[1]; if (!class_exists($controllerName)) { throw new HTTPException('Not found', 404); } $controller = $this->container->get($controllerName); if (!method_exists($controller, $methodName)) { throw new HTTPException('Not found', 404); } $this->pendingAction = [ 'controller' => $controllerName, 'method' => $methodName, 'arguments' => $arguments, ]; return true; } return false; }
php
private function constructAction($action, array $arguments = []): bool { if (is_callable($action)) { $this->pendingAction = $action; return true; } elseif (is_string($action)) { $actionParts = explode('@', $action); $controllerName = 'App\\Http\\Controllers\\' . $actionParts[0]; $methodName = $actionParts[1]; if (!class_exists($controllerName)) { throw new HTTPException('Not found', 404); } $controller = $this->container->get($controllerName); if (!method_exists($controller, $methodName)) { throw new HTTPException('Not found', 404); } $this->pendingAction = [ 'controller' => $controllerName, 'method' => $methodName, 'arguments' => $arguments, ]; return true; } return false; }
[ "private", "function", "constructAction", "(", "$", "action", ",", "array", "$", "arguments", "=", "[", "]", ")", ":", "bool", "{", "if", "(", "is_callable", "(", "$", "action", ")", ")", "{", "$", "this", "->", "pendingAction", "=", "$", "action", ";", "return", "true", ";", "}", "elseif", "(", "is_string", "(", "$", "action", ")", ")", "{", "$", "actionParts", "=", "explode", "(", "'@'", ",", "$", "action", ")", ";", "$", "controllerName", "=", "'App\\\\Http\\\\Controllers\\\\'", ".", "$", "actionParts", "[", "0", "]", ";", "$", "methodName", "=", "$", "actionParts", "[", "1", "]", ";", "if", "(", "!", "class_exists", "(", "$", "controllerName", ")", ")", "{", "throw", "new", "HTTPException", "(", "'Not found'", ",", "404", ")", ";", "}", "$", "controller", "=", "$", "this", "->", "container", "->", "get", "(", "$", "controllerName", ")", ";", "if", "(", "!", "method_exists", "(", "$", "controller", ",", "$", "methodName", ")", ")", "{", "throw", "new", "HTTPException", "(", "'Not found'", ",", "404", ")", ";", "}", "$", "this", "->", "pendingAction", "=", "[", "'controller'", "=>", "$", "controllerName", ",", "'method'", "=>", "$", "methodName", ",", "'arguments'", "=>", "$", "arguments", ",", "]", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Construct action before running it. @param $action @param array $arguments @throws \Shorty\Framework\Routing\Exceptions\HTTPException @return bool
[ "Construct", "action", "before", "running", "it", "." ]
e03c991ea86aedbd87674d1ee2f9041b55b5e578
https://github.com/EdwinDayot/shorty-framework/blob/e03c991ea86aedbd87674d1ee2f9041b55b5e578/src/Framework/Routing/Router.php#L217-L249
train
EdwinDayot/shorty-framework
src/Framework/Routing/Router.php
Router.matchUri
private function matchUri(string $regex, string $uri): ?array { if (preg_match_all('/' . $regex . '/', $uri, $uriMatches)) { $uriMatches = array_filter($uriMatches, function ($key) { if (is_string($key)) { return true; } return false; }, ARRAY_FILTER_USE_KEY); $uriMatches = array_map(function ($match) { return $match[0]; }, $uriMatches); return $uriMatches; } return null; }
php
private function matchUri(string $regex, string $uri): ?array { if (preg_match_all('/' . $regex . '/', $uri, $uriMatches)) { $uriMatches = array_filter($uriMatches, function ($key) { if (is_string($key)) { return true; } return false; }, ARRAY_FILTER_USE_KEY); $uriMatches = array_map(function ($match) { return $match[0]; }, $uriMatches); return $uriMatches; } return null; }
[ "private", "function", "matchUri", "(", "string", "$", "regex", ",", "string", "$", "uri", ")", ":", "?", "array", "{", "if", "(", "preg_match_all", "(", "'/'", ".", "$", "regex", ".", "'/'", ",", "$", "uri", ",", "$", "uriMatches", ")", ")", "{", "$", "uriMatches", "=", "array_filter", "(", "$", "uriMatches", ",", "function", "(", "$", "key", ")", "{", "if", "(", "is_string", "(", "$", "key", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", ",", "ARRAY_FILTER_USE_KEY", ")", ";", "$", "uriMatches", "=", "array_map", "(", "function", "(", "$", "match", ")", "{", "return", "$", "match", "[", "0", "]", ";", "}", ",", "$", "uriMatches", ")", ";", "return", "$", "uriMatches", ";", "}", "return", "null", ";", "}" ]
Matches the URI. @param string $regex @param string $uri @return array|null
[ "Matches", "the", "URI", "." ]
e03c991ea86aedbd87674d1ee2f9041b55b5e578
https://github.com/EdwinDayot/shorty-framework/blob/e03c991ea86aedbd87674d1ee2f9041b55b5e578/src/Framework/Routing/Router.php#L258-L277
train
EdwinDayot/shorty-framework
src/Framework/Routing/Router.php
Router.getArguments
private function getArguments(string $uri, string $routeUri): ?array { if (preg_match_all('/({[a-z]+:)/i', $routeUri, $matches)) { $regex = str_replace('/', '\/', str_replace('}', ')', preg_replace('/{([a-z]+):/i', '(?<$1>', $routeUri) ) ); return $this->matchUri($regex, $uri); } return null; }
php
private function getArguments(string $uri, string $routeUri): ?array { if (preg_match_all('/({[a-z]+:)/i', $routeUri, $matches)) { $regex = str_replace('/', '\/', str_replace('}', ')', preg_replace('/{([a-z]+):/i', '(?<$1>', $routeUri) ) ); return $this->matchUri($regex, $uri); } return null; }
[ "private", "function", "getArguments", "(", "string", "$", "uri", ",", "string", "$", "routeUri", ")", ":", "?", "array", "{", "if", "(", "preg_match_all", "(", "'/({[a-z]+:)/i'", ",", "$", "routeUri", ",", "$", "matches", ")", ")", "{", "$", "regex", "=", "str_replace", "(", "'/'", ",", "'\\/'", ",", "str_replace", "(", "'}'", ",", "')'", ",", "preg_replace", "(", "'/{([a-z]+):/i'", ",", "'(?<$1>'", ",", "$", "routeUri", ")", ")", ")", ";", "return", "$", "this", "->", "matchUri", "(", "$", "regex", ",", "$", "uri", ")", ";", "}", "return", "null", ";", "}" ]
Get the arguments for the requested URI. @param string $uri @param string $routeUri @return array|null
[ "Get", "the", "arguments", "for", "the", "requested", "URI", "." ]
e03c991ea86aedbd87674d1ee2f9041b55b5e578
https://github.com/EdwinDayot/shorty-framework/blob/e03c991ea86aedbd87674d1ee2f9041b55b5e578/src/Framework/Routing/Router.php#L286-L299
train
modulusphp/http
Middleware/CheckForMaintenanceMode.php
CheckForMaintenanceMode.inExceptArray
protected function inExceptArray($request) { foreach ($this->except as $except) { if ($request->is($except)) { return true; } } return false; }
php
protected function inExceptArray($request) { foreach ($this->except as $except) { if ($request->is($except)) { return true; } } return false; }
[ "protected", "function", "inExceptArray", "(", "$", "request", ")", "{", "foreach", "(", "$", "this", "->", "except", "as", "$", "except", ")", "{", "if", "(", "$", "request", "->", "is", "(", "$", "except", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determine if the request has a URI that should be accessible in maintenance mode. @param \Modulus\Http\Request $request @return bool
[ "Determine", "if", "the", "request", "has", "a", "URI", "that", "should", "be", "accessible", "in", "maintenance", "mode", "." ]
fc5c0f2b582a04de1685578d3fb790686a0a240c
https://github.com/modulusphp/http/blob/fc5c0f2b582a04de1685578d3fb790686a0a240c/Middleware/CheckForMaintenanceMode.php#L65-L74
train
FuzeWorks/Core
src/FuzeWorks/TemplateEngine/SmartyEngine.php
SmartyEngine.loadSmarty
private function loadSmarty() { if (is_null($this->smartyInstance)) { $this->smartyInstance = new Smarty(); // Then prepare all variables $this->smartyInstance->setCompileDir(Core::$tempDir . DS . 'Smarty' . DS . 'Compile'); $this->smartyInstance->setCacheDir(Core::$tempDir . DS . 'Smarty'); } }
php
private function loadSmarty() { if (is_null($this->smartyInstance)) { $this->smartyInstance = new Smarty(); // Then prepare all variables $this->smartyInstance->setCompileDir(Core::$tempDir . DS . 'Smarty' . DS . 'Compile'); $this->smartyInstance->setCacheDir(Core::$tempDir . DS . 'Smarty'); } }
[ "private", "function", "loadSmarty", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "smartyInstance", ")", ")", "{", "$", "this", "->", "smartyInstance", "=", "new", "Smarty", "(", ")", ";", "// Then prepare all variables", "$", "this", "->", "smartyInstance", "->", "setCompileDir", "(", "Core", "::", "$", "tempDir", ".", "DS", ".", "'Smarty'", ".", "DS", ".", "'Compile'", ")", ";", "$", "this", "->", "smartyInstance", "->", "setCacheDir", "(", "Core", "::", "$", "tempDir", ".", "DS", ".", "'Smarty'", ")", ";", "}", "}" ]
Loads a Smarty instance if it is not already loaded.
[ "Loads", "a", "Smarty", "instance", "if", "it", "is", "not", "already", "loaded", "." ]
051c64fdaa3a648174cbd54557d05ad553dd826b
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/TemplateEngine/SmartyEngine.php#L95-L104
train
SlaxWeb/Router
src/Dispatcher.php
Dispatcher.enableSegMatch
public function enableSegMatch( string $namespace, array $params = [], string $prepend = "", string $defaultMethod = "index" ): Dispatcher { $this->segBasedMatch = [ "enabled" => true, "uriPrepend" => $prepend, "controller" => [ "namespace" => $namespace, "defaultMethod" => $defaultMethod, "params" => $params ] ]; return $this; }
php
public function enableSegMatch( string $namespace, array $params = [], string $prepend = "", string $defaultMethod = "index" ): Dispatcher { $this->segBasedMatch = [ "enabled" => true, "uriPrepend" => $prepend, "controller" => [ "namespace" => $namespace, "defaultMethod" => $defaultMethod, "params" => $params ] ]; return $this; }
[ "public", "function", "enableSegMatch", "(", "string", "$", "namespace", ",", "array", "$", "params", "=", "[", "]", ",", "string", "$", "prepend", "=", "\"\"", ",", "string", "$", "defaultMethod", "=", "\"index\"", ")", ":", "Dispatcher", "{", "$", "this", "->", "segBasedMatch", "=", "[", "\"enabled\"", "=>", "true", ",", "\"uriPrepend\"", "=>", "$", "prepend", ",", "\"controller\"", "=>", "[", "\"namespace\"", "=>", "$", "namespace", ",", "\"defaultMethod\"", "=>", "$", "defaultMethod", ",", "\"params\"", "=>", "$", "params", "]", "]", ";", "return", "$", "this", ";", "}" ]
Enable segment Based URI Matching Enables the segment based URI matching, sets the Controller namespace, and the default method to call if the second segment is not found in the URI. Default method has the default value of string("index"). @param string $namespace Controller namespace @param array $params Controller constructor parameters @param string $prepend URI prepend for segment based URI matching @param string $defaultMethod Default controller method for single segment URIs @return \SlaxWeb\Router\Dispatcher
[ "Enable", "segment", "Based", "URI", "Matching" ]
b4a25655710638c71787a8498d267a663ef2e819
https://github.com/SlaxWeb/Router/blob/b4a25655710638c71787a8498d267a663ef2e819/src/Dispatcher.php#L171-L187
train
SlaxWeb/Router
src/Dispatcher.php
Dispatcher.findRoute
protected function findRoute(int $method, string $uri) { $route = null; // if URI is empty and a default route is set, use it instead if ($uri !== "" || ($route = $this->routes->defaultRoute()) === null ) { return $this->checkContainer($method, $uri); } return $route; }
php
protected function findRoute(int $method, string $uri) { $route = null; // if URI is empty and a default route is set, use it instead if ($uri !== "" || ($route = $this->routes->defaultRoute()) === null ) { return $this->checkContainer($method, $uri); } return $route; }
[ "protected", "function", "findRoute", "(", "int", "$", "method", ",", "string", "$", "uri", ")", "{", "$", "route", "=", "null", ";", "// if URI is empty and a default route is set, use it instead", "if", "(", "$", "uri", "!==", "\"\"", "||", "(", "$", "route", "=", "$", "this", "->", "routes", "->", "defaultRoute", "(", ")", ")", "===", "null", ")", "{", "return", "$", "this", "->", "checkContainer", "(", "$", "method", ",", "$", "uri", ")", ";", "}", "return", "$", "route", ";", "}" ]
Find matching Route Try and obtain the route that bests fits the request and return it. If no such route is found, and no 404 route exists, nor is one returned from a 'routeNotFound' hook execution, null is returned. @param int $method Request Method @param string $uri Request Uri @return \SlaxWeb\Router\Route|null
[ "Find", "matching", "Route" ]
b4a25655710638c71787a8498d267a663ef2e819
https://github.com/SlaxWeb/Router/blob/b4a25655710638c71787a8498d267a663ef2e819/src/Dispatcher.php#L200-L210
train
SlaxWeb/Router
src/Dispatcher.php
Dispatcher.checkContainer
protected function checkContainer(int $method, string $uri) { while (($route = $this->routes->next()) !== false) { if (($route->method & $method) !== $method) { continue; } if (preg_match_all($this->posix2Pcre($route->uri), $uri, $matches) === 0) { continue; } $this->logger->info("Route match found"); if (is_array($matches)) { $this->addParams($matches); } return $route; } return null; }
php
protected function checkContainer(int $method, string $uri) { while (($route = $this->routes->next()) !== false) { if (($route->method & $method) !== $method) { continue; } if (preg_match_all($this->posix2Pcre($route->uri), $uri, $matches) === 0) { continue; } $this->logger->info("Route match found"); if (is_array($matches)) { $this->addParams($matches); } return $route; } return null; }
[ "protected", "function", "checkContainer", "(", "int", "$", "method", ",", "string", "$", "uri", ")", "{", "while", "(", "(", "$", "route", "=", "$", "this", "->", "routes", "->", "next", "(", ")", ")", "!==", "false", ")", "{", "if", "(", "(", "$", "route", "->", "method", "&", "$", "method", ")", "!==", "$", "method", ")", "{", "continue", ";", "}", "if", "(", "preg_match_all", "(", "$", "this", "->", "posix2Pcre", "(", "$", "route", "->", "uri", ")", ",", "$", "uri", ",", "$", "matches", ")", "===", "0", ")", "{", "continue", ";", "}", "$", "this", "->", "logger", "->", "info", "(", "\"Route match found\"", ")", ";", "if", "(", "is_array", "(", "$", "matches", ")", ")", "{", "$", "this", "->", "addParams", "(", "$", "matches", ")", ";", "}", "return", "$", "route", ";", "}", "return", "null", ";", "}" ]
Check Routes Container Iterates the routes container and tries to match the request to a Route in the container. Returns the matching Route object if found, or null otherwise. @param int $method Request Method @param string $uri Request Uri @return \SlaxWeb\Router\Route|null
[ "Check", "Routes", "Container" ]
b4a25655710638c71787a8498d267a663ef2e819
https://github.com/SlaxWeb/Router/blob/b4a25655710638c71787a8498d267a663ef2e819/src/Dispatcher.php#L222-L241
train
SlaxWeb/Router
src/Dispatcher.php
Dispatcher.handleNoMatch
protected function handleNoMatch() { $result = $this->hooks->exec("router.dispatcher.routeNotFound"); // check if hook call produced a valid Route object if ($result instanceof Route) { $this->logger->info("No Route found, hook call produced valid Route object, using it instead."); return $result; } elseif (is_array($result)) { foreach ($result as $r) { if ($r instanceof Route) { $this->logger->info("No Route found, hook call produced valid Route object, using it instead."); return $r; } } } return $this->routes->get404Route(); }
php
protected function handleNoMatch() { $result = $this->hooks->exec("router.dispatcher.routeNotFound"); // check if hook call produced a valid Route object if ($result instanceof Route) { $this->logger->info("No Route found, hook call produced valid Route object, using it instead."); return $result; } elseif (is_array($result)) { foreach ($result as $r) { if ($r instanceof Route) { $this->logger->info("No Route found, hook call produced valid Route object, using it instead."); return $r; } } } return $this->routes->get404Route(); }
[ "protected", "function", "handleNoMatch", "(", ")", "{", "$", "result", "=", "$", "this", "->", "hooks", "->", "exec", "(", "\"router.dispatcher.routeNotFound\"", ")", ";", "// check if hook call produced a valid Route object", "if", "(", "$", "result", "instanceof", "Route", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "\"No Route found, hook call produced valid Route object, using it instead.\"", ")", ";", "return", "$", "result", ";", "}", "elseif", "(", "is_array", "(", "$", "result", ")", ")", "{", "foreach", "(", "$", "result", "as", "$", "r", ")", "{", "if", "(", "$", "r", "instanceof", "Route", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "\"No Route found, hook call produced valid Route object, using it instead.\"", ")", ";", "return", "$", "r", ";", "}", "}", "}", "return", "$", "this", "->", "routes", "->", "get404Route", "(", ")", ";", "}" ]
Handle No Matching Route Found Execute the Route Not Found Hook definition with the help of the Hook component and return a valid Route object if it is found in the Hook execution return data. If no valid route is returned by the hook, try to obtain the 404 route from the Route Container object and return it. @return \SlaxWeb\Router\Route|null
[ "Handle", "No", "Matching", "Route", "Found" ]
b4a25655710638c71787a8498d267a663ef2e819
https://github.com/SlaxWeb/Router/blob/b4a25655710638c71787a8498d267a663ef2e819/src/Dispatcher.php#L253-L269
train
SlaxWeb/Router
src/Dispatcher.php
Dispatcher.posix2Pcre
protected function posix2Pcre( string $regex, array $names = ["params", "named"] ): string { $counters = []; foreach ($names as $type) { $regex = preg_replace_callback( "~\[:{$type}:\]~", function() use (&$counters, $type) { if (isset($counters[$type]) === false) { $counters[$type] = 0; } $counters[$type]++; $changed = "(?P<{$type}{$counters[$type]}>.+?)"; return $changed; }, $regex ); } return $regex; }
php
protected function posix2Pcre( string $regex, array $names = ["params", "named"] ): string { $counters = []; foreach ($names as $type) { $regex = preg_replace_callback( "~\[:{$type}:\]~", function() use (&$counters, $type) { if (isset($counters[$type]) === false) { $counters[$type] = 0; } $counters[$type]++; $changed = "(?P<{$type}{$counters[$type]}>.+?)"; return $changed; }, $regex ); } return $regex; }
[ "protected", "function", "posix2Pcre", "(", "string", "$", "regex", ",", "array", "$", "names", "=", "[", "\"params\"", ",", "\"named\"", "]", ")", ":", "string", "{", "$", "counters", "=", "[", "]", ";", "foreach", "(", "$", "names", "as", "$", "type", ")", "{", "$", "regex", "=", "preg_replace_callback", "(", "\"~\\[:{$type}:\\]~\"", ",", "function", "(", ")", "use", "(", "&", "$", "counters", ",", "$", "type", ")", "{", "if", "(", "isset", "(", "$", "counters", "[", "$", "type", "]", ")", "===", "false", ")", "{", "$", "counters", "[", "$", "type", "]", "=", "0", ";", "}", "$", "counters", "[", "$", "type", "]", "++", ";", "$", "changed", "=", "\"(?P<{$type}{$counters[$type]}>.+?)\"", ";", "return", "$", "changed", ";", "}", ",", "$", "regex", ")", ";", "}", "return", "$", "regex", ";", "}" ]
POSIX named class to PCRE capturing group Replace the special POSIX named classes with normal named capturing groups. @param string $regex Raw regexp string @param array $names POSIX class names array, default: ["params", "named"] @return string Replaced regexp string
[ "POSIX", "named", "class", "to", "PCRE", "capturing", "group" ]
b4a25655710638c71787a8498d267a663ef2e819
https://github.com/SlaxWeb/Router/blob/b4a25655710638c71787a8498d267a663ef2e819/src/Dispatcher.php#L367-L388
train
SlaxWeb/Router
src/Dispatcher.php
Dispatcher.addParams
protected function addParams(array $matches) { $params = []; foreach ($matches as $key => $value) { $value = $value[0]; if (strpos($key, "params") === 0) { $params["parameters"] = array_merge( $params["parameters"] ?? [], explode("/", $value) ); } if (strpos($key, "named") === 0) { $named = []; $key = ""; foreach (explode("/", $value) as $param) { if ($key === "") { $key = $param; $named[$key] = ""; } else { $named[$key] = $param; $key = ""; } } $params = array_merge($params, $named); } } $this->addQueryParams = $params; }
php
protected function addParams(array $matches) { $params = []; foreach ($matches as $key => $value) { $value = $value[0]; if (strpos($key, "params") === 0) { $params["parameters"] = array_merge( $params["parameters"] ?? [], explode("/", $value) ); } if (strpos($key, "named") === 0) { $named = []; $key = ""; foreach (explode("/", $value) as $param) { if ($key === "") { $key = $param; $named[$key] = ""; } else { $named[$key] = $param; $key = ""; } } $params = array_merge($params, $named); } } $this->addQueryParams = $params; }
[ "protected", "function", "addParams", "(", "array", "$", "matches", ")", "{", "$", "params", "=", "[", "]", ";", "foreach", "(", "$", "matches", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "value", "=", "$", "value", "[", "0", "]", ";", "if", "(", "strpos", "(", "$", "key", ",", "\"params\"", ")", "===", "0", ")", "{", "$", "params", "[", "\"parameters\"", "]", "=", "array_merge", "(", "$", "params", "[", "\"parameters\"", "]", "??", "[", "]", ",", "explode", "(", "\"/\"", ",", "$", "value", ")", ")", ";", "}", "if", "(", "strpos", "(", "$", "key", ",", "\"named\"", ")", "===", "0", ")", "{", "$", "named", "=", "[", "]", ";", "$", "key", "=", "\"\"", ";", "foreach", "(", "explode", "(", "\"/\"", ",", "$", "value", ")", "as", "$", "param", ")", "{", "if", "(", "$", "key", "===", "\"\"", ")", "{", "$", "key", "=", "$", "param", ";", "$", "named", "[", "$", "key", "]", "=", "\"\"", ";", "}", "else", "{", "$", "named", "[", "$", "key", "]", "=", "$", "param", ";", "$", "key", "=", "\"\"", ";", "}", "}", "$", "params", "=", "array_merge", "(", "$", "params", ",", "$", "named", ")", ";", "}", "}", "$", "this", "->", "addQueryParams", "=", "$", "params", ";", "}" ]
Add additional parameters Prepares the found matches from the URI and injects them into the 'addQueryParams' property. @param array $matches Regex matches @return void
[ "Add", "additional", "parameters" ]
b4a25655710638c71787a8498d267a663ef2e819
https://github.com/SlaxWeb/Router/blob/b4a25655710638c71787a8498d267a663ef2e819/src/Dispatcher.php#L399-L428
train
Retentio/Boomgo
src/Boomgo/Parser/AnnotationParser.php
AnnotationParser.parse
public function parse($filepath) { $metadata = array(); $reflectedClass = $this->getReflection($filepath); $metadata['class'] = $reflectedClass->getName(); $propertiesMetadata = $this->processPropertiesParsing($reflectedClass); $metadata = array_merge($metadata, $propertiesMetadata); return $metadata; }
php
public function parse($filepath) { $metadata = array(); $reflectedClass = $this->getReflection($filepath); $metadata['class'] = $reflectedClass->getName(); $propertiesMetadata = $this->processPropertiesParsing($reflectedClass); $metadata = array_merge($metadata, $propertiesMetadata); return $metadata; }
[ "public", "function", "parse", "(", "$", "filepath", ")", "{", "$", "metadata", "=", "array", "(", ")", ";", "$", "reflectedClass", "=", "$", "this", "->", "getReflection", "(", "$", "filepath", ")", ";", "$", "metadata", "[", "'class'", "]", "=", "$", "reflectedClass", "->", "getName", "(", ")", ";", "$", "propertiesMetadata", "=", "$", "this", "->", "processPropertiesParsing", "(", "$", "reflectedClass", ")", ";", "$", "metadata", "=", "array_merge", "(", "$", "metadata", ",", "$", "propertiesMetadata", ")", ";", "return", "$", "metadata", ";", "}" ]
ParserInterface implementation Extract className and metadata properties @param string $filepath @see ParserInterface::parse() @return array
[ "ParserInterface", "implementation", "Extract", "className", "and", "metadata", "properties" ]
95cc53777425dd76cd0034046fa4f9e72c04d73a
https://github.com/Retentio/Boomgo/blob/95cc53777425dd76cd0034046fa4f9e72c04d73a/src/Boomgo/Parser/AnnotationParser.php#L133-L144
train
Retentio/Boomgo
src/Boomgo/Parser/AnnotationParser.php
AnnotationParser.getReflection
protected function getReflection($filepath) { // Regexp instead of tokenizer because of the bad perf @link > https://gist.github.com/1886076 if (!preg_match('#^namespace\s+(.+?);.*class\s+(\w+).+;$#sm', file_get_contents($filepath), $captured)) { throw new \RuntimeException('Unable to find namespace or class declaration'); } $fqcn = $captured[1].'\\'.$captured[2]; try { $reflectedClass = new \ReflectionClass($fqcn); } catch (\ReflectionException $exception) { $this->registerAutoload($fqcn, $filepath); $reflectedClass = new \ReflectionClass($fqcn); } return $reflectedClass; }
php
protected function getReflection($filepath) { // Regexp instead of tokenizer because of the bad perf @link > https://gist.github.com/1886076 if (!preg_match('#^namespace\s+(.+?);.*class\s+(\w+).+;$#sm', file_get_contents($filepath), $captured)) { throw new \RuntimeException('Unable to find namespace or class declaration'); } $fqcn = $captured[1].'\\'.$captured[2]; try { $reflectedClass = new \ReflectionClass($fqcn); } catch (\ReflectionException $exception) { $this->registerAutoload($fqcn, $filepath); $reflectedClass = new \ReflectionClass($fqcn); } return $reflectedClass; }
[ "protected", "function", "getReflection", "(", "$", "filepath", ")", "{", "// Regexp instead of tokenizer because of the bad perf @link > https://gist.github.com/1886076", "if", "(", "!", "preg_match", "(", "'#^namespace\\s+(.+?);.*class\\s+(\\w+).+;$#sm'", ",", "file_get_contents", "(", "$", "filepath", ")", ",", "$", "captured", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to find namespace or class declaration'", ")", ";", "}", "$", "fqcn", "=", "$", "captured", "[", "1", "]", ".", "'\\\\'", ".", "$", "captured", "[", "2", "]", ";", "try", "{", "$", "reflectedClass", "=", "new", "\\", "ReflectionClass", "(", "$", "fqcn", ")", ";", "}", "catch", "(", "\\", "ReflectionException", "$", "exception", ")", "{", "$", "this", "->", "registerAutoload", "(", "$", "fqcn", ",", "$", "filepath", ")", ";", "$", "reflectedClass", "=", "new", "\\", "ReflectionClass", "(", "$", "fqcn", ")", ";", "}", "return", "$", "reflectedClass", ";", "}" ]
Extract the fully qualified namespace and return a ReflectionClass object @param string $filepath Path to the file to parse @return ReflectionClass
[ "Extract", "the", "fully", "qualified", "namespace", "and", "return", "a", "ReflectionClass", "object" ]
95cc53777425dd76cd0034046fa4f9e72c04d73a
https://github.com/Retentio/Boomgo/blob/95cc53777425dd76cd0034046fa4f9e72c04d73a/src/Boomgo/Parser/AnnotationParser.php#L153-L170
train
Retentio/Boomgo
src/Boomgo/Parser/AnnotationParser.php
AnnotationParser.processPropertiesParsing
protected function processPropertiesParsing(\ReflectionClass $reflectedClass) { $metadata = array(); $reflectedProperties = $reflectedClass->getProperties(); foreach ($reflectedProperties as $reflectedProperty) { if ($this->isBoomgoProperty($reflectedProperty)) { $propertyMetadata = $this->parseMetadataProperty($reflectedProperty); $metadata['definitions'][$reflectedProperty->getName()] = $propertyMetadata; } } return $metadata; }
php
protected function processPropertiesParsing(\ReflectionClass $reflectedClass) { $metadata = array(); $reflectedProperties = $reflectedClass->getProperties(); foreach ($reflectedProperties as $reflectedProperty) { if ($this->isBoomgoProperty($reflectedProperty)) { $propertyMetadata = $this->parseMetadataProperty($reflectedProperty); $metadata['definitions'][$reflectedProperty->getName()] = $propertyMetadata; } } return $metadata; }
[ "protected", "function", "processPropertiesParsing", "(", "\\", "ReflectionClass", "$", "reflectedClass", ")", "{", "$", "metadata", "=", "array", "(", ")", ";", "$", "reflectedProperties", "=", "$", "reflectedClass", "->", "getProperties", "(", ")", ";", "foreach", "(", "$", "reflectedProperties", "as", "$", "reflectedProperty", ")", "{", "if", "(", "$", "this", "->", "isBoomgoProperty", "(", "$", "reflectedProperty", ")", ")", "{", "$", "propertyMetadata", "=", "$", "this", "->", "parseMetadataProperty", "(", "$", "reflectedProperty", ")", ";", "$", "metadata", "[", "'definitions'", "]", "[", "$", "reflectedProperty", "->", "getName", "(", ")", "]", "=", "$", "propertyMetadata", ";", "}", "}", "return", "$", "metadata", ";", "}" ]
Parse class properties for metadata extraction if valid contains valid annotation local tag @param ReflectionClass $reflectedClass The document reflected object to parse @return array An array filled with Definition instance
[ "Parse", "class", "properties", "for", "metadata", "extraction", "if", "valid", "contains", "valid", "annotation", "local", "tag" ]
95cc53777425dd76cd0034046fa4f9e72c04d73a
https://github.com/Retentio/Boomgo/blob/95cc53777425dd76cd0034046fa4f9e72c04d73a/src/Boomgo/Parser/AnnotationParser.php#L179-L193
train
Retentio/Boomgo
src/Boomgo/Parser/AnnotationParser.php
AnnotationParser.isBoomgoProperty
private function isBoomgoProperty(\ReflectionProperty $property) { $propertyName = $property->getName(); $className = $property->getDeclaringClass()->getName(); $annotationTag = substr_count($property->getDocComment(), $this->getLocalAnnotation()); if (0 < $annotationTag) { if (1 === $annotationTag) { return true; } throw new \RuntimeException(sprintf('Boomgo annotation tag should occur only once for "%s->%s"', $className, $propertyName)); } return false; }
php
private function isBoomgoProperty(\ReflectionProperty $property) { $propertyName = $property->getName(); $className = $property->getDeclaringClass()->getName(); $annotationTag = substr_count($property->getDocComment(), $this->getLocalAnnotation()); if (0 < $annotationTag) { if (1 === $annotationTag) { return true; } throw new \RuntimeException(sprintf('Boomgo annotation tag should occur only once for "%s->%s"', $className, $propertyName)); } return false; }
[ "private", "function", "isBoomgoProperty", "(", "\\", "ReflectionProperty", "$", "property", ")", "{", "$", "propertyName", "=", "$", "property", "->", "getName", "(", ")", ";", "$", "className", "=", "$", "property", "->", "getDeclaringClass", "(", ")", "->", "getName", "(", ")", ";", "$", "annotationTag", "=", "substr_count", "(", "$", "property", "->", "getDocComment", "(", ")", ",", "$", "this", "->", "getLocalAnnotation", "(", ")", ")", ";", "if", "(", "0", "<", "$", "annotationTag", ")", "{", "if", "(", "1", "===", "$", "annotationTag", ")", "{", "return", "true", ";", "}", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Boomgo annotation tag should occur only once for \"%s->%s\"'", ",", "$", "className", ",", "$", "propertyName", ")", ")", ";", "}", "return", "false", ";", "}" ]
Check if an object property has to be processed by Boomgo @param ReflectionProperty $property the property to check @throws RuntimeException If annotation is malformed @return Boolean True if the property should be stored
[ "Check", "if", "an", "object", "property", "has", "to", "be", "processed", "by", "Boomgo" ]
95cc53777425dd76cd0034046fa4f9e72c04d73a
https://github.com/Retentio/Boomgo/blob/95cc53777425dd76cd0034046fa4f9e72c04d73a/src/Boomgo/Parser/AnnotationParser.php#L204-L219
train
Retentio/Boomgo
src/Boomgo/Parser/AnnotationParser.php
AnnotationParser.parseMetadataProperty
private function parseMetadataProperty(\ReflectionProperty $property) { $metadata = array(); $tag = '@var'; $docComment = $property->getDocComment(); $occurence = (int) substr_count($docComment, $tag); if (1 < $occurence) { throw new \RuntimeException(sprintf('"@var" tag is not unique for "%s->%s"', $property->getDeclaringClass()->getName(), $property->getName())); } $metadata['attribute'] = $property->getName(); // Grep type and optional namespaces preg_match('#@var\h+([a-zA-Z0-9\\\\_]+)(?:\h+\[([a-zA-Z0-9\\\\\s,_]+)\]\h*|.*)\v#', $docComment, $captured); if (!empty($captured)) { // Format var metadata $metadata['type'] = $captured[1]; if (isset($captured[2])) { $metadata['mappedClass'] = trim($captured[2]); } } return $metadata; }
php
private function parseMetadataProperty(\ReflectionProperty $property) { $metadata = array(); $tag = '@var'; $docComment = $property->getDocComment(); $occurence = (int) substr_count($docComment, $tag); if (1 < $occurence) { throw new \RuntimeException(sprintf('"@var" tag is not unique for "%s->%s"', $property->getDeclaringClass()->getName(), $property->getName())); } $metadata['attribute'] = $property->getName(); // Grep type and optional namespaces preg_match('#@var\h+([a-zA-Z0-9\\\\_]+)(?:\h+\[([a-zA-Z0-9\\\\\s,_]+)\]\h*|.*)\v#', $docComment, $captured); if (!empty($captured)) { // Format var metadata $metadata['type'] = $captured[1]; if (isset($captured[2])) { $metadata['mappedClass'] = trim($captured[2]); } } return $metadata; }
[ "private", "function", "parseMetadataProperty", "(", "\\", "ReflectionProperty", "$", "property", ")", "{", "$", "metadata", "=", "array", "(", ")", ";", "$", "tag", "=", "'@var'", ";", "$", "docComment", "=", "$", "property", "->", "getDocComment", "(", ")", ";", "$", "occurence", "=", "(", "int", ")", "substr_count", "(", "$", "docComment", ",", "$", "tag", ")", ";", "if", "(", "1", "<", "$", "occurence", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'\"@var\" tag is not unique for \"%s->%s\"'", ",", "$", "property", "->", "getDeclaringClass", "(", ")", "->", "getName", "(", ")", ",", "$", "property", "->", "getName", "(", ")", ")", ")", ";", "}", "$", "metadata", "[", "'attribute'", "]", "=", "$", "property", "->", "getName", "(", ")", ";", "// Grep type and optional namespaces", "preg_match", "(", "'#@var\\h+([a-zA-Z0-9\\\\\\\\_]+)(?:\\h+\\[([a-zA-Z0-9\\\\\\\\\\s,_]+)\\]\\h*|.*)\\v#'", ",", "$", "docComment", ",", "$", "captured", ")", ";", "if", "(", "!", "empty", "(", "$", "captured", ")", ")", "{", "// Format var metadata", "$", "metadata", "[", "'type'", "]", "=", "$", "captured", "[", "1", "]", ";", "if", "(", "isset", "(", "$", "captured", "[", "2", "]", ")", ")", "{", "$", "metadata", "[", "'mappedClass'", "]", "=", "trim", "(", "$", "captured", "[", "2", "]", ")", ";", "}", "}", "return", "$", "metadata", ";", "}" ]
Parse Boomgo metadata Extract metadata from the optional var tag @param \ReflectionProperty $property @return array
[ "Parse", "Boomgo", "metadata" ]
95cc53777425dd76cd0034046fa4f9e72c04d73a
https://github.com/Retentio/Boomgo/blob/95cc53777425dd76cd0034046fa4f9e72c04d73a/src/Boomgo/Parser/AnnotationParser.php#L230-L257
train
ekyna/SettingBundle
Manager/SettingsManager.php
SettingsManager.getParameters
private function getParameters($namespace) { $parameters = []; /** @var Parameter $parameter */ foreach ($this->parameterRepository->findBy(['namespace' => $namespace]) as $parameter) { $parameters[$parameter->getName()] = $parameter->getValue(); } return $parameters; }
php
private function getParameters($namespace) { $parameters = []; /** @var Parameter $parameter */ foreach ($this->parameterRepository->findBy(['namespace' => $namespace]) as $parameter) { $parameters[$parameter->getName()] = $parameter->getValue(); } return $parameters; }
[ "private", "function", "getParameters", "(", "$", "namespace", ")", "{", "$", "parameters", "=", "[", "]", ";", "/** @var Parameter $parameter */", "foreach", "(", "$", "this", "->", "parameterRepository", "->", "findBy", "(", "[", "'namespace'", "=>", "$", "namespace", "]", ")", "as", "$", "parameter", ")", "{", "$", "parameters", "[", "$", "parameter", "->", "getName", "(", ")", "]", "=", "$", "parameter", "->", "getValue", "(", ")", ";", "}", "return", "$", "parameters", ";", "}" ]
Load parameter from database. @param string $namespace @return array
[ "Load", "parameter", "from", "database", "." ]
df58f83eb3a01ef56cd76ea73639322c581e75c1
https://github.com/ekyna/SettingBundle/blob/df58f83eb3a01ef56cd76ea73639322c581e75c1/Manager/SettingsManager.php#L253-L263
train
bandama-framework/bandama-framework
src/foundation/router/Router.php
Router.get
public function get($path, $callable, $name = null) { return $this->add($path, $callable, $name, self::HTTP_METHOD_GET); }
php
public function get($path, $callable, $name = null) { return $this->add($path, $callable, $name, self::HTTP_METHOD_GET); }
[ "public", "function", "get", "(", "$", "path", ",", "$", "callable", ",", "$", "name", "=", "null", ")", "{", "return", "$", "this", "->", "add", "(", "$", "path", ",", "$", "callable", ",", "$", "name", ",", "self", "::", "HTTP_METHOD_GET", ")", ";", "}" ]
Add HTTP GET method route @see Router::add
[ "Add", "HTTP", "GET", "method", "route" ]
234ed703baf9e31268941c9d5f6d5e004cc53066
https://github.com/bandama-framework/bandama-framework/blob/234ed703baf9e31268941c9d5f6d5e004cc53066/src/foundation/router/Router.php#L89-L91
train
bandama-framework/bandama-framework
src/foundation/router/Router.php
Router.post
public function post($path, $callable, $name = null) { return $this->add($path, $callable, $name, self::HTTP_METHOD_POST); }
php
public function post($path, $callable, $name = null) { return $this->add($path, $callable, $name, self::HTTP_METHOD_POST); }
[ "public", "function", "post", "(", "$", "path", ",", "$", "callable", ",", "$", "name", "=", "null", ")", "{", "return", "$", "this", "->", "add", "(", "$", "path", ",", "$", "callable", ",", "$", "name", ",", "self", "::", "HTTP_METHOD_POST", ")", ";", "}" ]
Add HTTP POST method route @see Router::add
[ "Add", "HTTP", "POST", "method", "route" ]
234ed703baf9e31268941c9d5f6d5e004cc53066
https://github.com/bandama-framework/bandama-framework/blob/234ed703baf9e31268941c9d5f6d5e004cc53066/src/foundation/router/Router.php#L98-L100
train
bandama-framework/bandama-framework
src/foundation/router/Router.php
Router.put
public function put($path, $callable, $name = null) { return $this->add($path, $callable, $name, self::HTTP_METHOD_PUT); }
php
public function put($path, $callable, $name = null) { return $this->add($path, $callable, $name, self::HTTP_METHOD_PUT); }
[ "public", "function", "put", "(", "$", "path", ",", "$", "callable", ",", "$", "name", "=", "null", ")", "{", "return", "$", "this", "->", "add", "(", "$", "path", ",", "$", "callable", ",", "$", "name", ",", "self", "::", "HTTP_METHOD_PUT", ")", ";", "}" ]
Add HTTP PUT method route @see Router::add
[ "Add", "HTTP", "PUT", "method", "route" ]
234ed703baf9e31268941c9d5f6d5e004cc53066
https://github.com/bandama-framework/bandama-framework/blob/234ed703baf9e31268941c9d5f6d5e004cc53066/src/foundation/router/Router.php#L107-L109
train
bandama-framework/bandama-framework
src/foundation/router/Router.php
Router.patch
public function patch($path, $callable, $name = null) { return $this->add($path, $callable, $name, self::HTTP_METHOD_PATCH); }
php
public function patch($path, $callable, $name = null) { return $this->add($path, $callable, $name, self::HTTP_METHOD_PATCH); }
[ "public", "function", "patch", "(", "$", "path", ",", "$", "callable", ",", "$", "name", "=", "null", ")", "{", "return", "$", "this", "->", "add", "(", "$", "path", ",", "$", "callable", ",", "$", "name", ",", "self", "::", "HTTP_METHOD_PATCH", ")", ";", "}" ]
Add HTTP PATCH method route @see Router::add
[ "Add", "HTTP", "PATCH", "method", "route" ]
234ed703baf9e31268941c9d5f6d5e004cc53066
https://github.com/bandama-framework/bandama-framework/blob/234ed703baf9e31268941c9d5f6d5e004cc53066/src/foundation/router/Router.php#L116-L118
train
bandama-framework/bandama-framework
src/foundation/router/Router.php
Router.delete
public function delete($path, $callable, $name = null) { return $this->add($path, $callable, $name, self::HTTP_METHOD_DELETE); }
php
public function delete($path, $callable, $name = null) { return $this->add($path, $callable, $name, self::HTTP_METHOD_DELETE); }
[ "public", "function", "delete", "(", "$", "path", ",", "$", "callable", ",", "$", "name", "=", "null", ")", "{", "return", "$", "this", "->", "add", "(", "$", "path", ",", "$", "callable", ",", "$", "name", ",", "self", "::", "HTTP_METHOD_DELETE", ")", ";", "}" ]
Add HTTP DELETE method route @see Router::add
[ "Add", "HTTP", "DELETE", "method", "route" ]
234ed703baf9e31268941c9d5f6d5e004cc53066
https://github.com/bandama-framework/bandama-framework/blob/234ed703baf9e31268941c9d5f6d5e004cc53066/src/foundation/router/Router.php#L125-L127
train
bandama-framework/bandama-framework
src/foundation/router/Router.php
Router.route
public function route($url) { if (!isset($this->routes[$this->getHttpMethod()])) { throw new RouterException("REQUEST_METHOD does not exist : url = $url"); } foreach ($this->routes[$this->getHttpMethod()] as $route) { $matches = $route->match($url); if (is_array($matches)) { return $route->execute($matches); } } throw new RouterException("No route matches the URL $url"); }
php
public function route($url) { if (!isset($this->routes[$this->getHttpMethod()])) { throw new RouterException("REQUEST_METHOD does not exist : url = $url"); } foreach ($this->routes[$this->getHttpMethod()] as $route) { $matches = $route->match($url); if (is_array($matches)) { return $route->execute($matches); } } throw new RouterException("No route matches the URL $url"); }
[ "public", "function", "route", "(", "$", "url", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "routes", "[", "$", "this", "->", "getHttpMethod", "(", ")", "]", ")", ")", "{", "throw", "new", "RouterException", "(", "\"REQUEST_METHOD does not exist : url = $url\"", ")", ";", "}", "foreach", "(", "$", "this", "->", "routes", "[", "$", "this", "->", "getHttpMethod", "(", ")", "]", "as", "$", "route", ")", "{", "$", "matches", "=", "$", "route", "->", "match", "(", "$", "url", ")", ";", "if", "(", "is_array", "(", "$", "matches", ")", ")", "{", "return", "$", "route", "->", "execute", "(", "$", "matches", ")", ";", "}", "}", "throw", "new", "RouterException", "(", "\"No route matches the URL $url\"", ")", ";", "}" ]
Execute a callable of route that matchs the URL @param string $url HTTP request URL @throws RouterException When HTTP method doesn't exists or no route found @return mixed
[ "Execute", "a", "callable", "of", "route", "that", "matchs", "the", "URL" ]
234ed703baf9e31268941c9d5f6d5e004cc53066
https://github.com/bandama-framework/bandama-framework/blob/234ed703baf9e31268941c9d5f6d5e004cc53066/src/foundation/router/Router.php#L138-L152
train
bandama-framework/bandama-framework
src/foundation/router/Router.php
Router.add
private function add($path, $callable, $name, $method) { $route = new Route($path, $callable); $this->routes[$method][] = $route; if (is_string($callable) && $name === null) { $name = $callable; } // If the route has a name, add to named routes collection if ($name) { $this->namedRoutes[$name] = $route; } return $route; }
php
private function add($path, $callable, $name, $method) { $route = new Route($path, $callable); $this->routes[$method][] = $route; if (is_string($callable) && $name === null) { $name = $callable; } // If the route has a name, add to named routes collection if ($name) { $this->namedRoutes[$name] = $route; } return $route; }
[ "private", "function", "add", "(", "$", "path", ",", "$", "callable", ",", "$", "name", ",", "$", "method", ")", "{", "$", "route", "=", "new", "Route", "(", "$", "path", ",", "$", "callable", ")", ";", "$", "this", "->", "routes", "[", "$", "method", "]", "[", "]", "=", "$", "route", ";", "if", "(", "is_string", "(", "$", "callable", ")", "&&", "$", "name", "===", "null", ")", "{", "$", "name", "=", "$", "callable", ";", "}", "// If the route has a name, add to named routes collection", "if", "(", "$", "name", ")", "{", "$", "this", "->", "namedRoutes", "[", "$", "name", "]", "=", "$", "route", ";", "}", "return", "$", "route", ";", "}" ]
Add route to collection of routes, implements Fluent design pattern @param string $path HTTP request path @param string $callable Class method or function to call @param string $name Name of route @param string $method HTTP method e.g (GET, POST, PUT, DELETE, etc.) @return Route
[ "Add", "route", "to", "collection", "of", "routes", "implements", "Fluent", "design", "pattern" ]
234ed703baf9e31268941c9d5f6d5e004cc53066
https://github.com/bandama-framework/bandama-framework/blob/234ed703baf9e31268941c9d5f6d5e004cc53066/src/foundation/router/Router.php#L183-L198
train
PenoaksDev/Milky-Framework
src/Milky/Exceptions/Handler.php
Handler.dontReport
public function dontReport( $exceptions ) { $this->dontReport = array_merge( $this->dontReport, is_array( $exceptions ) ? $exceptions : [$exceptions] ); }
php
public function dontReport( $exceptions ) { $this->dontReport = array_merge( $this->dontReport, is_array( $exceptions ) ? $exceptions : [$exceptions] ); }
[ "public", "function", "dontReport", "(", "$", "exceptions", ")", "{", "$", "this", "->", "dontReport", "=", "array_merge", "(", "$", "this", "->", "dontReport", ",", "is_array", "(", "$", "exceptions", ")", "?", "$", "exceptions", ":", "[", "$", "exceptions", "]", ")", ";", "}" ]
Adds an exception to not be reported @param array|string $exceptions
[ "Adds", "an", "exception", "to", "not", "be", "reported" ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Exceptions/Handler.php#L56-L59
train
PenoaksDev/Milky-Framework
src/Milky/Exceptions/Handler.php
Handler.report
public function report( Exception $e ) { if ( !$this->shouldReport( $e ) ) return; try { $logger = Framework::log(); } catch ( Exception $ex ) { throw $e; // throw the original Exception } $logger->error( $e ); $level = $this->getLevel( $e ); $id = UniversalBuilder::resolveClass( ExceptionIdentifier::class )->identify( $e ); $logger->{$level}( $e, ['identification' => ['id' => $id]] ); }
php
public function report( Exception $e ) { if ( !$this->shouldReport( $e ) ) return; try { $logger = Framework::log(); } catch ( Exception $ex ) { throw $e; // throw the original Exception } $logger->error( $e ); $level = $this->getLevel( $e ); $id = UniversalBuilder::resolveClass( ExceptionIdentifier::class )->identify( $e ); $logger->{$level}( $e, ['identification' => ['id' => $id]] ); }
[ "public", "function", "report", "(", "Exception", "$", "e", ")", "{", "if", "(", "!", "$", "this", "->", "shouldReport", "(", "$", "e", ")", ")", "return", ";", "try", "{", "$", "logger", "=", "Framework", "::", "log", "(", ")", ";", "}", "catch", "(", "Exception", "$", "ex", ")", "{", "throw", "$", "e", ";", "// throw the original Exception", "}", "$", "logger", "->", "error", "(", "$", "e", ")", ";", "$", "level", "=", "$", "this", "->", "getLevel", "(", "$", "e", ")", ";", "$", "id", "=", "UniversalBuilder", "::", "resolveClass", "(", "ExceptionIdentifier", "::", "class", ")", "->", "identify", "(", "$", "e", ")", ";", "$", "logger", "->", "{", "$", "level", "}", "(", "$", "e", ",", "[", "'identification'", "=>", "[", "'id'", "=>", "$", "id", "]", "]", ")", ";", "}" ]
Report or log an Exception. @param Exception $e
[ "Report", "or", "log", "an", "Exception", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Exceptions/Handler.php#L123-L144
train
PenoaksDev/Milky-Framework
src/Milky/Exceptions/Handler.php
Handler.getLevel
protected function getLevel( Exception $exception ) { foreach ( array_get( $this->getConfig(), 'levels', [] ) as $class => $level ) if ( $exception instanceof $class ) return $level; return 'error'; }
php
protected function getLevel( Exception $exception ) { foreach ( array_get( $this->getConfig(), 'levels', [] ) as $class => $level ) if ( $exception instanceof $class ) return $level; return 'error'; }
[ "protected", "function", "getLevel", "(", "Exception", "$", "exception", ")", "{", "foreach", "(", "array_get", "(", "$", "this", "->", "getConfig", "(", ")", ",", "'levels'", ",", "[", "]", ")", "as", "$", "class", "=>", "$", "level", ")", "if", "(", "$", "exception", "instanceof", "$", "class", ")", "return", "$", "level", ";", "return", "'error'", ";", "}" ]
Get the exception level. @param \Exception $exception @return string
[ "Get", "the", "exception", "level", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Exceptions/Handler.php#L153-L160
train
PenoaksDev/Milky-Framework
src/Milky/Exceptions/Handler.php
Handler.shouldReport
protected function shouldReport( Exception $e ) { foreach ( $this->dontReport as $type ) if ( $e instanceof $type ) return false; return true; }
php
protected function shouldReport( Exception $e ) { foreach ( $this->dontReport as $type ) if ( $e instanceof $type ) return false; return true; }
[ "protected", "function", "shouldReport", "(", "Exception", "$", "e", ")", "{", "foreach", "(", "$", "this", "->", "dontReport", "as", "$", "type", ")", "if", "(", "$", "e", "instanceof", "$", "type", ")", "return", "false", ";", "return", "true", ";", "}" ]
Determine if the Exception is in the "do not report" list. @param Exception $e @return bool
[ "Determine", "if", "the", "Exception", "is", "in", "the", "do", "not", "report", "list", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Exceptions/Handler.php#L168-L175
train
PenoaksDev/Milky-Framework
src/Milky/Exceptions/Handler.php
Handler.render
public function render( $request, Exception $e ) { $transformed = $this->getTransformed( $e ); $response = method_exists( $e, 'getResponse' ) ? $e->getResponse() : null; if ( !$response instanceof Response ) try { $response = $this->getResponse( $request, $e, $transformed ); } catch ( Exception $e ) { $this->report( $e ); $response = new Response( 'Internal server error.', 500 ); } return $this->toHttpResponse( $response, $transformed ); }
php
public function render( $request, Exception $e ) { $transformed = $this->getTransformed( $e ); $response = method_exists( $e, 'getResponse' ) ? $e->getResponse() : null; if ( !$response instanceof Response ) try { $response = $this->getResponse( $request, $e, $transformed ); } catch ( Exception $e ) { $this->report( $e ); $response = new Response( 'Internal server error.', 500 ); } return $this->toHttpResponse( $response, $transformed ); }
[ "public", "function", "render", "(", "$", "request", ",", "Exception", "$", "e", ")", "{", "$", "transformed", "=", "$", "this", "->", "getTransformed", "(", "$", "e", ")", ";", "$", "response", "=", "method_exists", "(", "$", "e", ",", "'getResponse'", ")", "?", "$", "e", "->", "getResponse", "(", ")", ":", "null", ";", "if", "(", "!", "$", "response", "instanceof", "Response", ")", "try", "{", "$", "response", "=", "$", "this", "->", "getResponse", "(", "$", "request", ",", "$", "e", ",", "$", "transformed", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "this", "->", "report", "(", "$", "e", ")", ";", "$", "response", "=", "new", "Response", "(", "'Internal server error.'", ",", "500", ")", ";", "}", "return", "$", "this", "->", "toHttpResponse", "(", "$", "response", ",", "$", "transformed", ")", ";", "}" ]
Render an Exception into a response. @param Request $request @param Exception $e @return Response
[ "Render", "an", "Exception", "into", "a", "response", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Exceptions/Handler.php#L184-L202
train
PenoaksDev/Milky-Framework
src/Milky/Exceptions/Handler.php
Handler.toHttpResponse
protected function toHttpResponse( $response, Exception $e ) { $response = new Response( $response->getContent(), $response->getStatusCode(), $response->headers->all() ); return $response->withException( $e ); }
php
protected function toHttpResponse( $response, Exception $e ) { $response = new Response( $response->getContent(), $response->getStatusCode(), $response->headers->all() ); return $response->withException( $e ); }
[ "protected", "function", "toHttpResponse", "(", "$", "response", ",", "Exception", "$", "e", ")", "{", "$", "response", "=", "new", "Response", "(", "$", "response", "->", "getContent", "(", ")", ",", "$", "response", "->", "getStatusCode", "(", ")", ",", "$", "response", "->", "headers", "->", "all", "(", ")", ")", ";", "return", "$", "response", "->", "withException", "(", "$", "e", ")", ";", "}" ]
Map Exception into an response. @param Response $response @param Exception $e @return Response
[ "Map", "Exception", "into", "an", "response", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Exceptions/Handler.php#L211-L216
train
PenoaksDev/Milky-Framework
src/Milky/Exceptions/Handler.php
Handler.getConfig
public function getConfig( $key = null, $def = null ) { return Config::get( 'exceptions' . ( empty( $key ) ? "" : "." . $key ), $def ); }
php
public function getConfig( $key = null, $def = null ) { return Config::get( 'exceptions' . ( empty( $key ) ? "" : "." . $key ), $def ); }
[ "public", "function", "getConfig", "(", "$", "key", "=", "null", ",", "$", "def", "=", "null", ")", "{", "return", "Config", "::", "get", "(", "'exceptions'", ".", "(", "empty", "(", "$", "key", ")", "?", "\"\"", ":", "\".\"", ".", "$", "key", ")", ",", "$", "def", ")", ";", "}" ]
Get exceptions configuration @return array
[ "Get", "exceptions", "configuration" ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Exceptions/Handler.php#L223-L226
train
PenoaksDev/Milky-Framework
src/Milky/Exceptions/Handler.php
Handler.getResponse
protected function getResponse( Request $request, Exception $exception, Exception $transformed ) { $id = UniversalBuilder::resolve( 'exceptions.identifier' )->identify( $exception ); $flattened = FlattenException::create( $transformed ); $code = $flattened->getStatusCode(); $headers = $flattened->getHeaders(); return $this->getDisplayer( $request, $exception, $transformed, $code )->display( $transformed, $id, $code, $headers ); }
php
protected function getResponse( Request $request, Exception $exception, Exception $transformed ) { $id = UniversalBuilder::resolve( 'exceptions.identifier' )->identify( $exception ); $flattened = FlattenException::create( $transformed ); $code = $flattened->getStatusCode(); $headers = $flattened->getHeaders(); return $this->getDisplayer( $request, $exception, $transformed, $code )->display( $transformed, $id, $code, $headers ); }
[ "protected", "function", "getResponse", "(", "Request", "$", "request", ",", "Exception", "$", "exception", ",", "Exception", "$", "transformed", ")", "{", "$", "id", "=", "UniversalBuilder", "::", "resolve", "(", "'exceptions.identifier'", ")", "->", "identify", "(", "$", "exception", ")", ";", "$", "flattened", "=", "FlattenException", "::", "create", "(", "$", "transformed", ")", ";", "$", "code", "=", "$", "flattened", "->", "getStatusCode", "(", ")", ";", "$", "headers", "=", "$", "flattened", "->", "getHeaders", "(", ")", ";", "return", "$", "this", "->", "getDisplayer", "(", "$", "request", ",", "$", "exception", ",", "$", "transformed", ",", "$", "code", ")", "->", "display", "(", "$", "transformed", ",", "$", "id", ",", "$", "code", ",", "$", "headers", ")", ";", "}" ]
Get the appropriate response object. @param Request $request @param \Exception $transformed @param \Exception $exception @return Response
[ "Get", "the", "appropriate", "response", "object", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Exceptions/Handler.php#L237-L246
train
ScaraMVC/Framework
src/Scara/Auth/Authentication.php
Authentication.check
public function check() { if ($this->_session->has('auth')) { // They have an auth, let's attempt to check expiration // and master session $s = [ 'session' => $this->_session->get('SCARA_SESSION'), 'token' => $this->_session->get('SCARA_SESSION_TOKEN'), ]; $ua = $this->_ssl->untokenize($s['token'], $s['session']); if ($ua === hash('sha256', $_SERVER['HTTP_USER_AGENT'])) { $expire = $this->_session->get('expire'); if (time() < $expire) { return true; } else { $this->logout(); } } } return false; }
php
public function check() { if ($this->_session->has('auth')) { // They have an auth, let's attempt to check expiration // and master session $s = [ 'session' => $this->_session->get('SCARA_SESSION'), 'token' => $this->_session->get('SCARA_SESSION_TOKEN'), ]; $ua = $this->_ssl->untokenize($s['token'], $s['session']); if ($ua === hash('sha256', $_SERVER['HTTP_USER_AGENT'])) { $expire = $this->_session->get('expire'); if (time() < $expire) { return true; } else { $this->logout(); } } } return false; }
[ "public", "function", "check", "(", ")", "{", "if", "(", "$", "this", "->", "_session", "->", "has", "(", "'auth'", ")", ")", "{", "// They have an auth, let's attempt to check expiration", "// and master session", "$", "s", "=", "[", "'session'", "=>", "$", "this", "->", "_session", "->", "get", "(", "'SCARA_SESSION'", ")", ",", "'token'", "=>", "$", "this", "->", "_session", "->", "get", "(", "'SCARA_SESSION_TOKEN'", ")", ",", "]", ";", "$", "ua", "=", "$", "this", "->", "_ssl", "->", "untokenize", "(", "$", "s", "[", "'token'", "]", ",", "$", "s", "[", "'session'", "]", ")", ";", "if", "(", "$", "ua", "===", "hash", "(", "'sha256'", ",", "$", "_SERVER", "[", "'HTTP_USER_AGENT'", "]", ")", ")", "{", "$", "expire", "=", "$", "this", "->", "_session", "->", "get", "(", "'expire'", ")", ";", "if", "(", "time", "(", ")", "<", "$", "expire", ")", "{", "return", "true", ";", "}", "else", "{", "$", "this", "->", "logout", "(", ")", ";", "}", "}", "}", "return", "false", ";", "}" ]
Checks if a user is authenticated. @return bool
[ "Checks", "if", "a", "user", "is", "authenticated", "." ]
199b08b45fadf5dae14ac4732af03b36e15bbef2
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Auth/Authentication.php#L54-L77
train
SlabPHP/cache-manager
src/Request.php
Request.setCallback
public function setCallback($object, $callbackFunction, $parameters = array()) { $this->callbackObject = $object; $this->callbackFunction = $callbackFunction; $this->callbackParameters = $parameters; return $this; }
php
public function setCallback($object, $callbackFunction, $parameters = array()) { $this->callbackObject = $object; $this->callbackFunction = $callbackFunction; $this->callbackParameters = $parameters; return $this; }
[ "public", "function", "setCallback", "(", "$", "object", ",", "$", "callbackFunction", ",", "$", "parameters", "=", "array", "(", ")", ")", "{", "$", "this", "->", "callbackObject", "=", "$", "object", ";", "$", "this", "->", "callbackFunction", "=", "$", "callbackFunction", ";", "$", "this", "->", "callbackParameters", "=", "$", "parameters", ";", "return", "$", "this", ";", "}" ]
Set cache callback @param object $object @param string $callbackFunction @param array $parameters @return $this
[ "Set", "cache", "callback" ]
7bbf9fe6519071fe14d382e98925cd3e10010a3a
https://github.com/SlabPHP/cache-manager/blob/7bbf9fe6519071fe14d382e98925cd3e10010a3a/src/Request.php#L101-L110
train
SlabPHP/cache-manager
src/Request.php
Request.executeCallback
public function executeCallback() { if (method_exists($this->callbackObject, $this->callbackFunction)) { return call_user_func_array(array($this->callbackObject, $this->callbackFunction), $this->callbackParameters); } return null; }
php
public function executeCallback() { if (method_exists($this->callbackObject, $this->callbackFunction)) { return call_user_func_array(array($this->callbackObject, $this->callbackFunction), $this->callbackParameters); } return null; }
[ "public", "function", "executeCallback", "(", ")", "{", "if", "(", "method_exists", "(", "$", "this", "->", "callbackObject", ",", "$", "this", "->", "callbackFunction", ")", ")", "{", "return", "call_user_func_array", "(", "array", "(", "$", "this", "->", "callbackObject", ",", "$", "this", "->", "callbackFunction", ")", ",", "$", "this", "->", "callbackParameters", ")", ";", "}", "return", "null", ";", "}" ]
Activate the callback function @return mixed
[ "Activate", "the", "callback", "function" ]
7bbf9fe6519071fe14d382e98925cd3e10010a3a
https://github.com/SlabPHP/cache-manager/blob/7bbf9fe6519071fe14d382e98925cd3e10010a3a/src/Request.php#L147-L154
train
danielgp/common-lib
source/CommonBasic.php
CommonBasic.moveFilesIntoTargetFolder
protected function moveFilesIntoTargetFolder($sourcePath, $targetPath) { $filesystem = new \Symfony\Component\Filesystem\Filesystem(); $filesystem->mirror($sourcePath, $targetPath); $finder = new \Symfony\Component\Finder\Finder(); $iterator = $finder->files()->ignoreUnreadableDirs(true)->followLinks()->in($sourcePath); $sFiles = []; foreach ($iterator as $file) { $relativePathFile = str_replace($sourcePath, '', $file->getRealPath()); if (!file_exists($targetPath . $relativePathFile)) { $sFiles[$relativePathFile] = $targetPath . $relativePathFile; } } return $this->setArrayToJson($sFiles); }
php
protected function moveFilesIntoTargetFolder($sourcePath, $targetPath) { $filesystem = new \Symfony\Component\Filesystem\Filesystem(); $filesystem->mirror($sourcePath, $targetPath); $finder = new \Symfony\Component\Finder\Finder(); $iterator = $finder->files()->ignoreUnreadableDirs(true)->followLinks()->in($sourcePath); $sFiles = []; foreach ($iterator as $file) { $relativePathFile = str_replace($sourcePath, '', $file->getRealPath()); if (!file_exists($targetPath . $relativePathFile)) { $sFiles[$relativePathFile] = $targetPath . $relativePathFile; } } return $this->setArrayToJson($sFiles); }
[ "protected", "function", "moveFilesIntoTargetFolder", "(", "$", "sourcePath", ",", "$", "targetPath", ")", "{", "$", "filesystem", "=", "new", "\\", "Symfony", "\\", "Component", "\\", "Filesystem", "\\", "Filesystem", "(", ")", ";", "$", "filesystem", "->", "mirror", "(", "$", "sourcePath", ",", "$", "targetPath", ")", ";", "$", "finder", "=", "new", "\\", "Symfony", "\\", "Component", "\\", "Finder", "\\", "Finder", "(", ")", ";", "$", "iterator", "=", "$", "finder", "->", "files", "(", ")", "->", "ignoreUnreadableDirs", "(", "true", ")", "->", "followLinks", "(", ")", "->", "in", "(", "$", "sourcePath", ")", ";", "$", "sFiles", "=", "[", "]", ";", "foreach", "(", "$", "iterator", "as", "$", "file", ")", "{", "$", "relativePathFile", "=", "str_replace", "(", "$", "sourcePath", ",", "''", ",", "$", "file", "->", "getRealPath", "(", ")", ")", ";", "if", "(", "!", "file_exists", "(", "$", "targetPath", ".", "$", "relativePathFile", ")", ")", "{", "$", "sFiles", "[", "$", "relativePathFile", "]", "=", "$", "targetPath", ".", "$", "relativePathFile", ";", "}", "}", "return", "$", "this", "->", "setArrayToJson", "(", "$", "sFiles", ")", ";", "}" ]
Moves files into another folder @param string $sourcePath @param string $targetPath @return string
[ "Moves", "files", "into", "another", "folder" ]
627b99b4408414c7cd21a6c8016f6468dc9216b2
https://github.com/danielgp/common-lib/blob/627b99b4408414c7cd21a6c8016f6468dc9216b2/source/CommonBasic.php#L121-L135
train
danielgp/common-lib
source/CommonBasic.php
CommonBasic.setArrayToArrayKbr
protected function setArrayToArrayKbr(array $aElements) { $aReturn = []; foreach ($aElements as $key => $value) { $aReturn[str_replace(' ', '<br/>', $key)] = $value; } return $aReturn; }
php
protected function setArrayToArrayKbr(array $aElements) { $aReturn = []; foreach ($aElements as $key => $value) { $aReturn[str_replace(' ', '<br/>', $key)] = $value; } return $aReturn; }
[ "protected", "function", "setArrayToArrayKbr", "(", "array", "$", "aElements", ")", "{", "$", "aReturn", "=", "[", "]", ";", "foreach", "(", "$", "aElements", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "aReturn", "[", "str_replace", "(", "' '", ",", "'<br/>'", ",", "$", "key", ")", "]", "=", "$", "value", ";", "}", "return", "$", "aReturn", ";", "}" ]
Replace space with break line for each key element @param array $aElements @return array
[ "Replace", "space", "with", "break", "line", "for", "each", "key", "element" ]
627b99b4408414c7cd21a6c8016f6468dc9216b2
https://github.com/danielgp/common-lib/blob/627b99b4408414c7cd21a6c8016f6468dc9216b2/source/CommonBasic.php#L192-L199
train
danielgp/common-lib
source/CommonBasic.php
CommonBasic.setArrayToJson
public function setArrayToJson(array $inArray) { $rtrn = utf8_encode(json_encode($inArray, JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)); $jsonError = $this->setJsonErrorInPlainEnglish(); if ($jsonError == '') { $jsonError = $rtrn; } return $jsonError; }
php
public function setArrayToJson(array $inArray) { $rtrn = utf8_encode(json_encode($inArray, JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)); $jsonError = $this->setJsonErrorInPlainEnglish(); if ($jsonError == '') { $jsonError = $rtrn; } return $jsonError; }
[ "public", "function", "setArrayToJson", "(", "array", "$", "inArray", ")", "{", "$", "rtrn", "=", "utf8_encode", "(", "json_encode", "(", "$", "inArray", ",", "JSON_FORCE_OBJECT", "|", "JSON_UNESCAPED_SLASHES", "|", "JSON_PRETTY_PRINT", ")", ")", ";", "$", "jsonError", "=", "$", "this", "->", "setJsonErrorInPlainEnglish", "(", ")", ";", "if", "(", "$", "jsonError", "==", "''", ")", "{", "$", "jsonError", "=", "$", "rtrn", ";", "}", "return", "$", "jsonError", ";", "}" ]
Converts an array into JSON string @param array $inArray @return string
[ "Converts", "an", "array", "into", "JSON", "string" ]
627b99b4408414c7cd21a6c8016f6468dc9216b2
https://github.com/danielgp/common-lib/blob/627b99b4408414c7cd21a6c8016f6468dc9216b2/source/CommonBasic.php#L220-L228
train
danielgp/common-lib
source/CommonBasic.php
CommonBasic.setJsonErrorInPlainEnglish
protected function setJsonErrorInPlainEnglish() { $knownErrors = [ JSON_ERROR_NONE => '', JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded', ]; return $knownErrors[json_last_error()]; }
php
protected function setJsonErrorInPlainEnglish() { $knownErrors = [ JSON_ERROR_NONE => '', JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded', ]; return $knownErrors[json_last_error()]; }
[ "protected", "function", "setJsonErrorInPlainEnglish", "(", ")", "{", "$", "knownErrors", "=", "[", "JSON_ERROR_NONE", "=>", "''", ",", "JSON_ERROR_DEPTH", "=>", "'Maximum stack depth exceeded'", ",", "JSON_ERROR_STATE_MISMATCH", "=>", "'Underflow or the modes mismatch'", ",", "JSON_ERROR_CTRL_CHAR", "=>", "'Unexpected control character found'", ",", "JSON_ERROR_SYNTAX", "=>", "'Syntax error, malformed JSON'", ",", "JSON_ERROR_UTF8", "=>", "'Malformed UTF-8 characters, possibly incorrectly encoded'", ",", "]", ";", "return", "$", "knownErrors", "[", "json_last_error", "(", ")", "]", ";", "}" ]
Provides a list of all known JSON errors and their description @return string
[ "Provides", "a", "list", "of", "all", "known", "JSON", "errors", "and", "their", "description" ]
627b99b4408414c7cd21a6c8016f6468dc9216b2
https://github.com/danielgp/common-lib/blob/627b99b4408414c7cd21a6c8016f6468dc9216b2/source/CommonBasic.php#L235-L246
train
cogentParadigm/behat-starbug-extension
src/Context/CsvContext.php
CsvContext.similarCsvFile
public function similarCsvFile(TableNode $filepath) { $file = fopen($filepath, "r"); $expected = CSVTable::fromStream($file); fclose($file); $this->compareCsv($expected); }
php
public function similarCsvFile(TableNode $filepath) { $file = fopen($filepath, "r"); $expected = CSVTable::fromStream($file); fclose($file); $this->compareCsv($expected); }
[ "public", "function", "similarCsvFile", "(", "TableNode", "$", "filepath", ")", "{", "$", "file", "=", "fopen", "(", "$", "filepath", ",", "\"r\"", ")", ";", "$", "expected", "=", "CSVTable", "::", "fromStream", "(", "$", "file", ")", ";", "fclose", "(", "$", "file", ")", ";", "$", "this", "->", "compareCsv", "(", "$", "expected", ")", ";", "}" ]
CSV download with loose match. @Then I should get a CSV similar to :filepath
[ "CSV", "download", "with", "loose", "match", "." ]
76da5d943773857ad2388a7cccb6632176b452a9
https://github.com/cogentParadigm/behat-starbug-extension/blob/76da5d943773857ad2388a7cccb6632176b452a9/src/Context/CsvContext.php#L63-L68
train
cogentParadigm/behat-starbug-extension
src/Context/CsvContext.php
CsvContext.getComparators
public function getComparators(TableNode $table) { $comparators = []; $headers = $table->getRow(0); foreach ($headers as $header) { $comparators[$header] = function ($expected, $actual) { if (substr($expected, 0, 1) === "/") { return preg_match($expected, $actual); } else { return $expected === $actual; } }; } return $comparators; }
php
public function getComparators(TableNode $table) { $comparators = []; $headers = $table->getRow(0); foreach ($headers as $header) { $comparators[$header] = function ($expected, $actual) { if (substr($expected, 0, 1) === "/") { return preg_match($expected, $actual); } else { return $expected === $actual; } }; } return $comparators; }
[ "public", "function", "getComparators", "(", "TableNode", "$", "table", ")", "{", "$", "comparators", "=", "[", "]", ";", "$", "headers", "=", "$", "table", "->", "getRow", "(", "0", ")", ";", "foreach", "(", "$", "headers", "as", "$", "header", ")", "{", "$", "comparators", "[", "$", "header", "]", "=", "function", "(", "$", "expected", ",", "$", "actual", ")", "{", "if", "(", "substr", "(", "$", "expected", ",", "0", ",", "1", ")", "===", "\"/\"", ")", "{", "return", "preg_match", "(", "$", "expected", ",", "$", "actual", ")", ";", "}", "else", "{", "return", "$", "expected", "===", "$", "actual", ";", "}", "}", ";", "}", "return", "$", "comparators", ";", "}" ]
Helper method to generate generic regex comparators.
[ "Helper", "method", "to", "generate", "generic", "regex", "comparators", "." ]
76da5d943773857ad2388a7cccb6632176b452a9
https://github.com/cogentParadigm/behat-starbug-extension/blob/76da5d943773857ad2388a7cccb6632176b452a9/src/Context/CsvContext.php#L73-L86
train
ringoteam/RingoPhpRedmonBundle
Controller/SearchController.php
SearchController.indexAction
public function indexAction() { $results = array(); $key = ''; $db = '-1'; if($this->getRequest()->isMethod('POST')) { $key = $this->getRequest()->get('key'); $db = $this->getRequest()->get('database'); $keys = $this->getWorker()->keys($key, $db); if(empty($keys)) { $this->get('session')->getFlashBag()->add('notice', 'No result found'); }else if(is_array($keys)) { foreach($keys as $k) { $value = $this->getWorker()->get($k, $db); $ttl = $this->getWorker()->ttl($k, $db); $results[] = array( 'key' => $k, 'value' => $value, 'expireAt' => ($ttl == -1) ? '-' : strftime("%a %d %b %H:%M:%S %Y", time() + $ttl), 'weight' => (mb_strlen($value, '8bit') / 1000). ' Kb' ); } } } return $this->render( $this->getTemplatePath().'index.html.twig', array( 'instance' => $this->getCurrentInstance(), 'results' => $results, 'key' => $key, 'db' => $db ) ); }
php
public function indexAction() { $results = array(); $key = ''; $db = '-1'; if($this->getRequest()->isMethod('POST')) { $key = $this->getRequest()->get('key'); $db = $this->getRequest()->get('database'); $keys = $this->getWorker()->keys($key, $db); if(empty($keys)) { $this->get('session')->getFlashBag()->add('notice', 'No result found'); }else if(is_array($keys)) { foreach($keys as $k) { $value = $this->getWorker()->get($k, $db); $ttl = $this->getWorker()->ttl($k, $db); $results[] = array( 'key' => $k, 'value' => $value, 'expireAt' => ($ttl == -1) ? '-' : strftime("%a %d %b %H:%M:%S %Y", time() + $ttl), 'weight' => (mb_strlen($value, '8bit') / 1000). ' Kb' ); } } } return $this->render( $this->getTemplatePath().'index.html.twig', array( 'instance' => $this->getCurrentInstance(), 'results' => $results, 'key' => $key, 'db' => $db ) ); }
[ "public", "function", "indexAction", "(", ")", "{", "$", "results", "=", "array", "(", ")", ";", "$", "key", "=", "''", ";", "$", "db", "=", "'-1'", ";", "if", "(", "$", "this", "->", "getRequest", "(", ")", "->", "isMethod", "(", "'POST'", ")", ")", "{", "$", "key", "=", "$", "this", "->", "getRequest", "(", ")", "->", "get", "(", "'key'", ")", ";", "$", "db", "=", "$", "this", "->", "getRequest", "(", ")", "->", "get", "(", "'database'", ")", ";", "$", "keys", "=", "$", "this", "->", "getWorker", "(", ")", "->", "keys", "(", "$", "key", ",", "$", "db", ")", ";", "if", "(", "empty", "(", "$", "keys", ")", ")", "{", "$", "this", "->", "get", "(", "'session'", ")", "->", "getFlashBag", "(", ")", "->", "add", "(", "'notice'", ",", "'No result found'", ")", ";", "}", "else", "if", "(", "is_array", "(", "$", "keys", ")", ")", "{", "foreach", "(", "$", "keys", "as", "$", "k", ")", "{", "$", "value", "=", "$", "this", "->", "getWorker", "(", ")", "->", "get", "(", "$", "k", ",", "$", "db", ")", ";", "$", "ttl", "=", "$", "this", "->", "getWorker", "(", ")", "->", "ttl", "(", "$", "k", ",", "$", "db", ")", ";", "$", "results", "[", "]", "=", "array", "(", "'key'", "=>", "$", "k", ",", "'value'", "=>", "$", "value", ",", "'expireAt'", "=>", "(", "$", "ttl", "==", "-", "1", ")", "?", "'-'", ":", "strftime", "(", "\"%a %d %b %H:%M:%S %Y\"", ",", "time", "(", ")", "+", "$", "ttl", ")", ",", "'weight'", "=>", "(", "mb_strlen", "(", "$", "value", ",", "'8bit'", ")", "/", "1000", ")", ".", "' Kb'", ")", ";", "}", "}", "}", "return", "$", "this", "->", "render", "(", "$", "this", "->", "getTemplatePath", "(", ")", ".", "'index.html.twig'", ",", "array", "(", "'instance'", "=>", "$", "this", "->", "getCurrentInstance", "(", ")", ",", "'results'", "=>", "$", "results", ",", "'key'", "=>", "$", "key", ",", "'db'", "=>", "$", "db", ")", ")", ";", "}" ]
Search index action @return \Symfony\Component\HttpFoundation\Response
[ "Search", "index", "action" ]
9aab989a9bee9e6152ec19f8a30bc24f3bde6012
https://github.com/ringoteam/RingoPhpRedmonBundle/blob/9aab989a9bee9e6152ec19f8a30bc24f3bde6012/Controller/SearchController.php#L27-L63
train
gplcart/dev
Main.php
Main.setLogger
protected function setLogger() { $settings = $this->module->getSettings('dev'); $this->logger->printError(!empty($settings['print_error'])) ->errorToException(!empty($settings['error_to_exception'])) ->printBacktrace(!empty($settings['print_error_backtrace'])); }
php
protected function setLogger() { $settings = $this->module->getSettings('dev'); $this->logger->printError(!empty($settings['print_error'])) ->errorToException(!empty($settings['error_to_exception'])) ->printBacktrace(!empty($settings['print_error_backtrace'])); }
[ "protected", "function", "setLogger", "(", ")", "{", "$", "settings", "=", "$", "this", "->", "module", "->", "getSettings", "(", "'dev'", ")", ";", "$", "this", "->", "logger", "->", "printError", "(", "!", "empty", "(", "$", "settings", "[", "'print_error'", "]", ")", ")", "->", "errorToException", "(", "!", "empty", "(", "$", "settings", "[", "'error_to_exception'", "]", ")", ")", "->", "printBacktrace", "(", "!", "empty", "(", "$", "settings", "[", "'print_error_backtrace'", "]", ")", ")", ";", "}" ]
Configure system logger
[ "Configure", "system", "logger" ]
81352a220995a8db1e2b2bff73997780d1500f09
https://github.com/gplcart/dev/blob/81352a220995a8db1e2b2bff73997780d1500f09/Main.php#L186-L193
train
ekyna/Table
Bridge/Doctrine/ORM/Util/FilterUtil.php
FilterUtil.buildExpression
static public function buildExpression($property, $operator, $parameter = null) { FilterOperator::isValid($operator, true); $expr = new Expr(); switch (intval($operator)) { case FilterOperator::NOT_EQUAL: return $expr->neq($property, $parameter); case FilterOperator::LOWER_THAN: return $expr->lt($property, $parameter); case FilterOperator::LOWER_THAN_OR_EQUAL: return $expr->lte($property, $parameter); case FilterOperator::GREATER_THAN: return $expr->gt($property, $parameter); case FilterOperator::GREATER_THAN_OR_EQUAL: return $expr->gte($property, $parameter); case FilterOperator::IN: return $expr->in($property, $parameter); case FilterOperator::NOT_IN: return $expr->notIn($property, $parameter); case FilterOperator::MEMBER: return $expr->isMemberOf($parameter, $property); case FilterOperator::NOT_MEMBER: return $expr->not($expr->isMemberOf($parameter, $property)); case FilterOperator::LIKE: return $expr->like($property, $parameter); case FilterOperator::NOT_LIKE: return $expr->notLike($property, $parameter); case FilterOperator::START_WITH: return $expr->like($property, $parameter); case FilterOperator::NOT_START_WITH: return $expr->notLike($property, $parameter); case FilterOperator::END_WITH: return $expr->like($property, $parameter); case FilterOperator::NOT_END_WITH: return $expr->notLike($property, $parameter); case FilterOperator::IS_NULL: return $expr->isNull($property); case FilterOperator::IS_NOT_NULL: return $expr->isNotNull($property); default: return $expr->eq($property, $parameter); } }
php
static public function buildExpression($property, $operator, $parameter = null) { FilterOperator::isValid($operator, true); $expr = new Expr(); switch (intval($operator)) { case FilterOperator::NOT_EQUAL: return $expr->neq($property, $parameter); case FilterOperator::LOWER_THAN: return $expr->lt($property, $parameter); case FilterOperator::LOWER_THAN_OR_EQUAL: return $expr->lte($property, $parameter); case FilterOperator::GREATER_THAN: return $expr->gt($property, $parameter); case FilterOperator::GREATER_THAN_OR_EQUAL: return $expr->gte($property, $parameter); case FilterOperator::IN: return $expr->in($property, $parameter); case FilterOperator::NOT_IN: return $expr->notIn($property, $parameter); case FilterOperator::MEMBER: return $expr->isMemberOf($parameter, $property); case FilterOperator::NOT_MEMBER: return $expr->not($expr->isMemberOf($parameter, $property)); case FilterOperator::LIKE: return $expr->like($property, $parameter); case FilterOperator::NOT_LIKE: return $expr->notLike($property, $parameter); case FilterOperator::START_WITH: return $expr->like($property, $parameter); case FilterOperator::NOT_START_WITH: return $expr->notLike($property, $parameter); case FilterOperator::END_WITH: return $expr->like($property, $parameter); case FilterOperator::NOT_END_WITH: return $expr->notLike($property, $parameter); case FilterOperator::IS_NULL: return $expr->isNull($property); case FilterOperator::IS_NOT_NULL: return $expr->isNotNull($property); default: return $expr->eq($property, $parameter); } }
[ "static", "public", "function", "buildExpression", "(", "$", "property", ",", "$", "operator", ",", "$", "parameter", "=", "null", ")", "{", "FilterOperator", "::", "isValid", "(", "$", "operator", ",", "true", ")", ";", "$", "expr", "=", "new", "Expr", "(", ")", ";", "switch", "(", "intval", "(", "$", "operator", ")", ")", "{", "case", "FilterOperator", "::", "NOT_EQUAL", ":", "return", "$", "expr", "->", "neq", "(", "$", "property", ",", "$", "parameter", ")", ";", "case", "FilterOperator", "::", "LOWER_THAN", ":", "return", "$", "expr", "->", "lt", "(", "$", "property", ",", "$", "parameter", ")", ";", "case", "FilterOperator", "::", "LOWER_THAN_OR_EQUAL", ":", "return", "$", "expr", "->", "lte", "(", "$", "property", ",", "$", "parameter", ")", ";", "case", "FilterOperator", "::", "GREATER_THAN", ":", "return", "$", "expr", "->", "gt", "(", "$", "property", ",", "$", "parameter", ")", ";", "case", "FilterOperator", "::", "GREATER_THAN_OR_EQUAL", ":", "return", "$", "expr", "->", "gte", "(", "$", "property", ",", "$", "parameter", ")", ";", "case", "FilterOperator", "::", "IN", ":", "return", "$", "expr", "->", "in", "(", "$", "property", ",", "$", "parameter", ")", ";", "case", "FilterOperator", "::", "NOT_IN", ":", "return", "$", "expr", "->", "notIn", "(", "$", "property", ",", "$", "parameter", ")", ";", "case", "FilterOperator", "::", "MEMBER", ":", "return", "$", "expr", "->", "isMemberOf", "(", "$", "parameter", ",", "$", "property", ")", ";", "case", "FilterOperator", "::", "NOT_MEMBER", ":", "return", "$", "expr", "->", "not", "(", "$", "expr", "->", "isMemberOf", "(", "$", "parameter", ",", "$", "property", ")", ")", ";", "case", "FilterOperator", "::", "LIKE", ":", "return", "$", "expr", "->", "like", "(", "$", "property", ",", "$", "parameter", ")", ";", "case", "FilterOperator", "::", "NOT_LIKE", ":", "return", "$", "expr", "->", "notLike", "(", "$", "property", ",", "$", "parameter", ")", ";", "case", "FilterOperator", "::", "START_WITH", ":", "return", "$", "expr", "->", "like", "(", "$", "property", ",", "$", "parameter", ")", ";", "case", "FilterOperator", "::", "NOT_START_WITH", ":", "return", "$", "expr", "->", "notLike", "(", "$", "property", ",", "$", "parameter", ")", ";", "case", "FilterOperator", "::", "END_WITH", ":", "return", "$", "expr", "->", "like", "(", "$", "property", ",", "$", "parameter", ")", ";", "case", "FilterOperator", "::", "NOT_END_WITH", ":", "return", "$", "expr", "->", "notLike", "(", "$", "property", ",", "$", "parameter", ")", ";", "case", "FilterOperator", "::", "IS_NULL", ":", "return", "$", "expr", "->", "isNull", "(", "$", "property", ")", ";", "case", "FilterOperator", "::", "IS_NOT_NULL", ":", "return", "$", "expr", "->", "isNotNull", "(", "$", "property", ")", ";", "default", ":", "return", "$", "expr", "->", "eq", "(", "$", "property", ",", "$", "parameter", ")", ";", "}", "}" ]
Builds the query builder expression. @param string $property @param string $operator @param string $parameter @return string|Expr\Comparison|Expr\Func
[ "Builds", "the", "query", "builder", "expression", "." ]
6f06e8fd8a3248d52f3a91f10508471344db311a
https://github.com/ekyna/Table/blob/6f06e8fd8a3248d52f3a91f10508471344db311a/Bridge/Doctrine/ORM/Util/FilterUtil.php#L30-L73
train
ekyna/Table
Bridge/Doctrine/ORM/Util/FilterUtil.php
FilterUtil.buildParameterValue
static public function buildParameterValue($operator, $value) { FilterOperator::isValid($operator, true); switch (intval($operator)) { case FilterOperator::LIKE: case FilterOperator::NOT_LIKE: return sprintf('%%%s%%', $value); case FilterOperator::START_WITH: case FilterOperator::NOT_START_WITH: return sprintf('%s%%', $value); case FilterOperator::END_WITH: case FilterOperator::NOT_END_WITH: return sprintf('%%%s', $value); default: return $value; } }
php
static public function buildParameterValue($operator, $value) { FilterOperator::isValid($operator, true); switch (intval($operator)) { case FilterOperator::LIKE: case FilterOperator::NOT_LIKE: return sprintf('%%%s%%', $value); case FilterOperator::START_WITH: case FilterOperator::NOT_START_WITH: return sprintf('%s%%', $value); case FilterOperator::END_WITH: case FilterOperator::NOT_END_WITH: return sprintf('%%%s', $value); default: return $value; } }
[ "static", "public", "function", "buildParameterValue", "(", "$", "operator", ",", "$", "value", ")", "{", "FilterOperator", "::", "isValid", "(", "$", "operator", ",", "true", ")", ";", "switch", "(", "intval", "(", "$", "operator", ")", ")", "{", "case", "FilterOperator", "::", "LIKE", ":", "case", "FilterOperator", "::", "NOT_LIKE", ":", "return", "sprintf", "(", "'%%%s%%'", ",", "$", "value", ")", ";", "case", "FilterOperator", "::", "START_WITH", ":", "case", "FilterOperator", "::", "NOT_START_WITH", ":", "return", "sprintf", "(", "'%s%%'", ",", "$", "value", ")", ";", "case", "FilterOperator", "::", "END_WITH", ":", "case", "FilterOperator", "::", "NOT_END_WITH", ":", "return", "sprintf", "(", "'%%%s'", ",", "$", "value", ")", ";", "default", ":", "return", "$", "value", ";", "}", "}" ]
Builds the query builder parameter value. @param string $operator @param mixed $value @return Expr\Literal|mixed
[ "Builds", "the", "query", "builder", "parameter", "value", "." ]
6f06e8fd8a3248d52f3a91f10508471344db311a
https://github.com/ekyna/Table/blob/6f06e8fd8a3248d52f3a91f10508471344db311a/Bridge/Doctrine/ORM/Util/FilterUtil.php#L95-L112
train
brightnucleus/values
src/Value/AbstractValue.php
AbstractValue.escape
public function escape(string $target = EscapeTarget::HTML) { switch ($target) { case EscapeTarget::ATTRIBUTE: return $this->escapeAttribute(); case EscapeTarget::JS: return $this->escapeJS(); case EscapeTarget::HTML: default: return $this->escapeHTML(); } }
php
public function escape(string $target = EscapeTarget::HTML) { switch ($target) { case EscapeTarget::ATTRIBUTE: return $this->escapeAttribute(); case EscapeTarget::JS: return $this->escapeJS(); case EscapeTarget::HTML: default: return $this->escapeHTML(); } }
[ "public", "function", "escape", "(", "string", "$", "target", "=", "EscapeTarget", "::", "HTML", ")", "{", "switch", "(", "$", "target", ")", "{", "case", "EscapeTarget", "::", "ATTRIBUTE", ":", "return", "$", "this", "->", "escapeAttribute", "(", ")", ";", "case", "EscapeTarget", "::", "JS", ":", "return", "$", "this", "->", "escapeJS", "(", ")", ";", "case", "EscapeTarget", "::", "HTML", ":", "default", ":", "return", "$", "this", "->", "escapeHTML", "(", ")", ";", "}", "}" ]
Get an escaped version of the value. @since 0.1.0 @param string $target Optional. Escaping target to use. Defaults to HTML. @return mixed Sanitized version of the value.
[ "Get", "an", "escaped", "version", "of", "the", "value", "." ]
e9bdfbec949f6f964631aacaccaa98a0f13d916f
https://github.com/brightnucleus/values/blob/e9bdfbec949f6f964631aacaccaa98a0f13d916f/src/Value/AbstractValue.php#L186-L197
train
brightnucleus/values
src/Value/AbstractValue.php
AbstractValue.initializeValue
protected function initializeValue($value) { if ($this->isEmpty($value) && ! $this->flags & Value::CAN_BE_EMPTY) { throw FailedToValidate::fromValueForClass($value, $this); } if (! $this->isEmpty($value)) { $value = $this->validate($value); } if (null === $value) { throw FailedToValidate::fromValueForClass($value, $this); } $this->value = $value; }
php
protected function initializeValue($value) { if ($this->isEmpty($value) && ! $this->flags & Value::CAN_BE_EMPTY) { throw FailedToValidate::fromValueForClass($value, $this); } if (! $this->isEmpty($value)) { $value = $this->validate($value); } if (null === $value) { throw FailedToValidate::fromValueForClass($value, $this); } $this->value = $value; }
[ "protected", "function", "initializeValue", "(", "$", "value", ")", "{", "if", "(", "$", "this", "->", "isEmpty", "(", "$", "value", ")", "&&", "!", "$", "this", "->", "flags", "&", "Value", "::", "CAN_BE_EMPTY", ")", "{", "throw", "FailedToValidate", "::", "fromValueForClass", "(", "$", "value", ",", "$", "this", ")", ";", "}", "if", "(", "!", "$", "this", "->", "isEmpty", "(", "$", "value", ")", ")", "{", "$", "value", "=", "$", "this", "->", "validate", "(", "$", "value", ")", ";", "}", "if", "(", "null", "===", "$", "value", ")", "{", "throw", "FailedToValidate", "::", "fromValueForClass", "(", "$", "value", ",", "$", "this", ")", ";", "}", "$", "this", "->", "value", "=", "$", "value", ";", "}" ]
Initialize the value. @since 0.1.1 @param $value
[ "Initialize", "the", "value", "." ]
e9bdfbec949f6f964631aacaccaa98a0f13d916f
https://github.com/brightnucleus/values/blob/e9bdfbec949f6f964631aacaccaa98a0f13d916f/src/Value/AbstractValue.php#L232-L247
train
brightnucleus/values
src/Value/AbstractValue.php
AbstractValue.validateEncoding
protected function validateEncoding(): string { if (function_exists('mb_check_encoding') && mb_check_encoding($this->value, 'UTF-8') ) { return $this->value; } return function_exists('iconv') ? iconv('utf-8', 'utf-8', $this->value) : ''; }
php
protected function validateEncoding(): string { if (function_exists('mb_check_encoding') && mb_check_encoding($this->value, 'UTF-8') ) { return $this->value; } return function_exists('iconv') ? iconv('utf-8', 'utf-8', $this->value) : ''; }
[ "protected", "function", "validateEncoding", "(", ")", ":", "string", "{", "if", "(", "function_exists", "(", "'mb_check_encoding'", ")", "&&", "mb_check_encoding", "(", "$", "this", "->", "value", ",", "'UTF-8'", ")", ")", "{", "return", "$", "this", "->", "value", ";", "}", "return", "function_exists", "(", "'iconv'", ")", "?", "iconv", "(", "'utf-8'", ",", "'utf-8'", ",", "$", "this", "->", "value", ")", ":", "''", ";", "}" ]
Make sure the value is correctly encoded UTF-8. This prevents the so-called "Invalid Encoding Attack". @since 0.1.0 @return string Valid UTF-8 encoded string.
[ "Make", "sure", "the", "value", "is", "correctly", "encoded", "UTF", "-", "8", "." ]
e9bdfbec949f6f964631aacaccaa98a0f13d916f
https://github.com/brightnucleus/values/blob/e9bdfbec949f6f964631aacaccaa98a0f13d916f/src/Value/AbstractValue.php#L258-L269
train
brightnucleus/values
src/Value/AbstractValue.php
AbstractValue.escapeAttribute
protected function escapeAttribute(): string { $value = $this->validateEncoding(); $value = strip_tags($value); return htmlspecialchars($value, ENT_QUOTES); }
php
protected function escapeAttribute(): string { $value = $this->validateEncoding(); $value = strip_tags($value); return htmlspecialchars($value, ENT_QUOTES); }
[ "protected", "function", "escapeAttribute", "(", ")", ":", "string", "{", "$", "value", "=", "$", "this", "->", "validateEncoding", "(", ")", ";", "$", "value", "=", "strip_tags", "(", "$", "value", ")", ";", "return", "htmlspecialchars", "(", "$", "value", ",", "ENT_QUOTES", ")", ";", "}" ]
Escape the value to be used as a HTML attribute. @since 0.1.0 @return string
[ "Escape", "the", "value", "to", "be", "used", "as", "a", "HTML", "attribute", "." ]
e9bdfbec949f6f964631aacaccaa98a0f13d916f
https://github.com/brightnucleus/values/blob/e9bdfbec949f6f964631aacaccaa98a0f13d916f/src/Value/AbstractValue.php#L292-L298
train
brightnucleus/values
src/Value/AbstractValue.php
AbstractValue.escapeJS
protected function escapeJS(): string { $value = $this->validateEncoding(); $value = htmlspecialchars($value, ENT_COMPAT); $value = preg_replace('/&#(x)?0*(?(1)27|39);?/i', '\'', stripslashes($value)); $value = str_replace("\r", '', $value); return str_replace("\n", '\\n', addslashes($value)); }
php
protected function escapeJS(): string { $value = $this->validateEncoding(); $value = htmlspecialchars($value, ENT_COMPAT); $value = preg_replace('/&#(x)?0*(?(1)27|39);?/i', '\'', stripslashes($value)); $value = str_replace("\r", '', $value); return str_replace("\n", '\\n', addslashes($value)); }
[ "protected", "function", "escapeJS", "(", ")", ":", "string", "{", "$", "value", "=", "$", "this", "->", "validateEncoding", "(", ")", ";", "$", "value", "=", "htmlspecialchars", "(", "$", "value", ",", "ENT_COMPAT", ")", ";", "$", "value", "=", "preg_replace", "(", "'/&#(x)?0*(?(1)27|39);?/i'", ",", "'\\''", ",", "stripslashes", "(", "$", "value", ")", ")", ";", "$", "value", "=", "str_replace", "(", "\"\\r\"", ",", "''", ",", "$", "value", ")", ";", "return", "str_replace", "(", "\"\\n\"", ",", "'\\\\n'", ",", "addslashes", "(", "$", "value", ")", ")", ";", "}" ]
Escape the value to be used within JavaScript. @since 0.1.0 @return string
[ "Escape", "the", "value", "to", "be", "used", "within", "JavaScript", "." ]
e9bdfbec949f6f964631aacaccaa98a0f13d916f
https://github.com/brightnucleus/values/blob/e9bdfbec949f6f964631aacaccaa98a0f13d916f/src/Value/AbstractValue.php#L307-L316
train