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
hail-framework/framework
src/Image/Imagick/Color.php
Color.getInt
public function getInt() { $r = $this->getRedValue(); $g = $this->getGreenValue(); $b = $this->getBlueValue(); $a = (int) round($this->getAlphaValue() * 255); return (int) (($a << 24) + ($r << 16) + ($g << 8) + $b); }
php
public function getInt() { $r = $this->getRedValue(); $g = $this->getGreenValue(); $b = $this->getBlueValue(); $a = (int) round($this->getAlphaValue() * 255); return (int) (($a << 24) + ($r << 16) + ($g << 8) + $b); }
[ "public", "function", "getInt", "(", ")", "{", "$", "r", "=", "$", "this", "->", "getRedValue", "(", ")", ";", "$", "g", "=", "$", "this", "->", "getGreenValue", "(", ")", ";", "$", "b", "=", "$", "this", "->", "getBlueValue", "(", ")", ";", "$...
Calculates integer value of current color instance @return int
[ "Calculates", "integer", "value", "of", "current", "color", "instance" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Image/Imagick/Color.php#L128-L136
train
hail-framework/framework
src/Image/Imagick/Color.php
Color.setPixel
private function setPixel($r, $g, $b, $a = null) { $a = $a ?? 1; return $this->pixel = new \ImagickPixel( sprintf('rgba(%d, %d, %d, %.2F)', $r, $g, $b, $a) ); }
php
private function setPixel($r, $g, $b, $a = null) { $a = $a ?? 1; return $this->pixel = new \ImagickPixel( sprintf('rgba(%d, %d, %d, %.2F)', $r, $g, $b, $a) ); }
[ "private", "function", "setPixel", "(", "$", "r", ",", "$", "g", ",", "$", "b", ",", "$", "a", "=", "null", ")", "{", "$", "a", "=", "$", "a", "??", "1", ";", "return", "$", "this", "->", "pixel", "=", "new", "\\", "ImagickPixel", "(", "sprin...
Initiates ImagickPixel from given RGBA values @param int $r ; @param int $g @param int $b @param int $a @return \ImagickPixel
[ "Initiates", "ImagickPixel", "from", "given", "RGBA", "values" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Image/Imagick/Color.php#L262-L269
train
hail-framework/framework
src/Http/Message/Uri.php
Uri.filterUserInfo
private function filterUserInfo(string $part): string { // Note the addition of `%` to initial charset; this allows `|` portion // to match and thus prevent double-encoding. return \preg_replace_callback( '/(?:[^%' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . ']+|%(?![A-Fa-f0-9]{2}))/u', [$this, 'urlEncodeChar'], $part ); }
php
private function filterUserInfo(string $part): string { // Note the addition of `%` to initial charset; this allows `|` portion // to match and thus prevent double-encoding. return \preg_replace_callback( '/(?:[^%' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . ']+|%(?![A-Fa-f0-9]{2}))/u', [$this, 'urlEncodeChar'], $part ); }
[ "private", "function", "filterUserInfo", "(", "string", "$", "part", ")", ":", "string", "{", "// Note the addition of `%` to initial charset; this allows `|` portion", "// to match and thus prevent double-encoding.", "return", "\\", "preg_replace_callback", "(", "'/(?:[^%'", "."...
Filters a part of user info in a URI to ensure it is properly encoded. @param string $part @return string
[ "Filters", "a", "part", "of", "user", "info", "in", "a", "URI", "to", "ensure", "it", "is", "properly", "encoded", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Message/Uri.php#L350-L359
train
hail-framework/framework
src/Http/Message/Uri.php
Uri.fromArray
public static function fromArray(array $server) { $uri = new self(''); if (isset($server['HTTPS'])) { $uri->scheme = $server['HTTPS'] === 'on' ? 'https' : 'http'; } [$host, $port] = Helpers::getHostAndPortFromArray($server); $uri->host = \strtolower($host); $uri->port = $uri->filterPort($port); $path = Helpers::getRequestUri($server); $fragment = ''; if (\strpos($path, '#') !== false) { [$path, $fragment] = \explode('#', $path, 2); } $uri->path = $uri->filterPath(\explode('?', $path, 2)[0]); $uri->fragment = $uri->filterFragment($fragment); if (isset($server['QUERY_STRING'])) { $uri->query = $uri->filterQuery($server['QUERY_STRING']); } return $uri; }
php
public static function fromArray(array $server) { $uri = new self(''); if (isset($server['HTTPS'])) { $uri->scheme = $server['HTTPS'] === 'on' ? 'https' : 'http'; } [$host, $port] = Helpers::getHostAndPortFromArray($server); $uri->host = \strtolower($host); $uri->port = $uri->filterPort($port); $path = Helpers::getRequestUri($server); $fragment = ''; if (\strpos($path, '#') !== false) { [$path, $fragment] = \explode('#', $path, 2); } $uri->path = $uri->filterPath(\explode('?', $path, 2)[0]); $uri->fragment = $uri->filterFragment($fragment); if (isset($server['QUERY_STRING'])) { $uri->query = $uri->filterQuery($server['QUERY_STRING']); } return $uri; }
[ "public", "static", "function", "fromArray", "(", "array", "$", "server", ")", "{", "$", "uri", "=", "new", "self", "(", "''", ")", ";", "if", "(", "isset", "(", "$", "server", "[", "'HTTPS'", "]", ")", ")", "{", "$", "uri", "->", "scheme", "=", ...
Get a Uri populated with values from server variables. @param array $server Typically $_SERVER or similar structure. @return UriInterface @throws \InvalidArgumentException
[ "Get", "a", "Uri", "populated", "with", "values", "from", "server", "variables", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Message/Uri.php#L481-L509
train
hail-framework/framework
src/Filesystem/Adapter/Sftp.php
Sftp.setNetSftpConnection
public function setNetSftpConnection($connection, $sftp) { $this->connection = $connection; $this->sftp = $sftp; return $this; }
php
public function setNetSftpConnection($connection, $sftp) { $this->connection = $connection; $this->sftp = $sftp; return $this; }
[ "public", "function", "setNetSftpConnection", "(", "$", "connection", ",", "$", "sftp", ")", "{", "$", "this", "->", "connection", "=", "$", "connection", ";", "$", "this", "->", "sftp", "=", "$", "sftp", ";", "return", "$", "this", ";", "}" ]
Inject the SFTP instance. @param resource $connection @param resource $sftp @return $this
[ "Inject", "the", "SFTP", "instance", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Adapter/Sftp.php#L103-L109
train
hail-framework/framework
src/Image/Gd/Commands/BlurCommand.php
BlurCommand.execute
public function execute($image) { $amount = (int) $this->argument(0)->between(0, 100)->value(1); for ($i=0; $i < $amount; ++$i) { imagefilter($image->getCore(), IMG_FILTER_GAUSSIAN_BLUR); } return true; }
php
public function execute($image) { $amount = (int) $this->argument(0)->between(0, 100)->value(1); for ($i=0; $i < $amount; ++$i) { imagefilter($image->getCore(), IMG_FILTER_GAUSSIAN_BLUR); } return true; }
[ "public", "function", "execute", "(", "$", "image", ")", "{", "$", "amount", "=", "(", "int", ")", "$", "this", "->", "argument", "(", "0", ")", "->", "between", "(", "0", ",", "100", ")", "->", "value", "(", "1", ")", ";", "for", "(", "$", "...
Applies blur effect on image @param \Hail\Image\Image $image @return bool
[ "Applies", "blur", "effect", "on", "image" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Image/Gd/Commands/BlurCommand.php#L13-L22
train
systemson/collection
src/Set.php
Set.groupBy
public function groupBy(string $column): CollectionInterface { $return = []; foreach ($this->toArray() as $item) { if (isset($item[$column])) { $key = $item[$column]; $return[$key] = $item; } // Must throw exception if item column does not exists } return new Collection($return); }
php
public function groupBy(string $column): CollectionInterface { $return = []; foreach ($this->toArray() as $item) { if (isset($item[$column])) { $key = $item[$column]; $return[$key] = $item; } // Must throw exception if item column does not exists } return new Collection($return); }
[ "public", "function", "groupBy", "(", "string", "$", "column", ")", ":", "CollectionInterface", "{", "$", "return", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "toArray", "(", ")", "as", "$", "item", ")", "{", "if", "(", "isset", "(", "$...
Returns a new Collection grouped by the specified column. @todo MUST throw exception if the column does not exists @param string $column The column to group by. @return Collection A new collection instance.
[ "Returns", "a", "new", "Collection", "grouped", "by", "the", "specified", "column", "." ]
fb3ae1a78806aafabc0562db96822e8b99dc2a64
https://github.com/systemson/collection/blob/fb3ae1a78806aafabc0562db96822e8b99dc2a64/src/Set.php#L79-L92
train
hail-framework/framework
src/Console/Completion/ZshGenerator.php
ZshGenerator.command_args
public function command_args(CommandInterface $cmd, $cmdSignature) { $args = []; $arguments = $cmd->getArguments(); // for command that does not define an argument, we just complete the argument by file paths. if ($arguments === []) { return ['*:default:_files']; } $idx = 0; foreach ($arguments as $a) { $comp = ''; if ($a->multiple) { $comp .= '*:' . $a->name; } else { $comp .= ':' . $a->name; } if ($a->validValues || $a->suggestions) { if ($a->validValues) { if (is_callable($a->validValues)) { $comp .= ':{' . implode(' ', [ $this->meta_command_name(), Util::qq($a->name), $cmdSignature, 'arg', $idx, 'valid-values', ]) . '}'; } elseif ($values = $a->getValidValues()) { $comp .= ':(' . implode(' ', Util::array_qq($values)) . ')'; } } elseif ($a->suggestions) { if (is_callable($a->suggestions)) { $comp .= ':{' . implode(' ', [ $this->meta_command_name(), Util::qq($a->name), $cmdSignature, 'arg', $idx, 'suggestions', ]) . '}'; } elseif ($values = $a->getSuggestions()) { $comp .= ':(' . implode(' ', Util::array_qq($values)) . ')'; } } } elseif (in_array($a->isa, ['file', 'path', 'dir'], true)) { switch ($a->isa) { case 'file': $comp .= ':_files'; break; case 'path': $comp .= ':_path_files'; break; case 'dir': $comp .= ':_directories'; break; } if ($a->glob) { $comp .= " -g \"{$a->glob}\""; } } $args[] = Util::q($comp); $idx++; } return empty($args) ? null : $args; }
php
public function command_args(CommandInterface $cmd, $cmdSignature) { $args = []; $arguments = $cmd->getArguments(); // for command that does not define an argument, we just complete the argument by file paths. if ($arguments === []) { return ['*:default:_files']; } $idx = 0; foreach ($arguments as $a) { $comp = ''; if ($a->multiple) { $comp .= '*:' . $a->name; } else { $comp .= ':' . $a->name; } if ($a->validValues || $a->suggestions) { if ($a->validValues) { if (is_callable($a->validValues)) { $comp .= ':{' . implode(' ', [ $this->meta_command_name(), Util::qq($a->name), $cmdSignature, 'arg', $idx, 'valid-values', ]) . '}'; } elseif ($values = $a->getValidValues()) { $comp .= ':(' . implode(' ', Util::array_qq($values)) . ')'; } } elseif ($a->suggestions) { if (is_callable($a->suggestions)) { $comp .= ':{' . implode(' ', [ $this->meta_command_name(), Util::qq($a->name), $cmdSignature, 'arg', $idx, 'suggestions', ]) . '}'; } elseif ($values = $a->getSuggestions()) { $comp .= ':(' . implode(' ', Util::array_qq($values)) . ')'; } } } elseif (in_array($a->isa, ['file', 'path', 'dir'], true)) { switch ($a->isa) { case 'file': $comp .= ':_files'; break; case 'path': $comp .= ':_path_files'; break; case 'dir': $comp .= ':_directories'; break; } if ($a->glob) { $comp .= " -g \"{$a->glob}\""; } } $args[] = Util::q($comp); $idx++; } return empty($args) ? null : $args; }
[ "public", "function", "command_args", "(", "CommandInterface", "$", "cmd", ",", "$", "cmdSignature", ")", "{", "$", "args", "=", "[", "]", ";", "$", "arguments", "=", "$", "cmd", "->", "getArguments", "(", ")", ";", "// for command that does not define an argu...
Return args as a alternative "*:args:{ _alternative ':importpaths:__go_list' ':files:_path_files -g \"*.go\"' }"
[ "Return", "args", "as", "a", "alternative" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Completion/ZshGenerator.php#L200-L269
train
hail-framework/framework
src/Console/Completion/ZshGenerator.php
ZshGenerator.command_args_case
public function command_args_case(CommandInterface $cmd) { $buf = new Buffer; $buf->appendLine('case $state in'); foreach ($cmd->getArguments() as $a) { $buf->appendLine("({$a->name})"); if ($a->validValues || $a->suggestions) { $buf->appendLine('_values ' . $this->render_argument_completion_values($a) . ' && ret=0'); } elseif (in_array($a->isa, ['file', 'path', 'dir'], true)) { $buf->appendLine($this->render_argument_completion_handler($a) . ' && ret=0'); } $buf->appendLine(';;'); } $buf->appendLine('esac'); return $buf->__toString(); }
php
public function command_args_case(CommandInterface $cmd) { $buf = new Buffer; $buf->appendLine('case $state in'); foreach ($cmd->getArguments() as $a) { $buf->appendLine("({$a->name})"); if ($a->validValues || $a->suggestions) { $buf->appendLine('_values ' . $this->render_argument_completion_values($a) . ' && ret=0'); } elseif (in_array($a->isa, ['file', 'path', 'dir'], true)) { $buf->appendLine($this->render_argument_completion_handler($a) . ' && ret=0'); } $buf->appendLine(';;'); } $buf->appendLine('esac'); return $buf->__toString(); }
[ "public", "function", "command_args_case", "(", "CommandInterface", "$", "cmd", ")", "{", "$", "buf", "=", "new", "Buffer", ";", "$", "buf", "->", "appendLine", "(", "'case $state in'", ")", ";", "foreach", "(", "$", "cmd", "->", "getArguments", "(", ")", ...
complete argument cases
[ "complete", "argument", "cases" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Completion/ZshGenerator.php#L349-L367
train
hail-framework/framework
src/Console/Completion/ZshGenerator.php
ZshGenerator.commandFlags
public function commandFlags(CommandInterface $cmd, $cmdSignature) { $args = []; $specs = $cmd->getOptionCollection(); /* '(- 1 *)--version[display version and copyright information]' \ '(- 1 *)--help[print a short help statement]' \ */ foreach ($specs->options as $opt) { $args[] = $this->optionFlagItem($opt, $cmdSignature); } return empty($args) ? null : $args; }
php
public function commandFlags(CommandInterface $cmd, $cmdSignature) { $args = []; $specs = $cmd->getOptionCollection(); /* '(- 1 *)--version[display version and copyright information]' \ '(- 1 *)--help[print a short help statement]' \ */ foreach ($specs->options as $opt) { $args[] = $this->optionFlagItem($opt, $cmdSignature); } return empty($args) ? null : $args; }
[ "public", "function", "commandFlags", "(", "CommandInterface", "$", "cmd", ",", "$", "cmdSignature", ")", "{", "$", "args", "=", "[", "]", ";", "$", "specs", "=", "$", "cmd", "->", "getOptionCollection", "(", ")", ";", "/*\n '(- 1 *)--version[display ve...
Return the zsh array code of the flags of a command. @return string[]
[ "Return", "the", "zsh", "array", "code", "of", "the", "flags", "of", "a", "command", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Completion/ZshGenerator.php#L374-L387
train
hail-framework/framework
src/Console/Completion/ZshGenerator.php
ZshGenerator.commandSubcommandStates
public function commandSubcommandStates(CommandInterface $cmd) { $args = []; $cmds = $this->visibleCommands($cmd->getCommands()); foreach ($cmds as $c) { $args[] = sprintf("'%s:->%s'", $c->name(), $c->name()); // generate argument states } return $args; }
php
public function commandSubcommandStates(CommandInterface $cmd) { $args = []; $cmds = $this->visibleCommands($cmd->getCommands()); foreach ($cmds as $c) { $args[] = sprintf("'%s:->%s'", $c->name(), $c->name()); // generate argument states } return $args; }
[ "public", "function", "commandSubcommandStates", "(", "CommandInterface", "$", "cmd", ")", "{", "$", "args", "=", "[", "]", ";", "$", "cmds", "=", "$", "this", "->", "visibleCommands", "(", "$", "cmd", "->", "getCommands", "(", ")", ")", ";", "foreach", ...
Return subcommand completion status as an array of string @param Command $cmd The command object @return string[]
[ "Return", "subcommand", "completion", "status", "as", "an", "array", "of", "string" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Completion/ZshGenerator.php#L397-L406
train
hail-framework/framework
src/Console/Completion/ZshGenerator.php
ZshGenerator.commandmetaCallbackFunction
public function commandmetaCallbackFunction(CommandInterface $cmd) { $cmdSignature = $cmd->getSignature(); $buf = new Buffer; $buf->indent(); $buf->appendLine("local curcontext=\$curcontext state line ret=1"); $buf->appendLine("declare -A opt_args"); $buf->appendLine("declare -A values"); $buf->appendLine("local ret=1"); /* values=$(example/demo meta commit arg 1 valid-values) _values "description" ${=values} && ret=0 return ret */ $buf->appendLine("local desc=\$1"); $buf->appendLine("local valtype=\$3"); $buf->appendLine("local pos=\$4"); $buf->appendLine("local completion=\$5"); $metaCommand = [$this->programName, 'meta', $cmdSignature, '$valtype', '$pos', '$completion']; $buf->appendLine('$(' . implode(" ", $metaCommand) . ')'); $buf->appendLine('_values $desc ${=values} && ret=0'); // expand value array as arguments $buf->appendLine('return ret'); $funcName = $this->commandFunctionName($cmdSignature); return $this->compFunction($funcName, $buf); }
php
public function commandmetaCallbackFunction(CommandInterface $cmd) { $cmdSignature = $cmd->getSignature(); $buf = new Buffer; $buf->indent(); $buf->appendLine("local curcontext=\$curcontext state line ret=1"); $buf->appendLine("declare -A opt_args"); $buf->appendLine("declare -A values"); $buf->appendLine("local ret=1"); /* values=$(example/demo meta commit arg 1 valid-values) _values "description" ${=values} && ret=0 return ret */ $buf->appendLine("local desc=\$1"); $buf->appendLine("local valtype=\$3"); $buf->appendLine("local pos=\$4"); $buf->appendLine("local completion=\$5"); $metaCommand = [$this->programName, 'meta', $cmdSignature, '$valtype', '$pos', '$completion']; $buf->appendLine('$(' . implode(" ", $metaCommand) . ')'); $buf->appendLine('_values $desc ${=values} && ret=0'); // expand value array as arguments $buf->appendLine('return ret'); $funcName = $this->commandFunctionName($cmdSignature); return $this->compFunction($funcName, $buf); }
[ "public", "function", "commandmetaCallbackFunction", "(", "CommandInterface", "$", "cmd", ")", "{", "$", "cmdSignature", "=", "$", "cmd", "->", "getSignature", "(", ")", ";", "$", "buf", "=", "new", "Buffer", ";", "$", "buf", "->", "indent", "(", ")", ";...
Zsh function usage example/demo meta commit arg 1 valid-values appName meta sub1.sub2.sub3 opt email valid-values
[ "Zsh", "function", "usage" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Completion/ZshGenerator.php#L476-L507
train
hail-framework/framework
src/Console/Completion/ZshGenerator.php
ZshGenerator.compFunction
protected function compFunction($name, $code) { $buf = new Buffer; $buf->appendLine("$name () {"); $buf->indent(); $buf->appendBuffer($code); $buf->unindent(); $buf->appendLine("}"); return $buf; }
php
protected function compFunction($name, $code) { $buf = new Buffer; $buf->appendLine("$name () {"); $buf->indent(); $buf->appendBuffer($code); $buf->unindent(); $buf->appendLine("}"); return $buf; }
[ "protected", "function", "compFunction", "(", "$", "name", ",", "$", "code", ")", "{", "$", "buf", "=", "new", "Buffer", ";", "$", "buf", "->", "appendLine", "(", "\"$name () {\"", ")", ";", "$", "buf", "->", "indent", "(", ")", ";", "$", "buf", "-...
wrap zsh code with function
[ "wrap", "zsh", "code", "with", "function" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Completion/ZshGenerator.php#L629-L639
train
TheBnl/silverstripe-pageslices
src/model/PageSlice.php
PageSlice.onAfterDuplicate
public function onAfterDuplicate(PageSlice $slice) { // Check if there are relations set // Loop over each set relation // Copy all items in the relation over to the new object if ($hasManyRelations = $slice->data()->hasMany()) { foreach ($hasManyRelations as $relation => $class) { foreach ($slice->$relation() as $object) { /** @var DataObject $object */ $copy = $object->duplicate(true); $this->$relation()->add($copy); } } } }
php
public function onAfterDuplicate(PageSlice $slice) { // Check if there are relations set // Loop over each set relation // Copy all items in the relation over to the new object if ($hasManyRelations = $slice->data()->hasMany()) { foreach ($hasManyRelations as $relation => $class) { foreach ($slice->$relation() as $object) { /** @var DataObject $object */ $copy = $object->duplicate(true); $this->$relation()->add($copy); } } } }
[ "public", "function", "onAfterDuplicate", "(", "PageSlice", "$", "slice", ")", "{", "// Check if there are relations set", "// Loop over each set relation", "// Copy all items in the relation over to the new object", "if", "(", "$", "hasManyRelations", "=", "$", "slice", "->", ...
If this slice holds has_many content on duplicate copy the content over @param PageSlice $slice
[ "If", "this", "slice", "holds", "has_many", "content", "on", "duplicate", "copy", "the", "content", "over" ]
5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b
https://github.com/TheBnl/silverstripe-pageslices/blob/5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b/src/model/PageSlice.php#L88-L102
train
TheBnl/silverstripe-pageslices
src/model/PageSlice.php
PageSlice.createSliceID
private function createSliceID() { $urlFilter = URLSegmentFilter::create(); if ($sliceID = $urlFilter->filter($this->getField('Title'))) { if (!$this->Parent()->PageSlices()->filter(array('ID:not' => $this->ID, 'SliceID' => $sliceID))->exists()) { $this->setField('SliceID', $sliceID); } else { $this->setField('SliceID', "$sliceID-{$this->ID}"); } } }
php
private function createSliceID() { $urlFilter = URLSegmentFilter::create(); if ($sliceID = $urlFilter->filter($this->getField('Title'))) { if (!$this->Parent()->PageSlices()->filter(array('ID:not' => $this->ID, 'SliceID' => $sliceID))->exists()) { $this->setField('SliceID', $sliceID); } else { $this->setField('SliceID', "$sliceID-{$this->ID}"); } } }
[ "private", "function", "createSliceID", "(", ")", "{", "$", "urlFilter", "=", "URLSegmentFilter", "::", "create", "(", ")", ";", "if", "(", "$", "sliceID", "=", "$", "urlFilter", "->", "filter", "(", "$", "this", "->", "getField", "(", "'Title'", ")", ...
Create a readable ID based on the slice title
[ "Create", "a", "readable", "ID", "based", "on", "the", "slice", "title" ]
5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b
https://github.com/TheBnl/silverstripe-pageslices/blob/5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b/src/model/PageSlice.php#L128-L138
train
hail-framework/framework
src/Image/AbstractEncoder.php
AbstractEncoder.process
public function process(Image $image, $format = null, $quality = null) { $this->setImage($image); $this->setFormat($format); $this->setQuality($quality); switch (strtolower($this->format)) { case 'data-url': $this->result = $this->processDataUrl(); break; case 'gif': case 'image/gif': $this->result = $this->processGif(); break; case 'png': case 'image/png': case 'image/x-png': $this->result = $this->processPng(); break; case 'jpg': case 'jpeg': case 'image/jpg': case 'image/jpeg': case 'image/pjpeg': $this->result = $this->processJpeg(); break; case 'tif': case 'tiff': case 'image/tiff': case 'image/tif': case 'image/x-tif': case 'image/x-tiff': $this->result = $this->processTiff(); break; case 'bmp': case 'ms-bmp': case 'x-bitmap': case 'x-bmp': case 'x-ms-bmp': case 'x-win-bitmap': case 'x-windows-bmp': case 'x-xbitmap': case 'image/bmp': case 'image/ms-bmp': case 'image/x-bitmap': case 'image/x-bmp': case 'image/x-ms-bmp': case 'image/x-win-bitmap': case 'image/x-windows-bmp': case 'image/x-xbitmap': $this->result = $this->processBmp(); break; case 'ico': case 'image/x-ico': case 'image/x-icon': case 'image/vnd.microsoft.icon': $this->result = $this->processIco(); break; case 'psd': case 'image/vnd.adobe.photoshop': $this->result = $this->processPsd(); break; case 'webp': case 'image/webp': case 'image/x-webp': $this->result = $this->processWebp(); break; default: throw new \Hail\Image\Exception\NotSupportedException( "Encoding format ({$format}) is not supported." ); } $this->setImage(null); return $image->setEncoded($this->result); }
php
public function process(Image $image, $format = null, $quality = null) { $this->setImage($image); $this->setFormat($format); $this->setQuality($quality); switch (strtolower($this->format)) { case 'data-url': $this->result = $this->processDataUrl(); break; case 'gif': case 'image/gif': $this->result = $this->processGif(); break; case 'png': case 'image/png': case 'image/x-png': $this->result = $this->processPng(); break; case 'jpg': case 'jpeg': case 'image/jpg': case 'image/jpeg': case 'image/pjpeg': $this->result = $this->processJpeg(); break; case 'tif': case 'tiff': case 'image/tiff': case 'image/tif': case 'image/x-tif': case 'image/x-tiff': $this->result = $this->processTiff(); break; case 'bmp': case 'ms-bmp': case 'x-bitmap': case 'x-bmp': case 'x-ms-bmp': case 'x-win-bitmap': case 'x-windows-bmp': case 'x-xbitmap': case 'image/bmp': case 'image/ms-bmp': case 'image/x-bitmap': case 'image/x-bmp': case 'image/x-ms-bmp': case 'image/x-win-bitmap': case 'image/x-windows-bmp': case 'image/x-xbitmap': $this->result = $this->processBmp(); break; case 'ico': case 'image/x-ico': case 'image/x-icon': case 'image/vnd.microsoft.icon': $this->result = $this->processIco(); break; case 'psd': case 'image/vnd.adobe.photoshop': $this->result = $this->processPsd(); break; case 'webp': case 'image/webp': case 'image/x-webp': $this->result = $this->processWebp(); break; default: throw new \Hail\Image\Exception\NotSupportedException( "Encoding format ({$format}) is not supported." ); } $this->setImage(null); return $image->setEncoded($this->result); }
[ "public", "function", "process", "(", "Image", "$", "image", ",", "$", "format", "=", "null", ",", "$", "quality", "=", "null", ")", "{", "$", "this", "->", "setImage", "(", "$", "image", ")", ";", "$", "this", "->", "setFormat", "(", "$", "format"...
Process a given image @param Image $image @param string $format @param int $quality @return Image
[ "Process", "a", "given", "image" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Image/AbstractEncoder.php#L92-L178
train
hail-framework/framework
src/Database/Migration/Manager.php
Manager.getMigrationFiles
protected function getMigrationFiles() { $config = $this->getConfig(); $paths = $config->getMigrationPaths(); $files = []; foreach ($paths as $path) { $files[] = Util::glob($path . DIRECTORY_SEPARATOR . '*.php'); } $files = array_merge(...$files); // glob() can return the same file multiple times // This will cause the migration to fail with a // false assumption of duplicate migrations // http://php.net/manual/en/function.glob.php#110340 return array_unique($files); }
php
protected function getMigrationFiles() { $config = $this->getConfig(); $paths = $config->getMigrationPaths(); $files = []; foreach ($paths as $path) { $files[] = Util::glob($path . DIRECTORY_SEPARATOR . '*.php'); } $files = array_merge(...$files); // glob() can return the same file multiple times // This will cause the migration to fail with a // false assumption of duplicate migrations // http://php.net/manual/en/function.glob.php#110340 return array_unique($files); }
[ "protected", "function", "getMigrationFiles", "(", ")", "{", "$", "config", "=", "$", "this", "->", "getConfig", "(", ")", ";", "$", "paths", "=", "$", "config", "->", "getMigrationPaths", "(", ")", ";", "$", "files", "=", "[", "]", ";", "foreach", "...
Returns a list of migration files found in the provided migration paths. @return string[]
[ "Returns", "a", "list", "of", "migration", "files", "found", "in", "the", "provided", "migration", "paths", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Manager.php#L682-L699
train
hail-framework/framework
src/Database/Migration/Manager.php
Manager.getSeedDependenciesInstances
private function getSeedDependenciesInstances(AbstractSeed $seed) { $dependenciesInstances = []; $dependencies = $seed->getDependencies(); if (!empty($dependencies)) { foreach ($dependencies as $dependency) { foreach ($this->seeds as $seed) { if (\get_class($seed) === $dependency) { $dependenciesInstances[$dependency] = $seed; } } } } return $dependenciesInstances; }
php
private function getSeedDependenciesInstances(AbstractSeed $seed) { $dependenciesInstances = []; $dependencies = $seed->getDependencies(); if (!empty($dependencies)) { foreach ($dependencies as $dependency) { foreach ($this->seeds as $seed) { if (\get_class($seed) === $dependency) { $dependenciesInstances[$dependency] = $seed; } } } } return $dependenciesInstances; }
[ "private", "function", "getSeedDependenciesInstances", "(", "AbstractSeed", "$", "seed", ")", "{", "$", "dependenciesInstances", "=", "[", "]", ";", "$", "dependencies", "=", "$", "seed", "->", "getDependencies", "(", ")", ";", "if", "(", "!", "empty", "(", ...
Get seed dependencies instances from seed dependency array @param AbstractSeed $seed Seed @return AbstractSeed[]
[ "Get", "seed", "dependencies", "instances", "from", "seed", "dependency", "array" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Manager.php#L722-L737
train
hail-framework/framework
src/Database/Migration/Manager.php
Manager.orderSeedsByDependencies
private function orderSeedsByDependencies(array $seeds) { $orderedSeeds = []; foreach ($seeds as $seed) { $key = \get_class($seed); $dependencies = $this->getSeedDependenciesInstances($seed); if (!empty($dependencies)) { $orderedSeeds[$key] = $seed; $orderedSeeds = \array_merge($this->orderSeedsByDependencies($dependencies), $orderedSeeds); } else { $orderedSeeds[$key] = $seed; } } return $orderedSeeds; }
php
private function orderSeedsByDependencies(array $seeds) { $orderedSeeds = []; foreach ($seeds as $seed) { $key = \get_class($seed); $dependencies = $this->getSeedDependenciesInstances($seed); if (!empty($dependencies)) { $orderedSeeds[$key] = $seed; $orderedSeeds = \array_merge($this->orderSeedsByDependencies($dependencies), $orderedSeeds); } else { $orderedSeeds[$key] = $seed; } } return $orderedSeeds; }
[ "private", "function", "orderSeedsByDependencies", "(", "array", "$", "seeds", ")", "{", "$", "orderedSeeds", "=", "[", "]", ";", "foreach", "(", "$", "seeds", "as", "$", "seed", ")", "{", "$", "key", "=", "\\", "get_class", "(", "$", "seed", ")", ";...
Order seeds by dependencies @param AbstractSeed[] $seeds Seeds @return AbstractSeed[]
[ "Order", "seeds", "by", "dependencies" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Manager.php#L746-L761
train
hail-framework/framework
src/Database/Migration/Manager.php
Manager.getSeeds
public function getSeeds() { if (null === $this->seeds) { $phpFiles = $this->getSeedFiles(); // filter the files to only get the ones that match our naming scheme $fileNames = []; /** @var AbstractSeed[] $seeds */ $seeds = []; foreach ($phpFiles as $filePath) { if (Util::isValidSeedFileName(basename($filePath))) { $config = $this->getConfig(); $namespace = $config->getSeedNamespaceByPath(dirname($filePath)); // convert the filename to a class name $class = (null === $namespace ? '' : $namespace . '\\') . pathinfo($filePath, PATHINFO_FILENAME); $fileNames[$class] = basename($filePath); // load the seed file /** @noinspection PhpIncludeInspection */ require_once $filePath; if (!class_exists($class)) { throw new \InvalidArgumentException(sprintf( 'Could not find class "%s" in file "%s"', $class, $filePath )); } // instantiate it $seed = new $class($this->getCommand()); if (!($seed instanceof AbstractSeed)) { throw new \InvalidArgumentException(sprintf( 'The class "%s" in file "%s" must extend \Hail\Database\Migration\Seed\AbstractSeed', $class, $filePath )); } $seeds[$class] = $seed; } } ksort($seeds); $this->setSeeds($seeds); } $this->seeds = $this->orderSeedsByDependencies($this->seeds); return $this->seeds; }
php
public function getSeeds() { if (null === $this->seeds) { $phpFiles = $this->getSeedFiles(); // filter the files to only get the ones that match our naming scheme $fileNames = []; /** @var AbstractSeed[] $seeds */ $seeds = []; foreach ($phpFiles as $filePath) { if (Util::isValidSeedFileName(basename($filePath))) { $config = $this->getConfig(); $namespace = $config->getSeedNamespaceByPath(dirname($filePath)); // convert the filename to a class name $class = (null === $namespace ? '' : $namespace . '\\') . pathinfo($filePath, PATHINFO_FILENAME); $fileNames[$class] = basename($filePath); // load the seed file /** @noinspection PhpIncludeInspection */ require_once $filePath; if (!class_exists($class)) { throw new \InvalidArgumentException(sprintf( 'Could not find class "%s" in file "%s"', $class, $filePath )); } // instantiate it $seed = new $class($this->getCommand()); if (!($seed instanceof AbstractSeed)) { throw new \InvalidArgumentException(sprintf( 'The class "%s" in file "%s" must extend \Hail\Database\Migration\Seed\AbstractSeed', $class, $filePath )); } $seeds[$class] = $seed; } } ksort($seeds); $this->setSeeds($seeds); } $this->seeds = $this->orderSeedsByDependencies($this->seeds); return $this->seeds; }
[ "public", "function", "getSeeds", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "seeds", ")", "{", "$", "phpFiles", "=", "$", "this", "->", "getSeedFiles", "(", ")", ";", "// filter the files to only get the ones that match our naming scheme", "$",...
Gets an array of database seeders. @throws \InvalidArgumentException @return AbstractSeed[]
[ "Gets", "an", "array", "of", "database", "seeders", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Manager.php#L769-L821
train
systemson/collection
src/Bag.php
Bag.pushTo
public function pushTo($key, $value): bool { if (is_array($value)) { foreach ($value as $subKeykey => $value) { $this[$key][$subKeykey] = $value; } } else { $this[$key][] = $value; } return true; }
php
public function pushTo($key, $value): bool { if (is_array($value)) { foreach ($value as $subKeykey => $value) { $this[$key][$subKeykey] = $value; } } else { $this[$key][] = $value; } return true; }
[ "public", "function", "pushTo", "(", "$", "key", ",", "$", "value", ")", ":", "bool", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "foreach", "(", "$", "value", "as", "$", "subKeykey", "=>", "$", "value", ")", "{", "$", "this", ...
Push a new item at the end of a item in the collection. @todo MUST accept multilevel keys. @param string $key The item's key @param mixed $value The item's value @return bool
[ "Push", "a", "new", "item", "at", "the", "end", "of", "a", "item", "in", "the", "collection", "." ]
fb3ae1a78806aafabc0562db96822e8b99dc2a64
https://github.com/systemson/collection/blob/fb3ae1a78806aafabc0562db96822e8b99dc2a64/src/Bag.php#L37-L48
train
hiqdev/hipanel-module-dns
src/validators/MxValueValidator.php
MxValueValidator.extractPriority
public function extractPriority($model, $attribute) { $priorityAttribute = $this->priorityAttribute; preg_match($this->priorityExtractPattern, $model->$attribute, $matches); if ($matches[2] !== '') { $model->$priorityAttribute = $matches[2]; $model->$attribute = $matches[3]; } }
php
public function extractPriority($model, $attribute) { $priorityAttribute = $this->priorityAttribute; preg_match($this->priorityExtractPattern, $model->$attribute, $matches); if ($matches[2] !== '') { $model->$priorityAttribute = $matches[2]; $model->$attribute = $matches[3]; } }
[ "public", "function", "extractPriority", "(", "$", "model", ",", "$", "attribute", ")", "{", "$", "priorityAttribute", "=", "$", "this", "->", "priorityAttribute", ";", "preg_match", "(", "$", "this", "->", "priorityExtractPattern", ",", "$", "model", "->", ...
Extracts priority to separated model attribute. @param $model Model @param $attribute
[ "Extracts", "priority", "to", "separated", "model", "attribute", "." ]
7e9199c95d91a979b7bd4fd07fe801dbe9e69183
https://github.com/hiqdev/hipanel-module-dns/blob/7e9199c95d91a979b7bd4fd07fe801dbe9e69183/src/validators/MxValueValidator.php#L57-L65
train
Wikifab/mediawiki-extensions-MsUpload
SetFileDescription.php
SetFileDescription.APIFauxRequest
private function APIFauxRequest($data = [], $wasPosted = false, $session = null, $protocol = 'http' ){ $res = array(); $apiParams = new \FauxRequest($data, $wasPosted, $session, $protocol); try { $api = new \ApiMain( $apiParams ); $api->execute(); $res = $api->getResult()->getResultData(); } catch (\Exception $e) { trigger_error("API exception : " . $e->getMessage(), E_USER_WARNING); } return $res; }
php
private function APIFauxRequest($data = [], $wasPosted = false, $session = null, $protocol = 'http' ){ $res = array(); $apiParams = new \FauxRequest($data, $wasPosted, $session, $protocol); try { $api = new \ApiMain( $apiParams ); $api->execute(); $res = $api->getResult()->getResultData(); } catch (\Exception $e) { trigger_error("API exception : " . $e->getMessage(), E_USER_WARNING); } return $res; }
[ "private", "function", "APIFauxRequest", "(", "$", "data", "=", "[", "]", ",", "$", "wasPosted", "=", "false", ",", "$", "session", "=", "null", ",", "$", "protocol", "=", "'http'", ")", "{", "$", "res", "=", "array", "(", ")", ";", "$", "apiParams...
Execute a request to the API within mediawiki using FauxRequest @param $data array Array of non-urlencoded key => value pairs, the fake GET/POST values @param $wasPosted bool Whether to treat the data as POST @param $session MediaWiki\\Session\\Session | array | null Session, session data array, or null @param $protocol string 'http' or 'https' @return array the result data array @see https://doc.wikimedia.org/mediawiki-core/master/php/classFauxRequest.html
[ "Execute", "a", "request", "to", "the", "API", "within", "mediawiki", "using", "FauxRequest" ]
77bdf0b66dcfc7b12a710fc6cb2b17a0baf7b5ac
https://github.com/Wikifab/mediawiki-extensions-MsUpload/blob/77bdf0b66dcfc7b12a710fc6cb2b17a0baf7b5ac/SetFileDescription.php#L186-L204
train
hail-framework/framework
src/Util/MimeType.php
MimeType.getMimeTypeByFile
public static function getMimeTypeByFile(string $file) { if (!\is_file($file) || !\class_exists('\finfo', false)) { return null; } try { $finfo = new \finfo(FILEINFO_MIME_TYPE); return $finfo->file($file) ?: null; // @codeCoverageIgnoreStart } catch (\ErrorException $e) { // This is caused by an array to string conversion error. return null; } }
php
public static function getMimeTypeByFile(string $file) { if (!\is_file($file) || !\class_exists('\finfo', false)) { return null; } try { $finfo = new \finfo(FILEINFO_MIME_TYPE); return $finfo->file($file) ?: null; // @codeCoverageIgnoreStart } catch (\ErrorException $e) { // This is caused by an array to string conversion error. return null; } }
[ "public", "static", "function", "getMimeTypeByFile", "(", "string", "$", "file", ")", "{", "if", "(", "!", "\\", "is_file", "(", "$", "file", ")", "||", "!", "\\", "class_exists", "(", "'\\finfo'", ",", "false", ")", ")", "{", "return", "null", ";", ...
Detects MIME Type based on file. @param string $file @return string|null MIME Type or NULL if no mime type detected
[ "Detects", "MIME", "Type", "based", "on", "file", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/MimeType.php#L111-L126
train
hail-framework/framework
src/Session/Segment.php
Segment.get
public function get($key, $alt = null) { $this->resumeSession(); return $_SESSION[$this->name][$key] ?? $alt; }
php
public function get($key, $alt = null) { $this->resumeSession(); return $_SESSION[$this->name][$key] ?? $alt; }
[ "public", "function", "get", "(", "$", "key", ",", "$", "alt", "=", "null", ")", "{", "$", "this", "->", "resumeSession", "(", ")", ";", "return", "$", "_SESSION", "[", "$", "this", "->", "name", "]", "[", "$", "key", "]", "??", "$", "alt", ";"...
Returns the value of a key in the segment. @param string $key The key in the segment. @param mixed $alt An alternative value to return if the key is not set. @return mixed
[ "Returns", "the", "value", "of", "a", "key", "in", "the", "segment", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Session/Segment.php#L60-L65
train
hail-framework/framework
src/Util/StreamFilter.php
StreamFilter.append
public static function append($stream, $callback, $read_write = STREAM_FILTER_ALL) { $ret = @\stream_filter_append($stream, self::register(), $read_write, $callback); if ($ret === false) { $error = \error_get_last() + ['message' => '']; throw new \RuntimeException('Unable to append filter: ' . $error['message']); } return $ret; }
php
public static function append($stream, $callback, $read_write = STREAM_FILTER_ALL) { $ret = @\stream_filter_append($stream, self::register(), $read_write, $callback); if ($ret === false) { $error = \error_get_last() + ['message' => '']; throw new \RuntimeException('Unable to append filter: ' . $error['message']); } return $ret; }
[ "public", "static", "function", "append", "(", "$", "stream", ",", "$", "callback", ",", "$", "read_write", "=", "STREAM_FILTER_ALL", ")", "{", "$", "ret", "=", "@", "\\", "stream_filter_append", "(", "$", "stream", ",", "self", "::", "register", "(", ")...
append a callback filter to the given stream @param resource $stream @param callable $callback @param int $read_write @return resource filter resource which can be used for `remove()` @throws \RuntimeException on error @uses stream_filter_append()
[ "append", "a", "callback", "filter", "to", "the", "given", "stream" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/StreamFilter.php#L23-L32
train
hail-framework/framework
src/Util/StreamFilter.php
StreamFilter.prepend
public static function prepend($stream, $callback, $read_write = STREAM_FILTER_ALL) { $ret = @\stream_filter_prepend($stream, self::register(), $read_write, $callback); if ($ret === false) { $error = \error_get_last() + ['message' => '']; throw new \RuntimeException('Unable to prepend filter: ' . $error['message']); } return $ret; }
php
public static function prepend($stream, $callback, $read_write = STREAM_FILTER_ALL) { $ret = @\stream_filter_prepend($stream, self::register(), $read_write, $callback); if ($ret === false) { $error = \error_get_last() + ['message' => '']; throw new \RuntimeException('Unable to prepend filter: ' . $error['message']); } return $ret; }
[ "public", "static", "function", "prepend", "(", "$", "stream", ",", "$", "callback", ",", "$", "read_write", "=", "STREAM_FILTER_ALL", ")", "{", "$", "ret", "=", "@", "\\", "stream_filter_prepend", "(", "$", "stream", ",", "self", "::", "register", "(", ...
prepend a callback filter to the given stream @param resource $stream @param callable $callback @param int $read_write @return resource filter resource which can be used for `remove()` @throws \RuntimeException on error @uses stream_filter_prepend()
[ "prepend", "a", "callback", "filter", "to", "the", "given", "stream" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/StreamFilter.php#L45-L54
train
hail-framework/framework
src/Util/StreamFilter.php
StreamFilter.register
public static function register() { if (self::$registered === null) { self::$registered = 'stream-callback'; \stream_filter_register(self::$registered, CallbackFilter::class); } return self::$registered; }
php
public static function register() { if (self::$registered === null) { self::$registered = 'stream-callback'; \stream_filter_register(self::$registered, CallbackFilter::class); } return self::$registered; }
[ "public", "static", "function", "register", "(", ")", "{", "if", "(", "self", "::", "$", "registered", "===", "null", ")", "{", "self", "::", "$", "registered", "=", "'stream-callback'", ";", "\\", "stream_filter_register", "(", "self", "::", "$", "registe...
registers the callback filter and returns the resulting filter name There should be little reason to call this function manually. @return string filter name @uses CallbackFilter
[ "registers", "the", "callback", "filter", "and", "returns", "the", "resulting", "filter", "name" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/StreamFilter.php#L147-L155
train
mcrumm/pecan
src/Readline.php
Readline.setCompleter
public function setCompleter(callable $completer) { if (!Readline::isFullySupported()) { throw new \LogicException(sprintf('%s requires readline support to use the completer.', __CLASS__)); } $this->completer = $completer; return $this; }
php
public function setCompleter(callable $completer) { if (!Readline::isFullySupported()) { throw new \LogicException(sprintf('%s requires readline support to use the completer.', __CLASS__)); } $this->completer = $completer; return $this; }
[ "public", "function", "setCompleter", "(", "callable", "$", "completer", ")", "{", "if", "(", "!", "Readline", "::", "isFullySupported", "(", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'%s requires readline support to use the comp...
Sets the auto-complete callback @param callable $completer @return $this @throws \LogicException When PHP is not compiled with readline support.
[ "Sets", "the", "auto", "-", "complete", "callback" ]
f35f01249587a4df45c7d3ab78f3e51919471177
https://github.com/mcrumm/pecan/blob/f35f01249587a4df45c7d3ab78f3e51919471177/src/Readline.php#L134-L142
train
mcrumm/pecan
src/Readline.php
Readline.prompt
public function prompt() { if ($this->hasReadline) { readline_callback_handler_install($this->getPrompt(), [ $this, 'lineHandler' ]); } else { if ($this->paused) { $this->resume(); } $this->console->log($this->getPrompt()); } return $this; }
php
public function prompt() { if ($this->hasReadline) { readline_callback_handler_install($this->getPrompt(), [ $this, 'lineHandler' ]); } else { if ($this->paused) { $this->resume(); } $this->console->log($this->getPrompt()); } return $this; }
[ "public", "function", "prompt", "(", ")", "{", "if", "(", "$", "this", "->", "hasReadline", ")", "{", "readline_callback_handler_install", "(", "$", "this", "->", "getPrompt", "(", ")", ",", "[", "$", "this", ",", "'lineHandler'", "]", ")", ";", "}", "...
Writes the prompt to the output. @return $this
[ "Writes", "the", "prompt", "to", "the", "output", "." ]
f35f01249587a4df45c7d3ab78f3e51919471177
https://github.com/mcrumm/pecan/blob/f35f01249587a4df45c7d3ab78f3e51919471177/src/Readline.php#L182-L192
train
mcrumm/pecan
src/Readline.php
Readline.question
public function question($query, callable $callback) { if (!is_callable($callback)) { return $this; } if ($this->questionCallback) { $this->prompt(); } else { $this->oldPrompt = $this->prompt; $this->setPrompt($query); $this->questionCallback = $callback; $this->prompt(); } return $this; }
php
public function question($query, callable $callback) { if (!is_callable($callback)) { return $this; } if ($this->questionCallback) { $this->prompt(); } else { $this->oldPrompt = $this->prompt; $this->setPrompt($query); $this->questionCallback = $callback; $this->prompt(); } return $this; }
[ "public", "function", "question", "(", "$", "query", ",", "callable", "$", "callback", ")", "{", "if", "(", "!", "is_callable", "(", "$", "callback", ")", ")", "{", "return", "$", "this", ";", "}", "if", "(", "$", "this", "->", "questionCallback", ")...
Prompts for input. @param string $query @param callable $callback @return $this
[ "Prompts", "for", "input", "." ]
f35f01249587a4df45c7d3ab78f3e51919471177
https://github.com/mcrumm/pecan/blob/f35f01249587a4df45c7d3ab78f3e51919471177/src/Readline.php#L201-L215
train
mcrumm/pecan
src/Readline.php
Readline.pause
public function pause() { if ($this->paused) { return $this; } $this->input->pause(); $this->paused = true; $this->emit('pause'); return $this; }
php
public function pause() { if ($this->paused) { return $this; } $this->input->pause(); $this->paused = true; $this->emit('pause'); return $this; }
[ "public", "function", "pause", "(", ")", "{", "if", "(", "$", "this", "->", "paused", ")", "{", "return", "$", "this", ";", "}", "$", "this", "->", "input", "->", "pause", "(", ")", ";", "$", "this", "->", "paused", "=", "true", ";", "$", "this...
Pauses the input stream. @return $this
[ "Pauses", "the", "input", "stream", "." ]
f35f01249587a4df45c7d3ab78f3e51919471177
https://github.com/mcrumm/pecan/blob/f35f01249587a4df45c7d3ab78f3e51919471177/src/Readline.php#L221-L228
train
mcrumm/pecan
src/Readline.php
Readline.resume
public function resume() { if (!$this->paused) { return $this; } $this->input->resume(); $this->paused = false; $this->emit('resume'); return $this; }
php
public function resume() { if (!$this->paused) { return $this; } $this->input->resume(); $this->paused = false; $this->emit('resume'); return $this; }
[ "public", "function", "resume", "(", ")", "{", "if", "(", "!", "$", "this", "->", "paused", ")", "{", "return", "$", "this", ";", "}", "$", "this", "->", "input", "->", "resume", "(", ")", ";", "$", "this", "->", "paused", "=", "false", ";", "$...
Resumes the input stream. @return $this
[ "Resumes", "the", "input", "stream", "." ]
f35f01249587a4df45c7d3ab78f3e51919471177
https://github.com/mcrumm/pecan/blob/f35f01249587a4df45c7d3ab78f3e51919471177/src/Readline.php#L234-L241
train
mcrumm/pecan
src/Readline.php
Readline.close
public function close() { if ($this->closed) { return; } $this->pause(); $this->closed = true; $this->emit('close'); }
php
public function close() { if ($this->closed) { return; } $this->pause(); $this->closed = true; $this->emit('close'); }
[ "public", "function", "close", "(", ")", "{", "if", "(", "$", "this", "->", "closed", ")", "{", "return", ";", "}", "$", "this", "->", "pause", "(", ")", ";", "$", "this", "->", "closed", "=", "true", ";", "$", "this", "->", "emit", "(", "'clos...
Closes the streams. @return $this
[ "Closes", "the", "streams", "." ]
f35f01249587a4df45c7d3ab78f3e51919471177
https://github.com/mcrumm/pecan/blob/f35f01249587a4df45c7d3ab78f3e51919471177/src/Readline.php#L247-L253
train
hail-framework/framework
src/Util/Inflector.php
Inflector.camelize
public static function camelize(string $string, string $delimiter = '_'): string { $cacheKey = __FUNCTION__ . $delimiter; $result = static::_cache($cacheKey, $string); if ($result === false) { $result = \str_replace(' ', '', static::humanize($string, $delimiter)); static::_cache($cacheKey, $string, $result); } return $result; }
php
public static function camelize(string $string, string $delimiter = '_'): string { $cacheKey = __FUNCTION__ . $delimiter; $result = static::_cache($cacheKey, $string); if ($result === false) { $result = \str_replace(' ', '', static::humanize($string, $delimiter)); static::_cache($cacheKey, $string, $result); } return $result; }
[ "public", "static", "function", "camelize", "(", "string", "$", "string", ",", "string", "$", "delimiter", "=", "'_'", ")", ":", "string", "{", "$", "cacheKey", "=", "__FUNCTION__", ".", "$", "delimiter", ";", "$", "result", "=", "static", "::", "_cache"...
Returns the input lower_case_delimited_string as a CamelCasedString. @param string $string String to camelize @param string $delimiter the delimiter in the input string @return string CamelizedStringLikeThis. @link http://book.cakephp.org/3.0/en/core-libraries/inflector.html#creating-camelcase-and-under-scored-forms
[ "Returns", "the", "input", "lower_case_delimited_string", "as", "a", "CamelCasedString", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Inflector.php#L586-L598
train
Becklyn/RadBundle
src/Model/SortableModelTrait.php
SortableModelTrait.flushSortOrderMapping
protected function flushSortOrderMapping (SortableHelper $sortableHelper, $sortMapping, array $where = []) : bool { if ($sortableHelper->applySorting($sortMapping, $where)) { $this->flush(); return true; } return false; }
php
protected function flushSortOrderMapping (SortableHelper $sortableHelper, $sortMapping, array $where = []) : bool { if ($sortableHelper->applySorting($sortMapping, $where)) { $this->flush(); return true; } return false; }
[ "protected", "function", "flushSortOrderMapping", "(", "SortableHelper", "$", "sortableHelper", ",", "$", "sortMapping", ",", "array", "$", "where", "=", "[", "]", ")", ":", "bool", "{", "if", "(", "$", "sortableHelper", "->", "applySorting", "(", "$", "sort...
Applies the sort order mapping as provided in the parameters. The model should wrap this method and use type hints on the $where parameter entries. @param SortableHelper $sortableHelper @param array|mixed $sortMapping @param array $where @return bool
[ "Applies", "the", "sort", "order", "mapping", "as", "provided", "in", "the", "parameters", "." ]
34d5887e13f5a4018843b77dcbefc2eb2f3169f4
https://github.com/Becklyn/RadBundle/blob/34d5887e13f5a4018843b77dcbefc2eb2f3169f4/src/Model/SortableModelTrait.php#L21-L30
train
bradfeehan/guzzle-modular-service-descriptions
lib/ServiceDescriptionLoader.php
ServiceDescriptionLoader.loadModular
protected function loadModular($path) { $config = array(); // Loop over files in $path (recursing into sub-directories) foreach ($this->filesIn($path) as $file) { // Determine the relative path of the current file by // stripping $path from the beginning of the absolute path $nestPath = $this->getNestPath($file->getPathname(), $path); $content = $this->configLoader->load($file->getPathname()); $config = $this->merge($config, $this->nest($content, $nestPath)); } return $config; }
php
protected function loadModular($path) { $config = array(); // Loop over files in $path (recursing into sub-directories) foreach ($this->filesIn($path) as $file) { // Determine the relative path of the current file by // stripping $path from the beginning of the absolute path $nestPath = $this->getNestPath($file->getPathname(), $path); $content = $this->configLoader->load($file->getPathname()); $config = $this->merge($config, $this->nest($content, $nestPath)); } return $config; }
[ "protected", "function", "loadModular", "(", "$", "path", ")", "{", "$", "config", "=", "array", "(", ")", ";", "// Loop over files in $path (recursing into sub-directories)", "foreach", "(", "$", "this", "->", "filesIn", "(", "$", "path", ")", "as", "$", "fil...
Loads a modular service description @param string $path Path to the service description to load @return array
[ "Loads", "a", "modular", "service", "description" ]
81fe516ffcfd2c12b28fe1232b832e633f817e3b
https://github.com/bradfeehan/guzzle-modular-service-descriptions/blob/81fe516ffcfd2c12b28fe1232b832e633f817e3b/lib/ServiceDescriptionLoader.php#L86-L101
train
bradfeehan/guzzle-modular-service-descriptions
lib/ServiceDescriptionLoader.php
ServiceDescriptionLoader.getNestPath
protected function getNestPath($path, $base) { $ds = preg_quote(DIRECTORY_SEPARATOR, '#'); return preg_replace( // patterns to remove array( // strip the leading path (make it relative to the // root of the service description) '#^' . preg_quote($base, '#') . $ds . '#', // Ignore trailing __index.foo '#^(.*?)(:?' . $ds . '?__index)?\\.(:?\\w+)$#', // Remove path components ending with .group '#\\w+\\.group(' . $ds . '|$)#', // Remove any trailing slash '#' . $ds . '+$#', // Translate any remaining backslash delimiters (Windows) '#\\\\#' ), // replacements (corresponding with patterns above) array( '', '\\1', '', '', '/' ), $path ); }
php
protected function getNestPath($path, $base) { $ds = preg_quote(DIRECTORY_SEPARATOR, '#'); return preg_replace( // patterns to remove array( // strip the leading path (make it relative to the // root of the service description) '#^' . preg_quote($base, '#') . $ds . '#', // Ignore trailing __index.foo '#^(.*?)(:?' . $ds . '?__index)?\\.(:?\\w+)$#', // Remove path components ending with .group '#\\w+\\.group(' . $ds . '|$)#', // Remove any trailing slash '#' . $ds . '+$#', // Translate any remaining backslash delimiters (Windows) '#\\\\#' ), // replacements (corresponding with patterns above) array( '', '\\1', '', '', '/' ), $path ); }
[ "protected", "function", "getNestPath", "(", "$", "path", ",", "$", "base", ")", "{", "$", "ds", "=", "preg_quote", "(", "DIRECTORY_SEPARATOR", ",", "'#'", ")", ";", "return", "preg_replace", "(", "// patterns to remove", "array", "(", "// strip the leading path...
Determines the path to nest content for a file's path name @param string $path The absolute path to the file @param string $base The absolute path to the base directory of the service description this file belongs to @return string
[ "Determines", "the", "path", "to", "nest", "content", "for", "a", "file", "s", "path", "name" ]
81fe516ffcfd2c12b28fe1232b832e633f817e3b
https://github.com/bradfeehan/guzzle-modular-service-descriptions/blob/81fe516ffcfd2c12b28fe1232b832e633f817e3b/lib/ServiceDescriptionLoader.php#L125-L158
train
bradfeehan/guzzle-modular-service-descriptions
lib/ServiceDescriptionLoader.php
ServiceDescriptionLoader.nest
private function nest($value, $path) { if ($path) { $elements = explode('/', $path); foreach (array_reverse($elements) as $element) { $value = array($element => $value); } } return $value; }
php
private function nest($value, $path) { if ($path) { $elements = explode('/', $path); foreach (array_reverse($elements) as $element) { $value = array($element => $value); } } return $value; }
[ "private", "function", "nest", "(", "$", "value", ",", "$", "path", ")", "{", "if", "(", "$", "path", ")", "{", "$", "elements", "=", "explode", "(", "'/'", ",", "$", "path", ")", ";", "foreach", "(", "array_reverse", "(", "$", "elements", ")", "...
Nests an array under a particular path As an example: nest(array('foo' => 'bar'), 'baz/qux') This will return: array( 'baz' => array( 'qux' => array( 'foo' => 'bar' ) ) ) @param mixed $value The value to put at the given path @param string $path The slash-separated path to put the value @return array
[ "Nests", "an", "array", "under", "a", "particular", "path" ]
81fe516ffcfd2c12b28fe1232b832e633f817e3b
https://github.com/bradfeehan/guzzle-modular-service-descriptions/blob/81fe516ffcfd2c12b28fe1232b832e633f817e3b/lib/ServiceDescriptionLoader.php#L203-L214
train
bradfeehan/guzzle-modular-service-descriptions
lib/ServiceDescriptionLoader.php
ServiceDescriptionLoader.sortConfig
protected function sortConfig(array $config) { // Sort operations if (isset($config['operations'])) { $operations = $config['operations']; $nodes = array(); // Create empty dependencies array foreach (array_keys($operations) as $key) { $nodes[$key] = array( 'in' => array(), // inbound dependencies 'out' => array(), // outbound dependencies ); } // Populate dependencies foreach ($operations as $key => $operation) { if (isset($operation['extends'])) { // This key depends on the thing being extended $nodes[$key]['in'][] = $operation['extends']; // The thing being extended depends on this key $nodes[$operation['extends']]['out'][] = $key; } } // Build up $independent $independent = array(); foreach ($nodes as $key => $node) { if (empty($node['in'])) { $independent[] = $key; } } // While we have nodes with no inbound edges, remove it // from the graph and add it to the end of the list $sorted = array(); while (!empty($independent)) { $key = array_shift($independent); $sorted[$key] = $operations[$key]; // Go over this node's dependencies foreach ($nodes[$key]['out'] as $dependency) { $nodes[$dependency]['in'] = array_diff( $nodes[$dependency]['in'], array($key) ); // If the dependency has all of its inbound deps... if (empty($nodes[$dependency]['in'])) { // ...it's ready to be processed, add it to $independent. $independent[] = $dependency; } } $nodes[$key]['out'] = array(); } foreach ($nodes as $node) { if (!empty($node['in']) or !empty($node['out'])) { throw new RuntimeException( "Couldn't sort graph, cycle detected!" ); } } $config['operations'] = $sorted; } return $config; }
php
protected function sortConfig(array $config) { // Sort operations if (isset($config['operations'])) { $operations = $config['operations']; $nodes = array(); // Create empty dependencies array foreach (array_keys($operations) as $key) { $nodes[$key] = array( 'in' => array(), // inbound dependencies 'out' => array(), // outbound dependencies ); } // Populate dependencies foreach ($operations as $key => $operation) { if (isset($operation['extends'])) { // This key depends on the thing being extended $nodes[$key]['in'][] = $operation['extends']; // The thing being extended depends on this key $nodes[$operation['extends']]['out'][] = $key; } } // Build up $independent $independent = array(); foreach ($nodes as $key => $node) { if (empty($node['in'])) { $independent[] = $key; } } // While we have nodes with no inbound edges, remove it // from the graph and add it to the end of the list $sorted = array(); while (!empty($independent)) { $key = array_shift($independent); $sorted[$key] = $operations[$key]; // Go over this node's dependencies foreach ($nodes[$key]['out'] as $dependency) { $nodes[$dependency]['in'] = array_diff( $nodes[$dependency]['in'], array($key) ); // If the dependency has all of its inbound deps... if (empty($nodes[$dependency]['in'])) { // ...it's ready to be processed, add it to $independent. $independent[] = $dependency; } } $nodes[$key]['out'] = array(); } foreach ($nodes as $node) { if (!empty($node['in']) or !empty($node['out'])) { throw new RuntimeException( "Couldn't sort graph, cycle detected!" ); } } $config['operations'] = $sorted; } return $config; }
[ "protected", "function", "sortConfig", "(", "array", "$", "config", ")", "{", "// Sort operations", "if", "(", "isset", "(", "$", "config", "[", "'operations'", "]", ")", ")", "{", "$", "operations", "=", "$", "config", "[", "'operations'", "]", ";", "$"...
Sorts the config so that dependencies are defined before use Guzzle requires things to be defined before they're used as the target of an "extends" declaration. This method sorts the config so that this is the case. This is called a topological sort. @param array $config The configuration to sort @return array The sorted configuration
[ "Sorts", "the", "config", "so", "that", "dependencies", "are", "defined", "before", "use" ]
81fe516ffcfd2c12b28fe1232b832e633f817e3b
https://github.com/bradfeehan/guzzle-modular-service-descriptions/blob/81fe516ffcfd2c12b28fe1232b832e633f817e3b/lib/ServiceDescriptionLoader.php#L247-L317
train
hail-framework/framework
src/I18n/Gettext/Extractors/VueJs.php
VueJs.isAttributeMatching
private static function isAttributeMatching($attributeName, $attributePrefixes) { foreach ($attributePrefixes as $prefix) { if (\strpos($attributeName, $prefix) === 0) { return true; } } return false; }
php
private static function isAttributeMatching($attributeName, $attributePrefixes) { foreach ($attributePrefixes as $prefix) { if (\strpos($attributeName, $prefix) === 0) { return true; } } return false; }
[ "private", "static", "function", "isAttributeMatching", "(", "$", "attributeName", ",", "$", "attributePrefixes", ")", "{", "foreach", "(", "$", "attributePrefixes", "as", "$", "prefix", ")", "{", "if", "(", "\\", "strpos", "(", "$", "attributeName", ",", "$...
Check if this attribute name should be parsed for translations @param string $attributeName @param string[] $attributePrefixes @return bool
[ "Check", "if", "this", "attribute", "name", "should", "be", "parsed", "for", "translations" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Extractors/VueJs.php#L240-L249
train
cfxmarkets/php-public-models
src/Exchange/Asset.php
Asset.serializeAttribute
public function serializeAttribute($name) { if ($name === 'issuanceCloseDate') { $val = $this->getIssuanceCloseDate(); if ($val instanceof \DateTimeInterface) { $val = $val->format(\DateTime::RFC3339); } return (string)$val; } return parent::serializeAttribute($name); }
php
public function serializeAttribute($name) { if ($name === 'issuanceCloseDate') { $val = $this->getIssuanceCloseDate(); if ($val instanceof \DateTimeInterface) { $val = $val->format(\DateTime::RFC3339); } return (string)$val; } return parent::serializeAttribute($name); }
[ "public", "function", "serializeAttribute", "(", "$", "name", ")", "{", "if", "(", "$", "name", "===", "'issuanceCloseDate'", ")", "{", "$", "val", "=", "$", "this", "->", "getIssuanceCloseDate", "(", ")", ";", "if", "(", "$", "val", "instanceof", "\\", ...
Serialize issuanceCloseDate field to a value that SQL understands We have to do this here because when order intents are serialized that already have a issuanceCloseDate date set, they end up sending malformed data to the API. This is because \DateTime actually does implement jsonSerialize, but in a way that breaks our implementation.
[ "Serialize", "issuanceCloseDate", "field", "to", "a", "value", "that", "SQL", "understands" ]
b91a58f7d9519b98b29c58f0911e976e361a5f65
https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/Exchange/Asset.php#L217-L227
train
hail-framework/framework
src/Debugger/Bar/QueryPanel.php
QueryPanel.getColorInRange
public function getColorInRange($value) { $a = [54, 170, 31]; $b = [220, 1, 57]; [$min, $max] = $this->extremes; $d = $max - $min; $lin = ($value - $min) / ($d ?: 0.5); // prevent x/0 $color = []; for ($i = 0; $i < 3; ++$i) { $color[$i] = (int) ($a[$i] + ($b[$i] - $a[$i]) * $lin); } return 'rgb(' . \implode(',', $color) . ')'; }
php
public function getColorInRange($value) { $a = [54, 170, 31]; $b = [220, 1, 57]; [$min, $max] = $this->extremes; $d = $max - $min; $lin = ($value - $min) / ($d ?: 0.5); // prevent x/0 $color = []; for ($i = 0; $i < 3; ++$i) { $color[$i] = (int) ($a[$i] + ($b[$i] - $a[$i]) * $lin); } return 'rgb(' . \implode(',', $color) . ')'; }
[ "public", "function", "getColorInRange", "(", "$", "value", ")", "{", "$", "a", "=", "[", "54", ",", "170", ",", "31", "]", ";", "$", "b", "=", "[", "220", ",", "1", ",", "57", "]", ";", "[", "$", "min", ",", "$", "max", "]", "=", "$", "t...
Linear color gradient @param float $value @return string hex color @internal
[ "Linear", "color", "gradient" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Bar/QueryPanel.php#L91-L104
train
hail-framework/framework
src/Console/Option/OptionParser.php
OptionParser.preprocessingArguments
protected function preprocessingArguments(array $argv) { // preprocessing arguments $newArgv = []; $extra = []; $afterDash = false; foreach ($argv as $arg) { if ($arg === '--') { $afterDash = true; continue; } if ($afterDash) { $extra[] = $arg; continue; } $a = new Argument($arg); if ($a->anyOfOptions($this->specs) && $a->containsOptionValue()) { list($opt, $val) = $a->splitAsOption(); array_push($newArgv, $opt, $val); } else { $newArgv[] = $arg; } } return [$newArgv, $extra]; }
php
protected function preprocessingArguments(array $argv) { // preprocessing arguments $newArgv = []; $extra = []; $afterDash = false; foreach ($argv as $arg) { if ($arg === '--') { $afterDash = true; continue; } if ($afterDash) { $extra[] = $arg; continue; } $a = new Argument($arg); if ($a->anyOfOptions($this->specs) && $a->containsOptionValue()) { list($opt, $val) = $a->splitAsOption(); array_push($newArgv, $opt, $val); } else { $newArgv[] = $arg; } } return [$newArgv, $extra]; }
[ "protected", "function", "preprocessingArguments", "(", "array", "$", "argv", ")", "{", "// preprocessing arguments", "$", "newArgv", "=", "[", "]", ";", "$", "extra", "=", "[", "]", ";", "$", "afterDash", "=", "false", ";", "foreach", "(", "$", "argv", ...
preprocess the argv array - split option and option value - separate arguments after "--"
[ "preprocess", "the", "argv", "array" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Option/OptionParser.php#L104-L130
train
hail-framework/framework
src/I18n/Gettext/Languages/Language.php
Language.getAll
public static function getAll() { $result = []; foreach (\array_keys(CldrData::getLanguageNames()) as $cldrLanguageId) { $result[] = new Language(CldrData::getLanguageInfo($cldrLanguageId)); } return $result; }
php
public static function getAll() { $result = []; foreach (\array_keys(CldrData::getLanguageNames()) as $cldrLanguageId) { $result[] = new Language(CldrData::getLanguageInfo($cldrLanguageId)); } return $result; }
[ "public", "static", "function", "getAll", "(", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "\\", "array_keys", "(", "CldrData", "::", "getLanguageNames", "(", ")", ")", "as", "$", "cldrLanguageId", ")", "{", "$", "result", "[", "]", ...
Return a list of all languages available. @return Language[]
[ "Return", "a", "list", "of", "all", "languages", "available", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Languages/Language.php#L116-L124
train
hail-framework/framework
src/I18n/Gettext/Languages/Language.php
Language.getById
public static function getById($id) { $result = null; $info = CldrData::getLanguageInfo($id); if (isset($info)) { $result = new Language($info); } return $result; }
php
public static function getById($id) { $result = null; $info = CldrData::getLanguageInfo($id); if (isset($info)) { $result = new Language($info); } return $result; }
[ "public", "static", "function", "getById", "(", "$", "id", ")", "{", "$", "result", "=", "null", ";", "$", "info", "=", "CldrData", "::", "getLanguageInfo", "(", "$", "id", ")", ";", "if", "(", "isset", "(", "$", "info", ")", ")", "{", "$", "resu...
Return a Language instance given the language id @param string $id @return Language|null
[ "Return", "a", "Language", "instance", "given", "the", "language", "id" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Languages/Language.php#L133-L142
train
hail-framework/framework
src/I18n/Gettext/Languages/Language.php
Language.buildFormula
private function buildFormula() { $numCategories = \count($this->categories); switch ($numCategories) { case 1: // Just one category return '0'; case 2: return self::reduceFormula(self::reverseFormula($this->categories[0]->formula)); default: $formula = (string) ($numCategories - 1); for ($i = $numCategories - 2; $i >= 0; $i--) { $fl = self::reduceFormula($this->categories[$i]->formula); if (!\preg_match('/^\([^()]+\)$/', $fl)) { $fl = "($fl)"; } $formula = "$fl ? $i : $formula"; if ($i > 0) { $formula = "($formula)"; } } return $formula; } }
php
private function buildFormula() { $numCategories = \count($this->categories); switch ($numCategories) { case 1: // Just one category return '0'; case 2: return self::reduceFormula(self::reverseFormula($this->categories[0]->formula)); default: $formula = (string) ($numCategories - 1); for ($i = $numCategories - 2; $i >= 0; $i--) { $fl = self::reduceFormula($this->categories[$i]->formula); if (!\preg_match('/^\([^()]+\)$/', $fl)) { $fl = "($fl)"; } $formula = "$fl ? $i : $formula"; if ($i > 0) { $formula = "($formula)"; } } return $formula; } }
[ "private", "function", "buildFormula", "(", ")", "{", "$", "numCategories", "=", "\\", "count", "(", "$", "this", "->", "categories", ")", ";", "switch", "(", "$", "numCategories", ")", "{", "case", "1", ":", "// Just one category", "return", "'0'", ";", ...
Build the formula starting from the currently defined categories. @return string
[ "Build", "the", "formula", "starting", "from", "the", "currently", "defined", "categories", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Languages/Language.php#L284-L308
train
hail-framework/framework
src/I18n/Gettext/Languages/Language.php
Language.reverseFormula
private static function reverseFormula($formula) { if (\preg_match('/^n( % \d+)? == \d+(\.\.\d+|,\d+)*?$/', $formula)) { return \str_replace(' == ', ' != ', $formula); } if (\preg_match('/^n( % \d+)? != \d+(\.\.\d+|,\d+)*?$/', $formula)) { return \str_replace(' != ', ' == ', $formula); } if (\preg_match('/^\(?n == \d+ \|\| n == \d+\)?$/', $formula)) { return \trim(\str_replace([' == ', ' || '], [' != ', ' && '], $formula), '()'); } $m = null; if (\preg_match('/^(n(?: % \d+)?) == (\d+) && (n(?: % \d+)?) != (\d+)$/', $formula, $m)) { return "{$m[1]} != {$m[2]} || {$m[3]} == {$m[4]}"; } switch ($formula) { case '(n == 1 || n == 2 || n == 3) || n % 10 != 4 && n % 10 != 6 && n % 10 != 9': return 'n != 1 && n != 2 && n != 3 && (n % 10 == 4 || n % 10 == 6 || n % 10 == 9)'; case '(n == 0 || n == 1) || n >= 11 && n <= 99': return 'n >= 2 && (n < 11 || n > 99)'; } throw new \InvalidArgumentException("Unable to reverse the formula '$formula'"); }
php
private static function reverseFormula($formula) { if (\preg_match('/^n( % \d+)? == \d+(\.\.\d+|,\d+)*?$/', $formula)) { return \str_replace(' == ', ' != ', $formula); } if (\preg_match('/^n( % \d+)? != \d+(\.\.\d+|,\d+)*?$/', $formula)) { return \str_replace(' != ', ' == ', $formula); } if (\preg_match('/^\(?n == \d+ \|\| n == \d+\)?$/', $formula)) { return \trim(\str_replace([' == ', ' || '], [' != ', ' && '], $formula), '()'); } $m = null; if (\preg_match('/^(n(?: % \d+)?) == (\d+) && (n(?: % \d+)?) != (\d+)$/', $formula, $m)) { return "{$m[1]} != {$m[2]} || {$m[3]} == {$m[4]}"; } switch ($formula) { case '(n == 1 || n == 2 || n == 3) || n % 10 != 4 && n % 10 != 6 && n % 10 != 9': return 'n != 1 && n != 2 && n != 3 && (n % 10 == 4 || n % 10 == 6 || n % 10 == 9)'; case '(n == 0 || n == 1) || n >= 11 && n <= 99': return 'n >= 2 && (n < 11 || n > 99)'; } throw new \InvalidArgumentException("Unable to reverse the formula '$formula'"); }
[ "private", "static", "function", "reverseFormula", "(", "$", "formula", ")", "{", "if", "(", "\\", "preg_match", "(", "'/^n( % \\d+)? == \\d+(\\.\\.\\d+|,\\d+)*?$/'", ",", "$", "formula", ")", ")", "{", "return", "\\", "str_replace", "(", "' == '", ",", "' != '"...
Reverse a formula. @param string $formula @throws \InvalidArgumentException @return string
[ "Reverse", "a", "formula", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Languages/Language.php#L318-L340
train
hail-framework/framework
src/I18n/Gettext/Languages/Language.php
Language.getUSAsciiClone
public function getUSAsciiClone() { $clone = clone $this; $clone->name = Strings::toAscii($clone->name); $clone->formula = Strings::toAscii($clone->formula); $clone->categories = []; foreach ($this->categories as $category) { $categoryClone = clone $category; $categoryClone->examples = Strings::toAscii($categoryClone->examples); $clone->categories[] = $categoryClone; } return $clone; }
php
public function getUSAsciiClone() { $clone = clone $this; $clone->name = Strings::toAscii($clone->name); $clone->formula = Strings::toAscii($clone->formula); $clone->categories = []; foreach ($this->categories as $category) { $categoryClone = clone $category; $categoryClone->examples = Strings::toAscii($categoryClone->examples); $clone->categories[] = $categoryClone; } return $clone; }
[ "public", "function", "getUSAsciiClone", "(", ")", "{", "$", "clone", "=", "clone", "$", "this", ";", "$", "clone", "->", "name", "=", "Strings", "::", "toAscii", "(", "$", "clone", "->", "name", ")", ";", "$", "clone", "->", "formula", "=", "Strings...
Returns a clone of this instance with all the strings to US-ASCII. @return Language
[ "Returns", "a", "clone", "of", "this", "instance", "with", "all", "the", "strings", "to", "US", "-", "ASCII", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Languages/Language.php#L365-L378
train
hail-framework/framework
src/Cache/Simple/Riak.php
Riak.isExpired
private function isExpired(Riak\Object $object) { $metadataMap = $object->getMetadataMap(); return isset($metadataMap[self::EXPIRES_HEADER]) && $metadataMap[self::EXPIRES_HEADER] < \time(); }
php
private function isExpired(Riak\Object $object) { $metadataMap = $object->getMetadataMap(); return isset($metadataMap[self::EXPIRES_HEADER]) && $metadataMap[self::EXPIRES_HEADER] < \time(); }
[ "private", "function", "isExpired", "(", "Riak", "\\", "Object", "$", "object", ")", "{", "$", "metadataMap", "=", "$", "object", "->", "getMetadataMap", "(", ")", ";", "return", "isset", "(", "$", "metadataMap", "[", "self", "::", "EXPIRES_HEADER", "]", ...
Check if a given Riak Object have expired. @param \Riak\Object $object @return bool
[ "Check", "if", "a", "given", "Riak", "Object", "have", "expired", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Cache/Simple/Riak.php#L201-L207
train
Becklyn/RadBundle
src/Model/SortableHelper.php
SortableHelper.getNextSortOrder
public function getNextSortOrder (array $where = []) : int { $queryBuild = $this->repository->createQueryBuilder("t") ->select("MAX(t.sortOrder)"); // apply the where clauses if (0 < \count($completeWhere = $this->getCompleteWhere($where))) { $queryParts = []; $index = 0; foreach ($completeWhere as $key => $value) { if (null === $value) { $queryParts[] = "t.{$key} IS NULL"; } else { $queryParts[] = "t.{$key} = :where_value_{$index}"; $queryBuild->setParameter("where_value_{$index}", $value); } ++$index; } $queryBuild->where(\implode(" AND ", $queryParts)); } $currentMaxValue = $queryBuild ->getQuery() ->getSingleScalarResult(); return null !== $currentMaxValue ? 1 + (int) $currentMaxValue : 0; }
php
public function getNextSortOrder (array $where = []) : int { $queryBuild = $this->repository->createQueryBuilder("t") ->select("MAX(t.sortOrder)"); // apply the where clauses if (0 < \count($completeWhere = $this->getCompleteWhere($where))) { $queryParts = []; $index = 0; foreach ($completeWhere as $key => $value) { if (null === $value) { $queryParts[] = "t.{$key} IS NULL"; } else { $queryParts[] = "t.{$key} = :where_value_{$index}"; $queryBuild->setParameter("where_value_{$index}", $value); } ++$index; } $queryBuild->where(\implode(" AND ", $queryParts)); } $currentMaxValue = $queryBuild ->getQuery() ->getSingleScalarResult(); return null !== $currentMaxValue ? 1 + (int) $currentMaxValue : 0; }
[ "public", "function", "getNextSortOrder", "(", "array", "$", "where", "=", "[", "]", ")", ":", "int", "{", "$", "queryBuild", "=", "$", "this", "->", "repository", "->", "createQueryBuilder", "(", "\"t\"", ")", "->", "select", "(", "\"MAX(t.sortOrder)\"", ...
Returns the next sort order value. @param array $where @return int
[ "Returns", "the", "next", "sort", "order", "value", "." ]
34d5887e13f5a4018843b77dcbefc2eb2f3169f4
https://github.com/Becklyn/RadBundle/blob/34d5887e13f5a4018843b77dcbefc2eb2f3169f4/src/Model/SortableHelper.php#L42-L78
train
Becklyn/RadBundle
src/Model/SortableHelper.php
SortableHelper.prependEntities
public function prependEntities (array $prepended, array $where = []) : void { $all = $this->getAllEntities($where); $index = 0; // first prepend foreach ($prepended as $prependedEntity) { $prependedEntity->setSortOrder($index); ++$index; } // then sort the rest foreach ($all as $entity) { if (\in_array($entity, $prepended, true)) { continue; } $entity->setSortOrder($index); ++$index; } }
php
public function prependEntities (array $prepended, array $where = []) : void { $all = $this->getAllEntities($where); $index = 0; // first prepend foreach ($prepended as $prependedEntity) { $prependedEntity->setSortOrder($index); ++$index; } // then sort the rest foreach ($all as $entity) { if (\in_array($entity, $prepended, true)) { continue; } $entity->setSortOrder($index); ++$index; } }
[ "public", "function", "prependEntities", "(", "array", "$", "prepended", ",", "array", "$", "where", "=", "[", "]", ")", ":", "void", "{", "$", "all", "=", "$", "this", "->", "getAllEntities", "(", "$", "where", ")", ";", "$", "index", "=", "0", ";...
Prepends the given entities to the list. @param SortableEntityInterface[] $prepended @param array $where
[ "Prepends", "the", "given", "entities", "to", "the", "list", "." ]
34d5887e13f5a4018843b77dcbefc2eb2f3169f4
https://github.com/Becklyn/RadBundle/blob/34d5887e13f5a4018843b77dcbefc2eb2f3169f4/src/Model/SortableHelper.php#L111-L134
train
Becklyn/RadBundle
src/Model/SortableHelper.php
SortableHelper.applySorting
public function applySorting ($sortMapping, array $where = []) : bool { if (!\is_array($sortMapping) || empty($sortMapping)) { // if value is not in correct format or an empty array. return false; } $all = $this->getAllEntities($where); // check sort values $possibleSortValues = \range(0, \count($all) - 1); if (!$this->arraysAreIdentical($possibleSortValues, \array_values($sortMapping))) { // the given sort values are wrong return false; } // check item ids $allIds = \array_map(function (SortableEntityInterface $entity) { return $entity->getId(); }, $all); if (!$this->arraysAreIdentical($allIds, \array_keys($sortMapping))) { // the given item ids are wrong return false; } foreach ($all as $entity) { $entity->setSortOrder($sortMapping[$entity->getId()]); } return true; }
php
public function applySorting ($sortMapping, array $where = []) : bool { if (!\is_array($sortMapping) || empty($sortMapping)) { // if value is not in correct format or an empty array. return false; } $all = $this->getAllEntities($where); // check sort values $possibleSortValues = \range(0, \count($all) - 1); if (!$this->arraysAreIdentical($possibleSortValues, \array_values($sortMapping))) { // the given sort values are wrong return false; } // check item ids $allIds = \array_map(function (SortableEntityInterface $entity) { return $entity->getId(); }, $all); if (!$this->arraysAreIdentical($allIds, \array_keys($sortMapping))) { // the given item ids are wrong return false; } foreach ($all as $entity) { $entity->setSortOrder($sortMapping[$entity->getId()]); } return true; }
[ "public", "function", "applySorting", "(", "$", "sortMapping", ",", "array", "$", "where", "=", "[", "]", ")", ":", "bool", "{", "if", "(", "!", "\\", "is_array", "(", "$", "sortMapping", ")", "||", "empty", "(", "$", "sortMapping", ")", ")", "{", ...
Applies the sorting. Sort Mapping: entity-id => position (0-based) @param array $sortMapping @param array $where @return bool
[ "Applies", "the", "sorting", "." ]
34d5887e13f5a4018843b77dcbefc2eb2f3169f4
https://github.com/Becklyn/RadBundle/blob/34d5887e13f5a4018843b77dcbefc2eb2f3169f4/src/Model/SortableHelper.php#L149-L183
train
Becklyn/RadBundle
src/Model/SortableHelper.php
SortableHelper.arraysAreIdentical
private function arraysAreIdentical (array $array1, array $array2) : bool { return (0 === \count(\array_diff($array1, $array2))) && (0 === \count(\array_diff($array2, $array1))); }
php
private function arraysAreIdentical (array $array1, array $array2) : bool { return (0 === \count(\array_diff($array1, $array2))) && (0 === \count(\array_diff($array2, $array1))); }
[ "private", "function", "arraysAreIdentical", "(", "array", "$", "array1", ",", "array", "$", "array2", ")", ":", "bool", "{", "return", "(", "0", "===", "\\", "count", "(", "\\", "array_diff", "(", "$", "array1", ",", "$", "array2", ")", ")", ")", "&...
Returns whether two arrays are identical. @param array $array1 @param array $array2 @return bool
[ "Returns", "whether", "two", "arrays", "are", "identical", "." ]
34d5887e13f5a4018843b77dcbefc2eb2f3169f4
https://github.com/Becklyn/RadBundle/blob/34d5887e13f5a4018843b77dcbefc2eb2f3169f4/src/Model/SortableHelper.php#L209-L213
train
hail-framework/framework
src/Console/Option/OptionPrinter.php
OptionPrinter.renderOption
public function renderOption(Option $opt): string { $columns = []; if ($opt->short) { $columns[] = $this->formatter->format('-' . $opt->short, 'strong_white') . $this->renderOptionValueHint($opt, false); } if ($opt->long) { $columns[] = $this->formatter->format('--' . $opt->long, 'strong_white') . $this->renderOptionValueHint($opt, true); } return implode(', ', $columns); }
php
public function renderOption(Option $opt): string { $columns = []; if ($opt->short) { $columns[] = $this->formatter->format('-' . $opt->short, 'strong_white') . $this->renderOptionValueHint($opt, false); } if ($opt->long) { $columns[] = $this->formatter->format('--' . $opt->long, 'strong_white') . $this->renderOptionValueHint($opt, true); } return implode(', ', $columns); }
[ "public", "function", "renderOption", "(", "Option", "$", "opt", ")", ":", "string", "{", "$", "columns", "=", "[", "]", ";", "if", "(", "$", "opt", "->", "short", ")", "{", "$", "columns", "[", "]", "=", "$", "this", "->", "formatter", "->", "fo...
Render readable spec @param Option $opt @return string
[ "Render", "readable", "spec" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Option/OptionPrinter.php#L40-L53
train
hail-framework/framework
src/Image/ImageManager.php
ImageManager.make
public function make($data) { $driver = $this->instance ?? $this->createDriver(); return $driver->init($data); }
php
public function make($data) { $driver = $this->instance ?? $this->createDriver(); return $driver->init($data); }
[ "public", "function", "make", "(", "$", "data", ")", "{", "$", "driver", "=", "$", "this", "->", "instance", "??", "$", "this", "->", "createDriver", "(", ")", ";", "return", "$", "driver", "->", "init", "(", "$", "data", ")", ";", "}" ]
Initiates an Image instance from different input types @param mixed $data @return \Hail\Image\Image
[ "Initiates", "an", "Image", "instance", "from", "different", "input", "types" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Image/ImageManager.php#L81-L86
train
hail-framework/framework
src/Image/ImageManager.php
ImageManager.cache
public function cache(Closure $callback, $lifetime = null, $returnObj = false) { if ($this->imageCache === null) { // create imagecache $this->imageCache = new ImageCache($this); } // run callback if (\is_callable($callback)) { $callback($this->imageCache); } return $this->imageCache->get($lifetime, $returnObj); }
php
public function cache(Closure $callback, $lifetime = null, $returnObj = false) { if ($this->imageCache === null) { // create imagecache $this->imageCache = new ImageCache($this); } // run callback if (\is_callable($callback)) { $callback($this->imageCache); } return $this->imageCache->get($lifetime, $returnObj); }
[ "public", "function", "cache", "(", "Closure", "$", "callback", ",", "$", "lifetime", "=", "null", ",", "$", "returnObj", "=", "false", ")", "{", "if", "(", "$", "this", "->", "imageCache", "===", "null", ")", "{", "// create imagecache", "$", "this", ...
Create new cached image and run callback @param Closure $callback @param int $lifetime @param boolean $returnObj @return Image @throws MissingDependencyException
[ "Create", "new", "cached", "image", "and", "run", "callback" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Image/ImageManager.php#L114-L127
train
hail-framework/framework
src/Database/Migration/Generator.php
Generator.getSchemaFileData
public function getSchemaFileData($settings) { $schemaFile = $this->getSchemaFilename($settings); $fileExt = pathinfo($schemaFile, PATHINFO_EXTENSION); if (!file_exists($schemaFile)) { return []; } if ($fileExt === 'php') { $data = $this->read($schemaFile); } elseif ($fileExt === 'json') { $content = file_get_contents($schemaFile); $data = json_decode($content, true); } else { throw new Exception(sprintf('Invalid schema file extension: %s', $fileExt)); } return $data; }
php
public function getSchemaFileData($settings) { $schemaFile = $this->getSchemaFilename($settings); $fileExt = pathinfo($schemaFile, PATHINFO_EXTENSION); if (!file_exists($schemaFile)) { return []; } if ($fileExt === 'php') { $data = $this->read($schemaFile); } elseif ($fileExt === 'json') { $content = file_get_contents($schemaFile); $data = json_decode($content, true); } else { throw new Exception(sprintf('Invalid schema file extension: %s', $fileExt)); } return $data; }
[ "public", "function", "getSchemaFileData", "(", "$", "settings", ")", "{", "$", "schemaFile", "=", "$", "this", "->", "getSchemaFilename", "(", "$", "settings", ")", ";", "$", "fileExt", "=", "pathinfo", "(", "$", "schemaFile", ",", "PATHINFO_EXTENSION", ")"...
Get schema data. @param array $settings @return array @throws Exception
[ "Get", "schema", "data", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator.php#L190-L209
train
hail-framework/framework
src/Database/Migration/Generator.php
Generator.getSchemaFilename
public function getSchemaFilename($settings) { // Default $schemaFile = sprintf('%s/%s', getcwd(), 'schema.php'); if (!empty($settings['schema_file'])) { $schemaFile = $settings['schema_file']; } return $schemaFile; }
php
public function getSchemaFilename($settings) { // Default $schemaFile = sprintf('%s/%s', getcwd(), 'schema.php'); if (!empty($settings['schema_file'])) { $schemaFile = $settings['schema_file']; } return $schemaFile; }
[ "public", "function", "getSchemaFilename", "(", "$", "settings", ")", "{", "// Default", "$", "schemaFile", "=", "sprintf", "(", "'%s/%s'", ",", "getcwd", "(", ")", ",", "'schema.php'", ")", ";", "if", "(", "!", "empty", "(", "$", "settings", "[", "'sche...
Generate schema filename. @param array $settings @return string Schema filename
[ "Generate", "schema", "filename", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator.php#L218-L227
train
hail-framework/framework
src/Database/Migration/Generator.php
Generator.compareSchema
public function compareSchema($newSchema, $oldSchema) { $this->getOutput()->writeln('Comparing schema file to the database.'); // To add or modify $result = $this->diff($newSchema, $oldSchema); // To remove $result2 = $this->diff($oldSchema, $newSchema); return [$result, $result2]; }
php
public function compareSchema($newSchema, $oldSchema) { $this->getOutput()->writeln('Comparing schema file to the database.'); // To add or modify $result = $this->diff($newSchema, $oldSchema); // To remove $result2 = $this->diff($oldSchema, $newSchema); return [$result, $result2]; }
[ "public", "function", "compareSchema", "(", "$", "newSchema", ",", "$", "oldSchema", ")", "{", "$", "this", "->", "getOutput", "(", ")", "->", "writeln", "(", "'Comparing schema file to the database.'", ")", ";", "// To add or modify", "$", "result", "=", "$", ...
Compare database schemas. @param array $newSchema @param array $oldSchema @return array Difference
[ "Compare", "database", "schemas", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator.php#L249-L260
train
hail-framework/framework
src/Database/Migration/Generator.php
Generator.diff
protected function diff($array1, $array2) { $difference = []; foreach ($array1 as $key => $value) { if (is_array($value)) { if (!isset($array2[$key]) || !is_array($array2[$key])) { $difference[$key] = $value; } else { $new_diff = $this->diff($value, $array2[$key]); if (!empty($new_diff)) { $difference[$key] = $new_diff; } } } else { if (!array_key_exists($key, $array2) || $array2[$key] !== $value) { $difference[$key] = $value; } } } return $difference; }
php
protected function diff($array1, $array2) { $difference = []; foreach ($array1 as $key => $value) { if (is_array($value)) { if (!isset($array2[$key]) || !is_array($array2[$key])) { $difference[$key] = $value; } else { $new_diff = $this->diff($value, $array2[$key]); if (!empty($new_diff)) { $difference[$key] = $new_diff; } } } else { if (!array_key_exists($key, $array2) || $array2[$key] !== $value) { $difference[$key] = $value; } } } return $difference; }
[ "protected", "function", "diff", "(", "$", "array1", ",", "$", "array2", ")", "{", "$", "difference", "=", "[", "]", ";", "foreach", "(", "$", "array1", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")"...
Intersect of recursive arrays. @param array $array1 @param array $array2 @return array
[ "Intersect", "of", "recursive", "arrays", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator.php#L270-L291
train
hail-framework/framework
src/Console/Component/Table/CellAttribute.php
CellAttribute.handleTextOverflow
public function handleTextOverflow($cell, $maxWidth) { $lines = explode("\n", $cell); if ($this->textOverflow == self::WRAP) { $maxLineWidth = max(array_map('mb_strlen', $lines)); if ($maxLineWidth > $maxWidth) { $cell = wordwrap($cell, $maxWidth, "\n"); // Re-explode the lines $lines = explode("\n", $cell); } } elseif ($this->textOverflow == self::ELLIPSIS) { if (mb_strlen($lines[0]) > $maxWidth) { $lines = [mb_substr($lines[0], 0, $maxWidth - 2) . '..']; } } elseif ($this->textOverflow == self::CLIP) { if (mb_strlen($lines[0]) > $maxWidth) { $lines = [mb_substr($lines[0], 0, $maxWidth)]; } } return $lines; }
php
public function handleTextOverflow($cell, $maxWidth) { $lines = explode("\n", $cell); if ($this->textOverflow == self::WRAP) { $maxLineWidth = max(array_map('mb_strlen', $lines)); if ($maxLineWidth > $maxWidth) { $cell = wordwrap($cell, $maxWidth, "\n"); // Re-explode the lines $lines = explode("\n", $cell); } } elseif ($this->textOverflow == self::ELLIPSIS) { if (mb_strlen($lines[0]) > $maxWidth) { $lines = [mb_substr($lines[0], 0, $maxWidth - 2) . '..']; } } elseif ($this->textOverflow == self::CLIP) { if (mb_strlen($lines[0]) > $maxWidth) { $lines = [mb_substr($lines[0], 0, $maxWidth)]; } } return $lines; }
[ "public", "function", "handleTextOverflow", "(", "$", "cell", ",", "$", "maxWidth", ")", "{", "$", "lines", "=", "explode", "(", "\"\\n\"", ",", "$", "cell", ")", ";", "if", "(", "$", "this", "->", "textOverflow", "==", "self", "::", "WRAP", ")", "{"...
When inserting rows, we pre-explode the lines to extra rows from Table hence this method is separated for pre-processing..
[ "When", "inserting", "rows", "we", "pre", "-", "explode", "the", "lines", "to", "extra", "rows", "from", "Table", "hence", "this", "method", "is", "separated", "for", "pre", "-", "processing", ".." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Component/Table/CellAttribute.php#L92-L113
train
DoSomething/gateway
src/Common/RestApiClient.php
RestApiClient.get
public function get($path, $query = [], $withAuthorization = true) { $options = [ 'query' => $query, ]; return $this->send('GET', $path, $options, $withAuthorization); }
php
public function get($path, $query = [], $withAuthorization = true) { $options = [ 'query' => $query, ]; return $this->send('GET', $path, $options, $withAuthorization); }
[ "public", "function", "get", "(", "$", "path", ",", "$", "query", "=", "[", "]", ",", "$", "withAuthorization", "=", "true", ")", "{", "$", "options", "=", "[", "'query'", "=>", "$", "query", ",", "]", ";", "return", "$", "this", "->", "send", "(...
Send a GET request to the given URL. @param string $path - URL to make request to (relative to base URL) @param array $query - Key-value array of query string values @param bool $withAuthorization - Should this request be authorized? @return array
[ "Send", "a", "GET", "request", "to", "the", "given", "URL", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Common/RestApiClient.php#L86-L93
train
DoSomething/gateway
src/Common/RestApiClient.php
RestApiClient.post
public function post($path, $payload = [], $withAuthorization = true) { $options = [ 'json' => $payload, ]; return $this->send('POST', $path, $options, $withAuthorization); }
php
public function post($path, $payload = [], $withAuthorization = true) { $options = [ 'json' => $payload, ]; return $this->send('POST', $path, $options, $withAuthorization); }
[ "public", "function", "post", "(", "$", "path", ",", "$", "payload", "=", "[", "]", ",", "$", "withAuthorization", "=", "true", ")", "{", "$", "options", "=", "[", "'json'", "=>", "$", "payload", ",", "]", ";", "return", "$", "this", "->", "send", ...
Send a POST request to the given URL. @param string $path - URL to make request to (relative to base URL) @param array $payload - Body of the POST request @param bool $withAuthorization - Should this request be authorized? @return array
[ "Send", "a", "POST", "request", "to", "the", "given", "URL", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Common/RestApiClient.php#L103-L110
train
DoSomething/gateway
src/Common/RestApiClient.php
RestApiClient.put
public function put($path, $payload = [], $withAuthorization = true) { $options = [ 'json' => $payload, ]; return $this->send('PUT', $path, $options, $withAuthorization); }
php
public function put($path, $payload = [], $withAuthorization = true) { $options = [ 'json' => $payload, ]; return $this->send('PUT', $path, $options, $withAuthorization); }
[ "public", "function", "put", "(", "$", "path", ",", "$", "payload", "=", "[", "]", ",", "$", "withAuthorization", "=", "true", ")", "{", "$", "options", "=", "[", "'json'", "=>", "$", "payload", ",", "]", ";", "return", "$", "this", "->", "send", ...
Send a PUT request to the given URL. @param string $path - URL to make request to (relative to base URL) @param array $payload - Body of the PUT request @param bool $withAuthorization - Should this request be authorized? @return array
[ "Send", "a", "PUT", "request", "to", "the", "given", "URL", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Common/RestApiClient.php#L120-L127
train
DoSomething/gateway
src/Common/RestApiClient.php
RestApiClient.patch
public function patch($path, $payload = [], $withAuthorization = true) { $options = [ 'json' => $payload, ]; return $this->send('PATCH', $path, $options, $withAuthorization); }
php
public function patch($path, $payload = [], $withAuthorization = true) { $options = [ 'json' => $payload, ]; return $this->send('PATCH', $path, $options, $withAuthorization); }
[ "public", "function", "patch", "(", "$", "path", ",", "$", "payload", "=", "[", "]", ",", "$", "withAuthorization", "=", "true", ")", "{", "$", "options", "=", "[", "'json'", "=>", "$", "payload", ",", "]", ";", "return", "$", "this", "->", "send",...
Send a PATCH request to the given URL. @param string $path - URL to make request to (relative to base URL) @param array $payload - Body of the PUT request @param bool $withAuthorization - Should this request be authorized? @return array
[ "Send", "a", "PATCH", "request", "to", "the", "given", "URL", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Common/RestApiClient.php#L137-L144
train
DoSomething/gateway
src/Common/RestApiClient.php
RestApiClient.delete
public function delete($path, $withAuthorization = true) { $response = $this->send('DELETE', $path, [], $withAuthorization); return $this->responseSuccessful($response); }
php
public function delete($path, $withAuthorization = true) { $response = $this->send('DELETE', $path, [], $withAuthorization); return $this->responseSuccessful($response); }
[ "public", "function", "delete", "(", "$", "path", ",", "$", "withAuthorization", "=", "true", ")", "{", "$", "response", "=", "$", "this", "->", "send", "(", "'DELETE'", ",", "$", "path", ",", "[", "]", ",", "$", "withAuthorization", ")", ";", "retur...
Send a DELETE request to the given URL. @param string $path - URL to make request to (relative to base URL) @param bool $withAuthorization - Should this request be authorized? @return bool
[ "Send", "a", "DELETE", "request", "to", "the", "given", "URL", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Common/RestApiClient.php#L153-L158
train
DoSomething/gateway
src/Common/RestApiClient.php
RestApiClient.handleValidationException
public function handleValidationException($endpoint, $response, $method, $path, $options) { $errors = $response['error']['fields']; throw new ValidationException($errors, $endpoint); }
php
public function handleValidationException($endpoint, $response, $method, $path, $options) { $errors = $response['error']['fields']; throw new ValidationException($errors, $endpoint); }
[ "public", "function", "handleValidationException", "(", "$", "endpoint", ",", "$", "response", ",", "$", "method", ",", "$", "path", ",", "$", "options", ")", "{", "$", "errors", "=", "$", "response", "[", "'error'", "]", "[", "'fields'", "]", ";", "th...
Handle validation exceptions. @param string $endpoint - The human-readable route that triggered the error. @param array $response - The body of the response. @param string $method - The HTTP method for the request that triggered the error, for optionally resending. @param string $path - The path for the request that triggered the error, for optionally resending. @param array $options - The options for the request that triggered the error, for optionally resending. @return \GuzzleHttp\Psr7\Response|void @throws UnauthorizedException
[ "Handle", "validation", "exceptions", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Common/RestApiClient.php#L209-L213
train
DoSomething/gateway
src/Common/RestApiClient.php
RestApiClient.send
public function send($method, $path, $options = [], $withAuthorization = true) { try { // Increment the number of attempts so we can eventually give up. $this->attempts++; // Make the request. Any error code will send us to the 'catch' below. $response = $this->raw($method, $path, $options, $withAuthorization); // Reset the number of attempts back to zero once we've had a successful // response, and then perform any other clean-up. $this->attempts = 0; $this->cleanUp(); return json_decode($response->getBody()->getContents(), true); } catch (\GuzzleHttp\Exception\ClientException $e) { $endpoint = strtoupper($method).' '.$path; $response = json_decode($e->getResponse()->getBody()->getContents(), true); switch ($e->getCode()) { // If the request is bad, throw a generic bad request exception. case 400: throw new BadRequestException($endpoint, json_encode($response)); // If the request is unauthorized, handle it. case 401: return $this->handleUnauthorizedException($endpoint, $response, $method, $path, $options); // If the request is forbidden, throw a generic forbidden exception. case 403: throw new ForbiddenException($endpoint, json_encode($response)); // If the resource doesn't exist, return null. case 404: return null; // If it's a validation error, throw a generic validation error. case 422: return $this->handleValidationException($endpoint, $response, $method, $path, $options); default: throw new InternalException($endpoint, $e->getCode(), $e->getMessage()); } } }
php
public function send($method, $path, $options = [], $withAuthorization = true) { try { // Increment the number of attempts so we can eventually give up. $this->attempts++; // Make the request. Any error code will send us to the 'catch' below. $response = $this->raw($method, $path, $options, $withAuthorization); // Reset the number of attempts back to zero once we've had a successful // response, and then perform any other clean-up. $this->attempts = 0; $this->cleanUp(); return json_decode($response->getBody()->getContents(), true); } catch (\GuzzleHttp\Exception\ClientException $e) { $endpoint = strtoupper($method).' '.$path; $response = json_decode($e->getResponse()->getBody()->getContents(), true); switch ($e->getCode()) { // If the request is bad, throw a generic bad request exception. case 400: throw new BadRequestException($endpoint, json_encode($response)); // If the request is unauthorized, handle it. case 401: return $this->handleUnauthorizedException($endpoint, $response, $method, $path, $options); // If the request is forbidden, throw a generic forbidden exception. case 403: throw new ForbiddenException($endpoint, json_encode($response)); // If the resource doesn't exist, return null. case 404: return null; // If it's a validation error, throw a generic validation error. case 422: return $this->handleValidationException($endpoint, $response, $method, $path, $options); default: throw new InternalException($endpoint, $e->getCode(), $e->getMessage()); } } }
[ "public", "function", "send", "(", "$", "method", ",", "$", "path", ",", "$", "options", "=", "[", "]", ",", "$", "withAuthorization", "=", "true", ")", "{", "try", "{", "// Increment the number of attempts so we can eventually give up.", "$", "this", "->", "a...
Send a Northstar API request, and parse any returned validation errors or status codes to present to the user. @param string $method - 'GET', 'POST', 'PUT', or 'DELETE' @param string $path - URL to make request to (relative to base URL) @param array $options - Guzzle options (http://guzzle.readthedocs.org/en/latest/request-options.html) @param bool $withAuthorization - Should this request be authorized? @return \GuzzleHttp\Psr7\Response|void @throws BadRequestException @throws ForbiddenException @throws InternalException @throws UnauthorizedException @throws ValidationException
[ "Send", "a", "Northstar", "API", "request", "and", "parse", "any", "returned", "validation", "errors", "or", "status", "codes", "to", "present", "to", "the", "user", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Common/RestApiClient.php#L230-L274
train
DoSomething/gateway
src/Common/RestApiClient.php
RestApiClient.raw
public function raw($method, $path, $options, $withAuthorization = true) { // Find what traits this class is using. $class = get_called_class(); $traits = Introspector::getAllClassTraits($class); if (empty($options['headers'])) { // Guzzle doesn't merge default headers with $options array $options['headers'] = $this->defaultHeaders ?: []; } // If these traits have a "hook" (uh oh!), run that before making a request. foreach ($traits as $trait) { $function = 'run'.Introspector::baseName($trait).'Tasks'; if (method_exists($class, $method)) { $this->{$function}($method, $path, $options, $withAuthorization); } } return $this->client->request($method, $path, $options); }
php
public function raw($method, $path, $options, $withAuthorization = true) { // Find what traits this class is using. $class = get_called_class(); $traits = Introspector::getAllClassTraits($class); if (empty($options['headers'])) { // Guzzle doesn't merge default headers with $options array $options['headers'] = $this->defaultHeaders ?: []; } // If these traits have a "hook" (uh oh!), run that before making a request. foreach ($traits as $trait) { $function = 'run'.Introspector::baseName($trait).'Tasks'; if (method_exists($class, $method)) { $this->{$function}($method, $path, $options, $withAuthorization); } } return $this->client->request($method, $path, $options); }
[ "public", "function", "raw", "(", "$", "method", ",", "$", "path", ",", "$", "options", ",", "$", "withAuthorization", "=", "true", ")", "{", "// Find what traits this class is using.", "$", "class", "=", "get_called_class", "(", ")", ";", "$", "traits", "="...
Send a raw API request, without attempting to handle error responses. @param $method @param $path @param array $options @param bool $withAuthorization @return Response
[ "Send", "a", "raw", "API", "request", "without", "attempting", "to", "handle", "error", "responses", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Common/RestApiClient.php#L285-L305
train
hail-framework/framework
src/Filesystem/Adapter/GridFS.php
GridFS.writeObject
protected function writeObject($path, $content, array $metadata) { try { if (\is_resource($content)) { $id = $this->client->storeFile($content, $metadata); } else { $id = $this->client->storeBytes($content, $metadata); } } catch (MongoGridFSException $e) { return false; } $file = $this->client->findOne(['_id' => $id]); return $this->normalizeGridFSFile($file, $path); }
php
protected function writeObject($path, $content, array $metadata) { try { if (\is_resource($content)) { $id = $this->client->storeFile($content, $metadata); } else { $id = $this->client->storeBytes($content, $metadata); } } catch (MongoGridFSException $e) { return false; } $file = $this->client->findOne(['_id' => $id]); return $this->normalizeGridFSFile($file, $path); }
[ "protected", "function", "writeObject", "(", "$", "path", ",", "$", "content", ",", "array", "$", "metadata", ")", "{", "try", "{", "if", "(", "\\", "is_resource", "(", "$", "content", ")", ")", "{", "$", "id", "=", "$", "this", "->", "client", "->...
Write an object to GridFS. @param array $metadata @return array|false normalized file representation
[ "Write", "an", "object", "to", "GridFS", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Adapter/GridFS.php#L216-L231
train
hail-framework/framework
src/Filesystem/Adapter/GridFS.php
GridFS.normalizeGridFSFile
protected function normalizeGridFSFile(MongoGridFSFile $file, $path = null) { $result = [ 'path' => \trim($path ?: $file->getFilename(), '/'), 'type' => 'file', 'size' => $file->getSize(), 'timestamp' => $file->file['uploadDate']->sec, ]; $result['dirname'] = Util::dirname($result['path']); if (isset($file->file['metadata']) && !empty($file->file['metadata']['mimetype'])) { $result['mimetype'] = $file->file['metadata']['mimetype']; } return $result; }
php
protected function normalizeGridFSFile(MongoGridFSFile $file, $path = null) { $result = [ 'path' => \trim($path ?: $file->getFilename(), '/'), 'type' => 'file', 'size' => $file->getSize(), 'timestamp' => $file->file['uploadDate']->sec, ]; $result['dirname'] = Util::dirname($result['path']); if (isset($file->file['metadata']) && !empty($file->file['metadata']['mimetype'])) { $result['mimetype'] = $file->file['metadata']['mimetype']; } return $result; }
[ "protected", "function", "normalizeGridFSFile", "(", "MongoGridFSFile", "$", "file", ",", "$", "path", "=", "null", ")", "{", "$", "result", "=", "[", "'path'", "=>", "\\", "trim", "(", "$", "path", "?", ":", "$", "file", "->", "getFilename", "(", ")",...
Normalize a MongoGridFs file to a response. @param MongoGridFSFile $file @param string $path @return array
[ "Normalize", "a", "MongoGridFs", "file", "to", "a", "response", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Adapter/GridFS.php#L241-L257
train
hail-framework/framework
src/I18n/Gettext/Languages/FormulaConverter.php
FormulaConverter.convertFormula
public static function convertFormula($cldrFormula) { if (\strpbrk($cldrFormula, '()') !== false) { throw new \InvalidArgumentException("Unable to convert the formula '$cldrFormula': parenthesis handling not implemented"); } $orSeparatedChunks = []; foreach (\explode(' or ', $cldrFormula) as $cldrFormulaChunk) { $gettextFormulaChunk = null; $andSeparatedChunks = []; foreach (\explode(' and ', $cldrFormulaChunk) as $cldrAtom) { $gettextAtom = self::convertAtom($cldrAtom); if ($gettextAtom === false) { // One atom joined by 'and' always evaluates to false => the whole 'and' group is always false $gettextFormulaChunk = false; break; } if ($gettextAtom !== true) { $andSeparatedChunks[] = $gettextAtom; } } if (!isset($gettextFormulaChunk)) { if (empty($andSeparatedChunks)) { // All the atoms joined by 'and' always evaluate to true => the whole 'and' group is always true $gettextFormulaChunk = true; } else { $gettextFormulaChunk = \implode(' && ', $andSeparatedChunks); // Special cases simplification switch ($gettextFormulaChunk) { case 'n >= 0 && n <= 2 && n != 2': $gettextFormulaChunk = 'n == 0 || n == 1'; break; } } } if ($gettextFormulaChunk === true) { // One part of the formula joined with the others by 'or' always evaluates to true => the whole formula always evaluates to true return true; } if ($gettextFormulaChunk !== false) { $orSeparatedChunks[] = $gettextFormulaChunk; } } if (empty($orSeparatedChunks)) { // All the parts joined by 'or' always evaluate to false => the whole formula always evaluates to false return false; } return \implode(' || ', $orSeparatedChunks); }
php
public static function convertFormula($cldrFormula) { if (\strpbrk($cldrFormula, '()') !== false) { throw new \InvalidArgumentException("Unable to convert the formula '$cldrFormula': parenthesis handling not implemented"); } $orSeparatedChunks = []; foreach (\explode(' or ', $cldrFormula) as $cldrFormulaChunk) { $gettextFormulaChunk = null; $andSeparatedChunks = []; foreach (\explode(' and ', $cldrFormulaChunk) as $cldrAtom) { $gettextAtom = self::convertAtom($cldrAtom); if ($gettextAtom === false) { // One atom joined by 'and' always evaluates to false => the whole 'and' group is always false $gettextFormulaChunk = false; break; } if ($gettextAtom !== true) { $andSeparatedChunks[] = $gettextAtom; } } if (!isset($gettextFormulaChunk)) { if (empty($andSeparatedChunks)) { // All the atoms joined by 'and' always evaluate to true => the whole 'and' group is always true $gettextFormulaChunk = true; } else { $gettextFormulaChunk = \implode(' && ', $andSeparatedChunks); // Special cases simplification switch ($gettextFormulaChunk) { case 'n >= 0 && n <= 2 && n != 2': $gettextFormulaChunk = 'n == 0 || n == 1'; break; } } } if ($gettextFormulaChunk === true) { // One part of the formula joined with the others by 'or' always evaluates to true => the whole formula always evaluates to true return true; } if ($gettextFormulaChunk !== false) { $orSeparatedChunks[] = $gettextFormulaChunk; } } if (empty($orSeparatedChunks)) { // All the parts joined by 'or' always evaluate to false => the whole formula always evaluates to false return false; } return \implode(' || ', $orSeparatedChunks); }
[ "public", "static", "function", "convertFormula", "(", "$", "cldrFormula", ")", "{", "if", "(", "\\", "strpbrk", "(", "$", "cldrFormula", ",", "'()'", ")", "!==", "false", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Unable to convert th...
Converts a formula from the CLDR representation to the gettext representation. @param string $cldrFormula The CLDR formula to convert. @throws \InvalidArgumentException @return bool|string Returns true if the gettext will always evaluate to true, false if gettext will always evaluate to false, return the gettext formula otherwise.
[ "Converts", "a", "formula", "from", "the", "CLDR", "representation", "to", "the", "gettext", "representation", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Languages/FormulaConverter.php#L18-L69
train
hail-framework/framework
src/I18n/Gettext/Languages/FormulaConverter.php
FormulaConverter.convertAtom
private static function convertAtom($cldrAtom) { $m = null; $gettextAtom = $cldrAtom; $gettextAtom = \str_replace([' = ', 'i'], [' == ', 'n'], $gettextAtom); if (\preg_match('/^n( % \d+)? (!=|==) \d+$/', $gettextAtom)) { return $gettextAtom; } if (\preg_match('/^n( % \d+)? (!=|==) \d+(,\d+|\.\.\d+)+$/', $gettextAtom)) { return self::expandAtom($gettextAtom); } if (\preg_match('/^(?:v|w)(?: % 10+)? == (\d+)(?:\.\.\d+)?$/', $gettextAtom, $m)) { // For gettext: v == 0, w == 0 return ((int) $m[1]) === 0; } if (\preg_match('/^(?:v|w)(?: % 10+)? != (\d+)(?:\.\.\d+)?$/', $gettextAtom, $m)) { // For gettext: v == 0, w == 0 return ((int) $m[1]) !== 0; } if (\preg_match('/^(?:f|t)(?: % 10+)? == (\d+)(?:\.\.\d+)?$/', $gettextAtom, $m)) { // f == empty, t == empty return ((int) $m[1]) === 0; } if (\preg_match('/^(?:f|t)(?: % 10+)? != (\d+)(?:\.\.\d+)?$/', $gettextAtom, $m)) { // f == empty, t == empty return ((int) $m[1]) !== 0; } throw new \InvalidArgumentException("Unable to convert the formula chunk '$cldrAtom' from CLDR to gettext"); }
php
private static function convertAtom($cldrAtom) { $m = null; $gettextAtom = $cldrAtom; $gettextAtom = \str_replace([' = ', 'i'], [' == ', 'n'], $gettextAtom); if (\preg_match('/^n( % \d+)? (!=|==) \d+$/', $gettextAtom)) { return $gettextAtom; } if (\preg_match('/^n( % \d+)? (!=|==) \d+(,\d+|\.\.\d+)+$/', $gettextAtom)) { return self::expandAtom($gettextAtom); } if (\preg_match('/^(?:v|w)(?: % 10+)? == (\d+)(?:\.\.\d+)?$/', $gettextAtom, $m)) { // For gettext: v == 0, w == 0 return ((int) $m[1]) === 0; } if (\preg_match('/^(?:v|w)(?: % 10+)? != (\d+)(?:\.\.\d+)?$/', $gettextAtom, $m)) { // For gettext: v == 0, w == 0 return ((int) $m[1]) !== 0; } if (\preg_match('/^(?:f|t)(?: % 10+)? == (\d+)(?:\.\.\d+)?$/', $gettextAtom, $m)) { // f == empty, t == empty return ((int) $m[1]) === 0; } if (\preg_match('/^(?:f|t)(?: % 10+)? != (\d+)(?:\.\.\d+)?$/', $gettextAtom, $m)) { // f == empty, t == empty return ((int) $m[1]) !== 0; } throw new \InvalidArgumentException("Unable to convert the formula chunk '$cldrAtom' from CLDR to gettext"); }
[ "private", "static", "function", "convertAtom", "(", "$", "cldrAtom", ")", "{", "$", "m", "=", "null", ";", "$", "gettextAtom", "=", "$", "cldrAtom", ";", "$", "gettextAtom", "=", "\\", "str_replace", "(", "[", "' = '", ",", "'i'", "]", ",", "[", "' ...
Converts an atomic part of the CLDR formula to its gettext representation. @param string $cldrAtom The CLDR formula atom to convert. @throws \InvalidArgumentException @return bool|string Returns true if the gettext will always evaluate to true, false if gettext will always evaluate to false, return the gettext formula otherwise.
[ "Converts", "an", "atomic", "part", "of", "the", "CLDR", "formula", "to", "its", "gettext", "representation", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Languages/FormulaConverter.php#L79-L107
train
hail-framework/framework
src/I18n/Gettext/Translations.php
Translations.setLanguage
public function setLanguage($language) { $this->setHeader(self::HEADER_LANGUAGE, trim($language)); if ($info = Language::getById($language)) { return $this->setPluralForms(\count($info->categories), $info->formula); } throw new InvalidArgumentException(sprintf('The language "%s" is not valid', $language)); }
php
public function setLanguage($language) { $this->setHeader(self::HEADER_LANGUAGE, trim($language)); if ($info = Language::getById($language)) { return $this->setPluralForms(\count($info->categories), $info->formula); } throw new InvalidArgumentException(sprintf('The language "%s" is not valid', $language)); }
[ "public", "function", "setLanguage", "(", "$", "language", ")", "{", "$", "this", "->", "setHeader", "(", "self", "::", "HEADER_LANGUAGE", ",", "trim", "(", "$", "language", ")", ")", ";", "if", "(", "$", "info", "=", "Language", "::", "getById", "(", ...
Sets the language and the plural forms. @param string $language @throws InvalidArgumentException if the language hasn't been recognized @return self
[ "Sets", "the", "language", "and", "the", "plural", "forms", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Translations.php#L350-L359
train
hail-framework/framework
src/I18n/Gettext/Translations.php
Translations.countTranslated
public function countTranslated() { $callback = function (Translation $v) { return $v->hasTranslation() ? $v->getTranslation() : null; }; return \count(\array_filter(\get_object_vars($this), $callback)); }
php
public function countTranslated() { $callback = function (Translation $v) { return $v->hasTranslation() ? $v->getTranslation() : null; }; return \count(\array_filter(\get_object_vars($this), $callback)); }
[ "public", "function", "countTranslated", "(", ")", "{", "$", "callback", "=", "function", "(", "Translation", "$", "v", ")", "{", "return", "$", "v", "->", "hasTranslation", "(", ")", "?", "$", "v", "->", "getTranslation", "(", ")", ":", "null", ";", ...
Count all elements translated @return integer
[ "Count", "all", "elements", "translated" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Translations.php#L433-L440
train
cfxmarkets/php-public-models
src/Brokerage/AssetIntent.php
AssetIntent.validateStatus
public function validateStatus() { if ($this->getStatus() === 'closed') { $this->setError('global', 'status-final', $this->getFactory()->newError([ "status" => 400, "title" => "Updates No Longer Permitted", "detail" => "This intent's status is in a final state and you can no longer update it. If you need to update the asset information, create a new intent with the new data." ])); return false; } else { $this->clearError('global', 'status-final'); return true; } }
php
public function validateStatus() { if ($this->getStatus() === 'closed') { $this->setError('global', 'status-final', $this->getFactory()->newError([ "status" => 400, "title" => "Updates No Longer Permitted", "detail" => "This intent's status is in a final state and you can no longer update it. If you need to update the asset information, create a new intent with the new data." ])); return false; } else { $this->clearError('global', 'status-final'); return true; } }
[ "public", "function", "validateStatus", "(", ")", "{", "if", "(", "$", "this", "->", "getStatus", "(", ")", "===", "'closed'", ")", "{", "$", "this", "->", "setError", "(", "'global'", ",", "'status-final'", ",", "$", "this", "->", "getFactory", "(", "...
Check to see if the status of this asset intent permits further updates @return bool
[ "Check", "to", "see", "if", "the", "status", "of", "this", "asset", "intent", "permits", "further", "updates" ]
b91a58f7d9519b98b29c58f0911e976e361a5f65
https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/Brokerage/AssetIntent.php#L227-L239
train
DoSomething/gateway
src/Server/Token.php
Token.getClaim
protected function getClaim($claim) { $token = $this->parseToken(); return $token ? $token->getClaim($claim) : null; }
php
protected function getClaim($claim) { $token = $this->parseToken(); return $token ? $token->getClaim($claim) : null; }
[ "protected", "function", "getClaim", "(", "$", "claim", ")", "{", "$", "token", "=", "$", "this", "->", "parseToken", "(", ")", ";", "return", "$", "token", "?", "$", "token", "->", "getClaim", "(", "$", "claim", ")", ":", "null", ";", "}" ]
Get the given claim from the JWT. @return mixed|null
[ "Get", "the", "given", "claim", "from", "the", "JWT", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Server/Token.php#L128-L133
train
DoSomething/gateway
src/Server/Token.php
Token.parseToken
protected function parseToken() { $request = $this->requestHandler->getRequest(); if (! $request->hasHeader('Authorization')) { return null; } try { // Attempt to parse and validate the JWT $jwt = $request->bearerToken(); $token = (new Parser())->parse($jwt); if (! $token->verify(new Sha256(), file_get_contents($this->publicKey))) { throw new AccessDeniedException( 'Access token could not be verified.', 'Check authorization and resource environment match & that token has not been tampered with.' ); } // Ensure access token hasn't expired $data = new ValidationData(); $data->setCurrentTime(Carbon::now()->timestamp); if ($token->validate($data) === false) { throw new AccessDeniedException('Access token is invalid or expired.'); } // We've made it! Save the details on the validator. return $token; } catch (\InvalidArgumentException $exception) { throw new AccessDeniedException('Could not parse JWT.', $exception->getMessage()); } catch (\RuntimeException $exception) { throw new AccessDeniedException('Error while decoding JWT contents.'); } }
php
protected function parseToken() { $request = $this->requestHandler->getRequest(); if (! $request->hasHeader('Authorization')) { return null; } try { // Attempt to parse and validate the JWT $jwt = $request->bearerToken(); $token = (new Parser())->parse($jwt); if (! $token->verify(new Sha256(), file_get_contents($this->publicKey))) { throw new AccessDeniedException( 'Access token could not be verified.', 'Check authorization and resource environment match & that token has not been tampered with.' ); } // Ensure access token hasn't expired $data = new ValidationData(); $data->setCurrentTime(Carbon::now()->timestamp); if ($token->validate($data) === false) { throw new AccessDeniedException('Access token is invalid or expired.'); } // We've made it! Save the details on the validator. return $token; } catch (\InvalidArgumentException $exception) { throw new AccessDeniedException('Could not parse JWT.', $exception->getMessage()); } catch (\RuntimeException $exception) { throw new AccessDeniedException('Error while decoding JWT contents.'); } }
[ "protected", "function", "parseToken", "(", ")", "{", "$", "request", "=", "$", "this", "->", "requestHandler", "->", "getRequest", "(", ")", ";", "if", "(", "!", "$", "request", "->", "hasHeader", "(", "'Authorization'", ")", ")", "{", "return", "null",...
Parse and validate the token from the request. @throws AccessDeniedHttpException @return JwtToken|null
[ "Parse", "and", "validate", "the", "token", "from", "the", "request", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Server/Token.php#L141-L173
train
hail-framework/framework
src/Http/Client/AbstractClient.php
AbstractClient.doValidateOptions
private function doValidateOptions(array $options = []): array { if ( isset($this->options['curl'], $options['curl']) && \is_array($this->options['curl']) && \is_array($options['curl']) ) { $parameters['curl'] = \array_replace($this->options['curl'], $options['curl']); } $options = \array_replace($this->options, $options); foreach (static::$types as $k => $v) { $type = \gettype($options[$k]); $v = (array) $v; $checked = false; foreach ($v as $t) { if ($t === $type || ($t === 'callable' && \is_callable($options[$k]))) { $checked = true; break; } } if (!$checked) { $should = \implode(', ', $v); throw new InvalidArgumentException("'$k' options should be '$should', but get '$type'"); } } return $options; }
php
private function doValidateOptions(array $options = []): array { if ( isset($this->options['curl'], $options['curl']) && \is_array($this->options['curl']) && \is_array($options['curl']) ) { $parameters['curl'] = \array_replace($this->options['curl'], $options['curl']); } $options = \array_replace($this->options, $options); foreach (static::$types as $k => $v) { $type = \gettype($options[$k]); $v = (array) $v; $checked = false; foreach ($v as $t) { if ($t === $type || ($t === 'callable' && \is_callable($options[$k]))) { $checked = true; break; } } if (!$checked) { $should = \implode(', ', $v); throw new InvalidArgumentException("'$k' options should be '$should', but get '$type'"); } } return $options; }
[ "private", "function", "doValidateOptions", "(", "array", "$", "options", "=", "[", "]", ")", ":", "array", "{", "if", "(", "isset", "(", "$", "this", "->", "options", "[", "'curl'", "]", ",", "$", "options", "[", "'curl'", "]", ")", "&&", "\\", "i...
Validate a set of options and return a array. @param array $options @return array
[ "Validate", "a", "set", "of", "options", "and", "return", "a", "array", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Client/AbstractClient.php#L61-L92
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getTableMigration
public function getTableMigration($output, $new, $old) { if (!empty($this->options['foreign_keys'])) { $output[] = $this->getSetUniqueChecks(0); $output[] = $this->getSetForeignKeyCheck(0); } $output = $this->getTableMigrationNewDatabase($output, $new, $old); $output = $this->getTableMigrationNewTables($output, $new, $old); if (!empty($this->options['foreign_keys'])) { $lines = $this->getForeignKeysMigrations($new, $old); $output = $this->appendLines($output, $lines); } $output = $this->getTableMigrationOldTables($output, $new, $old); if (!empty($this->options['foreign_keys'])) { $output[] = $this->getSetForeignKeyCheck(1); $output[] = $this->getSetUniqueChecks(1); } return $output; }
php
public function getTableMigration($output, $new, $old) { if (!empty($this->options['foreign_keys'])) { $output[] = $this->getSetUniqueChecks(0); $output[] = $this->getSetForeignKeyCheck(0); } $output = $this->getTableMigrationNewDatabase($output, $new, $old); $output = $this->getTableMigrationNewTables($output, $new, $old); if (!empty($this->options['foreign_keys'])) { $lines = $this->getForeignKeysMigrations($new, $old); $output = $this->appendLines($output, $lines); } $output = $this->getTableMigrationOldTables($output, $new, $old); if (!empty($this->options['foreign_keys'])) { $output[] = $this->getSetForeignKeyCheck(1); $output[] = $this->getSetUniqueChecks(1); } return $output; }
[ "public", "function", "getTableMigration", "(", "$", "output", ",", "$", "new", ",", "$", "old", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "options", "[", "'foreign_keys'", "]", ")", ")", "{", "$", "output", "[", "]", "=", "$", "...
Get table migration. @param string[] $output Output @param array $new New schema @param array $old Old schema @return array Output
[ "Get", "table", "migration", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L125-L148
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getAlterDatabaseCharset
protected function getAlterDatabaseCharset($charset, $database = null) { if ($database !== null) { $database = ' ' . $this->dba->ident($database); } $charset = $this->dba->quote($charset); return sprintf("%s\$this->execute(\"ALTER DATABASE%s CHARACTER SET %s;\");", $this->ind2, $database, $charset); }
php
protected function getAlterDatabaseCharset($charset, $database = null) { if ($database !== null) { $database = ' ' . $this->dba->ident($database); } $charset = $this->dba->quote($charset); return sprintf("%s\$this->execute(\"ALTER DATABASE%s CHARACTER SET %s;\");", $this->ind2, $database, $charset); }
[ "protected", "function", "getAlterDatabaseCharset", "(", "$", "charset", ",", "$", "database", "=", "null", ")", "{", "if", "(", "$", "database", "!==", "null", ")", "{", "$", "database", "=", "' '", ".", "$", "this", "->", "dba", "->", "ident", "(", ...
Generate alter database charset. @param string $charset @param string $database @return string
[ "Generate", "alter", "database", "charset", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L258-L266
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getAlterDatabaseCollate
protected function getAlterDatabaseCollate($collate, $database = null) { if ($database) { $database = ' ' . $this->dba->ident($database); } $collate = $this->dba->quote($collate); return sprintf("%s\$this->execute(\"ALTER DATABASE%s COLLATE=%s;\");", $this->ind2, $database, $collate); }
php
protected function getAlterDatabaseCollate($collate, $database = null) { if ($database) { $database = ' ' . $this->dba->ident($database); } $collate = $this->dba->quote($collate); return sprintf("%s\$this->execute(\"ALTER DATABASE%s COLLATE=%s;\");", $this->ind2, $database, $collate); }
[ "protected", "function", "getAlterDatabaseCollate", "(", "$", "collate", ",", "$", "database", "=", "null", ")", "{", "if", "(", "$", "database", ")", "{", "$", "database", "=", "' '", ".", "$", "this", "->", "dba", "->", "ident", "(", "$", "database",...
Generate alter database collate. @param string $collate @param string $database @return string
[ "Generate", "alter", "database", "collate", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L276-L284
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getCreateTable
protected function getCreateTable($output, $table, $tableName, $forceSave = false) { $output[] = $this->getTableVariable($table, $tableName); $alternatePrimaryKeys = $this->getAlternatePrimaryKeys($table); if (empty($alternatePrimaryKeys) || $forceSave) { $output[] = sprintf("%s\$table->save();", $this->ind2); } return $output; }
php
protected function getCreateTable($output, $table, $tableName, $forceSave = false) { $output[] = $this->getTableVariable($table, $tableName); $alternatePrimaryKeys = $this->getAlternatePrimaryKeys($table); if (empty($alternatePrimaryKeys) || $forceSave) { $output[] = sprintf("%s\$table->save();", $this->ind2); } return $output; }
[ "protected", "function", "getCreateTable", "(", "$", "output", ",", "$", "table", ",", "$", "tableName", ",", "$", "forceSave", "=", "false", ")", "{", "$", "output", "[", "]", "=", "$", "this", "->", "getTableVariable", "(", "$", "table", ",", "$", ...
Generate create table. @param array $output @param array $table @param bool $forceSave (false) @return array
[ "Generate", "create", "table", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L328-L338
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getTableVariable
protected function getTableVariable($table, $tableName) { $options = $this->getTableOptions($table); $result = sprintf("%s\$table = \$this->table(\"%s\", %s);", $this->ind2, $tableName, $options); return $result; }
php
protected function getTableVariable($table, $tableName) { $options = $this->getTableOptions($table); $result = sprintf("%s\$table = \$this->table(\"%s\", %s);", $this->ind2, $tableName, $options); return $result; }
[ "protected", "function", "getTableVariable", "(", "$", "table", ",", "$", "tableName", ")", "{", "$", "options", "=", "$", "this", "->", "getTableOptions", "(", "$", "table", ")", ";", "$", "result", "=", "sprintf", "(", "\"%s\\$table = \\$this->table(\\\"%s\\...
Generate create table variable. @param array $table @param string $tableName @return string
[ "Generate", "create", "table", "variable", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L348-L354
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getPhinxTablePrimaryKey
protected function getPhinxTablePrimaryKey($attributes, $table) { $alternatePrimaryKeys = $this->getAlternatePrimaryKeys($table); if (!empty($alternatePrimaryKeys)) { $attributes[] = "'id' => false"; $valueString = '[' . implode(', ', $alternatePrimaryKeys) . ']'; $attributes[] = "'primary_key' => " . $valueString; } return $attributes; }
php
protected function getPhinxTablePrimaryKey($attributes, $table) { $alternatePrimaryKeys = $this->getAlternatePrimaryKeys($table); if (!empty($alternatePrimaryKeys)) { $attributes[] = "'id' => false"; $valueString = '[' . implode(', ', $alternatePrimaryKeys) . ']'; $attributes[] = "'primary_key' => " . $valueString; } return $attributes; }
[ "protected", "function", "getPhinxTablePrimaryKey", "(", "$", "attributes", ",", "$", "table", ")", "{", "$", "alternatePrimaryKeys", "=", "$", "this", "->", "getAlternatePrimaryKeys", "(", "$", "table", ")", ";", "if", "(", "!", "empty", "(", "$", "alternat...
Define table id value @param array $attributes @param array $table @return array Attributes
[ "Define", "table", "id", "value" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L394-L404
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getAlternatePrimaryKeys
protected function getAlternatePrimaryKeys($table) { $alternatePrimaryKey = false; $primaryKeys = []; foreach ($table['columns'] as $column) { $columnName = $column['COLUMN_NAME']; $columnKey = $column['COLUMN_KEY']; if ($columnKey !== 'PRI') { continue; } if ($columnName !== 'id') { $alternatePrimaryKey = true; } $primaryKeys[] = '"' . $columnName . '"'; } if ($alternatePrimaryKey) { return $primaryKeys; } return null; }
php
protected function getAlternatePrimaryKeys($table) { $alternatePrimaryKey = false; $primaryKeys = []; foreach ($table['columns'] as $column) { $columnName = $column['COLUMN_NAME']; $columnKey = $column['COLUMN_KEY']; if ($columnKey !== 'PRI') { continue; } if ($columnName !== 'id') { $alternatePrimaryKey = true; } $primaryKeys[] = '"' . $columnName . '"'; } if ($alternatePrimaryKey) { return $primaryKeys; } return null; }
[ "protected", "function", "getAlternatePrimaryKeys", "(", "$", "table", ")", "{", "$", "alternatePrimaryKey", "=", "false", ";", "$", "primaryKeys", "=", "[", "]", ";", "foreach", "(", "$", "table", "[", "'columns'", "]", "as", "$", "column", ")", "{", "$...
Collect alternate primary keys @param array $table @return array|null
[ "Collect", "alternate", "primary", "keys" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L413-L433
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getPhinxTableComment
protected function getPhinxTableComment($attributes, $table) { if (!empty($table['table']['table_comment'])) { $attributes[] = '\'comment\' => "' . addslashes($table['table']['table_comment']) . '"'; } else { $attributes[] = '\'comment\' => ""'; } return $attributes; }
php
protected function getPhinxTableComment($attributes, $table) { if (!empty($table['table']['table_comment'])) { $attributes[] = '\'comment\' => "' . addslashes($table['table']['table_comment']) . '"'; } else { $attributes[] = '\'comment\' => ""'; } return $attributes; }
[ "protected", "function", "getPhinxTableComment", "(", "$", "attributes", ",", "$", "table", ")", "{", "if", "(", "!", "empty", "(", "$", "table", "[", "'table'", "]", "[", "'table_comment'", "]", ")", ")", "{", "$", "attributes", "[", "]", "=", "'\\'co...
Set a text comment on the table. @param array $attributes @param array $table @return array Attributes
[ "Set", "a", "text", "comment", "on", "the", "table", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L500-L509
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getColumnCreateId
protected function getColumnCreateId($schema, $table, $columnName) { $result = $this->getColumnCreate($schema, $table, $columnName); $output = []; $output[] = sprintf("%sif (\$this->table('%s')->hasColumn('%s')) {", $this->ind2, $result[0], $result[1]); $output[] = sprintf("%s\$this->table(\"%s\")->changeColumn('%s', '%s', %s)->update();", $this->ind3, $result[0], $result[1], $result[2], $result[3]); $output[] = sprintf("%s} else {", $this->ind2); $output[] = sprintf("%s\$this->table(\"%s\")->addColumn('%s', '%s', %s)->update();", $this->ind3, $result[0], $result[1], $result[2], $result[3]); $output[] = sprintf("%s}", $this->ind2); return implode($this->nl, $output); }
php
protected function getColumnCreateId($schema, $table, $columnName) { $result = $this->getColumnCreate($schema, $table, $columnName); $output = []; $output[] = sprintf("%sif (\$this->table('%s')->hasColumn('%s')) {", $this->ind2, $result[0], $result[1]); $output[] = sprintf("%s\$this->table(\"%s\")->changeColumn('%s', '%s', %s)->update();", $this->ind3, $result[0], $result[1], $result[2], $result[3]); $output[] = sprintf("%s} else {", $this->ind2); $output[] = sprintf("%s\$this->table(\"%s\")->addColumn('%s', '%s', %s)->update();", $this->ind3, $result[0], $result[1], $result[2], $result[3]); $output[] = sprintf("%s}", $this->ind2); return implode($this->nl, $output); }
[ "protected", "function", "getColumnCreateId", "(", "$", "schema", ",", "$", "table", ",", "$", "columnName", ")", "{", "$", "result", "=", "$", "this", "->", "getColumnCreate", "(", "$", "schema", ",", "$", "table", ",", "$", "columnName", ")", ";", "$...
Get primary key column update commands. @param array $schema @param string $table @param string $columnName @return string
[ "Get", "primary", "key", "column", "update", "commands", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L571-L584
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getMySQLColumnType
protected function getMySQLColumnType($columnData) { $type = $columnData['COLUMN_TYPE']; $pattern = '/^[a-z]+/'; $match = null; preg_match($pattern, $type, $match); return $match[0]; }
php
protected function getMySQLColumnType($columnData) { $type = $columnData['COLUMN_TYPE']; $pattern = '/^[a-z]+/'; $match = null; preg_match($pattern, $type, $match); return $match[0]; }
[ "protected", "function", "getMySQLColumnType", "(", "$", "columnData", ")", "{", "$", "type", "=", "$", "columnData", "[", "'COLUMN_TYPE'", "]", ";", "$", "pattern", "=", "'/^[a-z]+/'", ";", "$", "match", "=", "null", ";", "preg_match", "(", "$", "pattern"...
Get column type. @param array $columnData @return string
[ "Get", "column", "type", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L649-L657
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getPhinxColumnOptions
protected function getPhinxColumnOptions($phinxType, $columnData, $columns) { $attributes = []; $attributes = $this->getPhinxColumnOptionsNull($attributes, $columnData); // default value $attributes = $this->getPhinxColumnOptionsDefault($attributes, $columnData); // For timestamp columns: $attributes = $this->getPhinxColumnOptionsTimestamp($attributes, $columnData); // limit / length $attributes = $this->getPhinxColumnOptionsLimit($attributes, $columnData); // numeric attributes $attributes = $this->getPhinxColumnOptionsNumeric($attributes, $columnData); // enum values if ($phinxType === 'enum') { $attributes = $this->getOptionEnumValue($attributes, $columnData); } // Collation $attributes = $this->getPhinxColumnCollation($phinxType, $attributes, $columnData); // Encoding $attributes = $this->getPhinxColumnEncoding($phinxType, $attributes, $columnData); // Comment $attributes = $this->getPhinxColumnOptionsComment($attributes, $columnData); // after: specify the column that a new column should be placed after $attributes = $this->getPhinxColumnOptionsAfter($attributes, $columnData, $columns); // @todo // update set an action to be triggered when the row is updated (use with CURRENT_TIMESTAMP) // // For foreign key definitions: // update set an action to be triggered when the row is updated // delete set an action to be triggered when the row is deleted $result = '[' . implode(', ', $attributes) . ']'; return $result; }
php
protected function getPhinxColumnOptions($phinxType, $columnData, $columns) { $attributes = []; $attributes = $this->getPhinxColumnOptionsNull($attributes, $columnData); // default value $attributes = $this->getPhinxColumnOptionsDefault($attributes, $columnData); // For timestamp columns: $attributes = $this->getPhinxColumnOptionsTimestamp($attributes, $columnData); // limit / length $attributes = $this->getPhinxColumnOptionsLimit($attributes, $columnData); // numeric attributes $attributes = $this->getPhinxColumnOptionsNumeric($attributes, $columnData); // enum values if ($phinxType === 'enum') { $attributes = $this->getOptionEnumValue($attributes, $columnData); } // Collation $attributes = $this->getPhinxColumnCollation($phinxType, $attributes, $columnData); // Encoding $attributes = $this->getPhinxColumnEncoding($phinxType, $attributes, $columnData); // Comment $attributes = $this->getPhinxColumnOptionsComment($attributes, $columnData); // after: specify the column that a new column should be placed after $attributes = $this->getPhinxColumnOptionsAfter($attributes, $columnData, $columns); // @todo // update set an action to be triggered when the row is updated (use with CURRENT_TIMESTAMP) // // For foreign key definitions: // update set an action to be triggered when the row is updated // delete set an action to be triggered when the row is deleted $result = '[' . implode(', ', $attributes) . ']'; return $result; }
[ "protected", "function", "getPhinxColumnOptions", "(", "$", "phinxType", ",", "$", "columnData", ",", "$", "columns", ")", "{", "$", "attributes", "=", "[", "]", ";", "$", "attributes", "=", "$", "this", "->", "getPhinxColumnOptionsNull", "(", "$", "attribut...
Generate phinx column options. https://media.readthedocs.org/pdf/phinx/latest/phinx.pdf @param string $phinxType @param array $columnData @param array $columns @return string
[ "Generate", "phinx", "column", "options", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L670-L715
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getColumnLimit
public function getColumnLimit($columnData) { $limit = 0; $type = $this->getMySQLColumnType($columnData); switch ($type) { case 'int': $limit = 'MysqlAdapter::INT_REGULAR'; break; case 'tinyint': $limit = 'MysqlAdapter::INT_TINY'; break; case 'smallint': $limit = 'MysqlAdapter::INT_SMALL'; break; case 'mediumint': $limit = 'MysqlAdapter::INT_MEDIUM'; break; case 'bigint': $limit = 'MysqlAdapter::INT_BIG'; break; case 'tinytext': $limit = 'MysqlAdapter::TEXT_TINY'; break; case 'mediumtext': $limit = 'MysqlAdapter::TEXT_MEDIUM'; break; case 'longtext': $limit = 'MysqlAdapter::TEXT_LONG'; break; case 'longblob': $limit = 'MysqlAdapter::BLOB_LONG'; break; case 'mediumblob': $limit = 'MysqlAdapter::BLOB_MEDIUM'; break; case 'blob': $limit = 'MysqlAdapter::BLOB_REGULAR'; break; case 'tinyblob': $limit = 'MysqlAdapter::BLOB_TINY'; break; default: if (!empty($columnData['CHARACTER_MAXIMUM_LENGTH'])) { $limit = $columnData['CHARACTER_MAXIMUM_LENGTH']; } else { $pattern = '/\((\d+)\)/'; if (preg_match($pattern, $columnData['COLUMN_TYPE'], $match) === 1) { $limit = $match[1]; } } } return $limit; }
php
public function getColumnLimit($columnData) { $limit = 0; $type = $this->getMySQLColumnType($columnData); switch ($type) { case 'int': $limit = 'MysqlAdapter::INT_REGULAR'; break; case 'tinyint': $limit = 'MysqlAdapter::INT_TINY'; break; case 'smallint': $limit = 'MysqlAdapter::INT_SMALL'; break; case 'mediumint': $limit = 'MysqlAdapter::INT_MEDIUM'; break; case 'bigint': $limit = 'MysqlAdapter::INT_BIG'; break; case 'tinytext': $limit = 'MysqlAdapter::TEXT_TINY'; break; case 'mediumtext': $limit = 'MysqlAdapter::TEXT_MEDIUM'; break; case 'longtext': $limit = 'MysqlAdapter::TEXT_LONG'; break; case 'longblob': $limit = 'MysqlAdapter::BLOB_LONG'; break; case 'mediumblob': $limit = 'MysqlAdapter::BLOB_MEDIUM'; break; case 'blob': $limit = 'MysqlAdapter::BLOB_REGULAR'; break; case 'tinyblob': $limit = 'MysqlAdapter::BLOB_TINY'; break; default: if (!empty($columnData['CHARACTER_MAXIMUM_LENGTH'])) { $limit = $columnData['CHARACTER_MAXIMUM_LENGTH']; } else { $pattern = '/\((\d+)\)/'; if (preg_match($pattern, $columnData['COLUMN_TYPE'], $match) === 1) { $limit = $match[1]; } } } return $limit; }
[ "public", "function", "getColumnLimit", "(", "$", "columnData", ")", "{", "$", "limit", "=", "0", ";", "$", "type", "=", "$", "this", "->", "getMySQLColumnType", "(", "$", "columnData", ")", ";", "switch", "(", "$", "type", ")", "{", "case", "'int'", ...
Generate column limit. @param array $columnData @return string
[ "Generate", "column", "limit", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L799-L852
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getUpdateTable
protected function getUpdateTable($output, $table, $tableName) { $output = $this->getCreateTable($output, $table, $tableName, true); return $output; }
php
protected function getUpdateTable($output, $table, $tableName) { $output = $this->getCreateTable($output, $table, $tableName, true); return $output; }
[ "protected", "function", "getUpdateTable", "(", "$", "output", ",", "$", "table", ",", "$", "tableName", ")", "{", "$", "output", "=", "$", "this", "->", "getCreateTable", "(", "$", "output", ",", "$", "table", ",", "$", "tableName", ",", "true", ")", ...
Generate update table. @param array $output @param array $table @param string $tableName @return array
[ "Generate", "update", "table", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L1455-L1460
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getAlterTableEngine
protected function getAlterTableEngine($table, $engine) { $engine = $this->dba->quote($engine); return sprintf("%s\$this->execute(\"ALTER TABLE `%s` ENGINE=%s;\");", $this->ind2, $table, $engine); }
php
protected function getAlterTableEngine($table, $engine) { $engine = $this->dba->quote($engine); return sprintf("%s\$this->execute(\"ALTER TABLE `%s` ENGINE=%s;\");", $this->ind2, $table, $engine); }
[ "protected", "function", "getAlterTableEngine", "(", "$", "table", ",", "$", "engine", ")", "{", "$", "engine", "=", "$", "this", "->", "dba", "->", "quote", "(", "$", "engine", ")", ";", "return", "sprintf", "(", "\"%s\\$this->execute(\\\"ALTER TABLE `%s` ENG...
Generate Alter Table Engine. @param string $table @param string $engine @return string
[ "Generate", "Alter", "Table", "Engine", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L1470-L1475
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getAlterTableCharset
protected function getAlterTableCharset($table, $charset) { $table = $this->dba->ident($table); $charset = $this->dba->quote($charset); return sprintf("%s\$this->execute(\"ALTER TABLE %s CHARSET=%s;\");", $this->ind2, $table, $charset); }
php
protected function getAlterTableCharset($table, $charset) { $table = $this->dba->ident($table); $charset = $this->dba->quote($charset); return sprintf("%s\$this->execute(\"ALTER TABLE %s CHARSET=%s;\");", $this->ind2, $table, $charset); }
[ "protected", "function", "getAlterTableCharset", "(", "$", "table", ",", "$", "charset", ")", "{", "$", "table", "=", "$", "this", "->", "dba", "->", "ident", "(", "$", "table", ")", ";", "$", "charset", "=", "$", "this", "->", "dba", "->", "quote", ...
Generate Alter Table Charset. @param string $table @param string $charset @return string
[ "Generate", "Alter", "Table", "Charset", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L1485-L1491
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getAlterTableCollate
protected function getAlterTableCollate($table, $collate) { $table = $this->dba->ident($table); $collate = $this->dba->quote($collate); return sprintf("%s\$this->execute(\"ALTER TABLE %s COLLATE=%s;\");", $this->ind2, $table, $collate); }
php
protected function getAlterTableCollate($table, $collate) { $table = $this->dba->ident($table); $collate = $this->dba->quote($collate); return sprintf("%s\$this->execute(\"ALTER TABLE %s COLLATE=%s;\");", $this->ind2, $table, $collate); }
[ "protected", "function", "getAlterTableCollate", "(", "$", "table", ",", "$", "collate", ")", "{", "$", "table", "=", "$", "this", "->", "dba", "->", "ident", "(", "$", "table", ")", ";", "$", "collate", "=", "$", "this", "->", "dba", "->", "quote", ...
Generate Alter Table Collate @param string $table @param string $collate @return string
[ "Generate", "Alter", "Table", "Collate" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L1501-L1507
train
hail-framework/framework
src/Database/Migration/Generator/MySqlGenerator.php
MySqlGenerator.getAlterTableComment
protected function getAlterTableComment($table, $comment) { $table = $this->dba->ident($table); $commentSave = $this->dba->quote($comment); return sprintf("%s\$this->execute(\"ALTER TABLE %s COMMENT=%s;\");", $this->ind2, $table, $commentSave); }
php
protected function getAlterTableComment($table, $comment) { $table = $this->dba->ident($table); $commentSave = $this->dba->quote($comment); return sprintf("%s\$this->execute(\"ALTER TABLE %s COMMENT=%s;\");", $this->ind2, $table, $commentSave); }
[ "protected", "function", "getAlterTableComment", "(", "$", "table", ",", "$", "comment", ")", "{", "$", "table", "=", "$", "this", "->", "dba", "->", "ident", "(", "$", "table", ")", ";", "$", "commentSave", "=", "$", "this", "->", "dba", "->", "quot...
Generate alter table comment. @param string $table @param string $comment @return string
[ "Generate", "alter", "table", "comment", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlGenerator.php#L1517-L1523
train
hail-framework/framework
src/I18n/Gettext/Generators/Po.php
Po.multilineQuote
private static function multilineQuote($string) { $lines = \explode("\n", $string); $last = \count($lines) - 1; foreach ($lines as $k => $line) { if ($k === $last) { $lines[$k] = self::convertString($line); } else { $lines[$k] = self::convertString($line . "\n"); } } return $lines; }
php
private static function multilineQuote($string) { $lines = \explode("\n", $string); $last = \count($lines) - 1; foreach ($lines as $k => $line) { if ($k === $last) { $lines[$k] = self::convertString($line); } else { $lines[$k] = self::convertString($line . "\n"); } } return $lines; }
[ "private", "static", "function", "multilineQuote", "(", "$", "string", ")", "{", "$", "lines", "=", "\\", "explode", "(", "\"\\n\"", ",", "$", "string", ")", ";", "$", "last", "=", "\\", "count", "(", "$", "lines", ")", "-", "1", ";", "foreach", "(...
Escapes and adds double quotes to a string. @param string $string @return array
[ "Escapes", "and", "adds", "double", "quotes", "to", "a", "string", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Generators/Po.php#L86-L100
train
hail-framework/framework
src/I18n/Gettext/Generators/Po.php
Po.addLines
private static function addLines(array &$lines, $name, $value) { $newLines = self::multilineQuote($value); if (\count($newLines) === 1) { $lines[] = $name . ' ' . $newLines[0]; } else { $lines[] = $name . ' ""'; foreach ($newLines as $line) { $lines[] = $line; } } }
php
private static function addLines(array &$lines, $name, $value) { $newLines = self::multilineQuote($value); if (\count($newLines) === 1) { $lines[] = $name . ' ' . $newLines[0]; } else { $lines[] = $name . ' ""'; foreach ($newLines as $line) { $lines[] = $line; } } }
[ "private", "static", "function", "addLines", "(", "array", "&", "$", "lines", ",", "$", "name", ",", "$", "value", ")", "{", "$", "newLines", "=", "self", "::", "multilineQuote", "(", "$", "value", ")", ";", "if", "(", "\\", "count", "(", "$", "new...
Add one or more lines depending whether the string is multiline or not. @param array &$lines @param string $name @param string $value
[ "Add", "one", "or", "more", "lines", "depending", "whether", "the", "string", "is", "multiline", "or", "not", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Generators/Po.php#L109-L122
train
hail-framework/framework
src/Image/Commands/PolygonCommand.php
PolygonCommand.execute
public function execute($image) { $points = $this->argument(0)->type('array')->required()->value(); $callback = $this->argument(1)->type('closure')->value(); $vertices_count = count($points); // check if number if coordinates is even if ($vertices_count % 2 !== 0) { throw new \Hail\Image\Exception\InvalidArgumentException( "The number of given polygon vertices must be even." ); } if ($vertices_count < 6) { throw new \Hail\Image\Exception\InvalidArgumentException( "You must have at least 3 points in your array." ); } $namespace = $image->getDriver()->getNamespace(); $polygon_classname = "\{$namespace}\Shapes\PolygonShape"; $polygon = new $polygon_classname($points); if ($callback instanceof Closure) { $callback($polygon); } $polygon->applyToImage($image); return true; }
php
public function execute($image) { $points = $this->argument(0)->type('array')->required()->value(); $callback = $this->argument(1)->type('closure')->value(); $vertices_count = count($points); // check if number if coordinates is even if ($vertices_count % 2 !== 0) { throw new \Hail\Image\Exception\InvalidArgumentException( "The number of given polygon vertices must be even." ); } if ($vertices_count < 6) { throw new \Hail\Image\Exception\InvalidArgumentException( "You must have at least 3 points in your array." ); } $namespace = $image->getDriver()->getNamespace(); $polygon_classname = "\{$namespace}\Shapes\PolygonShape"; $polygon = new $polygon_classname($points); if ($callback instanceof Closure) { $callback($polygon); } $polygon->applyToImage($image); return true; }
[ "public", "function", "execute", "(", "$", "image", ")", "{", "$", "points", "=", "$", "this", "->", "argument", "(", "0", ")", "->", "type", "(", "'array'", ")", "->", "required", "(", ")", "->", "value", "(", ")", ";", "$", "callback", "=", "$"...
Draw a polygon on given image @param \Hail\Image\image $image @return bool
[ "Draw", "a", "polygon", "on", "given", "image" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Image/Commands/PolygonCommand.php#L16-L48
train