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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
parable-php/di | src/Container.php | Container.map | public function map(string $requested, string $replacement): void
{
$this->maps[$this->normalize($requested)] = $this->normalize($replacement);
} | php | public function map(string $requested, string $replacement): void
{
$this->maps[$this->normalize($requested)] = $this->normalize($replacement);
} | [
"public",
"function",
"map",
"(",
"string",
"$",
"requested",
",",
"string",
"$",
"replacement",
")",
":",
"void",
"{",
"$",
"this",
"->",
"maps",
"[",
"$",
"this",
"->",
"normalize",
"(",
"$",
"requested",
")",
"]",
"=",
"$",
"this",
"->",
"normaliz... | Map the requested name to the replacement name. When the requested
name is retrieved, the replacement name will be used to build the instance. | [
"Map",
"the",
"requested",
"name",
"to",
"the",
"replacement",
"name",
".",
"When",
"the",
"requested",
"name",
"is",
"retrieved",
"the",
"replacement",
"name",
"will",
"be",
"used",
"to",
"build",
"the",
"instance",
"."
] | 8dd34615f3245c602bb387ab4a48128f922ca763 | https://github.com/parable-php/di/blob/8dd34615f3245c602bb387ab4a48128f922ca763/src/Container.php#L112-L115 | train |
parable-php/di | src/Container.php | Container.getDependenciesFor | public function getDependenciesFor(
string $name,
int $useStoredDependencies = self::USE_STORED_DEPENDENCIES
): array {
$name = $this->getDefinitiveName($name);
try {
$reflection = new ReflectionClass($name);
} catch (Throwable $e) {
throw new ContainerException(sprintf(
'Could not create instance for class `%s`.',
$name
));
}
$constructor = $reflection->getConstructor();
if (!$constructor) {
return [];
}
$parameters = $constructor->getParameters();
$relationships = [];
$dependencies = [];
foreach ($parameters as $parameter) {
$class = $parameter->getClass();
if ($class === null) {
if (!$parameter->isOptional()) {
throw new ContainerException(sprintf(
'Cannot inject value for non-optional constructor parameter `$%s` without a default value.',
$parameter->name
));
}
$dependencies[] = $parameter->getDefaultValue();
continue;
}
$dependencyName = $this->getDefinitiveName($class->name);
$this->storeRelationship($name, $dependencyName);
$relationships[] = $dependencyName;
if ($useStoredDependencies === self::USE_NEW_DEPENDENCIES) {
$dependencies[] = $this->build($dependencyName);
} elseif ($useStoredDependencies === self::USE_STORED_DEPENDENCIES) {
$dependencies[] = $this->get($dependencyName);
} else {
throw new ContainerException(sprintf(
'Invalid dependency type value passed: `%d`.',
$useStoredDependencies
));
}
}
return $dependencies;
} | php | public function getDependenciesFor(
string $name,
int $useStoredDependencies = self::USE_STORED_DEPENDENCIES
): array {
$name = $this->getDefinitiveName($name);
try {
$reflection = new ReflectionClass($name);
} catch (Throwable $e) {
throw new ContainerException(sprintf(
'Could not create instance for class `%s`.',
$name
));
}
$constructor = $reflection->getConstructor();
if (!$constructor) {
return [];
}
$parameters = $constructor->getParameters();
$relationships = [];
$dependencies = [];
foreach ($parameters as $parameter) {
$class = $parameter->getClass();
if ($class === null) {
if (!$parameter->isOptional()) {
throw new ContainerException(sprintf(
'Cannot inject value for non-optional constructor parameter `$%s` without a default value.',
$parameter->name
));
}
$dependencies[] = $parameter->getDefaultValue();
continue;
}
$dependencyName = $this->getDefinitiveName($class->name);
$this->storeRelationship($name, $dependencyName);
$relationships[] = $dependencyName;
if ($useStoredDependencies === self::USE_NEW_DEPENDENCIES) {
$dependencies[] = $this->build($dependencyName);
} elseif ($useStoredDependencies === self::USE_STORED_DEPENDENCIES) {
$dependencies[] = $this->get($dependencyName);
} else {
throw new ContainerException(sprintf(
'Invalid dependency type value passed: `%d`.',
$useStoredDependencies
));
}
}
return $dependencies;
} | [
"public",
"function",
"getDependenciesFor",
"(",
"string",
"$",
"name",
",",
"int",
"$",
"useStoredDependencies",
"=",
"self",
"::",
"USE_STORED_DEPENDENCIES",
")",
":",
"array",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"getDefinitiveName",
"(",
"$",
"name",
... | Get the dependencies for an instance, based on the constructor.
Optionally use stored dependencies or always create new ones.
@throws ContainerException | [
"Get",
"the",
"dependencies",
"for",
"an",
"instance",
"based",
"on",
"the",
"constructor",
".",
"Optionally",
"use",
"stored",
"dependencies",
"or",
"always",
"create",
"new",
"ones",
"."
] | 8dd34615f3245c602bb387ab4a48128f922ca763 | https://github.com/parable-php/di/blob/8dd34615f3245c602bb387ab4a48128f922ca763/src/Container.php#L131-L191 | train |
parable-php/di | src/Container.php | Container.store | public function store($instance, string $name = null): void
{
if ($name === null) {
$name = get_class($instance);
}
$name = $this->getDefinitiveName($name);
$this->instances[$name] = $instance;
} | php | public function store($instance, string $name = null): void
{
if ($name === null) {
$name = get_class($instance);
}
$name = $this->getDefinitiveName($name);
$this->instances[$name] = $instance;
} | [
"public",
"function",
"store",
"(",
"$",
"instance",
",",
"string",
"$",
"name",
"=",
"null",
")",
":",
"void",
"{",
"if",
"(",
"$",
"name",
"===",
"null",
")",
"{",
"$",
"name",
"=",
"get_class",
"(",
"$",
"instance",
")",
";",
"}",
"$",
"name",... | Store the provided instance with the provided id, or the class name of the object. | [
"Store",
"the",
"provided",
"instance",
"with",
"the",
"provided",
"id",
"or",
"the",
"class",
"name",
"of",
"the",
"object",
"."
] | 8dd34615f3245c602bb387ab4a48128f922ca763 | https://github.com/parable-php/di/blob/8dd34615f3245c602bb387ab4a48128f922ca763/src/Container.php#L196-L205 | train |
parable-php/di | src/Container.php | Container.clear | public function clear(string $name): void
{
$name = $this->getDefinitiveName($name);
if (!$this->has($name)) {
throw NotFoundException::fromId($name);
}
unset($this->instances[$name]);
$this->clearRelationship($name);
} | php | public function clear(string $name): void
{
$name = $this->getDefinitiveName($name);
if (!$this->has($name)) {
throw NotFoundException::fromId($name);
}
unset($this->instances[$name]);
$this->clearRelationship($name);
} | [
"public",
"function",
"clear",
"(",
"string",
"$",
"name",
")",
":",
"void",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"getDefinitiveName",
"(",
"$",
"name",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"has",
"(",
"$",
"name",
")",
")",
"{",
"... | Clear the requested instance.
@throws NotFoundException | [
"Clear",
"the",
"requested",
"instance",
"."
] | 8dd34615f3245c602bb387ab4a48128f922ca763 | https://github.com/parable-php/di/blob/8dd34615f3245c602bb387ab4a48128f922ca763/src/Container.php#L212-L223 | train |
parable-php/di | src/Container.php | Container.clearExcept | public function clearExcept(array $keep): void
{
$kept = [];
foreach ($keep as $name) {
$name = $this->getDefinitiveName($name);
if (!$this->has($name)) {
throw NotFoundException::fromId($name);
}
$kept[$name] = $this->get($name);
}
$this->instances = $kept;
} | php | public function clearExcept(array $keep): void
{
$kept = [];
foreach ($keep as $name) {
$name = $this->getDefinitiveName($name);
if (!$this->has($name)) {
throw NotFoundException::fromId($name);
}
$kept[$name] = $this->get($name);
}
$this->instances = $kept;
} | [
"public",
"function",
"clearExcept",
"(",
"array",
"$",
"keep",
")",
":",
"void",
"{",
"$",
"kept",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"keep",
"as",
"$",
"name",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"getDefinitiveName",
"(",
"$",
... | Clear all instances except those provided.
@param string[] $keep
@throws ContainerException
@throws NotFoundException | [
"Clear",
"all",
"instances",
"except",
"those",
"provided",
"."
] | 8dd34615f3245c602bb387ab4a48128f922ca763 | https://github.com/parable-php/di/blob/8dd34615f3245c602bb387ab4a48128f922ca763/src/Container.php#L233-L247 | train |
parable-php/di | src/Container.php | Container.storeRelationship | protected function storeRelationship(string $class, string $dependency): void
{
$this->relationships[$class][$dependency] = true;
if (isset($this->relationships[$class][$dependency]) && isset($this->relationships[$dependency][$class])) {
throw new ContainerException(sprintf(
'Cyclical dependency found between `%s` and `%s`.',
$class,
$dependency
));
}
} | php | protected function storeRelationship(string $class, string $dependency): void
{
$this->relationships[$class][$dependency] = true;
if (isset($this->relationships[$class][$dependency]) && isset($this->relationships[$dependency][$class])) {
throw new ContainerException(sprintf(
'Cyclical dependency found between `%s` and `%s`.',
$class,
$dependency
));
}
} | [
"protected",
"function",
"storeRelationship",
"(",
"string",
"$",
"class",
",",
"string",
"$",
"dependency",
")",
":",
"void",
"{",
"$",
"this",
"->",
"relationships",
"[",
"$",
"class",
"]",
"[",
"$",
"dependency",
"]",
"=",
"true",
";",
"if",
"(",
"i... | Store the relationship between the two items.
@throws ContainerException | [
"Store",
"the",
"relationship",
"between",
"the",
"two",
"items",
"."
] | 8dd34615f3245c602bb387ab4a48128f922ca763 | https://github.com/parable-php/di/blob/8dd34615f3245c602bb387ab4a48128f922ca763/src/Container.php#L263-L274 | train |
parable-php/di | src/Container.php | Container.clearRelationship | protected function clearRelationship(string $name): void
{
// Clear from the left
unset($this->relationships[$name]);
// And clear from the right
foreach ($this->relationships as $left => &$objectNames) {
if (isset($objectNames[$name])) {
unset($objectNames[$name]);
}
}
} | php | protected function clearRelationship(string $name): void
{
// Clear from the left
unset($this->relationships[$name]);
// And clear from the right
foreach ($this->relationships as $left => &$objectNames) {
if (isset($objectNames[$name])) {
unset($objectNames[$name]);
}
}
} | [
"protected",
"function",
"clearRelationship",
"(",
"string",
"$",
"name",
")",
":",
"void",
"{",
"// Clear from the left",
"unset",
"(",
"$",
"this",
"->",
"relationships",
"[",
"$",
"name",
"]",
")",
";",
"// And clear from the right",
"foreach",
"(",
"$",
"t... | Clear the relationship for the provided id. | [
"Clear",
"the",
"relationship",
"for",
"the",
"provided",
"id",
"."
] | 8dd34615f3245c602bb387ab4a48128f922ca763 | https://github.com/parable-php/di/blob/8dd34615f3245c602bb387ab4a48128f922ca763/src/Container.php#L279-L290 | train |
spiral/odm | source/Spiral/ODM/Entities/DocumentInstantiator.php | DocumentInstantiator.defineClass | protected function defineClass($fields)
{
//Rule to define class instance
$definition = $this->schema[DocumentEntity::SH_INSTANTIATION];
if (is_string($definition)) {
//Document has no variations
return $definition;
}
if (!is_array($fields)) {
//Unable to resolve for non array set, using same class as given
return $this->class;
}
$defined = $this->class;
foreach ($definition as $field => $child) {
if (array_key_exists($field, $fields)) {
//Apparently this is child
$defined = $child;
break;
}
}
return $defined;
} | php | protected function defineClass($fields)
{
//Rule to define class instance
$definition = $this->schema[DocumentEntity::SH_INSTANTIATION];
if (is_string($definition)) {
//Document has no variations
return $definition;
}
if (!is_array($fields)) {
//Unable to resolve for non array set, using same class as given
return $this->class;
}
$defined = $this->class;
foreach ($definition as $field => $child) {
if (array_key_exists($field, $fields)) {
//Apparently this is child
$defined = $child;
break;
}
}
return $defined;
} | [
"protected",
"function",
"defineClass",
"(",
"$",
"fields",
")",
"{",
"//Rule to define class instance",
"$",
"definition",
"=",
"$",
"this",
"->",
"schema",
"[",
"DocumentEntity",
"::",
"SH_INSTANTIATION",
"]",
";",
"if",
"(",
"is_string",
"(",
"$",
"definition... | Define document class using it's fieldset and definition.
@param \ArrayAccess|array $fields
@return string
@throws DefinitionException | [
"Define",
"document",
"class",
"using",
"it",
"s",
"fieldset",
"and",
"definition",
"."
] | 06087691a05dcfaa86c6c461660c6029db4de06e | https://github.com/spiral/odm/blob/06087691a05dcfaa86c6c461660c6029db4de06e/source/Spiral/ODM/Entities/DocumentInstantiator.php#L106-L131 | train |
bookboon/api-php | src/Client/HashTrait.php | HashTrait.isCachable | public function isCachable(string $url, string $httpMethod) : bool
{
return $httpMethod === ClientInterface::HTTP_GET && $this->getCache() !== null;
} | php | public function isCachable(string $url, string $httpMethod) : bool
{
return $httpMethod === ClientInterface::HTTP_GET && $this->getCache() !== null;
} | [
"public",
"function",
"isCachable",
"(",
"string",
"$",
"url",
",",
"string",
"$",
"httpMethod",
")",
":",
"bool",
"{",
"return",
"$",
"httpMethod",
"===",
"ClientInterface",
"::",
"HTTP_GET",
"&&",
"$",
"this",
"->",
"getCache",
"(",
")",
"!==",
"null",
... | Determine whether cache should be attempted.
@param string $url
@param string $httpMethod
@return bool
@internal param $variables | [
"Determine",
"whether",
"cache",
"should",
"be",
"attempted",
"."
] | dc386b94dd21589606335a5d16a5300c226ecc21 | https://github.com/bookboon/api-php/blob/dc386b94dd21589606335a5d16a5300c226ecc21/src/Client/HashTrait.php#L43-L46 | train |
solspace/craft3-commons | src/Helpers/ColorHelper.php | ColorHelper.getContrastYIQ | public static function getContrastYIQ($hexColor): string
{
$hexColor = str_replace('#', '', $hexColor);
$r = hexdec(substr($hexColor, 0, 2));
$g = hexdec(substr($hexColor, 2, 2));
$b = hexdec(substr($hexColor, 4, 2));
$yiq = (($r * 299) + ($g * 587) + ($b * 114)) / 1000;
return ($yiq >= 128) ? 'black' : 'white';
} | php | public static function getContrastYIQ($hexColor): string
{
$hexColor = str_replace('#', '', $hexColor);
$r = hexdec(substr($hexColor, 0, 2));
$g = hexdec(substr($hexColor, 2, 2));
$b = hexdec(substr($hexColor, 4, 2));
$yiq = (($r * 299) + ($g * 587) + ($b * 114)) / 1000;
return ($yiq >= 128) ? 'black' : 'white';
} | [
"public",
"static",
"function",
"getContrastYIQ",
"(",
"$",
"hexColor",
")",
":",
"string",
"{",
"$",
"hexColor",
"=",
"str_replace",
"(",
"'#'",
",",
"''",
",",
"$",
"hexColor",
")",
";",
"$",
"r",
"=",
"hexdec",
"(",
"substr",
"(",
"$",
"hexColor",
... | Determines if the contrasting color to be used based on a HEX color code
@param string $hexColor
@return string | [
"Determines",
"if",
"the",
"contrasting",
"color",
"to",
"be",
"used",
"based",
"on",
"a",
"HEX",
"color",
"code"
] | 2de20a76e83efe3ed615a2a102dfef18e2295420 | https://github.com/solspace/craft3-commons/blob/2de20a76e83efe3ed615a2a102dfef18e2295420/src/Helpers/ColorHelper.php#L33-L43 | train |
phpcq/author-validation | src/AuthorExtractor/PhpDocAuthorExtractor.php | PhpDocAuthorExtractor.setAuthors | protected function setAuthors($docBlock, $authors)
{
$newAuthors = array_unique(array_values($authors));
$lines = \explode("\n", $docBlock);
$lastAuthor = 0;
$indention = ' * @author ';
$cleaned = [];
foreach ($lines as $number => $line) {
if (\strpos($line, '@author') === false) {
continue;
}
$lastAuthor = $number;
$suffix = \trim(\substr($line, (\strpos($line, '@author') + 7)));
$indention = \substr($line, 0, (\strlen($line) - \strlen($suffix)));
$index = $this->searchAuthor($line, $newAuthors);
// Obsolete entry, remove it.
if (false === $index) {
$lines[$number] = null;
$cleaned[] = $number;
} else {
unset($newAuthors[$index]);
}
}
$lines = $this->addNewAuthors($lines, $newAuthors, $cleaned, $lastAuthor, $indention);
return \implode("\n", \array_filter($lines, function ($value) {
return null !== $value;
}));
} | php | protected function setAuthors($docBlock, $authors)
{
$newAuthors = array_unique(array_values($authors));
$lines = \explode("\n", $docBlock);
$lastAuthor = 0;
$indention = ' * @author ';
$cleaned = [];
foreach ($lines as $number => $line) {
if (\strpos($line, '@author') === false) {
continue;
}
$lastAuthor = $number;
$suffix = \trim(\substr($line, (\strpos($line, '@author') + 7)));
$indention = \substr($line, 0, (\strlen($line) - \strlen($suffix)));
$index = $this->searchAuthor($line, $newAuthors);
// Obsolete entry, remove it.
if (false === $index) {
$lines[$number] = null;
$cleaned[] = $number;
} else {
unset($newAuthors[$index]);
}
}
$lines = $this->addNewAuthors($lines, $newAuthors, $cleaned, $lastAuthor, $indention);
return \implode("\n", \array_filter($lines, function ($value) {
return null !== $value;
}));
} | [
"protected",
"function",
"setAuthors",
"(",
"$",
"docBlock",
",",
"$",
"authors",
")",
"{",
"$",
"newAuthors",
"=",
"array_unique",
"(",
"array_values",
"(",
"$",
"authors",
")",
")",
";",
"$",
"lines",
"=",
"\\",
"explode",
"(",
"\"\\n\"",
",",
"$",
"... | Set the author information in doc block.
@param string $docBlock The doc block.
@param array $authors The authors to set in the doc block.
@return string The updated doc block. | [
"Set",
"the",
"author",
"information",
"in",
"doc",
"block",
"."
] | 1e22f6133dcadea486a7961274f4e611b5ef4c0c | https://github.com/phpcq/author-validation/blob/1e22f6133dcadea486a7961274f4e611b5ef4c0c/src/AuthorExtractor/PhpDocAuthorExtractor.php#L102-L134 | train |
phpcq/author-validation | src/AuthorExtractor/PhpDocAuthorExtractor.php | PhpDocAuthorExtractor.addNewAuthors | protected function addNewAuthors(array $lines, array $newAuthors, array $emptyLines, $lastAuthor, $indention)
{
if (empty($newAuthors)) {
return $lines;
}
// Fill the gaps we just made.
foreach ($emptyLines as $number) {
if (null === $author = \array_shift($newAuthors)) {
break;
}
$lines[$number] = $indention . $author;
}
if ((int) $lastAuthor === 0) {
$lastAuthor = (\count($lines) - 2);
}
if (0 === ($count = count($newAuthors))) {
return $lines;
}
// Still not empty, we have mooooore.
$lines = array_merge(
array_slice($lines, 0, ++$lastAuthor),
array_fill(0, $count, null),
array_slice($lines, $lastAuthor)
);
while ($author = \array_shift($newAuthors)) {
$lines[$lastAuthor++] = $indention . $author;
}
return $lines;
} | php | protected function addNewAuthors(array $lines, array $newAuthors, array $emptyLines, $lastAuthor, $indention)
{
if (empty($newAuthors)) {
return $lines;
}
// Fill the gaps we just made.
foreach ($emptyLines as $number) {
if (null === $author = \array_shift($newAuthors)) {
break;
}
$lines[$number] = $indention . $author;
}
if ((int) $lastAuthor === 0) {
$lastAuthor = (\count($lines) - 2);
}
if (0 === ($count = count($newAuthors))) {
return $lines;
}
// Still not empty, we have mooooore.
$lines = array_merge(
array_slice($lines, 0, ++$lastAuthor),
array_fill(0, $count, null),
array_slice($lines, $lastAuthor)
);
while ($author = \array_shift($newAuthors)) {
$lines[$lastAuthor++] = $indention . $author;
}
return $lines;
} | [
"protected",
"function",
"addNewAuthors",
"(",
"array",
"$",
"lines",
",",
"array",
"$",
"newAuthors",
",",
"array",
"$",
"emptyLines",
",",
"$",
"lastAuthor",
",",
"$",
"indention",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"newAuthors",
")",
")",
"{",
... | Add new authors to a buffer.
@param array $lines The buffer to update.
@param array $newAuthors The new authors to add.
@param array $emptyLines The empty line numbers.
@param int $lastAuthor The index in the buffer where the last author annotation is.
@param string $indention The annotation prefix.
@return array | [
"Add",
"new",
"authors",
"to",
"a",
"buffer",
"."
] | 1e22f6133dcadea486a7961274f4e611b5ef4c0c | https://github.com/phpcq/author-validation/blob/1e22f6133dcadea486a7961274f4e611b5ef4c0c/src/AuthorExtractor/PhpDocAuthorExtractor.php#L147-L179 | train |
phpcq/author-validation | src/AuthorExtractor/PhpDocAuthorExtractor.php | PhpDocAuthorExtractor.searchAuthor | private function searchAuthor($line, $authors)
{
foreach ($authors as $index => $author) {
list($name, $email) = \explode(' <', $author);
$name = \trim($name);
$email = \trim(\substr($email, 0, -1));
if ((\strpos($line, $name) !== false) && (\strpos($line, $email) !== false)) {
unset($authors[$index]);
return $index;
}
}
return false;
} | php | private function searchAuthor($line, $authors)
{
foreach ($authors as $index => $author) {
list($name, $email) = \explode(' <', $author);
$name = \trim($name);
$email = \trim(\substr($email, 0, -1));
if ((\strpos($line, $name) !== false) && (\strpos($line, $email) !== false)) {
unset($authors[$index]);
return $index;
}
}
return false;
} | [
"private",
"function",
"searchAuthor",
"(",
"$",
"line",
",",
"$",
"authors",
")",
"{",
"foreach",
"(",
"$",
"authors",
"as",
"$",
"index",
"=>",
"$",
"author",
")",
"{",
"list",
"(",
"$",
"name",
",",
"$",
"email",
")",
"=",
"\\",
"explode",
"(",
... | Search the author in "line" in the passed array and return the index of the match or false if none matches.
@param string $line The author to search for.
@param string[] $authors The author list to search in.
@return false|int | [
"Search",
"the",
"author",
"in",
"line",
"in",
"the",
"passed",
"array",
"and",
"return",
"the",
"index",
"of",
"the",
"match",
"or",
"false",
"if",
"none",
"matches",
"."
] | 1e22f6133dcadea486a7961274f4e611b5ef4c0c | https://github.com/phpcq/author-validation/blob/1e22f6133dcadea486a7961274f4e611b5ef4c0c/src/AuthorExtractor/PhpDocAuthorExtractor.php#L189-L203 | train |
droath/project-x | src/EngineTrait.php | EngineTrait.getEngineOptions | protected function getEngineOptions()
{
$config = ProjectX::getProjectConfig();
$engine = $config->getEngine();
$options = $config->getOptions();
return isset($options[$engine])
? $options[$engine]
: [];
} | php | protected function getEngineOptions()
{
$config = ProjectX::getProjectConfig();
$engine = $config->getEngine();
$options = $config->getOptions();
return isset($options[$engine])
? $options[$engine]
: [];
} | [
"protected",
"function",
"getEngineOptions",
"(",
")",
"{",
"$",
"config",
"=",
"ProjectX",
"::",
"getProjectConfig",
"(",
")",
";",
"$",
"engine",
"=",
"$",
"config",
"->",
"getEngine",
"(",
")",
";",
"$",
"options",
"=",
"$",
"config",
"->",
"getOption... | Get environment engine options.
@return array
An array of engine options defined in the project-x configuration. | [
"Get",
"environment",
"engine",
"options",
"."
] | 85a7a4879bd041f4c5cb565356646e5f5e2435b7 | https://github.com/droath/project-x/blob/85a7a4879bd041f4c5cb565356646e5f5e2435b7/src/EngineTrait.php#L42-L52 | train |
droath/project-x | src/EngineTrait.php | EngineTrait.executeEngineCommand | protected function executeEngineCommand($command, $service = null, $options = [], $quiet = false, $localhost = false)
{
if ($command instanceof CommandBuilder) {
$command = $command->build();
}
$engine = $this->getEngineInstance();
if ($engine instanceof DockerEngineType && !$localhost) {
$results = $engine->execRaw($command, $service, $options, $quiet);
} else {
$results = $this->_exec($command);
}
$this->validateTaskResult($results);
return $results;
} | php | protected function executeEngineCommand($command, $service = null, $options = [], $quiet = false, $localhost = false)
{
if ($command instanceof CommandBuilder) {
$command = $command->build();
}
$engine = $this->getEngineInstance();
if ($engine instanceof DockerEngineType && !$localhost) {
$results = $engine->execRaw($command, $service, $options, $quiet);
} else {
$results = $this->_exec($command);
}
$this->validateTaskResult($results);
return $results;
} | [
"protected",
"function",
"executeEngineCommand",
"(",
"$",
"command",
",",
"$",
"service",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"]",
",",
"$",
"quiet",
"=",
"false",
",",
"$",
"localhost",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"command",
"in... | Execute environment engine command.
@param $command
@param null $service
@param array $options
@param bool $quiet
@param bool $localhost
@return \Robo\Result|\Robo\ResultData | [
"Execute",
"environment",
"engine",
"command",
"."
] | 85a7a4879bd041f4c5cb565356646e5f5e2435b7 | https://github.com/droath/project-x/blob/85a7a4879bd041f4c5cb565356646e5f5e2435b7/src/EngineTrait.php#L79-L95 | train |
silvercommerce/catalogue-admin | src/import/ProductCSVBulkLoader.php | ProductCSVBulkLoader.createRelationFromList | protected function createRelationFromList(
$object,
$relation,
$list,
$class,
$column,
$create = false
) {
$object->$relation()->removeAll();
foreach ($list as $name) {
$name = trim($name);
if (!empty($name)) {
$obj = $class::get()->find($column, $name);
if (empty($obj) && $create) {
$obj = $class::create();
$obj->$column = $name;
$obj->write();
}
if (!empty($obj)) {
$object->$relation()->add($obj);
}
}
}
} | php | protected function createRelationFromList(
$object,
$relation,
$list,
$class,
$column,
$create = false
) {
$object->$relation()->removeAll();
foreach ($list as $name) {
$name = trim($name);
if (!empty($name)) {
$obj = $class::get()->find($column, $name);
if (empty($obj) && $create) {
$obj = $class::create();
$obj->$column = $name;
$obj->write();
}
if (!empty($obj)) {
$object->$relation()->add($obj);
}
}
}
} | [
"protected",
"function",
"createRelationFromList",
"(",
"$",
"object",
",",
"$",
"relation",
",",
"$",
"list",
",",
"$",
"class",
",",
"$",
"column",
",",
"$",
"create",
"=",
"false",
")",
"{",
"$",
"object",
"->",
"$",
"relation",
"(",
")",
"->",
"r... | Generate the selected relation from the provided array of values
@param string $object The current object being imported
@param string $relation The name of the relation (eg Images)
@param array $list The list of values
@param string $class The source class of the relation (eg SilverStripe\Assets\Image)
@param string $column The name of the column to search for existing records
@param string $create Create a new object if none found
@return void | [
"Generate",
"the",
"selected",
"relation",
"from",
"the",
"provided",
"array",
"of",
"values"
] | 17dbd180538822e43c597444016fe09d699506ff | https://github.com/silvercommerce/catalogue-admin/blob/17dbd180538822e43c597444016fe09d699506ff/src/import/ProductCSVBulkLoader.php#L65-L92 | train |
spiral/odm | source/Spiral/ODM/Schemas/InheritanceHelper.php | InheritanceHelper.makeDefinition | public function makeDefinition()
{
//Find only first level children stored in the same collection
$children = $this->findChildren(true, true);
if (empty($children)) {
//Nothing to inherit
return $this->schema->getClass();
}
//We must sort child in order or unique fields
uasort($children, [$this, 'sortChildren']);
//Fields which are common for parent and child models
$commonFields = $this->schema->getReflection()->getSchema();
$definition = [];
foreach ($children as $schema) {
//Child document fields
$fields = $schema->getReflection()->getSchema();
if (empty($fields)) {
throw new DefinitionException(
"Child document '{$schema->getClass()}' of '{$this->schema->getClass()}' does not have any fields"
);
}
$uniqueField = null;
if (empty($commonFields)) {
//Parent did not declare any fields, happen sometimes
$commonFields = $fields;
$uniqueField = key($fields);
} else {
foreach ($fields as $field => $type) {
if (!isset($commonFields[$field])) {
if (empty($uniqueField)) {
$uniqueField = $field;
}
//New non unique field (must be excluded from analysis)
$commonFields[$field] = true;
}
}
}
if (empty($uniqueField)) {
throw new DefinitionException(
"Child document '{$schema->getClass()}' of '{$this->schema->getClass()}' does not have any unique field"
);
}
$definition[$uniqueField] = $schema->getClass();
}
return $definition;
} | php | public function makeDefinition()
{
//Find only first level children stored in the same collection
$children = $this->findChildren(true, true);
if (empty($children)) {
//Nothing to inherit
return $this->schema->getClass();
}
//We must sort child in order or unique fields
uasort($children, [$this, 'sortChildren']);
//Fields which are common for parent and child models
$commonFields = $this->schema->getReflection()->getSchema();
$definition = [];
foreach ($children as $schema) {
//Child document fields
$fields = $schema->getReflection()->getSchema();
if (empty($fields)) {
throw new DefinitionException(
"Child document '{$schema->getClass()}' of '{$this->schema->getClass()}' does not have any fields"
);
}
$uniqueField = null;
if (empty($commonFields)) {
//Parent did not declare any fields, happen sometimes
$commonFields = $fields;
$uniqueField = key($fields);
} else {
foreach ($fields as $field => $type) {
if (!isset($commonFields[$field])) {
if (empty($uniqueField)) {
$uniqueField = $field;
}
//New non unique field (must be excluded from analysis)
$commonFields[$field] = true;
}
}
}
if (empty($uniqueField)) {
throw new DefinitionException(
"Child document '{$schema->getClass()}' of '{$this->schema->getClass()}' does not have any unique field"
);
}
$definition[$uniqueField] = $schema->getClass();
}
return $definition;
} | [
"public",
"function",
"makeDefinition",
"(",
")",
"{",
"//Find only first level children stored in the same collection",
"$",
"children",
"=",
"$",
"this",
"->",
"findChildren",
"(",
"true",
",",
"true",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"children",
")",
"... | Compile information required to resolve class instance using given set of fields. Fields
based definition will analyze unique fields in every child model to create association
between model class and required set of fields. Only document from same collection will be
involved in definition creation. Definition built only for child of first order.
@return array|string
@throws DefinitionException | [
"Compile",
"information",
"required",
"to",
"resolve",
"class",
"instance",
"using",
"given",
"set",
"of",
"fields",
".",
"Fields",
"based",
"definition",
"will",
"analyze",
"unique",
"fields",
"in",
"every",
"child",
"model",
"to",
"create",
"association",
"bet... | 06087691a05dcfaa86c6c461660c6029db4de06e | https://github.com/spiral/odm/blob/06087691a05dcfaa86c6c461660c6029db4de06e/source/Spiral/ODM/Schemas/InheritanceHelper.php#L51-L106 | train |
spiral/odm | source/Spiral/ODM/Schemas/InheritanceHelper.php | InheritanceHelper.findChildren | public function findChildren(bool $sameCollection = false, bool $directChildren = false)
{
$result = [];
foreach ($this->schemas as $schema) {
//Only Document and DocumentEntity classes supported
if (!$schema instanceof DocumentSchema) {
continue;
}
//ReflectionEntity
$reflection = $schema->getReflection();
if ($reflection->isSubclassOf($this->schema->getClass())) {
if ($sameCollection && !$this->compareCollection($schema)) {
//Child changed collection or database
continue;
}
if (
$directChildren
&& $reflection->getParentClass()->getName() != $this->schema->getClass()
) {
//Grandson
continue;
}
$result[] = $schema;
}
}
return $result;
} | php | public function findChildren(bool $sameCollection = false, bool $directChildren = false)
{
$result = [];
foreach ($this->schemas as $schema) {
//Only Document and DocumentEntity classes supported
if (!$schema instanceof DocumentSchema) {
continue;
}
//ReflectionEntity
$reflection = $schema->getReflection();
if ($reflection->isSubclassOf($this->schema->getClass())) {
if ($sameCollection && !$this->compareCollection($schema)) {
//Child changed collection or database
continue;
}
if (
$directChildren
&& $reflection->getParentClass()->getName() != $this->schema->getClass()
) {
//Grandson
continue;
}
$result[] = $schema;
}
}
return $result;
} | [
"public",
"function",
"findChildren",
"(",
"bool",
"$",
"sameCollection",
"=",
"false",
",",
"bool",
"$",
"directChildren",
"=",
"false",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"schemas",
"as",
"$",
"schema",
")... | Get Document child classes.
Example:
Class A
Class B extends A
Class D extends A
Class E extends D
Result: B, D, E
@see getPrimary()
@param bool $sameCollection Find only children related to same collection as parent.
@param bool $directChildren Only child extended directly from current document.
@return DocumentSchema[] | [
"Get",
"Document",
"child",
"classes",
"."
] | 06087691a05dcfaa86c6c461660c6029db4de06e | https://github.com/spiral/odm/blob/06087691a05dcfaa86c6c461660c6029db4de06e/source/Spiral/ODM/Schemas/InheritanceHelper.php#L126-L158 | train |
spiral/odm | source/Spiral/ODM/Schemas/InheritanceHelper.php | InheritanceHelper.findPrimary | public function findPrimary(bool $sameCollection = true): string
{
$primary = $this->schema->getClass();
foreach ($this->schemas as $schema) {
//Only Document and DocumentEntity classes supported
if (!$schema instanceof DocumentSchema) {
continue;
}
if ($this->schema->getReflection()->isSubclassOf($schema->getClass())) {
if ($sameCollection && !$this->compareCollection($schema)) {
//Child changed collection or database
continue;
}
$primary = $schema->getClass();
}
}
return $primary;
} | php | public function findPrimary(bool $sameCollection = true): string
{
$primary = $this->schema->getClass();
foreach ($this->schemas as $schema) {
//Only Document and DocumentEntity classes supported
if (!$schema instanceof DocumentSchema) {
continue;
}
if ($this->schema->getReflection()->isSubclassOf($schema->getClass())) {
if ($sameCollection && !$this->compareCollection($schema)) {
//Child changed collection or database
continue;
}
$primary = $schema->getClass();
}
}
return $primary;
} | [
"public",
"function",
"findPrimary",
"(",
"bool",
"$",
"sameCollection",
"=",
"true",
")",
":",
"string",
"{",
"$",
"primary",
"=",
"$",
"this",
"->",
"schema",
"->",
"getClass",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"schemas",
"as",
"$",
... | Find primary class needed to represent model and model childs.
@param bool $sameCollection Find only parent related to same collection as model.
@return string | [
"Find",
"primary",
"class",
"needed",
"to",
"represent",
"model",
"and",
"model",
"childs",
"."
] | 06087691a05dcfaa86c6c461660c6029db4de06e | https://github.com/spiral/odm/blob/06087691a05dcfaa86c6c461660c6029db4de06e/source/Spiral/ODM/Schemas/InheritanceHelper.php#L167-L187 | train |
spiral/odm | source/Spiral/ODM/Schemas/InheritanceHelper.php | InheritanceHelper.compareCollection | protected function compareCollection(DocumentSchema $document)
{
if ($document->getDatabase() != $this->schema->getDatabase()) {
return false;
}
return $document->getCollection() == $this->schema->getCollection();
} | php | protected function compareCollection(DocumentSchema $document)
{
if ($document->getDatabase() != $this->schema->getDatabase()) {
return false;
}
return $document->getCollection() == $this->schema->getCollection();
} | [
"protected",
"function",
"compareCollection",
"(",
"DocumentSchema",
"$",
"document",
")",
"{",
"if",
"(",
"$",
"document",
"->",
"getDatabase",
"(",
")",
"!=",
"$",
"this",
"->",
"schema",
"->",
"getDatabase",
"(",
")",
")",
"{",
"return",
"false",
";",
... | Check if both document schemas belongs to same collection. Documents without declared
collection must be counted as documents from same collection.
@param DocumentSchema $document
@return bool | [
"Check",
"if",
"both",
"document",
"schemas",
"belongs",
"to",
"same",
"collection",
".",
"Documents",
"without",
"declared",
"collection",
"must",
"be",
"counted",
"as",
"documents",
"from",
"same",
"collection",
"."
] | 06087691a05dcfaa86c6c461660c6029db4de06e | https://github.com/spiral/odm/blob/06087691a05dcfaa86c6c461660c6029db4de06e/source/Spiral/ODM/Schemas/InheritanceHelper.php#L205-L212 | train |
spiral/odm | source/Spiral/ODM/Schemas/InheritanceHelper.php | InheritanceHelper.sortChildren | private function sortChildren(DocumentSchema $childA, DocumentSchema $childB)
{
return count($childA->getReflection()->getSchema()) > count($childB->getReflection()->getSchema());
} | php | private function sortChildren(DocumentSchema $childA, DocumentSchema $childB)
{
return count($childA->getReflection()->getSchema()) > count($childB->getReflection()->getSchema());
} | [
"private",
"function",
"sortChildren",
"(",
"DocumentSchema",
"$",
"childA",
",",
"DocumentSchema",
"$",
"childB",
")",
"{",
"return",
"count",
"(",
"$",
"childA",
"->",
"getReflection",
"(",
")",
"->",
"getSchema",
"(",
")",
")",
">",
"count",
"(",
"$",
... | Sort child documents in order or declared fields.
@param DocumentSchema $childA
@param DocumentSchema $childB
@return int | [
"Sort",
"child",
"documents",
"in",
"order",
"or",
"declared",
"fields",
"."
] | 06087691a05dcfaa86c6c461660c6029db4de06e | https://github.com/spiral/odm/blob/06087691a05dcfaa86c6c461660c6029db4de06e/source/Spiral/ODM/Schemas/InheritanceHelper.php#L222-L225 | train |
mbarwick83/twitter-api | src/TwitterApi.php | TwitterApi.authorizeUrl | public function authorizeUrl()
{
$request_token = $this->oauth('oauth/request_token', array('oauth_callback' => $this->callbackUrl));
if ($request_token)
{
Session::put('oauth_token', $request_token['oauth_token']);
Session::put('oauth_token_secret', $request_token['oauth_token_secret']);
$url = $this->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));
return $url;
}
throw new TwitterOAuthException($request_token);
} | php | public function authorizeUrl()
{
$request_token = $this->oauth('oauth/request_token', array('oauth_callback' => $this->callbackUrl));
if ($request_token)
{
Session::put('oauth_token', $request_token['oauth_token']);
Session::put('oauth_token_secret', $request_token['oauth_token_secret']);
$url = $this->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));
return $url;
}
throw new TwitterOAuthException($request_token);
} | [
"public",
"function",
"authorizeUrl",
"(",
")",
"{",
"$",
"request_token",
"=",
"$",
"this",
"->",
"oauth",
"(",
"'oauth/request_token'",
",",
"array",
"(",
"'oauth_callback'",
"=>",
"$",
"this",
"->",
"callbackUrl",
")",
")",
";",
"if",
"(",
"$",
"request... | Generate 'request_token' and build authorize URL.
@return string | [
"Generate",
"request_token",
"and",
"build",
"authorize",
"URL",
"."
] | 3bcbec31e178e9b0b4d1acaccd30284ca5b191a6 | https://github.com/mbarwick83/twitter-api/blob/3bcbec31e178e9b0b4d1acaccd30284ca5b191a6/src/TwitterApi.php#L114-L128 | train |
mbarwick83/twitter-api | src/TwitterApi.php | TwitterApi.encodeAppAuthorization | private function encodeAppAuthorization($consumer)
{
// TODO: key and secret should be rfc 1738 encoded
$key = $consumer->key;
$secret = $consumer->secret;
return base64_encode($key . ':' . $secret);
} | php | private function encodeAppAuthorization($consumer)
{
// TODO: key and secret should be rfc 1738 encoded
$key = $consumer->key;
$secret = $consumer->secret;
return base64_encode($key . ':' . $secret);
} | [
"private",
"function",
"encodeAppAuthorization",
"(",
"$",
"consumer",
")",
"{",
"// TODO: key and secret should be rfc 1738 encoded",
"$",
"key",
"=",
"$",
"consumer",
"->",
"key",
";",
"$",
"secret",
"=",
"$",
"consumer",
"->",
"secret",
";",
"return",
"base64_e... | Encode application authorization header with base64.
@param Consumer $consumer
@return string | [
"Encode",
"application",
"authorization",
"header",
"with",
"base64",
"."
] | 3bcbec31e178e9b0b4d1acaccd30284ca5b191a6 | https://github.com/mbarwick83/twitter-api/blob/3bcbec31e178e9b0b4d1acaccd30284ca5b191a6/src/TwitterApi.php#L467-L473 | train |
emmanuelballery/EBPlantUMLBundle | Drawer/PlantUML.php | PlantUML.dump | public function dump(Graph $graph, $file, $format = PlantUML::FORMAT_TXT)
{
$format = $format ?: self::FORMAT_TXT;
try {
$content = implode(PHP_EOL, $graph->toArray()) . PHP_EOL;
if (self::FORMAT_UML === $format) {
$url = sprintf('http://www.plantuml.com/plantuml/uml/%s', $this->urlEncode($content));
if (false !== fwrite($file, $url . PHP_EOL)) {
return fclose($file);
}
return false;
}
if (self::FORMAT_TXT === $format) {
if (false !== fwrite($file, $content)) {
return fclose($file);
}
return false;
}
if (in_array($format, [self::FORMAT_PNG, self::FORMAT_SVG, self::FORMAT_ATXT, self::FORMAT_UTXT], true)) {
if (null === $this->java) {
return false;
}
$prefix = sys_get_temp_dir() . '/' . uniqid();
$txtPath = $prefix . '.txt';
$pngPath = $prefix . '.' . $format;
$clean = function () use ($txtPath, $pngPath) {
$this->fs->remove([$txtPath, $pngPath]);
};
$this->fs->dumpFile($txtPath, $content);
$builder = new ProcessBuilder();
$builder
->add($this->java)
->add('-jar')
->add(__DIR__ . '/../Resources/lib/plantuml.1.2017.19.jar')
->add($txtPath);
if (self::FORMAT_SVG === $format) {
$builder->add('-tsvg');
}
if (self::FORMAT_ATXT === $format) {
$builder->add('-txt');
}
if (self::FORMAT_UTXT === $format) {
$builder->add('-utxt');
}
$plantUml = $builder->getProcess();
$plantUml->run();
if ($plantUml->isSuccessful()) {
if (false !== $png = fopen($pngPath, 'r')) {
if (0 !== stream_copy_to_stream($png, $file)) {
$clean();
return fclose($file);
}
}
} else {
$this->logger->error($plantUml->getErrorOutput());
}
$clean();
return false;
}
return false;
} catch (\Exception $e) {
return false;
}
} | php | public function dump(Graph $graph, $file, $format = PlantUML::FORMAT_TXT)
{
$format = $format ?: self::FORMAT_TXT;
try {
$content = implode(PHP_EOL, $graph->toArray()) . PHP_EOL;
if (self::FORMAT_UML === $format) {
$url = sprintf('http://www.plantuml.com/plantuml/uml/%s', $this->urlEncode($content));
if (false !== fwrite($file, $url . PHP_EOL)) {
return fclose($file);
}
return false;
}
if (self::FORMAT_TXT === $format) {
if (false !== fwrite($file, $content)) {
return fclose($file);
}
return false;
}
if (in_array($format, [self::FORMAT_PNG, self::FORMAT_SVG, self::FORMAT_ATXT, self::FORMAT_UTXT], true)) {
if (null === $this->java) {
return false;
}
$prefix = sys_get_temp_dir() . '/' . uniqid();
$txtPath = $prefix . '.txt';
$pngPath = $prefix . '.' . $format;
$clean = function () use ($txtPath, $pngPath) {
$this->fs->remove([$txtPath, $pngPath]);
};
$this->fs->dumpFile($txtPath, $content);
$builder = new ProcessBuilder();
$builder
->add($this->java)
->add('-jar')
->add(__DIR__ . '/../Resources/lib/plantuml.1.2017.19.jar')
->add($txtPath);
if (self::FORMAT_SVG === $format) {
$builder->add('-tsvg');
}
if (self::FORMAT_ATXT === $format) {
$builder->add('-txt');
}
if (self::FORMAT_UTXT === $format) {
$builder->add('-utxt');
}
$plantUml = $builder->getProcess();
$plantUml->run();
if ($plantUml->isSuccessful()) {
if (false !== $png = fopen($pngPath, 'r')) {
if (0 !== stream_copy_to_stream($png, $file)) {
$clean();
return fclose($file);
}
}
} else {
$this->logger->error($plantUml->getErrorOutput());
}
$clean();
return false;
}
return false;
} catch (\Exception $e) {
return false;
}
} | [
"public",
"function",
"dump",
"(",
"Graph",
"$",
"graph",
",",
"$",
"file",
",",
"$",
"format",
"=",
"PlantUML",
"::",
"FORMAT_TXT",
")",
"{",
"$",
"format",
"=",
"$",
"format",
"?",
":",
"self",
"::",
"FORMAT_TXT",
";",
"try",
"{",
"$",
"content",
... | Dump array data
@param Graph $graph Graph
@param resource $file File
@param string $format Plant UML Format
@return bool | [
"Dump",
"array",
"data"
] | cc35481889460dba8a703ba3a61fd31c6fcc498c | https://github.com/emmanuelballery/EBPlantUMLBundle/blob/cc35481889460dba8a703ba3a61fd31c6fcc498c/Drawer/PlantUML.php#L61-L145 | train |
emmanuelballery/EBPlantUMLBundle | Drawer/PlantUML.php | PlantUML.urlAppend3bytes | private function urlAppend3bytes($b1, $b2, $b3)
{
$c1 = $b1 >> 2;
$c2 = (($b1 & 0x3) << 4) | ($b2 >> 4);
$c3 = (($b2 & 0xF) << 2) | ($b3 >> 6);
$c4 = $b3 & 0x3F;
return implode([
$this->urlEncode6bit($c1 & 0x3F),
$this->urlEncode6bit($c2 & 0x3F),
$this->urlEncode6bit($c3 & 0x3F),
$this->urlEncode6bit($c4 & 0x3F),
]);
} | php | private function urlAppend3bytes($b1, $b2, $b3)
{
$c1 = $b1 >> 2;
$c2 = (($b1 & 0x3) << 4) | ($b2 >> 4);
$c3 = (($b2 & 0xF) << 2) | ($b3 >> 6);
$c4 = $b3 & 0x3F;
return implode([
$this->urlEncode6bit($c1 & 0x3F),
$this->urlEncode6bit($c2 & 0x3F),
$this->urlEncode6bit($c3 & 0x3F),
$this->urlEncode6bit($c4 & 0x3F),
]);
} | [
"private",
"function",
"urlAppend3bytes",
"(",
"$",
"b1",
",",
"$",
"b2",
",",
"$",
"b3",
")",
"{",
"$",
"c1",
"=",
"$",
"b1",
">>",
"2",
";",
"$",
"c2",
"=",
"(",
"(",
"$",
"b1",
"&",
"0x3",
")",
"<<",
"4",
")",
"|",
"(",
"$",
"b2",
">>"... | Url append 3bytes
@param int $b1
@param int $b2
@param int $b3
@return string | [
"Url",
"append",
"3bytes"
] | cc35481889460dba8a703ba3a61fd31c6fcc498c | https://github.com/emmanuelballery/EBPlantUMLBundle/blob/cc35481889460dba8a703ba3a61fd31c6fcc498c/Drawer/PlantUML.php#L206-L219 | train |
emmanuelballery/EBPlantUMLBundle | Drawer/PlantUML.php | PlantUML.urlEncode6bit | private function urlEncode6bit($b)
{
if ($b < 10) {
return chr(48 + $b);
}
$b -= 10;
if ($b < 26) {
return chr(65 + $b);
}
$b -= 26;
if ($b < 26) {
return chr(97 + $b);
}
$b -= 26;
if ($b == 0) {
return '-';
}
if ($b == 1) {
return '_';
}
return '?';
} | php | private function urlEncode6bit($b)
{
if ($b < 10) {
return chr(48 + $b);
}
$b -= 10;
if ($b < 26) {
return chr(65 + $b);
}
$b -= 26;
if ($b < 26) {
return chr(97 + $b);
}
$b -= 26;
if ($b == 0) {
return '-';
}
if ($b == 1) {
return '_';
}
return '?';
} | [
"private",
"function",
"urlEncode6bit",
"(",
"$",
"b",
")",
"{",
"if",
"(",
"$",
"b",
"<",
"10",
")",
"{",
"return",
"chr",
"(",
"48",
"+",
"$",
"b",
")",
";",
"}",
"$",
"b",
"-=",
"10",
";",
"if",
"(",
"$",
"b",
"<",
"26",
")",
"{",
"ret... | Url encode 6bit
@param int $b
@return string | [
"Url",
"encode",
"6bit"
] | cc35481889460dba8a703ba3a61fd31c6fcc498c | https://github.com/emmanuelballery/EBPlantUMLBundle/blob/cc35481889460dba8a703ba3a61fd31c6fcc498c/Drawer/PlantUML.php#L228-L250 | train |
austinheap/php-security-txt | src/Writer.php | Writer.comment | public function comment(string $comment = ''): Writer
{
$comment = trim($comment);
if (!empty($comment)) {
$comment = ' ' . $comment;
}
return $this->line(trim('#' . $comment));
} | php | public function comment(string $comment = ''): Writer
{
$comment = trim($comment);
if (!empty($comment)) {
$comment = ' ' . $comment;
}
return $this->line(trim('#' . $comment));
} | [
"public",
"function",
"comment",
"(",
"string",
"$",
"comment",
"=",
"''",
")",
":",
"Writer",
"{",
"$",
"comment",
"=",
"trim",
"(",
"$",
"comment",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"comment",
")",
")",
"{",
"$",
"comment",
"=",
"' '... | Add a comment to the output buffer.
@param string $comment
@return Writer | [
"Add",
"a",
"comment",
"to",
"the",
"output",
"buffer",
"."
] | 01c4f32858b2a0d020fe0232467f0900833c0ff3 | https://github.com/austinheap/php-security-txt/blob/01c4f32858b2a0d020fe0232467f0900833c0ff3/src/Writer.php#L51-L60 | train |
austinheap/php-security-txt | src/Writer.php | Writer.spacers | public function spacers(int $count = 1): Writer
{
for ($x = 0; $x < $count; $x++) {
$this->spacer();
}
return $this;
} | php | public function spacers(int $count = 1): Writer
{
for ($x = 0; $x < $count; $x++) {
$this->spacer();
}
return $this;
} | [
"public",
"function",
"spacers",
"(",
"int",
"$",
"count",
"=",
"1",
")",
":",
"Writer",
"{",
"for",
"(",
"$",
"x",
"=",
"0",
";",
"$",
"x",
"<",
"$",
"count",
";",
"$",
"x",
"++",
")",
"{",
"$",
"this",
"->",
"spacer",
"(",
")",
";",
"}",
... | Add multiple spacers to the output buffer.
@param int $count
@return Writer | [
"Add",
"multiple",
"spacers",
"to",
"the",
"output",
"buffer",
"."
] | 01c4f32858b2a0d020fe0232467f0900833c0ff3 | https://github.com/austinheap/php-security-txt/blob/01c4f32858b2a0d020fe0232467f0900833c0ff3/src/Writer.php#L79-L86 | train |
austinheap/php-security-txt | src/Writer.php | Writer.lines | public function lines(array $lines): Writer
{
foreach ($lines as $line) {
$this->line($line);
}
return $this;
} | php | public function lines(array $lines): Writer
{
foreach ($lines as $line) {
$this->line($line);
}
return $this;
} | [
"public",
"function",
"lines",
"(",
"array",
"$",
"lines",
")",
":",
"Writer",
"{",
"foreach",
"(",
"$",
"lines",
"as",
"$",
"line",
")",
"{",
"$",
"this",
"->",
"line",
"(",
"$",
"line",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Add multiple lines.
@param array $lines
@return Writer | [
"Add",
"multiple",
"lines",
"."
] | 01c4f32858b2a0d020fe0232467f0900833c0ff3 | https://github.com/austinheap/php-security-txt/blob/01c4f32858b2a0d020fe0232467f0900833c0ff3/src/Writer.php#L109-L116 | train |
spiral/odm | source/Spiral/ODM/Schemas/DocumentSchema.php | DocumentSchema.getCompositions | public function getCompositions(SchemaBuilder $builder): array
{
$result = [];
foreach ($this->reflection->getSchema() as $field => $type) {
if (is_string($type) && $builder->hasSchema($type)) {
$result[$field] = new CompositionDefinition(DocumentEntity::ONE, $type);
}
if (is_array($type) && isset($type[0]) && $builder->hasSchema($type[0])) {
$result[$field] = new CompositionDefinition(DocumentEntity::MANY, $type[0]);
}
}
return $result;
} | php | public function getCompositions(SchemaBuilder $builder): array
{
$result = [];
foreach ($this->reflection->getSchema() as $field => $type) {
if (is_string($type) && $builder->hasSchema($type)) {
$result[$field] = new CompositionDefinition(DocumentEntity::ONE, $type);
}
if (is_array($type) && isset($type[0]) && $builder->hasSchema($type[0])) {
$result[$field] = new CompositionDefinition(DocumentEntity::MANY, $type[0]);
}
}
return $result;
} | [
"public",
"function",
"getCompositions",
"(",
"SchemaBuilder",
"$",
"builder",
")",
":",
"array",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"reflection",
"->",
"getSchema",
"(",
")",
"as",
"$",
"field",
"=>",
"$",
"type... | Find all composition definitions, attention method require builder instance in order to
properly check that embedded class exists.
@param SchemaBuilder $builder
@return CompositionDefinition[] | [
"Find",
"all",
"composition",
"definitions",
"attention",
"method",
"require",
"builder",
"instance",
"in",
"order",
"to",
"properly",
"check",
"that",
"embedded",
"class",
"exists",
"."
] | 06087691a05dcfaa86c6c461660c6029db4de06e | https://github.com/spiral/odm/blob/06087691a05dcfaa86c6c461660c6029db4de06e/source/Spiral/ODM/Schemas/DocumentSchema.php#L214-L228 | train |
spiral/odm | source/Spiral/ODM/Schemas/DocumentSchema.php | DocumentSchema.packDefaults | protected function packDefaults(SchemaBuilder $builder, array $overwriteDefaults = []): array
{
//Defined compositions
$compositions = $this->getCompositions($builder);
//User defined default values
$userDefined = $overwriteDefaults + $this->getDefaults();
//We need mutators to normalize default values
$mutators = $this->getMutators();
$defaults = [];
foreach ($this->getFields() as $field => $type) {
$default = is_array($type) ? [] : null;
if (array_key_exists($field, $userDefined)) {
//No merge to keep fields order intact
$default = $userDefined[$field];
}
//Registering default values
$defaults[$field] = $this->mutateValue(
$builder,
$compositions,
$userDefined,
$mutators,
$field,
$default
);
}
return $defaults;
} | php | protected function packDefaults(SchemaBuilder $builder, array $overwriteDefaults = []): array
{
//Defined compositions
$compositions = $this->getCompositions($builder);
//User defined default values
$userDefined = $overwriteDefaults + $this->getDefaults();
//We need mutators to normalize default values
$mutators = $this->getMutators();
$defaults = [];
foreach ($this->getFields() as $field => $type) {
$default = is_array($type) ? [] : null;
if (array_key_exists($field, $userDefined)) {
//No merge to keep fields order intact
$default = $userDefined[$field];
}
//Registering default values
$defaults[$field] = $this->mutateValue(
$builder,
$compositions,
$userDefined,
$mutators,
$field,
$default
);
}
return $defaults;
} | [
"protected",
"function",
"packDefaults",
"(",
"SchemaBuilder",
"$",
"builder",
",",
"array",
"$",
"overwriteDefaults",
"=",
"[",
"]",
")",
":",
"array",
"{",
"//Defined compositions",
"$",
"compositions",
"=",
"$",
"this",
"->",
"getCompositions",
"(",
"$",
"b... | Entity default values.
@param SchemaBuilder $builder
@param array $overwriteDefaults Set of default values to replace user defined values.
@return array
@throws SchemaException | [
"Entity",
"default",
"values",
"."
] | 06087691a05dcfaa86c6c461660c6029db4de06e | https://github.com/spiral/odm/blob/06087691a05dcfaa86c6c461660c6029db4de06e/source/Spiral/ODM/Schemas/DocumentSchema.php#L339-L371 | train |
spiral/odm | source/Spiral/ODM/Schemas/DocumentSchema.php | DocumentSchema.packCompositions | public function packCompositions(SchemaBuilder $builder): array
{
$result = [];
foreach ($this->getCompositions($builder) as $name => $composition) {
$result[$name] = $composition->packSchema();
}
return $result;
} | php | public function packCompositions(SchemaBuilder $builder): array
{
$result = [];
foreach ($this->getCompositions($builder) as $name => $composition) {
$result[$name] = $composition->packSchema();
}
return $result;
} | [
"public",
"function",
"packCompositions",
"(",
"SchemaBuilder",
"$",
"builder",
")",
":",
"array",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getCompositions",
"(",
"$",
"builder",
")",
"as",
"$",
"name",
"=>",
"$",
"co... | Pack compositions into simple array definition.
@param SchemaBuilder $builder
@return array
@throws SchemaException | [
"Pack",
"compositions",
"into",
"simple",
"array",
"definition",
"."
] | 06087691a05dcfaa86c6c461660c6029db4de06e | https://github.com/spiral/odm/blob/06087691a05dcfaa86c6c461660c6029db4de06e/source/Spiral/ODM/Schemas/DocumentSchema.php#L382-L390 | train |
spiral/odm | source/Spiral/ODM/Schemas/DocumentSchema.php | DocumentSchema.packAggregations | protected function packAggregations(SchemaBuilder $builder): array
{
$result = [];
foreach ($this->getAggregations() as $name => $aggregation) {
if (!$builder->hasSchema($aggregation->getClass())) {
throw new SchemaException(
"Aggregation {$this->getClass()}.'{$name}' refers to undefined document '{$aggregation->getClass()}'"
);
}
if ($builder->getSchema($aggregation->getClass())->isEmbedded()) {
throw new SchemaException(
"Aggregation {$this->getClass()}.'{$name}' refers to non storable document '{$aggregation->getClass()}'"
);
}
$result[$name] = $aggregation->packSchema();
}
return $result;
} | php | protected function packAggregations(SchemaBuilder $builder): array
{
$result = [];
foreach ($this->getAggregations() as $name => $aggregation) {
if (!$builder->hasSchema($aggregation->getClass())) {
throw new SchemaException(
"Aggregation {$this->getClass()}.'{$name}' refers to undefined document '{$aggregation->getClass()}'"
);
}
if ($builder->getSchema($aggregation->getClass())->isEmbedded()) {
throw new SchemaException(
"Aggregation {$this->getClass()}.'{$name}' refers to non storable document '{$aggregation->getClass()}'"
);
}
$result[$name] = $aggregation->packSchema();
}
return $result;
} | [
"protected",
"function",
"packAggregations",
"(",
"SchemaBuilder",
"$",
"builder",
")",
":",
"array",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getAggregations",
"(",
")",
"as",
"$",
"name",
"=>",
"$",
"aggregation",
")"... | Pack aggregations into simple array definition.
@param SchemaBuilder $builder
@return array
@throws SchemaException | [
"Pack",
"aggregations",
"into",
"simple",
"array",
"definition",
"."
] | 06087691a05dcfaa86c6c461660c6029db4de06e | https://github.com/spiral/odm/blob/06087691a05dcfaa86c6c461660c6029db4de06e/source/Spiral/ODM/Schemas/DocumentSchema.php#L401-L421 | train |
spiral/odm | source/Spiral/ODM/Schemas/DocumentSchema.php | DocumentSchema.mutateValue | protected function mutateValue(
SchemaBuilder $builder,
array $compositions,
array $userDefined,
array $mutators,
string $field,
$default
) {
//Let's process default value using associated setter
if (isset($mutators[DocumentEntity::MUTATOR_SETTER][$field])) {
try {
$setter = $mutators[DocumentEntity::MUTATOR_SETTER][$field];
$default = call_user_func($setter, $default);
return $default;
} catch (\Exception $exception) {
//Unable to generate default value, use null or empty array as fallback
}
}
if (isset($mutators[DocumentEntity::MUTATOR_ACCESSOR][$field])) {
$default = $this->accessorDefault(
$default,
$mutators[DocumentEntity::MUTATOR_ACCESSOR][$field]
);
}
if (isset($compositions[$field])) {
if (is_null($default) && !array_key_exists($field, $userDefined)) {
//Let's force default value for composite fields
$default = [];
}
$default = $this->compositionDefault($default, $compositions[$field], $builder);
return $default;
}
return $default;
} | php | protected function mutateValue(
SchemaBuilder $builder,
array $compositions,
array $userDefined,
array $mutators,
string $field,
$default
) {
//Let's process default value using associated setter
if (isset($mutators[DocumentEntity::MUTATOR_SETTER][$field])) {
try {
$setter = $mutators[DocumentEntity::MUTATOR_SETTER][$field];
$default = call_user_func($setter, $default);
return $default;
} catch (\Exception $exception) {
//Unable to generate default value, use null or empty array as fallback
}
}
if (isset($mutators[DocumentEntity::MUTATOR_ACCESSOR][$field])) {
$default = $this->accessorDefault(
$default,
$mutators[DocumentEntity::MUTATOR_ACCESSOR][$field]
);
}
if (isset($compositions[$field])) {
if (is_null($default) && !array_key_exists($field, $userDefined)) {
//Let's force default value for composite fields
$default = [];
}
$default = $this->compositionDefault($default, $compositions[$field], $builder);
return $default;
}
return $default;
} | [
"protected",
"function",
"mutateValue",
"(",
"SchemaBuilder",
"$",
"builder",
",",
"array",
"$",
"compositions",
",",
"array",
"$",
"userDefined",
",",
"array",
"$",
"mutators",
",",
"string",
"$",
"field",
",",
"$",
"default",
")",
"{",
"//Let's process defau... | Ensure default value using associated mutators or pass thought composition.
@param SchemaBuilder $builder
@param array $compositions
@param array $userDefined User defined set of default values.
@param array $mutators
@param string $field
@param mixed $default
@return mixed | [
"Ensure",
"default",
"value",
"using",
"associated",
"mutators",
"or",
"pass",
"thought",
"composition",
"."
] | 06087691a05dcfaa86c6c461660c6029db4de06e | https://github.com/spiral/odm/blob/06087691a05dcfaa86c6c461660c6029db4de06e/source/Spiral/ODM/Schemas/DocumentSchema.php#L453-L492 | train |
spiral/odm | source/Spiral/ODM/Schemas/DocumentSchema.php | DocumentSchema.compositionDefault | protected function compositionDefault(
$default,
CompositionDefinition $composition,
SchemaBuilder $builder
) {
if (!is_array($default)) {
if ($composition->getType() == DocumentEntity::MANY) {
//Composition many must always defaults to array
return [];
}
//Composite ONE must always defaults to null if no default value are specified
return null;
}
//Nothing to do with value for composite many
if ($composition->getType() == DocumentEntity::MANY) {
return $default;
}
$embedded = $builder->getSchema($composition->getClass());
if (!$embedded instanceof self) {
//We can not normalize values handled by external schemas yet
return $default;
}
if ($embedded->getClass() == $this->getClass()) {
if (!empty($default)) {
throw new SchemaException(
"Possible recursion issue in '{$this->getClass()}', model refers to itself (has default value)"
);
}
//No recursions!
return null;
}
return $embedded->packDefaults($builder, $default);
} | php | protected function compositionDefault(
$default,
CompositionDefinition $composition,
SchemaBuilder $builder
) {
if (!is_array($default)) {
if ($composition->getType() == DocumentEntity::MANY) {
//Composition many must always defaults to array
return [];
}
//Composite ONE must always defaults to null if no default value are specified
return null;
}
//Nothing to do with value for composite many
if ($composition->getType() == DocumentEntity::MANY) {
return $default;
}
$embedded = $builder->getSchema($composition->getClass());
if (!$embedded instanceof self) {
//We can not normalize values handled by external schemas yet
return $default;
}
if ($embedded->getClass() == $this->getClass()) {
if (!empty($default)) {
throw new SchemaException(
"Possible recursion issue in '{$this->getClass()}', model refers to itself (has default value)"
);
}
//No recursions!
return null;
}
return $embedded->packDefaults($builder, $default);
} | [
"protected",
"function",
"compositionDefault",
"(",
"$",
"default",
",",
"CompositionDefinition",
"$",
"composition",
",",
"SchemaBuilder",
"$",
"builder",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"default",
")",
")",
"{",
"if",
"(",
"$",
"composition... | Ensure default value for composite field,
@param mixed $default
@param CompositionDefinition $composition
@param SchemaBuilder $builder
@return array
@throws SchemaException | [
"Ensure",
"default",
"value",
"for",
"composite",
"field"
] | 06087691a05dcfaa86c6c461660c6029db4de06e | https://github.com/spiral/odm/blob/06087691a05dcfaa86c6c461660c6029db4de06e/source/Spiral/ODM/Schemas/DocumentSchema.php#L531-L569 | train |
krystal-framework/krystal.framework | src/Krystal/ParamBag/ParamBag.php | ParamBag.hasMany | public function hasMany(array $params)
{
foreach ($params as $param) {
if (!$this->has($param)) {
return false;
}
}
return true;
} | php | public function hasMany(array $params)
{
foreach ($params as $param) {
if (!$this->has($param)) {
return false;
}
}
return true;
} | [
"public",
"function",
"hasMany",
"(",
"array",
"$",
"params",
")",
"{",
"foreach",
"(",
"$",
"params",
"as",
"$",
"param",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"has",
"(",
"$",
"param",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"... | Checks whether several parameters are defined at once
@param array $params
@return boolean | [
"Checks",
"whether",
"several",
"parameters",
"are",
"defined",
"at",
"once"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/ParamBag/ParamBag.php#L64-L73 | train |
krystal-framework/krystal.framework | src/Krystal/ParamBag/ParamBag.php | ParamBag.setMany | public function setMany(array $params)
{
foreach ($params as $key => $value) {
$this->set($key, $value);
}
return $this;
} | php | public function setMany(array $params)
{
foreach ($params as $key => $value) {
$this->set($key, $value);
}
return $this;
} | [
"public",
"function",
"setMany",
"(",
"array",
"$",
"params",
")",
"{",
"foreach",
"(",
"$",
"params",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"set",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"}",
"return",
"$",
"... | Append many parameters
@param array $params
@return \Krystal\ParamBag\ParamBag | [
"Append",
"many",
"parameters"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/ParamBag/ParamBag.php#L94-L101 | train |
Firesphere/silverstripe-newsmodule | code/objects/Tag.php | Tag.fieldLabels | public function fieldLabels($includerelations = true)
{
$labels = parent::fieldLabels($includerelations);
$tagLabels = array(
'Title' => _t('Tag.TITLE', 'Title'),
'Description' => _t('Tag.DESCRIPTION', 'Description'),
'Impression' => _t('Tag.IMPRESSION', 'Impression image'),
);
return array_merge($tagLabels, $labels);
} | php | public function fieldLabels($includerelations = true)
{
$labels = parent::fieldLabels($includerelations);
$tagLabels = array(
'Title' => _t('Tag.TITLE', 'Title'),
'Description' => _t('Tag.DESCRIPTION', 'Description'),
'Impression' => _t('Tag.IMPRESSION', 'Impression image'),
);
return array_merge($tagLabels, $labels);
} | [
"public",
"function",
"fieldLabels",
"(",
"$",
"includerelations",
"=",
"true",
")",
"{",
"$",
"labels",
"=",
"parent",
"::",
"fieldLabels",
"(",
"$",
"includerelations",
")",
";",
"$",
"tagLabels",
"=",
"array",
"(",
"'Title'",
"=>",
"_t",
"(",
"'Tag.TITL... | Setup the fieldlabels correctly.
@param boolean $includerelations
@return array The fieldlabels | [
"Setup",
"the",
"fieldlabels",
"correctly",
"."
] | 98c501bf940878ed9c044124409b85a3e3c4265c | https://github.com/Firesphere/silverstripe-newsmodule/blob/98c501bf940878ed9c044124409b85a3e3c4265c/code/objects/Tag.php#L97-L107 | train |
phpcq/author-validation | src/AuthorExtractor/PatchingAuthorExtractorTrait.php | PatchingAuthorExtractorTrait.calculateUpdatedAuthors | protected function calculateUpdatedAuthors($path, $authors)
{
return \array_merge(\array_intersect_key($this->extractAuthorsFor($path), $authors), $authors);
} | php | protected function calculateUpdatedAuthors($path, $authors)
{
return \array_merge(\array_intersect_key($this->extractAuthorsFor($path), $authors), $authors);
} | [
"protected",
"function",
"calculateUpdatedAuthors",
"(",
"$",
"path",
",",
"$",
"authors",
")",
"{",
"return",
"\\",
"array_merge",
"(",
"\\",
"array_intersect_key",
"(",
"$",
"this",
"->",
"extractAuthorsFor",
"(",
"$",
"path",
")",
",",
"$",
"authors",
")"... | Calculate the updated author map.
The passed authors will be used as new reference, all existing not mentioned anymore will not be contained in
the result.
@param string $path A path obtained via a prior call to AuthorExtractor::getFilePaths().
@param array $authors The new author list.
@return \string[] | [
"Calculate",
"the",
"updated",
"author",
"map",
"."
] | 1e22f6133dcadea486a7961274f4e611b5ef4c0c | https://github.com/phpcq/author-validation/blob/1e22f6133dcadea486a7961274f4e611b5ef4c0c/src/AuthorExtractor/PatchingAuthorExtractorTrait.php#L41-L44 | train |
signifly/shopify-php-sdk | src/RateLimit/DefaultRateLimitCalculator.php | DefaultRateLimitCalculator.calculate | public function calculate(int $callsMade, int $callsLimit)
{
$callPercentage = floatval($callsMade / $callsLimit);
$limitPercentage = floatval(($callsLimit - $this->processes - $this->buffer) / $callsLimit);
return $callPercentage > $limitPercentage ? ($this->processes * $this->cycle) : $this->cycle;
} | php | public function calculate(int $callsMade, int $callsLimit)
{
$callPercentage = floatval($callsMade / $callsLimit);
$limitPercentage = floatval(($callsLimit - $this->processes - $this->buffer) / $callsLimit);
return $callPercentage > $limitPercentage ? ($this->processes * $this->cycle) : $this->cycle;
} | [
"public",
"function",
"calculate",
"(",
"int",
"$",
"callsMade",
",",
"int",
"$",
"callsLimit",
")",
"{",
"$",
"callPercentage",
"=",
"floatval",
"(",
"$",
"callsMade",
"/",
"$",
"callsLimit",
")",
";",
"$",
"limitPercentage",
"=",
"floatval",
"(",
"(",
... | Calculate the time in seconds between each request.
@param int $callsMade
@param int $callsLimit
@return float|int | [
"Calculate",
"the",
"time",
"in",
"seconds",
"between",
"each",
"request",
"."
] | 0935b242d00653440e5571fb7901370b2869b99a | https://github.com/signifly/shopify-php-sdk/blob/0935b242d00653440e5571fb7901370b2869b99a/src/RateLimit/DefaultRateLimitCalculator.php#L49-L55 | train |
AOEpeople/Aoe_Api2 | app/code/community/Aoe/Api2/Model/Auth/Adapter/Session.php | Aoe_Api2_Model_Auth_Adapter_Session.getUserParams | public function getUserParams(Mage_Api2_Model_Request $request)
{
$userParamsObj = new stdClass();
$userParamsObj->type = null;
$userParamsObj->id = null;
if ($this->isApplicableToRequest($request)) {
$userParamsObj->id = $this->getHelper()->getCustomerSession()->getCustomerId();
$userParamsObj->type = self::USER_TYPE_CUSTOMER;
}
return $userParamsObj;
} | php | public function getUserParams(Mage_Api2_Model_Request $request)
{
$userParamsObj = new stdClass();
$userParamsObj->type = null;
$userParamsObj->id = null;
if ($this->isApplicableToRequest($request)) {
$userParamsObj->id = $this->getHelper()->getCustomerSession()->getCustomerId();
$userParamsObj->type = self::USER_TYPE_CUSTOMER;
}
return $userParamsObj;
} | [
"public",
"function",
"getUserParams",
"(",
"Mage_Api2_Model_Request",
"$",
"request",
")",
"{",
"$",
"userParamsObj",
"=",
"new",
"stdClass",
"(",
")",
";",
"$",
"userParamsObj",
"->",
"type",
"=",
"null",
";",
"$",
"userParamsObj",
"->",
"id",
"=",
"null",... | Process request and figure out an API user type and its identifier
Returns stdClass object with two properties: type and id
@param Mage_Api2_Model_Request $request
@return stdClass | [
"Process",
"request",
"and",
"figure",
"out",
"an",
"API",
"user",
"type",
"and",
"its",
"identifier"
] | d770221bcc4d6820e8e52f6a67a66191424c8e1a | https://github.com/AOEpeople/Aoe_Api2/blob/d770221bcc4d6820e8e52f6a67a66191424c8e1a/app/code/community/Aoe/Api2/Model/Auth/Adapter/Session.php#L19-L31 | train |
AOEpeople/Aoe_Api2 | app/code/community/Aoe/Api2/Model/Auth/Adapter/Session.php | Aoe_Api2_Model_Auth_Adapter_Session.isApplicableToRequest | public function isApplicableToRequest(Mage_Api2_Model_Request $request)
{
// This auth adapter is for frontend use only
if (Mage::app()->getStore()->isAdmin()) {
return false;
}
// Ensure frontend sessions are initialized using the proper cookie name
$this->getHelper()->getCoreSession();
// We are only applicable if the customer is logged in already
return $this->getHelper()->getCustomerSession()->isLoggedIn();
} | php | public function isApplicableToRequest(Mage_Api2_Model_Request $request)
{
// This auth adapter is for frontend use only
if (Mage::app()->getStore()->isAdmin()) {
return false;
}
// Ensure frontend sessions are initialized using the proper cookie name
$this->getHelper()->getCoreSession();
// We are only applicable if the customer is logged in already
return $this->getHelper()->getCustomerSession()->isLoggedIn();
} | [
"public",
"function",
"isApplicableToRequest",
"(",
"Mage_Api2_Model_Request",
"$",
"request",
")",
"{",
"// This auth adapter is for frontend use only",
"if",
"(",
"Mage",
"::",
"app",
"(",
")",
"->",
"getStore",
"(",
")",
"->",
"isAdmin",
"(",
")",
")",
"{",
"... | Check if request contains authentication info for adapter
@param Mage_Api2_Model_Request $request
@return boolean | [
"Check",
"if",
"request",
"contains",
"authentication",
"info",
"for",
"adapter"
] | d770221bcc4d6820e8e52f6a67a66191424c8e1a | https://github.com/AOEpeople/Aoe_Api2/blob/d770221bcc4d6820e8e52f6a67a66191424c8e1a/app/code/community/Aoe/Api2/Model/Auth/Adapter/Session.php#L40-L52 | train |
krystal-framework/krystal.framework | src/Krystal/Db/Sql/Relations/OneToMany.php | OneToMany.getResultSetWithoutSlaveColumnId | private function getResultSetWithoutSlaveColumnId(array $rows, $slaveColumnId)
{
// To be returned
$result = array();
foreach ($rows as $row) {
// Make sure the name is valid
if (isset($row[$slaveColumnId])) {
unset($row[$slaveColumnId]);
}
// Append filtered $row array to the outputting array
$result[] = $row;
}
return $result;
} | php | private function getResultSetWithoutSlaveColumnId(array $rows, $slaveColumnId)
{
// To be returned
$result = array();
foreach ($rows as $row) {
// Make sure the name is valid
if (isset($row[$slaveColumnId])) {
unset($row[$slaveColumnId]);
}
// Append filtered $row array to the outputting array
$result[] = $row;
}
return $result;
} | [
"private",
"function",
"getResultSetWithoutSlaveColumnId",
"(",
"array",
"$",
"rows",
",",
"$",
"slaveColumnId",
")",
"{",
"// To be returned",
"$",
"result",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"rows",
"as",
"$",
"row",
")",
"{",
"// Make sure... | Returns a result-set excluding slave column id name
@param array $rows Raw result-set
@param string $slaveColumnId Slave column id name to be excluded
@return array | [
"Returns",
"a",
"result",
"-",
"set",
"excluding",
"slave",
"column",
"id",
"name"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Db/Sql/Relations/OneToMany.php#L67-L83 | train |
krystal-framework/krystal.framework | src/Krystal/Cache/FileEngine/FileEngineFactory.php | FileEngineFactory.build | public static function build($file, $autoCreate = true)
{
$storage = new CacheFile(new NativeSerializer(), $file, $autoCreate);
$cache = new CacheEngine(new ArrayCache(), new ArraySignature(), $storage);
$cache->initialize();
return $cache;
} | php | public static function build($file, $autoCreate = true)
{
$storage = new CacheFile(new NativeSerializer(), $file, $autoCreate);
$cache = new CacheEngine(new ArrayCache(), new ArraySignature(), $storage);
$cache->initialize();
return $cache;
} | [
"public",
"static",
"function",
"build",
"(",
"$",
"file",
",",
"$",
"autoCreate",
"=",
"true",
")",
"{",
"$",
"storage",
"=",
"new",
"CacheFile",
"(",
"new",
"NativeSerializer",
"(",
")",
",",
"$",
"file",
",",
"$",
"autoCreate",
")",
";",
"$",
"cac... | Builds cache instance
@param string $file The path to the cache file
@param boolean $autoCreate
@return \Krystal\Cache\FileEngine\CacheEngine | [
"Builds",
"cache",
"instance"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Cache/FileEngine/FileEngineFactory.php#L25-L33 | train |
Firesphere/silverstripe-newsmodule | code/extensions/NewsControllerExtension.php | NewsControllerExtension.NewsArchive | public function NewsArchive($limit = 5, $random = null, $related = null)
{
if ($limit === 0) {
$limit = null;
}
$params = $this->owner->getURLParams();
$otherNews = null;
/** @var News $otherNews */
if ($related) {
$otherNews = $this->owner->getNews();
}
if (($otherNews && $otherNews->Tags()->count()) || !$related) {
return $this->getArchiveItems($otherNews, $limit, $random, $related, $params);
}
} | php | public function NewsArchive($limit = 5, $random = null, $related = null)
{
if ($limit === 0) {
$limit = null;
}
$params = $this->owner->getURLParams();
$otherNews = null;
/** @var News $otherNews */
if ($related) {
$otherNews = $this->owner->getNews();
}
if (($otherNews && $otherNews->Tags()->count()) || !$related) {
return $this->getArchiveItems($otherNews, $limit, $random, $related, $params);
}
} | [
"public",
"function",
"NewsArchive",
"(",
"$",
"limit",
"=",
"5",
",",
"$",
"random",
"=",
"null",
",",
"$",
"related",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"limit",
"===",
"0",
")",
"{",
"$",
"limit",
"=",
"null",
";",
"}",
"$",
"params",
"=... | Get all, or a limited, set of items.
@param $limit integer with chosen limit. Called from template via <% loop NewsArchive(5) %> for the 5 latest items.
@param $random boolean Called from template. e.g. <% loop NewsArchive(5,1) %> to show random posts, related via the tags.
@param $related boolean Called from template. e.g. <% loop NewsArchive(5,0,1) %> to show just the latest 5 related items.
Or, to show 5 random related items, use <% loop NewsArchive(5,1,1) %>. You're free to play with the settings :)
To loop ALL items, set the first parameter (@param $limit ) to zero. As you can see.
@return DataList|News[]
@todo implement subsites | [
"Get",
"all",
"or",
"a",
"limited",
"set",
"of",
"items",
"."
] | 98c501bf940878ed9c044124409b85a3e3c4265c | https://github.com/Firesphere/silverstripe-newsmodule/blob/98c501bf940878ed9c044124409b85a3e3c4265c/code/extensions/NewsControllerExtension.php#L28-L42 | train |
Firesphere/silverstripe-newsmodule | code/extensions/NewsControllerExtension.php | NewsControllerExtension.NewsArchiveByHolderID | public function NewsArchiveByHolderID($holderID = null, $limit = 5)
{
$filter = array(
'Live' => 1,
'NewsHolderPageID' => $holderID,
'PublishFrom:LessThan' => SS_Datetime::now()->Rfc2822(),
);
if ($limit === 0) {
$limit = null;
}
if (class_exists('Translatable')) {
$filter['Locale'] = Translatable::get_current_locale();
}
$news = News::get()
->filter($filter)
->limit($limit);
if ($news->count() === 0) {
return null;
}
return $news;
} | php | public function NewsArchiveByHolderID($holderID = null, $limit = 5)
{
$filter = array(
'Live' => 1,
'NewsHolderPageID' => $holderID,
'PublishFrom:LessThan' => SS_Datetime::now()->Rfc2822(),
);
if ($limit === 0) {
$limit = null;
}
if (class_exists('Translatable')) {
$filter['Locale'] = Translatable::get_current_locale();
}
$news = News::get()
->filter($filter)
->limit($limit);
if ($news->count() === 0) {
return null;
}
return $news;
} | [
"public",
"function",
"NewsArchiveByHolderID",
"(",
"$",
"holderID",
"=",
"null",
",",
"$",
"limit",
"=",
"5",
")",
"{",
"$",
"filter",
"=",
"array",
"(",
"'Live'",
"=>",
"1",
",",
"'NewsHolderPageID'",
"=>",
"$",
"holderID",
",",
"'PublishFrom:LessThan'",
... | Get all the items from a single newsholderPage.
@param int $holderID
@param $limit integer with chosen limit. Called from template via <% loop $NewsArchiveByHolderID(321,5) %> for the page with ID 321 and 5 latest items.
@todo many things, isn't finished
@fixed I refactored a bit. Only makes for a smaller function.
@author Marcio Barrientos
@return ArrayList|News[] | [
"Get",
"all",
"the",
"items",
"from",
"a",
"single",
"newsholderPage",
"."
] | 98c501bf940878ed9c044124409b85a3e3c4265c | https://github.com/Firesphere/silverstripe-newsmodule/blob/98c501bf940878ed9c044124409b85a3e3c4265c/code/extensions/NewsControllerExtension.php#L77-L100 | train |
vasily-kartashov/hamlet-core | src/Hamlet/Requests/Normalizer.php | Normalizer.getUriFromGlobals | public static function getUriFromGlobals(array $serverParams): UriInterface
{
$uri = new Uri('');
$uri = $uri->withScheme(isset($serverParams['HTTPS']) && $serverParams['HTTPS'] !== 'off' ? 'https' : 'http');
$hasPort = false;
if (isset($serverParams['HTTP_HOST'])) {
$hostHeaderParts = explode(':', $serverParams['HTTP_HOST'], 2);
$uri = $uri->withHost($hostHeaderParts[0]);
if (count($hostHeaderParts) > 1) {
$hasPort = true;
$uri = $uri->withPort((int) $hostHeaderParts[1]);
}
} elseif (isset($serverParams['SERVER_NAME'])) {
$uri = $uri->withHost($serverParams['SERVER_NAME']);
} elseif (isset($serverParams['SERVER_ADDR'])) {
$uri = $uri->withHost($serverParams['SERVER_ADDR']);
}
if (!$hasPort && isset($serverParams['SERVER_PORT'])) {
$uri = $uri->withPort($serverParams['SERVER_PORT']);
}
$hasQuery = false;
if (isset($serverParams['REQUEST_URI'])) {
$requestUriParts = explode('?', $serverParams['REQUEST_URI'], 2);
$uri = $uri->withPath($requestUriParts[0]);
if (count($requestUriParts) > 1) {
$hasQuery = true;
$uri = $uri->withQuery($requestUriParts[1]);
}
}
if (!$hasQuery && isset($serverParams['QUERY_STRING'])) {
$uri = $uri->withQuery($serverParams['QUERY_STRING']);
}
return $uri;
} | php | public static function getUriFromGlobals(array $serverParams): UriInterface
{
$uri = new Uri('');
$uri = $uri->withScheme(isset($serverParams['HTTPS']) && $serverParams['HTTPS'] !== 'off' ? 'https' : 'http');
$hasPort = false;
if (isset($serverParams['HTTP_HOST'])) {
$hostHeaderParts = explode(':', $serverParams['HTTP_HOST'], 2);
$uri = $uri->withHost($hostHeaderParts[0]);
if (count($hostHeaderParts) > 1) {
$hasPort = true;
$uri = $uri->withPort((int) $hostHeaderParts[1]);
}
} elseif (isset($serverParams['SERVER_NAME'])) {
$uri = $uri->withHost($serverParams['SERVER_NAME']);
} elseif (isset($serverParams['SERVER_ADDR'])) {
$uri = $uri->withHost($serverParams['SERVER_ADDR']);
}
if (!$hasPort && isset($serverParams['SERVER_PORT'])) {
$uri = $uri->withPort($serverParams['SERVER_PORT']);
}
$hasQuery = false;
if (isset($serverParams['REQUEST_URI'])) {
$requestUriParts = explode('?', $serverParams['REQUEST_URI'], 2);
$uri = $uri->withPath($requestUriParts[0]);
if (count($requestUriParts) > 1) {
$hasQuery = true;
$uri = $uri->withQuery($requestUriParts[1]);
}
}
if (!$hasQuery && isset($serverParams['QUERY_STRING'])) {
$uri = $uri->withQuery($serverParams['QUERY_STRING']);
}
return $uri;
} | [
"public",
"static",
"function",
"getUriFromGlobals",
"(",
"array",
"$",
"serverParams",
")",
":",
"UriInterface",
"{",
"$",
"uri",
"=",
"new",
"Uri",
"(",
"''",
")",
";",
"$",
"uri",
"=",
"$",
"uri",
"->",
"withScheme",
"(",
"isset",
"(",
"$",
"serverP... | Get a Uri populated with values from server params.
@param array $serverParams
@return UriInterface | [
"Get",
"a",
"Uri",
"populated",
"with",
"values",
"from",
"server",
"params",
"."
] | 646a2fc9d90a62afa402fe14b3f9570477538d4c | https://github.com/vasily-kartashov/hamlet-core/blob/646a2fc9d90a62afa402fe14b3f9570477538d4c/src/Hamlet/Requests/Normalizer.php#L91-L130 | train |
i-lateral/silverstripe-checkout | code/extensions/CheckoutUsersControllerExtension.php | CheckoutUserAccountControllerExtension.updateAccountMenu | public function updateAccountMenu($menu)
{
$curr_action = $this->owner->request->param("Action");
$menu->add(new ArrayData(array(
"ID" => 11,
"Title" => _t('Checkout.Addresses', 'Addresses'),
"Link" => $this->owner->Link("addresses"),
"LinkingMode" => ($curr_action == "addresses") ? "current" : "link"
)));
} | php | public function updateAccountMenu($menu)
{
$curr_action = $this->owner->request->param("Action");
$menu->add(new ArrayData(array(
"ID" => 11,
"Title" => _t('Checkout.Addresses', 'Addresses'),
"Link" => $this->owner->Link("addresses"),
"LinkingMode" => ($curr_action == "addresses") ? "current" : "link"
)));
} | [
"public",
"function",
"updateAccountMenu",
"(",
"$",
"menu",
")",
"{",
"$",
"curr_action",
"=",
"$",
"this",
"->",
"owner",
"->",
"request",
"->",
"param",
"(",
"\"Action\"",
")",
";",
"$",
"menu",
"->",
"add",
"(",
"new",
"ArrayData",
"(",
"array",
"(... | Add links to account menu | [
"Add",
"links",
"to",
"account",
"menu"
] | 2089b57ac2b7feb86dccde8a6864ae70ce463497 | https://github.com/i-lateral/silverstripe-checkout/blob/2089b57ac2b7feb86dccde8a6864ae70ce463497/code/extensions/CheckoutUsersControllerExtension.php#L224-L234 | train |
i-lateral/silverstripe-checkout | code/extensions/CheckoutUsersControllerExtension.php | CheckoutUserAccountControllerExtension.updateEditAccountForm | public function updateEditAccountForm($form)
{
// Add company name field
$company_field = TextField::create(
"Company",
_t('CheckoutUsers.Company', "Company")
);
$company_field->setRightTitle(_t("Checkout.Optional", "Optional"));
$form->Fields()->insertBefore($company_field, "FirstName");
// Add contact phone number field
$phone_field = TextField::create(
"PhoneNumber",
_t("CheckoutUsers.PhoneNumber", "Phone Number")
);
$phone_field->setRightTitle(_t("Checkout.Optional", "Optional"));
$form->Fields()->add($phone_field);
} | php | public function updateEditAccountForm($form)
{
// Add company name field
$company_field = TextField::create(
"Company",
_t('CheckoutUsers.Company', "Company")
);
$company_field->setRightTitle(_t("Checkout.Optional", "Optional"));
$form->Fields()->insertBefore($company_field, "FirstName");
// Add contact phone number field
$phone_field = TextField::create(
"PhoneNumber",
_t("CheckoutUsers.PhoneNumber", "Phone Number")
);
$phone_field->setRightTitle(_t("Checkout.Optional", "Optional"));
$form->Fields()->add($phone_field);
} | [
"public",
"function",
"updateEditAccountForm",
"(",
"$",
"form",
")",
"{",
"// Add company name field",
"$",
"company_field",
"=",
"TextField",
"::",
"create",
"(",
"\"Company\"",
",",
"_t",
"(",
"'CheckoutUsers.Company'",
",",
"\"Company\"",
")",
")",
";",
"$",
... | Add fields used by this module to the profile editing form | [
"Add",
"fields",
"used",
"by",
"this",
"module",
"to",
"the",
"profile",
"editing",
"form"
] | 2089b57ac2b7feb86dccde8a6864ae70ce463497 | https://github.com/i-lateral/silverstripe-checkout/blob/2089b57ac2b7feb86dccde8a6864ae70ce463497/code/extensions/CheckoutUsersControllerExtension.php#L240-L257 | train |
phpcq/author-validation | src/AuthorExtractor/JsonAuthorExtractorTrait.php | JsonAuthorExtractorTrait.loadFile | protected function loadFile($path)
{
$composerJson = $this->fileData($path);
return (null === $composerJson) ? null : (array) \json_decode($composerJson, true);
} | php | protected function loadFile($path)
{
$composerJson = $this->fileData($path);
return (null === $composerJson) ? null : (array) \json_decode($composerJson, true);
} | [
"protected",
"function",
"loadFile",
"(",
"$",
"path",
")",
"{",
"$",
"composerJson",
"=",
"$",
"this",
"->",
"fileData",
"(",
"$",
"path",
")",
";",
"return",
"(",
"null",
"===",
"$",
"composerJson",
")",
"?",
"null",
":",
"(",
"array",
")",
"\\",
... | Read the .json file and return it as array.
@param string $path A path obtained via a prior call to JsonAuthorExtractorTrait::getFilePaths().
@return array | [
"Read",
"the",
".",
"json",
"file",
"and",
"return",
"it",
"as",
"array",
"."
] | 1e22f6133dcadea486a7961274f4e611b5ef4c0c | https://github.com/phpcq/author-validation/blob/1e22f6133dcadea486a7961274f4e611b5ef4c0c/src/AuthorExtractor/JsonAuthorExtractorTrait.php#L39-L44 | train |
Tecnocreaciones/ToolsBundle | Service/SequenceGenerator.php | SequenceGenerator.generateNextTemp | function generateNextTemp(\Doctrine\ORM\QueryBuilder $qb,$field)
{
$temporaryMask = $this->getTemporaryMask().'-{000}';
return $this->generate($qb,$temporaryMask ,$field,self::MODE_NEXT);
} | php | function generateNextTemp(\Doctrine\ORM\QueryBuilder $qb,$field)
{
$temporaryMask = $this->getTemporaryMask().'-{000}';
return $this->generate($qb,$temporaryMask ,$field,self::MODE_NEXT);
} | [
"function",
"generateNextTemp",
"(",
"\\",
"Doctrine",
"\\",
"ORM",
"\\",
"QueryBuilder",
"$",
"qb",
",",
"$",
"field",
")",
"{",
"$",
"temporaryMask",
"=",
"$",
"this",
"->",
"getTemporaryMask",
"(",
")",
".",
"'-{000}'",
";",
"return",
"$",
"this",
"->... | Generates the last sequence temporaly according to the parameters
@param \Doctrine\ORM\QueryBuilder $qb
@param type $field Field to consult the entity
@return type | [
"Generates",
"the",
"last",
"sequence",
"temporaly",
"according",
"to",
"the",
"parameters"
] | 8edc159b91ea41d7a880d2ca0860352d7b05370f | https://github.com/Tecnocreaciones/ToolsBundle/blob/8edc159b91ea41d7a880d2ca0860352d7b05370f/Service/SequenceGenerator.php#L253-L257 | train |
phpcodecrafting/php-beanstalk | lib/Beanstalk/Exception.php | Exception.getCodeAsString | public function getCodeAsString()
{
switch ($this->getCode()) {
case self::BURIED:
return 'Buried';
break;
case self::NOT_FOUND:
return 'Not Found';
break;
case self::EXPECTED_CRLF:
return 'Expected CRLF';
break;
case self::JOB_TOO_BIG:
return 'Job Too Big';
break;
case self::DEADLINE_SOON:
return 'Deadline Soon';
break;
case self::TIMED_OUT:
return 'Timed Out';
break;
case self::TUBE_NAME_TOO_LONG:
return 'Tube Name Too Long';
break;
case self::NOT_IGNORED:
return 'Not Ignored';
break;
case self::OUT_OF_MEMORY:
return 'Out of Memory';
break;
case self::INTERNAL_ERROR:
return 'Internal Error';
break;
case self::BAD_FORMAT:
return 'Bad Format';
break;
case self::UNKNOWN_COMMAND:
return 'Unknown Command';
break;
case self::SERVER_OFFLINE:
return 'Server Offline';
break;
case self::SERVER_READ:
return 'Server Read Error';
break;
case self::SERVER_WRITE:
return 'Server Write Error';
break;
default:
return 'Unknown';
break;
}
} | php | public function getCodeAsString()
{
switch ($this->getCode()) {
case self::BURIED:
return 'Buried';
break;
case self::NOT_FOUND:
return 'Not Found';
break;
case self::EXPECTED_CRLF:
return 'Expected CRLF';
break;
case self::JOB_TOO_BIG:
return 'Job Too Big';
break;
case self::DEADLINE_SOON:
return 'Deadline Soon';
break;
case self::TIMED_OUT:
return 'Timed Out';
break;
case self::TUBE_NAME_TOO_LONG:
return 'Tube Name Too Long';
break;
case self::NOT_IGNORED:
return 'Not Ignored';
break;
case self::OUT_OF_MEMORY:
return 'Out of Memory';
break;
case self::INTERNAL_ERROR:
return 'Internal Error';
break;
case self::BAD_FORMAT:
return 'Bad Format';
break;
case self::UNKNOWN_COMMAND:
return 'Unknown Command';
break;
case self::SERVER_OFFLINE:
return 'Server Offline';
break;
case self::SERVER_READ:
return 'Server Read Error';
break;
case self::SERVER_WRITE:
return 'Server Write Error';
break;
default:
return 'Unknown';
break;
}
} | [
"public",
"function",
"getCodeAsString",
"(",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"getCode",
"(",
")",
")",
"{",
"case",
"self",
"::",
"BURIED",
":",
"return",
"'Buried'",
";",
"break",
";",
"case",
"self",
"::",
"NOT_FOUND",
":",
"return",
"'N... | Get a string representation of a given code
@param integer $code Code to get string representation of
@return string | [
"Get",
"a",
"string",
"representation",
"of",
"a",
"given",
"code"
] | 833c52122bb4879ef2945dab34b32992a6bd718c | https://github.com/phpcodecrafting/php-beanstalk/blob/833c52122bb4879ef2945dab34b32992a6bd718c/lib/Beanstalk/Exception.php#L107-L174 | train |
krystal-framework/krystal.framework | src/Krystal/Validate/Input/InputValidator.php | InputValidator.factory | public static function factory(array $source, array $definitions, $translator)
{
return new self($source, $definitions, new DefinitionParser(new ConstraintFactory()), $translator);
} | php | public static function factory(array $source, array $definitions, $translator)
{
return new self($source, $definitions, new DefinitionParser(new ConstraintFactory()), $translator);
} | [
"public",
"static",
"function",
"factory",
"(",
"array",
"$",
"source",
",",
"array",
"$",
"definitions",
",",
"$",
"translator",
")",
"{",
"return",
"new",
"self",
"(",
"$",
"source",
",",
"$",
"definitions",
",",
"new",
"DefinitionParser",
"(",
"new",
... | Builds an instance
@param array $source
@param array $definitions
@param Translator $translator
@return \Krystal\Validate\Input\InputValidator | [
"Builds",
"an",
"instance"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Validate/Input/InputValidator.php#L28-L31 | train |
luismanuelamengual/NeoPHP | src/NeoPHP/Http/Response.php | Response.clear | public function clear() {
$this->statusCode = self::HTTP_OK;
$this->headers = [];
$this->cookies = [];
$this->content = null;
$this->sent = false;
} | php | public function clear() {
$this->statusCode = self::HTTP_OK;
$this->headers = [];
$this->cookies = [];
$this->content = null;
$this->sent = false;
} | [
"public",
"function",
"clear",
"(",
")",
"{",
"$",
"this",
"->",
"statusCode",
"=",
"self",
"::",
"HTTP_OK",
";",
"$",
"this",
"->",
"headers",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"cookies",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"content",
"=... | Clears the response | [
"Clears",
"the",
"response"
] | da7c5831974b37dd4b0b170d9aa64e61404d819b | https://github.com/luismanuelamengual/NeoPHP/blob/da7c5831974b37dd4b0b170d9aa64e61404d819b/src/NeoPHP/Http/Response.php#L103-L109 | train |
luismanuelamengual/NeoPHP | src/NeoPHP/Http/Response.php | Response.sendHeaders | private function sendHeaders() {
if (!headers_sent()) {
http_response_code($this->statusCode);
foreach ($this->headers as $header) {
header($header);
}
foreach ($this->cookies as $cookie) {
call_user_func_array("setcookie", $cookie);
}
}
} | php | private function sendHeaders() {
if (!headers_sent()) {
http_response_code($this->statusCode);
foreach ($this->headers as $header) {
header($header);
}
foreach ($this->cookies as $cookie) {
call_user_func_array("setcookie", $cookie);
}
}
} | [
"private",
"function",
"sendHeaders",
"(",
")",
"{",
"if",
"(",
"!",
"headers_sent",
"(",
")",
")",
"{",
"http_response_code",
"(",
"$",
"this",
"->",
"statusCode",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"headers",
"as",
"$",
"header",
")",
"{",
... | Sends the response headers | [
"Sends",
"the",
"response",
"headers"
] | da7c5831974b37dd4b0b170d9aa64e61404d819b | https://github.com/luismanuelamengual/NeoPHP/blob/da7c5831974b37dd4b0b170d9aa64e61404d819b/src/NeoPHP/Http/Response.php#L227-L237 | train |
luismanuelamengual/NeoPHP | src/NeoPHP/Http/Response.php | Response.sendConfig | private function sendConfig() {
if ($this->content !== null) {
if (($this->content instanceof stdClass) || is_array($this->content)) {
$content = ob_get_contents();
if (empty($content)) {
$this->contentType("application/json");
$this->content = json_encode($this->content);
}
}
}
} | php | private function sendConfig() {
if ($this->content !== null) {
if (($this->content instanceof stdClass) || is_array($this->content)) {
$content = ob_get_contents();
if (empty($content)) {
$this->contentType("application/json");
$this->content = json_encode($this->content);
}
}
}
} | [
"private",
"function",
"sendConfig",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"content",
"!==",
"null",
")",
"{",
"if",
"(",
"(",
"$",
"this",
"->",
"content",
"instanceof",
"stdClass",
")",
"||",
"is_array",
"(",
"$",
"this",
"->",
"content",
")... | Configures the response before sending | [
"Configures",
"the",
"response",
"before",
"sending"
] | da7c5831974b37dd4b0b170d9aa64e61404d819b | https://github.com/luismanuelamengual/NeoPHP/blob/da7c5831974b37dd4b0b170d9aa64e61404d819b/src/NeoPHP/Http/Response.php#L242-L252 | train |
luismanuelamengual/NeoPHP | src/NeoPHP/Http/Response.php | Response.sendContent | private function sendContent() {
if ($this->content !== null) {
if ($this->content instanceof View) {
$this->content->render();
}
else if (($this->content instanceof stdClass) || is_array($this->content)) {
echo "<pre>";
print_r ($this->content);
echo "</pre>";
}
else {
echo $this->content;
}
}
} | php | private function sendContent() {
if ($this->content !== null) {
if ($this->content instanceof View) {
$this->content->render();
}
else if (($this->content instanceof stdClass) || is_array($this->content)) {
echo "<pre>";
print_r ($this->content);
echo "</pre>";
}
else {
echo $this->content;
}
}
} | [
"private",
"function",
"sendContent",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"content",
"!==",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"content",
"instanceof",
"View",
")",
"{",
"$",
"this",
"->",
"content",
"->",
"render",
"(",
")",
... | Sends the content of the response | [
"Sends",
"the",
"content",
"of",
"the",
"response"
] | da7c5831974b37dd4b0b170d9aa64e61404d819b | https://github.com/luismanuelamengual/NeoPHP/blob/da7c5831974b37dd4b0b170d9aa64e61404d819b/src/NeoPHP/Http/Response.php#L257-L271 | train |
manusreload/GLFramework | modules/debugbar/src/Collectors/ErrorCollector.php | ErrorCollector.formatExceptionData | public function formatExceptionData(GeneratedError $e)
{
$filePath = $e->getFile();
if ($filePath && file_exists($filePath)) {
$lines = file($filePath);
$start = $e->getLine() - 4;
$lines = array_slice($lines, $start < 0 ? 0 : $start, 7);
} else {
$lines = array("Cannot open the file ($filePath) in which the exception occurred ");
}
return array(
// 'type' => get_class($e),
'type' => '',
'message' => $e->getMessage(),
'code' => $e->getCode(),
'file' => $filePath,
'line' => $e->getLine(),
'surrounding_lines' => $lines
);
} | php | public function formatExceptionData(GeneratedError $e)
{
$filePath = $e->getFile();
if ($filePath && file_exists($filePath)) {
$lines = file($filePath);
$start = $e->getLine() - 4;
$lines = array_slice($lines, $start < 0 ? 0 : $start, 7);
} else {
$lines = array("Cannot open the file ($filePath) in which the exception occurred ");
}
return array(
// 'type' => get_class($e),
'type' => '',
'message' => $e->getMessage(),
'code' => $e->getCode(),
'file' => $filePath,
'line' => $e->getLine(),
'surrounding_lines' => $lines
);
} | [
"public",
"function",
"formatExceptionData",
"(",
"GeneratedError",
"$",
"e",
")",
"{",
"$",
"filePath",
"=",
"$",
"e",
"->",
"getFile",
"(",
")",
";",
"if",
"(",
"$",
"filePath",
"&&",
"file_exists",
"(",
"$",
"filePath",
")",
")",
"{",
"$",
"lines",
... | Returns exception data as an array
@param \Throwable $e
@return array | [
"Returns",
"exception",
"data",
"as",
"an",
"array"
] | 6867bdf22482cff4e92adbba6849818860228104 | https://github.com/manusreload/GLFramework/blob/6867bdf22482cff4e92adbba6849818860228104/modules/debugbar/src/Collectors/ErrorCollector.php#L69-L89 | train |
phpcodecrafting/php-beanstalk | lib/Beanstalk/Job.php | Job.release | public function release($delay = 10, $priority = 5)
{
return $this->getConnection()->release($this->getId(), $priority, $delay);
} | php | public function release($delay = 10, $priority = 5)
{
return $this->getConnection()->release($this->getId(), $priority, $delay);
} | [
"public",
"function",
"release",
"(",
"$",
"delay",
"=",
"10",
",",
"$",
"priority",
"=",
"5",
")",
"{",
"return",
"$",
"this",
"->",
"getConnection",
"(",
")",
"->",
"release",
"(",
"$",
"this",
"->",
"getId",
"(",
")",
",",
"$",
"priority",
",",
... | Release the job
The release command puts a reserved job back into the ready queue (and marks
its state as "ready") to be run by any client. It is normally used when the job
fails because of a transitory error.
@param integer $delay Number of seconds to wait before putting the job in the ready queue.
The job will be in the "delayed" state during this time
@param integer $priority A new priority to assign to the job
@throws BeanstalkException
@return boolean | [
"Release",
"the",
"job"
] | 833c52122bb4879ef2945dab34b32992a6bd718c | https://github.com/phpcodecrafting/php-beanstalk/blob/833c52122bb4879ef2945dab34b32992a6bd718c/lib/Beanstalk/Job.php#L109-L112 | train |
krystal-framework/krystal.framework | src/Krystal/Stdlib/VirtualEntity.php | VirtualEntity.handle | private function handle($method, array $arguments, $default)
{
// Target property (drop set or get word)
$property = substr($method, 3);
// Convert to snake case
$property = TextUtils::snakeCase($property);
$start = substr($method, 0, 3);
// Are we dealing with a getter?
if ($start == 'get') {
if ($property === false) {
throw new LogicException('Attempted to call a getter on undefined property');
}
// getter is being used
if ($this->has($property)) {
return $this->container[$property];
} else {
return $default;
}
// Are we dealing with a setter?
} else if ($start == 'set') {
if ($this->once === true && $this->has($property)) {
throw new RuntimeException(sprintf('You can write to "%s" only once', $property));
}
// Make sure the first argument is supplied
if (array_key_exists(0, $arguments)) {
$value = $arguments[0];
} else {
throw new UnderflowException(sprintf(
'The virtual setter for "%s" expects at least one argument, which would be a value. None supplied.', $property
));
}
// If filter is defined, then use it
if (isset($arguments[1])) {
// Override value with filtered one
$value = Filter::sanitize($value, $arguments[1]);
}
// setter is being used
$this->container[$property] = $value;
return $this;
} else {
// Throw exception only on strict mode
if ($this->strict == true) {
throw new RuntimeException(sprintf(
'Virtual method name must start either from "get" or "set". You provided "%s"', $method
));
}
}
} | php | private function handle($method, array $arguments, $default)
{
// Target property (drop set or get word)
$property = substr($method, 3);
// Convert to snake case
$property = TextUtils::snakeCase($property);
$start = substr($method, 0, 3);
// Are we dealing with a getter?
if ($start == 'get') {
if ($property === false) {
throw new LogicException('Attempted to call a getter on undefined property');
}
// getter is being used
if ($this->has($property)) {
return $this->container[$property];
} else {
return $default;
}
// Are we dealing with a setter?
} else if ($start == 'set') {
if ($this->once === true && $this->has($property)) {
throw new RuntimeException(sprintf('You can write to "%s" only once', $property));
}
// Make sure the first argument is supplied
if (array_key_exists(0, $arguments)) {
$value = $arguments[0];
} else {
throw new UnderflowException(sprintf(
'The virtual setter for "%s" expects at least one argument, which would be a value. None supplied.', $property
));
}
// If filter is defined, then use it
if (isset($arguments[1])) {
// Override value with filtered one
$value = Filter::sanitize($value, $arguments[1]);
}
// setter is being used
$this->container[$property] = $value;
return $this;
} else {
// Throw exception only on strict mode
if ($this->strict == true) {
throw new RuntimeException(sprintf(
'Virtual method name must start either from "get" or "set". You provided "%s"', $method
));
}
}
} | [
"private",
"function",
"handle",
"(",
"$",
"method",
",",
"array",
"$",
"arguments",
",",
"$",
"default",
")",
"{",
"// Target property (drop set or get word)",
"$",
"property",
"=",
"substr",
"(",
"$",
"method",
",",
"3",
")",
";",
"// Convert to snake case",
... | Handles the Data Value object logic
@param string $method
@param array $arguments
@param mixed $default Default value to be returned if getter fails
@throws \RuntimeException If has and violated writing constraint or method doesn't start from get or get
@throws \LogicException If trying to get undefined property
@return mixed | [
"Handles",
"the",
"Data",
"Value",
"object",
"logic"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Stdlib/VirtualEntity.php#L138-L194 | train |
krystal-framework/krystal.framework | src/Krystal/Session/SessionBag.php | SessionBag.initHandler | private function initHandler(SaveHandlerInterface $handler)
{
return session_set_save_handler(array($handler, 'open'),
array($handler, 'close'),
array($handler, 'read'),
array($handler, 'write'),
array($handler, 'destroy'),
array($handler, 'gc'));
} | php | private function initHandler(SaveHandlerInterface $handler)
{
return session_set_save_handler(array($handler, 'open'),
array($handler, 'close'),
array($handler, 'read'),
array($handler, 'write'),
array($handler, 'destroy'),
array($handler, 'gc'));
} | [
"private",
"function",
"initHandler",
"(",
"SaveHandlerInterface",
"$",
"handler",
")",
"{",
"return",
"session_set_save_handler",
"(",
"array",
"(",
"$",
"handler",
",",
"'open'",
")",
",",
"array",
"(",
"$",
"handler",
",",
"'close'",
")",
",",
"array",
"(... | Initializes the session storage adapter
@param \Krystal\Session\Adapter\SaveHandlerInterface $handler
@return boolean | [
"Initializes",
"the",
"session",
"storage",
"adapter"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Session/SessionBag.php#L80-L88 | train |
krystal-framework/krystal.framework | src/Krystal/Session/SessionBag.php | SessionBag.start | public function start(array $options = array())
{
if ($this->isStarted() === false) {
// Cookie parameters must be defined before session_start()!
if (!empty($options)) {
$this->setCookieParams($options);
}
if (!session_start()) {
return false;
}
}
// Reference is important! Because we are going to deal with $_SESSION itself
// not with its copy, or this simply won't work the way we expect
$this->session =& $_SESSION;
// Store unique data to validator
$this->sessionValidator->write($this);
return true;
} | php | public function start(array $options = array())
{
if ($this->isStarted() === false) {
// Cookie parameters must be defined before session_start()!
if (!empty($options)) {
$this->setCookieParams($options);
}
if (!session_start()) {
return false;
}
}
// Reference is important! Because we are going to deal with $_SESSION itself
// not with its copy, or this simply won't work the way we expect
$this->session =& $_SESSION;
// Store unique data to validator
$this->sessionValidator->write($this);
return true;
} | [
"public",
"function",
"start",
"(",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isStarted",
"(",
")",
"===",
"false",
")",
"{",
"// Cookie parameters must be defined before session_start()!",
"if",
"(",
"!",
"emp... | Starts a new session or continues existing one
@param array $options Cookie options
@return boolean | [
"Starts",
"a",
"new",
"session",
"or",
"continues",
"existing",
"one"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Session/SessionBag.php#L136-L157 | train |
krystal-framework/krystal.framework | src/Krystal/Session/SessionBag.php | SessionBag.setMany | public function setMany(array $collection)
{
foreach ($collection as $key => $value) {
$this->set($key, $value);
}
return $this;
} | php | public function setMany(array $collection)
{
foreach ($collection as $key => $value) {
$this->set($key, $value);
}
return $this;
} | [
"public",
"function",
"setMany",
"(",
"array",
"$",
"collection",
")",
"{",
"foreach",
"(",
"$",
"collection",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"set",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"}",
"return",
... | Set many keys at once
@param array $collection
@return \Krystal\Session\SessionBag | [
"Set",
"many",
"keys",
"at",
"once"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Session/SessionBag.php#L240-L247 | train |
krystal-framework/krystal.framework | src/Krystal/Session/SessionBag.php | SessionBag.hasMany | public function hasMany(array $keys)
{
foreach ($keys as $key) {
if (!$this->has($key)) {
return false;
}
}
return true;
} | php | public function hasMany(array $keys)
{
foreach ($keys as $key) {
if (!$this->has($key)) {
return false;
}
}
return true;
} | [
"public",
"function",
"hasMany",
"(",
"array",
"$",
"keys",
")",
"{",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"has",
"(",
"$",
"key",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",... | Determines whether all keys present in the session storage
@param array $keys
@return boolean | [
"Determines",
"whether",
"all",
"keys",
"present",
"in",
"the",
"session",
"storage"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Session/SessionBag.php#L266-L275 | train |
krystal-framework/krystal.framework | src/Krystal/Session/SessionBag.php | SessionBag.get | public function get($key, $default = false)
{
if ($this->has($key) !== false) {
return $this->session[$key];
} else {
return $default;
}
} | php | public function get($key, $default = false)
{
if ($this->has($key) !== false) {
return $this->session[$key];
} else {
return $default;
}
} | [
"public",
"function",
"get",
"(",
"$",
"key",
",",
"$",
"default",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"has",
"(",
"$",
"key",
")",
"!==",
"false",
")",
"{",
"return",
"$",
"this",
"->",
"session",
"[",
"$",
"key",
"]",
";",
... | Reads data from a session
@param string $key
@param mixed $default Default value to be returned if request key doesn't exist
@return mixed | [
"Reads",
"data",
"from",
"a",
"session"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Session/SessionBag.php#L302-L309 | train |
krystal-framework/krystal.framework | src/Krystal/Session/SessionBag.php | SessionBag.remove | public function remove($key)
{
if ($this->has($key)) {
unset($this->session[$key]);
return true;
} else {
return false;
}
} | php | public function remove($key)
{
if ($this->has($key)) {
unset($this->session[$key]);
return true;
} else {
return false;
}
} | [
"public",
"function",
"remove",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"has",
"(",
"$",
"key",
")",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"session",
"[",
"$",
"key",
"]",
")",
";",
"return",
"true",
";",
"}",
"else",
"{... | Removes a key from the storage
@param string $key
@return boolean | [
"Removes",
"a",
"key",
"from",
"the",
"storage"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Session/SessionBag.php#L338-L346 | train |
krystal-framework/krystal.framework | src/Krystal/Session/SessionBag.php | SessionBag.setCookieParams | public function setCookieParams(array $params)
{
$defaults = $this->getCookieParams();
// Override defaults if present
$params = array_merge($defaults, $params);
return session_set_cookie_params(
intval($params['lifetime']),
$params['path'],
$params['domain'],
(bool) $params['secure'],
(bool) $params['httponly']
);
} | php | public function setCookieParams(array $params)
{
$defaults = $this->getCookieParams();
// Override defaults if present
$params = array_merge($defaults, $params);
return session_set_cookie_params(
intval($params['lifetime']),
$params['path'],
$params['domain'],
(bool) $params['secure'],
(bool) $params['httponly']
);
} | [
"public",
"function",
"setCookieParams",
"(",
"array",
"$",
"params",
")",
"{",
"$",
"defaults",
"=",
"$",
"this",
"->",
"getCookieParams",
"(",
")",
";",
"// Override defaults if present",
"$",
"params",
"=",
"array_merge",
"(",
"$",
"defaults",
",",
"$",
"... | Returns cookie parameters for the session
@param array $params
@return array | [
"Returns",
"cookie",
"parameters",
"for",
"the",
"session"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Session/SessionBag.php#L420-L434 | train |
krystal-framework/krystal.framework | src/Krystal/Session/SessionBag.php | SessionBag.destroy | public function destroy()
{
// Erase the id on the client side
if ($this->cookieBag->has($this->getName())) {
$this->cookieBag->remove($this->getName());
}
// Erase on the server side
return session_destroy();
} | php | public function destroy()
{
// Erase the id on the client side
if ($this->cookieBag->has($this->getName())) {
$this->cookieBag->remove($this->getName());
}
// Erase on the server side
return session_destroy();
} | [
"public",
"function",
"destroy",
"(",
")",
"{",
"// Erase the id on the client side",
"if",
"(",
"$",
"this",
"->",
"cookieBag",
"->",
"has",
"(",
"$",
"this",
"->",
"getName",
"(",
")",
")",
")",
"{",
"$",
"this",
"->",
"cookieBag",
"->",
"remove",
"(",... | Destroys the session
@return boolean | [
"Destroys",
"the",
"session"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Session/SessionBag.php#L461-L470 | train |
krystal-framework/krystal.framework | src/Krystal/Authentication/Cookie/ReAuth.php | ReAuth.getUserBag | public function getUserBag()
{
$userBag = new UserBag();
$userBag->setLogin($this->cookieBag->get(self::CLIENT_LOGIN_KEY))
->setPasswordHash($this->cookieBag->get(self::CLIENT_LOGIN_PASSWORD_HASH_KEY));
return $userBag;
} | php | public function getUserBag()
{
$userBag = new UserBag();
$userBag->setLogin($this->cookieBag->get(self::CLIENT_LOGIN_KEY))
->setPasswordHash($this->cookieBag->get(self::CLIENT_LOGIN_PASSWORD_HASH_KEY));
return $userBag;
} | [
"public",
"function",
"getUserBag",
"(",
")",
"{",
"$",
"userBag",
"=",
"new",
"UserBag",
"(",
")",
";",
"$",
"userBag",
"->",
"setLogin",
"(",
"$",
"this",
"->",
"cookieBag",
"->",
"get",
"(",
"self",
"::",
"CLIENT_LOGIN_KEY",
")",
")",
"->",
"setPass... | Returns user bag
@return \Krystal\Authentication\Cookie\UserBag | [
"Returns",
"user",
"bag"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Authentication/Cookie/ReAuth.php#L96-L103 | train |
krystal-framework/krystal.framework | src/Krystal/Authentication/Cookie/ReAuth.php | ReAuth.isStored | public function isStored()
{
foreach ($this->getKeys() as $key) {
if (!$this->cookieBag->has($key)) {
return false;
}
}
// Now start checking the signature
if (!$this->isValidSignature(
$this->cookieBag->get(self::CLIENT_LOGIN_KEY),
$this->cookieBag->get(self::CLIENT_LOGIN_PASSWORD_HASH_KEY),
$this->cookieBag->get(self::CLIENT_TOKEN_KEY)
)) {
return false;
}
return true;
} | php | public function isStored()
{
foreach ($this->getKeys() as $key) {
if (!$this->cookieBag->has($key)) {
return false;
}
}
// Now start checking the signature
if (!$this->isValidSignature(
$this->cookieBag->get(self::CLIENT_LOGIN_KEY),
$this->cookieBag->get(self::CLIENT_LOGIN_PASSWORD_HASH_KEY),
$this->cookieBag->get(self::CLIENT_TOKEN_KEY)
)) {
return false;
}
return true;
} | [
"public",
"function",
"isStored",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getKeys",
"(",
")",
"as",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"cookieBag",
"->",
"has",
"(",
"$",
"key",
")",
")",
"{",
"return",
"false",
... | Checks whether data is stored
@return boolean | [
"Checks",
"whether",
"data",
"is",
"stored"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Authentication/Cookie/ReAuth.php#L110-L128 | train |
krystal-framework/krystal.framework | src/Krystal/Authentication/Cookie/ReAuth.php | ReAuth.clear | public function clear()
{
$keys = $this->getKeys();
foreach ($keys as $key) {
$this->cookieBag->remove($key);
}
return true;
} | php | public function clear()
{
$keys = $this->getKeys();
foreach ($keys as $key) {
$this->cookieBag->remove($key);
}
return true;
} | [
"public",
"function",
"clear",
"(",
")",
"{",
"$",
"keys",
"=",
"$",
"this",
"->",
"getKeys",
"(",
")",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"key",
")",
"{",
"$",
"this",
"->",
"cookieBag",
"->",
"remove",
"(",
"$",
"key",
")",
";",
"}"... | Clears all related data from cookies
@return boolean | [
"Clears",
"all",
"related",
"data",
"from",
"cookies"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Authentication/Cookie/ReAuth.php#L135-L144 | train |
krystal-framework/krystal.framework | src/Krystal/Authentication/Cookie/ReAuth.php | ReAuth.store | public function store($login, $passwordHash)
{
// Data to store on client machine
$data = array(
self::CLIENT_LOGIN_KEY => $login,
self::CLIENT_LOGIN_PASSWORD_HASH_KEY => $passwordHash,
self::CLIENT_TOKEN_KEY => $this->makeToken($login, $passwordHash)
);
foreach ($data as $key => $value) {
$this->cookieBag->set($key, $value, self::CLIENT_LIFETIME);
}
} | php | public function store($login, $passwordHash)
{
// Data to store on client machine
$data = array(
self::CLIENT_LOGIN_KEY => $login,
self::CLIENT_LOGIN_PASSWORD_HASH_KEY => $passwordHash,
self::CLIENT_TOKEN_KEY => $this->makeToken($login, $passwordHash)
);
foreach ($data as $key => $value) {
$this->cookieBag->set($key, $value, self::CLIENT_LIFETIME);
}
} | [
"public",
"function",
"store",
"(",
"$",
"login",
",",
"$",
"passwordHash",
")",
"{",
"// Data to store on client machine",
"$",
"data",
"=",
"array",
"(",
"self",
"::",
"CLIENT_LOGIN_KEY",
"=>",
"$",
"login",
",",
"self",
"::",
"CLIENT_LOGIN_PASSWORD_HASH_KEY",
... | Stores auth data on client machine
@param string $login
@param string $passwordHash
@return void | [
"Stores",
"auth",
"data",
"on",
"client",
"machine"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Authentication/Cookie/ReAuth.php#L153-L165 | train |
Tecnocreaciones/ToolsBundle | Asset/AssetManager.php | AssetManager.parseModes | protected function parseModes()
{
foreach ($this->modeDirs as $dir) {
$absDir = $this->fileLocator->locate($dir);
$finder = Finder::create()->files()->in($absDir)->notName("*test.js")->name('*.js');
foreach ($finder as $file) {
$this->addModesFromFile($dir,$file);
}
}
#save to cache if env prod
if ($this->env == 'prod') {
$this->cacheDriver->save(static::CACHE_MODES_NAME, $this->getModes());
}
} | php | protected function parseModes()
{
foreach ($this->modeDirs as $dir) {
$absDir = $this->fileLocator->locate($dir);
$finder = Finder::create()->files()->in($absDir)->notName("*test.js")->name('*.js');
foreach ($finder as $file) {
$this->addModesFromFile($dir,$file);
}
}
#save to cache if env prod
if ($this->env == 'prod') {
$this->cacheDriver->save(static::CACHE_MODES_NAME, $this->getModes());
}
} | [
"protected",
"function",
"parseModes",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"modeDirs",
"as",
"$",
"dir",
")",
"{",
"$",
"absDir",
"=",
"$",
"this",
"->",
"fileLocator",
"->",
"locate",
"(",
"$",
"dir",
")",
";",
"$",
"finder",
"=",
"F... | Parse editor mode from dir | [
"Parse",
"editor",
"mode",
"from",
"dir"
] | 8edc159b91ea41d7a880d2ca0860352d7b05370f | https://github.com/Tecnocreaciones/ToolsBundle/blob/8edc159b91ea41d7a880d2ca0860352d7b05370f/Asset/AssetManager.php#L122-L137 | train |
Tecnocreaciones/ToolsBundle | Asset/AssetManager.php | AssetManager.addModesFromFile | protected function addModesFromFile($dir,$file)
{
$dir = $this->parseDir($dir);
$jsContent = $file->getContents();
preg_match_all('#defineMIME\(\s*(\'|")([^\'"]+)(\'|")#', $jsContent, $modes);
if (count($modes[2])) {
foreach ($modes[2] as $mode) {
$this->addMode($mode, $dir."/".$file->getRelativePathname());
}
}
$this->addMode($file->getRelativePath(), $dir."/".$file->getRelativePathname());
#save to cache if env prod
if ($this->env == 'prod') {
$this->cacheDriver->save(static::CACHE_MODES_NAME, $this->getThemes());
}
} | php | protected function addModesFromFile($dir,$file)
{
$dir = $this->parseDir($dir);
$jsContent = $file->getContents();
preg_match_all('#defineMIME\(\s*(\'|")([^\'"]+)(\'|")#', $jsContent, $modes);
if (count($modes[2])) {
foreach ($modes[2] as $mode) {
$this->addMode($mode, $dir."/".$file->getRelativePathname());
}
}
$this->addMode($file->getRelativePath(), $dir."/".$file->getRelativePathname());
#save to cache if env prod
if ($this->env == 'prod') {
$this->cacheDriver->save(static::CACHE_MODES_NAME, $this->getThemes());
}
} | [
"protected",
"function",
"addModesFromFile",
"(",
"$",
"dir",
",",
"$",
"file",
")",
"{",
"$",
"dir",
"=",
"$",
"this",
"->",
"parseDir",
"(",
"$",
"dir",
")",
";",
"$",
"jsContent",
"=",
"$",
"file",
"->",
"getContents",
"(",
")",
";",
"preg_match_a... | Parse editor modes from dir | [
"Parse",
"editor",
"modes",
"from",
"dir"
] | 8edc159b91ea41d7a880d2ca0860352d7b05370f | https://github.com/Tecnocreaciones/ToolsBundle/blob/8edc159b91ea41d7a880d2ca0860352d7b05370f/Asset/AssetManager.php#L152-L169 | train |
Tecnocreaciones/ToolsBundle | Asset/AssetManager.php | AssetManager.parseThemes | protected function parseThemes()
{
foreach ($this->themesDirs as $dir) {
$absDir = $this->fileLocator->locate($dir);
$finder = Finder::create()->files()->in($absDir)->name('*.css');
foreach ($finder as $file) {
$this->addTheme($file->getBasename('.css'), $file->getPathname());
}
}
#save to cache if env prod
if ($this->env == 'prod') {
$this->cacheDriver->save(static::CACHE_THEMES_NAME, $this->getThemes());
}
} | php | protected function parseThemes()
{
foreach ($this->themesDirs as $dir) {
$absDir = $this->fileLocator->locate($dir);
$finder = Finder::create()->files()->in($absDir)->name('*.css');
foreach ($finder as $file) {
$this->addTheme($file->getBasename('.css'), $file->getPathname());
}
}
#save to cache if env prod
if ($this->env == 'prod') {
$this->cacheDriver->save(static::CACHE_THEMES_NAME, $this->getThemes());
}
} | [
"protected",
"function",
"parseThemes",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"themesDirs",
"as",
"$",
"dir",
")",
"{",
"$",
"absDir",
"=",
"$",
"this",
"->",
"fileLocator",
"->",
"locate",
"(",
"$",
"dir",
")",
";",
"$",
"finder",
"=",
... | Parse editor themes from dir | [
"Parse",
"editor",
"themes",
"from",
"dir"
] | 8edc159b91ea41d7a880d2ca0860352d7b05370f | https://github.com/Tecnocreaciones/ToolsBundle/blob/8edc159b91ea41d7a880d2ca0860352d7b05370f/Asset/AssetManager.php#L173-L186 | train |
Riimu/Kit-BaseConversion | src/BaseConverter.php | BaseConverter.baseConvert | public static function baseConvert($number, $fromBase, $toBase, $precision = -1)
{
$converter = new self($fromBase, $toBase);
$converter->setPrecision($precision);
return $converter->convert($number);
} | php | public static function baseConvert($number, $fromBase, $toBase, $precision = -1)
{
$converter = new self($fromBase, $toBase);
$converter->setPrecision($precision);
return $converter->convert($number);
} | [
"public",
"static",
"function",
"baseConvert",
"(",
"$",
"number",
",",
"$",
"fromBase",
",",
"$",
"toBase",
",",
"$",
"precision",
"=",
"-",
"1",
")",
"{",
"$",
"converter",
"=",
"new",
"self",
"(",
"$",
"fromBase",
",",
"$",
"toBase",
")",
";",
"... | Converts the provided number from base to another.
This method provides a convenient replacement to PHP's built in
`base_convert()`. The number bases are simply passed along to the
constructor, which means they can be instances of NumberBase class or
constructor parameters for that class.
Note that due to the way the constructor parameters for NumberBase work,
this method can be used exactly the same way as `base_convert()`.
@param string $number The number to convert
@param mixed $fromBase Number base used by the provided number
@param mixed $toBase Number base used by the returned number
@param int $precision Precision for inaccurate conversion
@return string|false The converted number or false on error | [
"Converts",
"the",
"provided",
"number",
"from",
"base",
"to",
"another",
"."
] | e0f486759590b69126c83622edd309217f783324 | https://github.com/Riimu/Kit-BaseConversion/blob/e0f486759590b69126c83622edd309217f783324/src/BaseConverter.php#L83-L89 | train |
Riimu/Kit-BaseConversion | src/BaseConverter.php | BaseConverter.convert | public function convert($number)
{
$integer = (string) $number;
$fractions = null;
$sign = '';
if (in_array(substr($integer, 0, 1), ['+', '-'], true)) {
$sign = $integer[0];
$integer = substr($integer, 1);
}
if (($pos = strpos($integer, '.')) !== false) {
$fractions = substr($integer, $pos + 1);
$integer = substr($integer, 0, $pos);
}
return $this->convertNumber($sign, $integer, $fractions);
} | php | public function convert($number)
{
$integer = (string) $number;
$fractions = null;
$sign = '';
if (in_array(substr($integer, 0, 1), ['+', '-'], true)) {
$sign = $integer[0];
$integer = substr($integer, 1);
}
if (($pos = strpos($integer, '.')) !== false) {
$fractions = substr($integer, $pos + 1);
$integer = substr($integer, 0, $pos);
}
return $this->convertNumber($sign, $integer, $fractions);
} | [
"public",
"function",
"convert",
"(",
"$",
"number",
")",
"{",
"$",
"integer",
"=",
"(",
"string",
")",
"$",
"number",
";",
"$",
"fractions",
"=",
"null",
";",
"$",
"sign",
"=",
"''",
";",
"if",
"(",
"in_array",
"(",
"substr",
"(",
"$",
"integer",
... | Converts the number provided as a string from source base to target base.
This method provides convenient conversions by accepting the number as
a string. The number may optionally be preceded by a plus or minus sign
which is prepended to the result as well. The number may also have a
period, which separates the integer part and the fractional part.
Due to the special meaning of `+`, `-` and `.`, it is not recommended to
use this method to convert numbers when using number bases that have a
meaning for these characters (such as base64).
If the number contains invalid characters, the method will return false
instead.
@param string $number The number to convert
@return string|false The converted number or false on error | [
"Converts",
"the",
"number",
"provided",
"as",
"a",
"string",
"from",
"source",
"base",
"to",
"target",
"base",
"."
] | e0f486759590b69126c83622edd309217f783324 | https://github.com/Riimu/Kit-BaseConversion/blob/e0f486759590b69126c83622edd309217f783324/src/BaseConverter.php#L109-L126 | train |
Riimu/Kit-BaseConversion | src/BaseConverter.php | BaseConverter.convertNumber | private function convertNumber($sign, $integer, $fractions)
{
try {
$result = implode('', $this->convertInteger($this->source->splitString($integer)));
if ($fractions !== null) {
$result .= '.' . implode('', $this->convertFractions($this->source->splitString($fractions)));
}
} catch (DigitList\InvalidDigitException $ex) {
return false;
}
return $sign . $result;
} | php | private function convertNumber($sign, $integer, $fractions)
{
try {
$result = implode('', $this->convertInteger($this->source->splitString($integer)));
if ($fractions !== null) {
$result .= '.' . implode('', $this->convertFractions($this->source->splitString($fractions)));
}
} catch (DigitList\InvalidDigitException $ex) {
return false;
}
return $sign . $result;
} | [
"private",
"function",
"convertNumber",
"(",
"$",
"sign",
",",
"$",
"integer",
",",
"$",
"fractions",
")",
"{",
"try",
"{",
"$",
"result",
"=",
"implode",
"(",
"''",
",",
"$",
"this",
"->",
"convertInteger",
"(",
"$",
"this",
"->",
"source",
"->",
"s... | Converts the different parts of the number and handles invalid digits.
@param string $sign Sign that preceded the number or an empty string
@param string $integer The integer part of the number
@param string|null $fractions The fractional part of the number or null if none
@return string|false The converted number or false on error | [
"Converts",
"the",
"different",
"parts",
"of",
"the",
"number",
"and",
"handles",
"invalid",
"digits",
"."
] | e0f486759590b69126c83622edd309217f783324 | https://github.com/Riimu/Kit-BaseConversion/blob/e0f486759590b69126c83622edd309217f783324/src/BaseConverter.php#L135-L148 | train |
nabu-3/provider-apache-httpd | files/CApacheAbstractFile.php | CApacheAbstractFile.populateCommonDocs | protected function populateCommonDocs(string $padding, string $commondocs) : string
{
$output = '';
if (is_dir($commondocs)) {
$h = opendir($commondocs);
while ($dir = readdir($h)) {
$folder = $commondocs . DIRECTORY_SEPARATOR . $dir;
if ($dir !== '.' && $dir !== '..' && is_dir($folder)) {
$output .= "\n"
. $padding . "Alias /$dir \"$folder\"\n"
. $padding . "<Directory \"$folder\">\n"
. $padding . " AllowOverride All\n"
. $padding . " Require all granted\n"
. $padding . "</Directory>\n"
;
}
}
closedir($h);
}
return $output;
} | php | protected function populateCommonDocs(string $padding, string $commondocs) : string
{
$output = '';
if (is_dir($commondocs)) {
$h = opendir($commondocs);
while ($dir = readdir($h)) {
$folder = $commondocs . DIRECTORY_SEPARATOR . $dir;
if ($dir !== '.' && $dir !== '..' && is_dir($folder)) {
$output .= "\n"
. $padding . "Alias /$dir \"$folder\"\n"
. $padding . "<Directory \"$folder\">\n"
. $padding . " AllowOverride All\n"
. $padding . " Require all granted\n"
. $padding . "</Directory>\n"
;
}
}
closedir($h);
}
return $output;
} | [
"protected",
"function",
"populateCommonDocs",
"(",
"string",
"$",
"padding",
",",
"string",
"$",
"commondocs",
")",
":",
"string",
"{",
"$",
"output",
"=",
"''",
";",
"if",
"(",
"is_dir",
"(",
"$",
"commondocs",
")",
")",
"{",
"$",
"h",
"=",
"opendir"... | Populates all subfolders in commondocs folder as Alias Apache primitives.
@param string $padding Padding before each line
@param string $commondocs Common Docs base path to be populated
@return string Returns a well formed string of Apache primitives with all aliases or an empty string if
the folder is empty. | [
"Populates",
"all",
"subfolders",
"in",
"commondocs",
"folder",
"as",
"Alias",
"Apache",
"primitives",
"."
] | 122f6190f9fb25baae12f4efb70f01241c1417c8 | https://github.com/nabu-3/provider-apache-httpd/blob/122f6190f9fb25baae12f4efb70f01241c1417c8/files/CApacheAbstractFile.php#L82-L104 | train |
wpfulcrum/extender | src/Extender/Str/StrCheckers.php | StrCheckers.hasSubstring | public static function hasSubstring($haystack, $needles, $characterEncoding = 'UTF-8')
{
foreach ((array)$needles as $needle) {
if ($needle == '') {
continue;
}
if (mb_strpos($haystack, $needle, 0, $characterEncoding) !== false) {
return true;
}
}
return false;
} | php | public static function hasSubstring($haystack, $needles, $characterEncoding = 'UTF-8')
{
foreach ((array)$needles as $needle) {
if ($needle == '') {
continue;
}
if (mb_strpos($haystack, $needle, 0, $characterEncoding) !== false) {
return true;
}
}
return false;
} | [
"public",
"static",
"function",
"hasSubstring",
"(",
"$",
"haystack",
",",
"$",
"needles",
",",
"$",
"characterEncoding",
"=",
"'UTF-8'",
")",
"{",
"foreach",
"(",
"(",
"array",
")",
"$",
"needles",
"as",
"$",
"needle",
")",
"{",
"if",
"(",
"$",
"needl... | Checks if the given string contains the given substring.
When passing an array of needles, the first needle match
returns `true`. Therefore, only one word in the array
needs to match.
@since 3.0.0
@param string $haystack The given string to check
@param string|array $needles The substring(s) to check for
@param string $characterEncoding (optional) Character encoding
Default is 'UTF-8'.
@return bool | [
"Checks",
"if",
"the",
"given",
"string",
"contains",
"the",
"given",
"substring",
"."
] | 96c9170d94959c0513c1d487bae2a67de6a20348 | https://github.com/wpfulcrum/extender/blob/96c9170d94959c0513c1d487bae2a67de6a20348/src/Extender/Str/StrCheckers.php#L23-L36 | train |
wpfulcrum/extender | src/Extender/Str/StrCheckers.php | StrCheckers.startsWith | public static function startsWith($haystack, $needles)
{
foreach ((array)$needles as $needle) {
if ($needle == '') {
continue;
}
$substring = mb_substr($haystack, 0, mb_strlen($needle));
if (self::doesStringMatchNeedle($substring, $needle)) {
return true;
}
}
return false;
} | php | public static function startsWith($haystack, $needles)
{
foreach ((array)$needles as $needle) {
if ($needle == '') {
continue;
}
$substring = mb_substr($haystack, 0, mb_strlen($needle));
if (self::doesStringMatchNeedle($substring, $needle)) {
return true;
}
}
return false;
} | [
"public",
"static",
"function",
"startsWith",
"(",
"$",
"haystack",
",",
"$",
"needles",
")",
"{",
"foreach",
"(",
"(",
"array",
")",
"$",
"needles",
"as",
"$",
"needle",
")",
"{",
"if",
"(",
"$",
"needle",
"==",
"''",
")",
"{",
"continue",
";",
"}... | Checks if the given string begins with the given substring.
When passing an array of needles, the first needle match
returns `true`. Therefore, only one word in the array
needs to match.
@since 3.0.0
@param string $haystack The given string to check
@param string|array $needles The substring(s) to check for
@return bool | [
"Checks",
"if",
"the",
"given",
"string",
"begins",
"with",
"the",
"given",
"substring",
"."
] | 96c9170d94959c0513c1d487bae2a67de6a20348 | https://github.com/wpfulcrum/extender/blob/96c9170d94959c0513c1d487bae2a67de6a20348/src/Extender/Str/StrCheckers.php#L79-L94 | train |
wpfulcrum/extender | src/Extender/Str/StrCheckers.php | StrCheckers.matchesPattern | public static function matchesPattern($pattern, $givenString)
{
if ($pattern == $givenString) {
return true;
}
$pattern = preg_quote($pattern, '#');
$pattern = str_replace('\*', '.*', $pattern) . '\z';
return (bool)preg_match('#^' . $pattern . '#', $givenString);
} | php | public static function matchesPattern($pattern, $givenString)
{
if ($pattern == $givenString) {
return true;
}
$pattern = preg_quote($pattern, '#');
$pattern = str_replace('\*', '.*', $pattern) . '\z';
return (bool)preg_match('#^' . $pattern . '#', $givenString);
} | [
"public",
"static",
"function",
"matchesPattern",
"(",
"$",
"pattern",
",",
"$",
"givenString",
")",
"{",
"if",
"(",
"$",
"pattern",
"==",
"$",
"givenString",
")",
"{",
"return",
"true",
";",
"}",
"$",
"pattern",
"=",
"preg_quote",
"(",
"$",
"pattern",
... | Check if the given string matches the given pattern.
Asterisks can be used to indicate wildcards.
@since 3.0.0
@param string $pattern The pattern to check
@param string $givenString the string to compare to the pattern
@return bool | [
"Check",
"if",
"the",
"given",
"string",
"matches",
"the",
"given",
"pattern",
"."
] | 96c9170d94959c0513c1d487bae2a67de6a20348 | https://github.com/wpfulcrum/extender/blob/96c9170d94959c0513c1d487bae2a67de6a20348/src/Extender/Str/StrCheckers.php#L108-L118 | train |
krystal-framework/krystal.framework | src/Krystal/Widget/AbstractListWidget.php | AbstractListWidget.createListItem | protected function createListItem($class, $text)
{
$li = new NodeElement();
$li->openTag('li')
->addAttribute('class', $class)
->finalize(false);
if ($text !== null) {
$li->setText($text);
}
return $li->closeTag();
} | php | protected function createListItem($class, $text)
{
$li = new NodeElement();
$li->openTag('li')
->addAttribute('class', $class)
->finalize(false);
if ($text !== null) {
$li->setText($text);
}
return $li->closeTag();
} | [
"protected",
"function",
"createListItem",
"(",
"$",
"class",
",",
"$",
"text",
")",
"{",
"$",
"li",
"=",
"new",
"NodeElement",
"(",
")",
";",
"$",
"li",
"->",
"openTag",
"(",
"'li'",
")",
"->",
"addAttribute",
"(",
"'class'",
",",
"$",
"class",
")",... | Creates list item
@param string $class List item class
@param string $text Item inner text
@return string | [
"Creates",
"list",
"item"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Widget/AbstractListWidget.php#L44-L56 | train |
krystal-framework/krystal.framework | src/Krystal/Widget/AbstractListWidget.php | AbstractListWidget.renderList | protected function renderList($class, array $children)
{
$ul = new NodeElement();
$ul->openTag('ul')
->addAttribute('class', $class)
->finalize(true)
->appendChildren($children)
->closeTag();
return $ul->render();
} | php | protected function renderList($class, array $children)
{
$ul = new NodeElement();
$ul->openTag('ul')
->addAttribute('class', $class)
->finalize(true)
->appendChildren($children)
->closeTag();
return $ul->render();
} | [
"protected",
"function",
"renderList",
"(",
"$",
"class",
",",
"array",
"$",
"children",
")",
"{",
"$",
"ul",
"=",
"new",
"NodeElement",
"(",
")",
";",
"$",
"ul",
"->",
"openTag",
"(",
"'ul'",
")",
"->",
"addAttribute",
"(",
"'class'",
",",
"$",
"cla... | Creates a list
@param string $class UL class
@param array $children
@return string | [
"Creates",
"a",
"list"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Widget/AbstractListWidget.php#L65-L75 | train |
inc2734/mimizuku-core | src/App/Contract/Helper/Template.php | Template.get_include_files | public static function get_include_files( $directory, $exclude_underscore = false ) {
$return = [
'files' => [],
'directories' => [],
];
if ( ! is_dir( $directory ) ) {
return $return;
}
$directory_iterator = new \DirectoryIterator( $directory );
foreach ( $directory_iterator as $file ) {
if ( $file->isDot() ) {
continue;
}
if ( $file->isDir() ) {
$return['directories'][] = $file->getPathname();
continue;
}
if ( 'php' !== $file->getExtension() ) {
continue;
}
if ( $exclude_underscore ) {
if ( 0 === strpos( $file->getBasename(), '_' ) ) {
continue;
}
}
$return['files'][] = $file->getPathname();
}
return $return;
} | php | public static function get_include_files( $directory, $exclude_underscore = false ) {
$return = [
'files' => [],
'directories' => [],
];
if ( ! is_dir( $directory ) ) {
return $return;
}
$directory_iterator = new \DirectoryIterator( $directory );
foreach ( $directory_iterator as $file ) {
if ( $file->isDot() ) {
continue;
}
if ( $file->isDir() ) {
$return['directories'][] = $file->getPathname();
continue;
}
if ( 'php' !== $file->getExtension() ) {
continue;
}
if ( $exclude_underscore ) {
if ( 0 === strpos( $file->getBasename(), '_' ) ) {
continue;
}
}
$return['files'][] = $file->getPathname();
}
return $return;
} | [
"public",
"static",
"function",
"get_include_files",
"(",
"$",
"directory",
",",
"$",
"exclude_underscore",
"=",
"false",
")",
"{",
"$",
"return",
"=",
"[",
"'files'",
"=>",
"[",
"]",
",",
"'directories'",
"=>",
"[",
"]",
",",
"]",
";",
"if",
"(",
"!",... | Return included files and directories
@SuppressWarnings(PHPMD.BooleanArgumentFlag)
@param string $directory
@param boolean $exclude_underscore
@return void | [
"Return",
"included",
"files",
"and",
"directories"
] | d192a01f4a730e53bced3dfcd0ef29fbecc80330 | https://github.com/inc2734/mimizuku-core/blob/d192a01f4a730e53bced3dfcd0ef29fbecc80330/src/App/Contract/Helper/Template.php#L20-L56 | train |
inc2734/mimizuku-core | src/App/Contract/Helper/Template.php | Template.get_template_parts | public static function get_template_parts( $directory, $exclude_underscore = false ) {
if ( ! is_dir( $directory ) ) {
return;
}
$files = static::get_include_files( $directory, $exclude_underscore );
foreach ( $files['files'] as $file ) {
$file = realpath( $file );
$template_name = str_replace( [ trailingslashit( realpath( get_template_directory() ) ), '.php' ], '', $file );
\get_template_part( $template_name );
}
foreach ( $files['directories'] as $directory ) {
static::get_template_parts( $directory, $exclude_underscore );
}
} | php | public static function get_template_parts( $directory, $exclude_underscore = false ) {
if ( ! is_dir( $directory ) ) {
return;
}
$files = static::get_include_files( $directory, $exclude_underscore );
foreach ( $files['files'] as $file ) {
$file = realpath( $file );
$template_name = str_replace( [ trailingslashit( realpath( get_template_directory() ) ), '.php' ], '', $file );
\get_template_part( $template_name );
}
foreach ( $files['directories'] as $directory ) {
static::get_template_parts( $directory, $exclude_underscore );
}
} | [
"public",
"static",
"function",
"get_template_parts",
"(",
"$",
"directory",
",",
"$",
"exclude_underscore",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"directory",
")",
")",
"{",
"return",
";",
"}",
"$",
"files",
"=",
"static",
"::",
... | get_template_part php files
@SuppressWarnings(PHPMD.BooleanArgumentFlag)
@param string $directory
@param boolean $exclude_underscore
@return void | [
"get_template_part",
"php",
"files"
] | d192a01f4a730e53bced3dfcd0ef29fbecc80330 | https://github.com/inc2734/mimizuku-core/blob/d192a01f4a730e53bced3dfcd0ef29fbecc80330/src/App/Contract/Helper/Template.php#L66-L82 | train |
inc2734/mimizuku-core | src/App/Contract/Helper/Template.php | Template.glob_recursive | public static function glob_recursive( $path ) {
$files = [];
if ( preg_match( '/\\' . DIRECTORY_SEPARATOR . 'vendor$/', $path ) ) {
return $files;
}
foreach ( glob( $path . '/*' ) as $file ) {
if ( is_dir( $file ) ) {
$files = array_merge( $files, static::glob_recursive( $file ) );
} elseif ( preg_match( '/\.php$/', $file ) ) {
$files[] = $file;
}
}
return $files;
} | php | public static function glob_recursive( $path ) {
$files = [];
if ( preg_match( '/\\' . DIRECTORY_SEPARATOR . 'vendor$/', $path ) ) {
return $files;
}
foreach ( glob( $path . '/*' ) as $file ) {
if ( is_dir( $file ) ) {
$files = array_merge( $files, static::glob_recursive( $file ) );
} elseif ( preg_match( '/\.php$/', $file ) ) {
$files[] = $file;
}
}
return $files;
} | [
"public",
"static",
"function",
"glob_recursive",
"(",
"$",
"path",
")",
"{",
"$",
"files",
"=",
"[",
"]",
";",
"if",
"(",
"preg_match",
"(",
"'/\\\\'",
".",
"DIRECTORY_SEPARATOR",
".",
"'vendor$/'",
",",
"$",
"path",
")",
")",
"{",
"return",
"$",
"fil... | Returns PHP file list
@param string Directory path
@return array PHP file list | [
"Returns",
"PHP",
"file",
"list"
] | d192a01f4a730e53bced3dfcd0ef29fbecc80330 | https://github.com/inc2734/mimizuku-core/blob/d192a01f4a730e53bced3dfcd0ef29fbecc80330/src/App/Contract/Helper/Template.php#L90-L105 | train |
jetwaves/laravel-util | src/CommonUtil.php | CommonUtil.getValidatorErrorMessage | public static function getValidatorErrorMessage($validator)
{
$messages = $validator->errors();
$msgArr = $messages->all();
$arr = [];
foreach ($msgArr as $k => $v) {
$arr[] = $v;
}
$ret = implode(",", $arr);
return $ret;
} | php | public static function getValidatorErrorMessage($validator)
{
$messages = $validator->errors();
$msgArr = $messages->all();
$arr = [];
foreach ($msgArr as $k => $v) {
$arr[] = $v;
}
$ret = implode(",", $arr);
return $ret;
} | [
"public",
"static",
"function",
"getValidatorErrorMessage",
"(",
"$",
"validator",
")",
"{",
"$",
"messages",
"=",
"$",
"validator",
"->",
"errors",
"(",
")",
";",
"$",
"msgArr",
"=",
"$",
"messages",
"->",
"all",
"(",
")",
";",
"$",
"arr",
"=",
"[",
... | make Validator Error Message Readable | [
"make",
"Validator",
"Error",
"Message",
"Readable"
] | 451592008fae5ca9519e8f2176ec9c873e16aa63 | https://github.com/jetwaves/laravel-util/blob/451592008fae5ca9519e8f2176ec9c873e16aa63/src/CommonUtil.php#L13-L23 | train |
jetwaves/laravel-util | src/CommonUtil.php | CommonUtil.randStr | public static function randStr($len = 6, $format = 'ALL')
{
switch (strtoupper($format)) {
case 'ALL':
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
break;
case 'CHAR':
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~';
break;
case 'NUMBER':
$chars = '0123456789';
break;
default :
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
break;
}
mt_srand((double)microtime() * 1000000 * getmypid());
$randStr = "";
while (strlen($randStr) < $len)
$randStr .= substr($chars, (mt_rand() % strlen($chars)), 1);
return $randStr;
} | php | public static function randStr($len = 6, $format = 'ALL')
{
switch (strtoupper($format)) {
case 'ALL':
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
break;
case 'CHAR':
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~';
break;
case 'NUMBER':
$chars = '0123456789';
break;
default :
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
break;
}
mt_srand((double)microtime() * 1000000 * getmypid());
$randStr = "";
while (strlen($randStr) < $len)
$randStr .= substr($chars, (mt_rand() % strlen($chars)), 1);
return $randStr;
} | [
"public",
"static",
"function",
"randStr",
"(",
"$",
"len",
"=",
"6",
",",
"$",
"format",
"=",
"'ALL'",
")",
"{",
"switch",
"(",
"strtoupper",
"(",
"$",
"format",
")",
")",
"{",
"case",
"'ALL'",
":",
"$",
"chars",
"=",
"'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg... | generate random string of 6 digits
@param int $len
@param string $format
@return string | [
"generate",
"random",
"string",
"of",
"6",
"digits"
] | 451592008fae5ca9519e8f2176ec9c873e16aa63 | https://github.com/jetwaves/laravel-util/blob/451592008fae5ca9519e8f2176ec9c873e16aa63/src/CommonUtil.php#L33-L54 | train |
fxpio/fxp-form-extensions | Form/ChoiceList/Formatter/FormatterUtil.php | FormatterUtil.formatResultData | public static function formatResultData(AjaxChoiceListFormatterInterface $formatter, ChoiceListView $choiceListView)
{
$result = [];
foreach ($choiceListView->choices as $i => $choiceView) {
if ($choiceView instanceof ChoiceGroupView) {
$group = $formatter->formatGroupChoice($choiceView);
foreach ($choiceView->choices as $j => $subChoiceView) {
$group = $formatter->addChoiceInGroup($group, $subChoiceView);
}
if (!$formatter->isEmptyGroup($group)) {
$result[] = $group;
}
} else {
$result[] = $formatter->formatChoice($choiceView);
}
}
return $result;
} | php | public static function formatResultData(AjaxChoiceListFormatterInterface $formatter, ChoiceListView $choiceListView)
{
$result = [];
foreach ($choiceListView->choices as $i => $choiceView) {
if ($choiceView instanceof ChoiceGroupView) {
$group = $formatter->formatGroupChoice($choiceView);
foreach ($choiceView->choices as $j => $subChoiceView) {
$group = $formatter->addChoiceInGroup($group, $subChoiceView);
}
if (!$formatter->isEmptyGroup($group)) {
$result[] = $group;
}
} else {
$result[] = $formatter->formatChoice($choiceView);
}
}
return $result;
} | [
"public",
"static",
"function",
"formatResultData",
"(",
"AjaxChoiceListFormatterInterface",
"$",
"formatter",
",",
"ChoiceListView",
"$",
"choiceListView",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"choiceListView",
"->",
"choices",
"as",
... | Format the result data.
@param AjaxChoiceListFormatterInterface $formatter The ajax formatter
@param ChoiceListView $choiceListView The choice list view
@return array The formatted result data | [
"Format",
"the",
"result",
"data",
"."
] | ef09edf557b109187d38248b0976df31e5583b5b | https://github.com/fxpio/fxp-form-extensions/blob/ef09edf557b109187d38248b0976df31e5583b5b/Form/ChoiceList/Formatter/FormatterUtil.php#L30-L51 | train |
luismanuelamengual/NeoPHP | src/NeoPHP/Database/ConnectionTable.php | ConnectionTable.pluck | public function pluck($field, $indexField=null) {
$fieldsFormat = $field;
$usingFormatting = preg_match_all('/{(\w+\.\w+|\w+)}/', $field, $matches);
//Obtención del campo/s de la consulta
$fields = [];
if ($usingFormatting) {
$fields = $matches[1];
foreach ($fields as $formatField) {
if (($pos = strpos($formatField, '.')) !== false) {
$replaceFormatField = substr($formatField, $pos + 1);
$fieldsFormat = str_replace($formatField, $replaceFormatField, $fieldsFormat);
}
}
}
else {
$fields = [$field];
}
//Establecer los campos del select
$selectFields = $fields;
if ($indexField != null && !in_array($indexField, $selectFields)) {
$selectFields[] = $indexField;
}
$this->selectFields($selectFields);
//Obtención del campo de indice
$returnIndexField = $indexField;
if (!empty($returnIndexField)) {
if (($pos = strpos($returnIndexField, '.')) !== false) {
$returnIndexField = substr($returnIndexField, $pos + 1);
}
}
//Obtención de los campos de retorno
$returnFields = [];
foreach ($fields as $returnField) {
if (($pos = strpos($returnField, '.')) !== false) {
$returnField = substr($returnField, $pos + 1);
}
$returnFields[] = $returnField;
}
//Creación del array de resultados
$fieldResults = [];
$results = $this->find();
foreach ($results as $result) {
$value = null;
if (!$usingFormatting) {
$value = $result->{$returnFields[0]};
}
else {
$value = $fieldsFormat;
foreach ($returnFields as $returnField) {
$value = str_replace("{" . $returnField . "}", $result->$returnField, $value);
}
}
if ($returnIndexField != null) {
$fieldResults[$result->$returnIndexField] = $value;
}
else {
$fieldResults[] = $value;
}
}
return $fieldResults;
} | php | public function pluck($field, $indexField=null) {
$fieldsFormat = $field;
$usingFormatting = preg_match_all('/{(\w+\.\w+|\w+)}/', $field, $matches);
//Obtención del campo/s de la consulta
$fields = [];
if ($usingFormatting) {
$fields = $matches[1];
foreach ($fields as $formatField) {
if (($pos = strpos($formatField, '.')) !== false) {
$replaceFormatField = substr($formatField, $pos + 1);
$fieldsFormat = str_replace($formatField, $replaceFormatField, $fieldsFormat);
}
}
}
else {
$fields = [$field];
}
//Establecer los campos del select
$selectFields = $fields;
if ($indexField != null && !in_array($indexField, $selectFields)) {
$selectFields[] = $indexField;
}
$this->selectFields($selectFields);
//Obtención del campo de indice
$returnIndexField = $indexField;
if (!empty($returnIndexField)) {
if (($pos = strpos($returnIndexField, '.')) !== false) {
$returnIndexField = substr($returnIndexField, $pos + 1);
}
}
//Obtención de los campos de retorno
$returnFields = [];
foreach ($fields as $returnField) {
if (($pos = strpos($returnField, '.')) !== false) {
$returnField = substr($returnField, $pos + 1);
}
$returnFields[] = $returnField;
}
//Creación del array de resultados
$fieldResults = [];
$results = $this->find();
foreach ($results as $result) {
$value = null;
if (!$usingFormatting) {
$value = $result->{$returnFields[0]};
}
else {
$value = $fieldsFormat;
foreach ($returnFields as $returnField) {
$value = str_replace("{" . $returnField . "}", $result->$returnField, $value);
}
}
if ($returnIndexField != null) {
$fieldResults[$result->$returnIndexField] = $value;
}
else {
$fieldResults[] = $value;
}
}
return $fieldResults;
} | [
"public",
"function",
"pluck",
"(",
"$",
"field",
",",
"$",
"indexField",
"=",
"null",
")",
"{",
"$",
"fieldsFormat",
"=",
"$",
"field",
";",
"$",
"usingFormatting",
"=",
"preg_match_all",
"(",
"'/{(\\w+\\.\\w+|\\w+)}/'",
",",
"$",
"field",
",",
"$",
"matc... | Obtiene una columna de los resultados en un array
@param string $field campo a mostrar en un array
@param string $indexField campo a utilizar como indice
@return array resultado | [
"Obtiene",
"una",
"columna",
"de",
"los",
"resultados",
"en",
"un",
"array"
] | da7c5831974b37dd4b0b170d9aa64e61404d819b | https://github.com/luismanuelamengual/NeoPHP/blob/da7c5831974b37dd4b0b170d9aa64e61404d819b/src/NeoPHP/Database/ConnectionTable.php#L53-L120 | train |
luismanuelamengual/NeoPHP | src/NeoPHP/Database/ConnectionTable.php | ConnectionTable.insert | public function insert(array $fields = []) {
$query = new InsertQuery($this->getTable());
$query->fields(!empty($fields)? $fields : $this->getFields());
return $this->connection->exec($query);
} | php | public function insert(array $fields = []) {
$query = new InsertQuery($this->getTable());
$query->fields(!empty($fields)? $fields : $this->getFields());
return $this->connection->exec($query);
} | [
"public",
"function",
"insert",
"(",
"array",
"$",
"fields",
"=",
"[",
"]",
")",
"{",
"$",
"query",
"=",
"new",
"InsertQuery",
"(",
"$",
"this",
"->",
"getTable",
"(",
")",
")",
";",
"$",
"query",
"->",
"fields",
"(",
"!",
"empty",
"(",
"$",
"fie... | Inserta un nuevo registro
@param array $fields
@return mixed | [
"Inserta",
"un",
"nuevo",
"registro"
] | da7c5831974b37dd4b0b170d9aa64e61404d819b | https://github.com/luismanuelamengual/NeoPHP/blob/da7c5831974b37dd4b0b170d9aa64e61404d819b/src/NeoPHP/Database/ConnectionTable.php#L204-L208 | train |
luismanuelamengual/NeoPHP | src/NeoPHP/Database/ConnectionTable.php | ConnectionTable.update | public function update(array $fields = []) {
$query = new UpdateQuery($this->getTable());
$query->fields(!empty($fields)? $fields : $this->getFields());
$query->whereConditionGroup($this->getWhereConditionGroup());
return $this->connection->exec($query);
} | php | public function update(array $fields = []) {
$query = new UpdateQuery($this->getTable());
$query->fields(!empty($fields)? $fields : $this->getFields());
$query->whereConditionGroup($this->getWhereConditionGroup());
return $this->connection->exec($query);
} | [
"public",
"function",
"update",
"(",
"array",
"$",
"fields",
"=",
"[",
"]",
")",
"{",
"$",
"query",
"=",
"new",
"UpdateQuery",
"(",
"$",
"this",
"->",
"getTable",
"(",
")",
")",
";",
"$",
"query",
"->",
"fields",
"(",
"!",
"empty",
"(",
"$",
"fie... | Actualiza un registro
@param array $fields
@return mixed | [
"Actualiza",
"un",
"registro"
] | da7c5831974b37dd4b0b170d9aa64e61404d819b | https://github.com/luismanuelamengual/NeoPHP/blob/da7c5831974b37dd4b0b170d9aa64e61404d819b/src/NeoPHP/Database/ConnectionTable.php#L215-L220 | train |
luismanuelamengual/NeoPHP | src/NeoPHP/Database/ConnectionTable.php | ConnectionTable.delete | public function delete() {
$query = new DeleteQuery($this->getTable());
$query->whereConditionGroup($this->getWhereConditionGroup());
return $this->connection->exec($query);
} | php | public function delete() {
$query = new DeleteQuery($this->getTable());
$query->whereConditionGroup($this->getWhereConditionGroup());
return $this->connection->exec($query);
} | [
"public",
"function",
"delete",
"(",
")",
"{",
"$",
"query",
"=",
"new",
"DeleteQuery",
"(",
"$",
"this",
"->",
"getTable",
"(",
")",
")",
";",
"$",
"query",
"->",
"whereConditionGroup",
"(",
"$",
"this",
"->",
"getWhereConditionGroup",
"(",
")",
")",
... | Borra un registro
@return mixed | [
"Borra",
"un",
"registro"
] | da7c5831974b37dd4b0b170d9aa64e61404d819b | https://github.com/luismanuelamengual/NeoPHP/blob/da7c5831974b37dd4b0b170d9aa64e61404d819b/src/NeoPHP/Database/ConnectionTable.php#L226-L230 | train |
Torann/localization-helpers | src/Commands/AbstractCommand.php | AbstractCommand.getPhpFiles | protected function getPhpFiles($path)
{
if (is_dir($path)) {
return new RegexIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
),
'/^.+\.php$/i',
RecursiveRegexIterator::GET_MATCH
);
}
else {
return [];
}
} | php | protected function getPhpFiles($path)
{
if (is_dir($path)) {
return new RegexIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
),
'/^.+\.php$/i',
RecursiveRegexIterator::GET_MATCH
);
}
else {
return [];
}
} | [
"protected",
"function",
"getPhpFiles",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"is_dir",
"(",
"$",
"path",
")",
")",
"{",
"return",
"new",
"RegexIterator",
"(",
"new",
"RecursiveIteratorIterator",
"(",
"new",
"RecursiveDirectoryIterator",
"(",
"$",
"path",
"... | return an iterator of php files in the provided paths and subpaths
@param string $path a source path
@return array a list of php file paths | [
"return",
"an",
"iterator",
"of",
"php",
"files",
"in",
"the",
"provided",
"paths",
"and",
"subpaths"
] | cf307ad328a6b5f7c54bce5d0d3867d4d623505f | https://github.com/Torann/localization-helpers/blob/cf307ad328a6b5f7c54bce5d0d3867d4d623505f/src/Commands/AbstractCommand.php#L188-L204 | train |
Torann/localization-helpers | src/Commands/AbstractCommand.php | AbstractCommand.dumpLangArray | protected function dumpLangArray($source, $code = '')
{
// Use array short syntax
if ($this->config('array_shorthand', true) === false) {
return $source;
}
// Split given source into PHP tokens
$tokens = token_get_all($source);
$brackets = [];
for ($i = 0; $i < count($tokens); $i++) {
$token = $tokens[$i];
if ($token === '(') {
$brackets[] = false;
}
elseif ($token === ')') {
$token = array_pop($brackets) ? ']' : ')';
}
elseif (is_array($token) && $token[0] === T_ARRAY) {
$a = $i + 1;
if (isset($tokens[$a]) && $tokens[$a][0] === T_WHITESPACE) {
$a++;
}
if (isset($tokens[$a]) && $tokens[$a] === '(') {
$i = $a;
$brackets[] = true;
$token = '[';
}
}
$code .= is_array($token) ? $token[1] : $token;
}
// Fix indenting
$code = preg_replace('/^ |\G /m', ' ', $code);
// Fix weird new line breaks at the beginning of arrays
$code = preg_replace('/=\>\s\n\s{4,}\[/m', '=> [', $code);
return $code;
} | php | protected function dumpLangArray($source, $code = '')
{
// Use array short syntax
if ($this->config('array_shorthand', true) === false) {
return $source;
}
// Split given source into PHP tokens
$tokens = token_get_all($source);
$brackets = [];
for ($i = 0; $i < count($tokens); $i++) {
$token = $tokens[$i];
if ($token === '(') {
$brackets[] = false;
}
elseif ($token === ')') {
$token = array_pop($brackets) ? ']' : ')';
}
elseif (is_array($token) && $token[0] === T_ARRAY) {
$a = $i + 1;
if (isset($tokens[$a]) && $tokens[$a][0] === T_WHITESPACE) {
$a++;
}
if (isset($tokens[$a]) && $tokens[$a] === '(') {
$i = $a;
$brackets[] = true;
$token = '[';
}
}
$code .= is_array($token) ? $token[1] : $token;
}
// Fix indenting
$code = preg_replace('/^ |\G /m', ' ', $code);
// Fix weird new line breaks at the beginning of arrays
$code = preg_replace('/=\>\s\n\s{4,}\[/m', '=> [', $code);
return $code;
} | [
"protected",
"function",
"dumpLangArray",
"(",
"$",
"source",
",",
"$",
"code",
"=",
"''",
")",
"{",
"// Use array short syntax",
"if",
"(",
"$",
"this",
"->",
"config",
"(",
"'array_shorthand'",
",",
"true",
")",
"===",
"false",
")",
"{",
"return",
"$",
... | Convert the arrays to the shorthand syntax.
@param string $source
@param string $code
@return string | [
"Convert",
"the",
"arrays",
"to",
"the",
"shorthand",
"syntax",
"."
] | cf307ad328a6b5f7c54bce5d0d3867d4d623505f | https://github.com/Torann/localization-helpers/blob/cf307ad328a6b5f7c54bce5d0d3867d4d623505f/src/Commands/AbstractCommand.php#L274-L317 | train |
spiral/odm | source/Spiral/ODM/MongoManager.php | MongoManager.addDatabase | public function addDatabase(string $name, MongoDatabase $database): MongoManager
{
if (isset($this->databases[$name])) {
throw new ODMException("Database '{$name}' already exists");
}
$this->databases[$name] = $database;
return $this;
} | php | public function addDatabase(string $name, MongoDatabase $database): MongoManager
{
if (isset($this->databases[$name])) {
throw new ODMException("Database '{$name}' already exists");
}
$this->databases[$name] = $database;
return $this;
} | [
"public",
"function",
"addDatabase",
"(",
"string",
"$",
"name",
",",
"MongoDatabase",
"$",
"database",
")",
":",
"MongoManager",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"databases",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"ODMEx... | Add new database in a database pull, database name will be automatically selected from given
instance.
@param string $name Internal database name.
@param MongoDatabase $database
@return self|$this
@throws ODMException | [
"Add",
"new",
"database",
"in",
"a",
"database",
"pull",
"database",
"name",
"will",
"be",
"automatically",
"selected",
"from",
"given",
"instance",
"."
] | 06087691a05dcfaa86c6c461660c6029db4de06e | https://github.com/spiral/odm/blob/06087691a05dcfaa86c6c461660c6029db4de06e/source/Spiral/ODM/MongoManager.php#L60-L69 | train |
spiral/odm | source/Spiral/ODM/MongoManager.php | MongoManager.database | public function database(string $database = null): MongoDatabase
{
if (empty($database)) {
$database = $this->config->defaultDatabase();
}
//Spiral support ability to link multiple virtual databases together using aliases
$database = $this->config->resolveAlias($database);
if (isset($this->databases[$database])) {
return $this->databases[$database];
}
if (!$this->config->hasDatabase($database)) {
throw new ODMException(
"Unable to initiate MongoDatabase, no presets for '{$database}' found"
);
}
$options = $this->config->databaseOptions($database);
//Initiating database instance
return $this->createDatabase(
$database,
$options['server'],
$options['database'],
$options['driverOptions'] ?? [],
$options['options'] ?? []
);
} | php | public function database(string $database = null): MongoDatabase
{
if (empty($database)) {
$database = $this->config->defaultDatabase();
}
//Spiral support ability to link multiple virtual databases together using aliases
$database = $this->config->resolveAlias($database);
if (isset($this->databases[$database])) {
return $this->databases[$database];
}
if (!$this->config->hasDatabase($database)) {
throw new ODMException(
"Unable to initiate MongoDatabase, no presets for '{$database}' found"
);
}
$options = $this->config->databaseOptions($database);
//Initiating database instance
return $this->createDatabase(
$database,
$options['server'],
$options['database'],
$options['driverOptions'] ?? [],
$options['options'] ?? []
);
} | [
"public",
"function",
"database",
"(",
"string",
"$",
"database",
"=",
"null",
")",
":",
"MongoDatabase",
"{",
"if",
"(",
"empty",
"(",
"$",
"database",
")",
")",
"{",
"$",
"database",
"=",
"$",
"this",
"->",
"config",
"->",
"defaultDatabase",
"(",
")"... | Create specified or select default instance of MongoDatabase.
@param string $database Database name (internal).
@return MongoDatabase
@throws ODMException | [
"Create",
"specified",
"or",
"select",
"default",
"instance",
"of",
"MongoDatabase",
"."
] | 06087691a05dcfaa86c6c461660c6029db4de06e | https://github.com/spiral/odm/blob/06087691a05dcfaa86c6c461660c6029db4de06e/source/Spiral/ODM/MongoManager.php#L111-L140 | train |
spiral/odm | source/Spiral/ODM/MongoManager.php | MongoManager.getDatabases | public function getDatabases(): array
{
$result = [];
//Include manually added databases
foreach ($this->config->databaseNames() as $name) {
$result[] = $this->database($name);
}
return $result;
} | php | public function getDatabases(): array
{
$result = [];
//Include manually added databases
foreach ($this->config->databaseNames() as $name) {
$result[] = $this->database($name);
}
return $result;
} | [
"public",
"function",
"getDatabases",
"(",
")",
":",
"array",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"//Include manually added databases",
"foreach",
"(",
"$",
"this",
"->",
"config",
"->",
"databaseNames",
"(",
")",
"as",
"$",
"name",
")",
"{",
"$",
"r... | Get every know database.
@return MongoDatabase[] | [
"Get",
"every",
"know",
"database",
"."
] | 06087691a05dcfaa86c6c461660c6029db4de06e | https://github.com/spiral/odm/blob/06087691a05dcfaa86c6c461660c6029db4de06e/source/Spiral/ODM/MongoManager.php#L147-L157 | train |
krystal-framework/krystal.framework | src/Krystal/Security/Crypter.php | Crypter.encryptValue | public function encryptValue($value)
{
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$text = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->salt, $value, MCRYPT_MODE_ECB, $iv);
return trim(base64_encode($text));
} | php | public function encryptValue($value)
{
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$text = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->salt, $value, MCRYPT_MODE_ECB, $iv);
return trim(base64_encode($text));
} | [
"public",
"function",
"encryptValue",
"(",
"$",
"value",
")",
"{",
"$",
"iv_size",
"=",
"mcrypt_get_iv_size",
"(",
"MCRYPT_RIJNDAEL_256",
",",
"MCRYPT_MODE_ECB",
")",
";",
"$",
"iv",
"=",
"mcrypt_create_iv",
"(",
"$",
"iv_size",
",",
"MCRYPT_RAND",
")",
";",
... | Encrypts a value
@param string $value
@return string | [
"Encrypts",
"a",
"value"
] | a5ff72384f3efbe74f390538793feb7d522b9c39 | https://github.com/krystal-framework/krystal.framework/blob/a5ff72384f3efbe74f390538793feb7d522b9c39/src/Krystal/Security/Crypter.php#L68-L75 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.