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
htmlburger/wpemerge-cli
src/App.php
App.isWordPressThemeDirectory
protected static function isWordPressThemeDirectory( $directory ) { $composer = Composer::getComposerJson( $directory ); if ( ! $composer ) { return false; } if ( $composer['type'] !== 'wordpress-theme' ) { return false; } return true; }
php
protected static function isWordPressThemeDirectory( $directory ) { $composer = Composer::getComposerJson( $directory ); if ( ! $composer ) { return false; } if ( $composer['type'] !== 'wordpress-theme' ) { return false; } return true; }
[ "protected", "static", "function", "isWordPressThemeDirectory", "(", "$", "directory", ")", "{", "$", "composer", "=", "Composer", "::", "getComposerJson", "(", "$", "directory", ")", ";", "if", "(", "!", "$", "composer", ")", "{", "return", "false", ";", ...
Check if a directory is a WordPress theme root. @param string $directory @return boolean
[ "Check", "if", "a", "directory", "is", "a", "WordPress", "theme", "root", "." ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/App.php#L207-L219
train
htmlburger/wpemerge-cli
src/App.php
App.execute
public static function execute( $command, $directory = null, $timeout = 120 ) { $directory = $directory !== null ? $directory : getcwd(); $process = new Process( $command, null, null, null, $timeout ); $process->setWorkingDirectory( $directory ); $process->mustRun(); return $process->getOutput(); }
php
public static function execute( $command, $directory = null, $timeout = 120 ) { $directory = $directory !== null ? $directory : getcwd(); $process = new Process( $command, null, null, null, $timeout ); $process->setWorkingDirectory( $directory ); $process->mustRun(); return $process->getOutput(); }
[ "public", "static", "function", "execute", "(", "$", "command", ",", "$", "directory", "=", "null", ",", "$", "timeout", "=", "120", ")", "{", "$", "directory", "=", "$", "directory", "!==", "null", "?", "$", "directory", ":", "getcwd", "(", ")", ";"...
Run a shell command. @param string $command @param string|null $directory @param integer $timeout @return string
[ "Run", "a", "shell", "command", "." ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/App.php#L229-L237
train
htmlburger/wpemerge-cli
src/App.php
App.liveExecute
public static function liveExecute( $command, OutputInterface $output, $directory = null, $timeout = 120 ) { $directory = $directory !== null ? $directory : getcwd(); $process = new Process( $command, null, null, null, $timeout ); $process->setWorkingDirectory( $directory ); $process->start(); $process->wait( function( $type, $buffer ) use ( $output ) { $output->writeln( $buffer ); } ); if ( ! $process->isSuccessful() ) { throw new ProcessFailedException( $process ); } return $process; }
php
public static function liveExecute( $command, OutputInterface $output, $directory = null, $timeout = 120 ) { $directory = $directory !== null ? $directory : getcwd(); $process = new Process( $command, null, null, null, $timeout ); $process->setWorkingDirectory( $directory ); $process->start(); $process->wait( function( $type, $buffer ) use ( $output ) { $output->writeln( $buffer ); } ); if ( ! $process->isSuccessful() ) { throw new ProcessFailedException( $process ); } return $process; }
[ "public", "static", "function", "liveExecute", "(", "$", "command", ",", "OutputInterface", "$", "output", ",", "$", "directory", "=", "null", ",", "$", "timeout", "=", "120", ")", "{", "$", "directory", "=", "$", "directory", "!==", "null", "?", "$", ...
Run a shell command and return the output as it comes in. @param string $command @param OutputInterface $output @param string|null $directory @param integer $timeout @return Process
[ "Run", "a", "shell", "command", "and", "return", "the", "output", "as", "it", "comes", "in", "." ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/App.php#L248-L264
train
wikimedia/ObjectFactory
src/ObjectFactory.php
ObjectFactory.getObjectFromSpec
public static function getObjectFromSpec( $spec ) { $args = isset( $spec['args'] ) ? $spec['args'] : []; $expandArgs = !isset( $spec['closure_expansion'] ) || $spec['closure_expansion'] === true; if ( $expandArgs ) { $args = static::expandClosures( $args ); } if ( isset( $spec['class'] ) ) { $clazz = $spec['class']; if ( !$args ) { $obj = new $clazz(); } else { $obj = static::constructClassInstance( $clazz, $args ); } } elseif ( isset( $spec['factory'] ) ) { $obj = call_user_func_array( $spec['factory'], $args ); } else { throw new InvalidArgumentException( 'Provided specification lacks both factory and class parameters.' ); } if ( isset( $spec['calls'] ) && is_array( $spec['calls'] ) ) { // Call additional methods on the newly created object foreach ( $spec['calls'] as $method => $margs ) { if ( $expandArgs ) { $margs = static::expandClosures( $margs ); } call_user_func_array( [ $obj, $method ], $margs ); } } return $obj; }
php
public static function getObjectFromSpec( $spec ) { $args = isset( $spec['args'] ) ? $spec['args'] : []; $expandArgs = !isset( $spec['closure_expansion'] ) || $spec['closure_expansion'] === true; if ( $expandArgs ) { $args = static::expandClosures( $args ); } if ( isset( $spec['class'] ) ) { $clazz = $spec['class']; if ( !$args ) { $obj = new $clazz(); } else { $obj = static::constructClassInstance( $clazz, $args ); } } elseif ( isset( $spec['factory'] ) ) { $obj = call_user_func_array( $spec['factory'], $args ); } else { throw new InvalidArgumentException( 'Provided specification lacks both factory and class parameters.' ); } if ( isset( $spec['calls'] ) && is_array( $spec['calls'] ) ) { // Call additional methods on the newly created object foreach ( $spec['calls'] as $method => $margs ) { if ( $expandArgs ) { $margs = static::expandClosures( $margs ); } call_user_func_array( [ $obj, $method ], $margs ); } } return $obj; }
[ "public", "static", "function", "getObjectFromSpec", "(", "$", "spec", ")", "{", "$", "args", "=", "isset", "(", "$", "spec", "[", "'args'", "]", ")", "?", "$", "spec", "[", "'args'", "]", ":", "[", "]", ";", "$", "expandArgs", "=", "!", "isset", ...
Instantiate an object based on a specification array. The specification array must contain a 'class' key with string value that specifies the class name to instantiate or a 'factory' key with a callable (is_callable() === true). It can optionally contain an 'args' key that provides arguments to pass to the constructor/callable. Values in the arguments collection which are Closure instances will be expanded by invoking them with no arguments before passing the resulting value on to the constructor/callable. This can be used to pass IDatabase instances or other live objects to the constructor/callable. This behavior can be suppressed by adding closure_expansion => false to the specification. The specification may also contain a 'calls' key that describes method calls to make on the newly created object before returning it. This pattern is often known as "setter injection". The value of this key is expected to be an associative array with method names as keys and argument lists as values. The argument list will be expanded (or not) in the same way as the 'args' key for the main object. @param array $spec Object specification @return object @throws InvalidArgumentException when object specification does not contain 'class' or 'factory' keys @throws ReflectionException when 'args' are supplied and 'class' constructor is non-public or non-existent
[ "Instantiate", "an", "object", "based", "on", "a", "specification", "array", "." ]
7e7ed475dfa09516f2d06a5cf0b61b8e3afba170
https://github.com/wikimedia/ObjectFactory/blob/7e7ed475dfa09516f2d06a5cf0b61b8e3afba170/src/ObjectFactory.php#L64-L99
train
wikimedia/ObjectFactory
src/ObjectFactory.php
ObjectFactory.expandClosures
protected static function expandClosures( $list ) { return array_map( function ( $value ) { if ( is_object( $value ) && $value instanceof Closure ) { // If $value is a Closure, call it. return $value(); } else { return $value; } }, $list ); }
php
protected static function expandClosures( $list ) { return array_map( function ( $value ) { if ( is_object( $value ) && $value instanceof Closure ) { // If $value is a Closure, call it. return $value(); } else { return $value; } }, $list ); }
[ "protected", "static", "function", "expandClosures", "(", "$", "list", ")", "{", "return", "array_map", "(", "function", "(", "$", "value", ")", "{", "if", "(", "is_object", "(", "$", "value", ")", "&&", "$", "value", "instanceof", "Closure", ")", "{", ...
Iterate a list and call any closures it contains. @param array $list List of things @return array List with any Closures replaced with their output
[ "Iterate", "a", "list", "and", "call", "any", "closures", "it", "contains", "." ]
7e7ed475dfa09516f2d06a5cf0b61b8e3afba170
https://github.com/wikimedia/ObjectFactory/blob/7e7ed475dfa09516f2d06a5cf0b61b8e3afba170/src/ObjectFactory.php#L107-L116
train
wikimedia/ObjectFactory
src/ObjectFactory.php
ObjectFactory.constructClassInstance
public static function constructClassInstance( $clazz, $args ) { // $args should be a non-associative array; show nice error if that's not the case if ( $args && array_keys( $args ) !== range( 0, count( $args ) - 1 ) ) { throw new InvalidArgumentException( __METHOD__ . ': $args cannot be an associative array' ); } return new $clazz( ...$args ); }
php
public static function constructClassInstance( $clazz, $args ) { // $args should be a non-associative array; show nice error if that's not the case if ( $args && array_keys( $args ) !== range( 0, count( $args ) - 1 ) ) { throw new InvalidArgumentException( __METHOD__ . ': $args cannot be an associative array' ); } return new $clazz( ...$args ); }
[ "public", "static", "function", "constructClassInstance", "(", "$", "clazz", ",", "$", "args", ")", "{", "// $args should be a non-associative array; show nice error if that's not the case", "if", "(", "$", "args", "&&", "array_keys", "(", "$", "args", ")", "!==", "ra...
Construct an instance of the given class using the given arguments. @param string $clazz Class name @param array $args Constructor arguments @return mixed Constructed instance
[ "Construct", "an", "instance", "of", "the", "given", "class", "using", "the", "given", "arguments", "." ]
7e7ed475dfa09516f2d06a5cf0b61b8e3afba170
https://github.com/wikimedia/ObjectFactory/blob/7e7ed475dfa09516f2d06a5cf0b61b8e3afba170/src/ObjectFactory.php#L125-L132
train
cedx/enum.php
lib/EnumTrait.php
EnumTrait.getEntries
final static function getEntries(): array { static $entries; if (!isset($entries)) { $entries = []; foreach ((new \ReflectionClass(static::class))->getConstants() as $name => $value) { $reflection = new \ReflectionClassConstant(static::class, $name); if ($reflection->isPublic()) $entries[$name] = $reflection->getValue(); } } return $entries; }
php
final static function getEntries(): array { static $entries; if (!isset($entries)) { $entries = []; foreach ((new \ReflectionClass(static::class))->getConstants() as $name => $value) { $reflection = new \ReflectionClassConstant(static::class, $name); if ($reflection->isPublic()) $entries[$name] = $reflection->getValue(); } } return $entries; }
[ "final", "static", "function", "getEntries", "(", ")", ":", "array", "{", "static", "$", "entries", ";", "if", "(", "!", "isset", "(", "$", "entries", ")", ")", "{", "$", "entries", "=", "[", "]", ";", "foreach", "(", "(", "new", "\\", "ReflectionC...
Gets an associative array of the pairs of names and values of the constants in this enumeration. @return array An associative array that contains the pairs of names and values of the constants in this enumeration.
[ "Gets", "an", "associative", "array", "of", "the", "pairs", "of", "names", "and", "values", "of", "the", "constants", "in", "this", "enumeration", "." ]
96ad9b95bb140ef009148aaa66598c7bbbd21c5a
https://github.com/cedx/enum.php/blob/96ad9b95bb140ef009148aaa66598c7bbbd21c5a/lib/EnumTrait.php#L44-L55
train
cedx/enum.php
lib/EnumTrait.php
EnumTrait.getIndex
final static function getIndex($value): int { $index = array_search($value, static::getValues(), true); return $index !== false ? $index : -1; }
php
final static function getIndex($value): int { $index = array_search($value, static::getValues(), true); return $index !== false ? $index : -1; }
[ "final", "static", "function", "getIndex", "(", "$", "value", ")", ":", "int", "{", "$", "index", "=", "array_search", "(", "$", "value", ",", "static", "::", "getValues", "(", ")", ",", "true", ")", ";", "return", "$", "index", "!==", "false", "?", ...
Gets the zero-based position of the constant in this enumeration that has the specified value. @param mixed $value The value of a constant in this enumeration. @return int The zero-based position of the constant that has the specified value, or `-1` if no such constant is found.
[ "Gets", "the", "zero", "-", "based", "position", "of", "the", "constant", "in", "this", "enumeration", "that", "has", "the", "specified", "value", "." ]
96ad9b95bb140ef009148aaa66598c7bbbd21c5a
https://github.com/cedx/enum.php/blob/96ad9b95bb140ef009148aaa66598c7bbbd21c5a/lib/EnumTrait.php#L62-L65
train
hail-framework/framework
src/Image/Commands/EllipseCommand.php
EllipseCommand.execute
public function execute($image) { $width = $this->argument(0)->type('numeric')->required()->value(); $height = $this->argument(1)->type('numeric')->required()->value(); $x = $this->argument(2)->type('numeric')->required()->value(); $y = $this->argument(3)->type('numeric')->required()->value(); $callback = $this->argument(4)->type('closure')->value(); $namespace = $image->getDriver()->getNamespace(); $ellipse_classname = "\{$namespace}\Shapes\EllipseShape"; $ellipse = new $ellipse_classname($width, $height); if ($callback instanceof Closure) { $callback($ellipse); } $ellipse->applyToImage($image, $x, $y); return true; }
php
public function execute($image) { $width = $this->argument(0)->type('numeric')->required()->value(); $height = $this->argument(1)->type('numeric')->required()->value(); $x = $this->argument(2)->type('numeric')->required()->value(); $y = $this->argument(3)->type('numeric')->required()->value(); $callback = $this->argument(4)->type('closure')->value(); $namespace = $image->getDriver()->getNamespace(); $ellipse_classname = "\{$namespace}\Shapes\EllipseShape"; $ellipse = new $ellipse_classname($width, $height); if ($callback instanceof Closure) { $callback($ellipse); } $ellipse->applyToImage($image, $x, $y); return true; }
[ "public", "function", "execute", "(", "$", "image", ")", "{", "$", "width", "=", "$", "this", "->", "argument", "(", "0", ")", "->", "type", "(", "'numeric'", ")", "->", "required", "(", ")", "->", "value", "(", ")", ";", "$", "height", "=", "$",...
Draws ellipse on given image @param \Hail\Image\Image $image @return bool
[ "Draws", "ellipse", "on", "given", "image" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Image/Commands/EllipseCommand.php#L16-L36
train
Kajna/K-Core
Core/Core/Core.php
Core.getInstance
public static function getInstance(Container $container = null) { if (null === self::$instance) { self::$instance = new Core($container); } return self::$instance; }
php
public static function getInstance(Container $container = null) { if (null === self::$instance) { self::$instance = new Core($container); } return self::$instance; }
[ "public", "static", "function", "getInstance", "(", "Container", "$", "container", "=", "null", ")", "{", "if", "(", "null", "===", "self", "::", "$", "instance", ")", "{", "self", "::", "$", "instance", "=", "new", "Core", "(", "$", "container", ")", ...
Get singleton instance of Core class. @param Container|null $container @return Core
[ "Get", "singleton", "instance", "of", "Core", "class", "." ]
6a354056cf95e471b9b1eb372c5626123fd77df2
https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Core/Core.php#L81-L87
train
Kajna/K-Core
Core/Core/Core.php
Core.execute
public function execute($silent = false) { try { // Execute middleware stack /** @var callable $start */ $start = $this->middleware->top(); $response = $start(); } catch (NotFoundException $e) { $response = $this->notFound($e); } catch (Exception $e) { $response = $this->internalError($e); } // Send response if (isset($response) && !$silent) { if (!$response instanceof ResponseInterface) { throw new Exception("Controllers, hooks and middleware must return instance of ResponseInterface"); } $response->send(); } // Post response hook. if (isset($this->hooks['after.execute'])) { $this->hooks['after.execute'](); } return $response; }
php
public function execute($silent = false) { try { // Execute middleware stack /** @var callable $start */ $start = $this->middleware->top(); $response = $start(); } catch (NotFoundException $e) { $response = $this->notFound($e); } catch (Exception $e) { $response = $this->internalError($e); } // Send response if (isset($response) && !$silent) { if (!$response instanceof ResponseInterface) { throw new Exception("Controllers, hooks and middleware must return instance of ResponseInterface"); } $response->send(); } // Post response hook. if (isset($this->hooks['after.execute'])) { $this->hooks['after.execute'](); } return $response; }
[ "public", "function", "execute", "(", "$", "silent", "=", "false", ")", "{", "try", "{", "// Execute middleware stack", "/** @var callable $start */", "$", "start", "=", "$", "this", "->", "middleware", "->", "top", "(", ")", ";", "$", "response", "=", "$", ...
Route request and execute associated action. @param bool $silent @return ResponseInterface @throws Exception
[ "Route", "request", "and", "execute", "associated", "action", "." ]
6a354056cf95e471b9b1eb372c5626123fd77df2
https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Core/Core.php#L96-L123
train
Kajna/K-Core
Core/Core/Core.php
Core.notFound
protected function notFound(NotFoundException $e) { if (isset($this->hooks['not.found'])) { return $this->hooks['not.found']($e); } else { return (new Response()) ->setStatusCode(404) ->setBody($e->getMessage()); } }
php
protected function notFound(NotFoundException $e) { if (isset($this->hooks['not.found'])) { return $this->hooks['not.found']($e); } else { return (new Response()) ->setStatusCode(404) ->setBody($e->getMessage()); } }
[ "protected", "function", "notFound", "(", "NotFoundException", "$", "e", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "hooks", "[", "'not.found'", "]", ")", ")", "{", "return", "$", "this", "->", "hooks", "[", "'not.found'", "]", "(", "$", "...
Handle 404. @param NotFoundException $e @return ResponseInterface
[ "Handle", "404", "." ]
6a354056cf95e471b9b1eb372c5626123fd77df2
https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Core/Core.php#L170-L179
train
hail-framework/framework
src/Image/Commands/RectangleCommand.php
RectangleCommand.execute
public function execute($image) { $x1 = $this->argument(0)->type('numeric')->required()->value(); $y1 = $this->argument(1)->type('numeric')->required()->value(); $x2 = $this->argument(2)->type('numeric')->required()->value(); $y2 = $this->argument(3)->type('numeric')->required()->value(); $callback = $this->argument(4)->type('closure')->value(); $namespace = $image->getDriver()->getNamespace(); $rectangle_classname = "\{$namespace}\Shapes\RectangleShape"; $rectangle = new $rectangle_classname($x1, $y1, $x2, $y2); if ($callback instanceof Closure) { $callback($rectangle); } $rectangle->applyToImage($image, $x1, $y1); return true; }
php
public function execute($image) { $x1 = $this->argument(0)->type('numeric')->required()->value(); $y1 = $this->argument(1)->type('numeric')->required()->value(); $x2 = $this->argument(2)->type('numeric')->required()->value(); $y2 = $this->argument(3)->type('numeric')->required()->value(); $callback = $this->argument(4)->type('closure')->value(); $namespace = $image->getDriver()->getNamespace(); $rectangle_classname = "\{$namespace}\Shapes\RectangleShape"; $rectangle = new $rectangle_classname($x1, $y1, $x2, $y2); if ($callback instanceof Closure) { $callback($rectangle); } $rectangle->applyToImage($image, $x1, $y1); return true; }
[ "public", "function", "execute", "(", "$", "image", ")", "{", "$", "x1", "=", "$", "this", "->", "argument", "(", "0", ")", "->", "type", "(", "'numeric'", ")", "->", "required", "(", ")", "->", "value", "(", ")", ";", "$", "y1", "=", "$", "thi...
Draws rectangle on given image @param \Hail\Image\Image $image @return bool
[ "Draws", "rectangle", "on", "given", "image" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Image/Commands/RectangleCommand.php#L16-L36
train
hail-framework/framework
src/Redis/Sentinel.php
Sentinel.createMasterClient
public function createMasterClient($name) { $master = $this->getMasterAddressByName($name); if (!isset($master[0], $master[1])) { throw new RedisException('Master not found'); } return Factory::client([ 'host' => $master[0], 'port' => $master[1], 'timeout' => $this->timeout, 'persistent' => $this->persistent, 'database' => $this->database, 'password' => $this->getPassword(), ]); }
php
public function createMasterClient($name) { $master = $this->getMasterAddressByName($name); if (!isset($master[0], $master[1])) { throw new RedisException('Master not found'); } return Factory::client([ 'host' => $master[0], 'port' => $master[1], 'timeout' => $this->timeout, 'persistent' => $this->persistent, 'database' => $this->database, 'password' => $this->getPassword(), ]); }
[ "public", "function", "createMasterClient", "(", "$", "name", ")", "{", "$", "master", "=", "$", "this", "->", "getMasterAddressByName", "(", "$", "name", ")", ";", "if", "(", "!", "isset", "(", "$", "master", "[", "0", "]", ",", "$", "master", "[", ...
Discover the master node automatically and return an instance of Credis_Client that connects to the master @param string $name @return RedisInterface @throws RedisException
[ "Discover", "the", "master", "node", "automatically", "and", "return", "an", "instance", "of", "Credis_Client", "that", "connects", "to", "the", "master" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Redis/Sentinel.php#L127-L142
train
hail-framework/framework
src/Redis/Sentinel.php
Sentinel.getMasterClient
public function getMasterClient($name) { if (!isset($this->master[$name])) { $this->master[$name] = $this->createMasterClient($name); } return $this->master[$name]; }
php
public function getMasterClient($name) { if (!isset($this->master[$name])) { $this->master[$name] = $this->createMasterClient($name); } return $this->master[$name]; }
[ "public", "function", "getMasterClient", "(", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "master", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "master", "[", "$", "name", "]", "=", "$", "this", "->", "c...
If a Credis_Client object exists for a master, return it. Otherwise create one and return it @param string $name @return Client @throws RedisException
[ "If", "a", "Credis_Client", "object", "exists", "for", "a", "master", "return", "it", ".", "Otherwise", "create", "one", "and", "return", "it" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Redis/Sentinel.php#L152-L159
train
hail-framework/framework
src/Redis/Sentinel.php
Sentinel.createSlaveClients
public function createSlaveClients($name) { $slaves = $this->slaves($name); $workingSlaves = []; foreach ($slaves as $slave) { if (!isset($slave[9])) { throw new RedisException('Can\' retrieve slave status'); } if (\strpos($slave[9], 's_down') === false && \strpos($slave[9], 'disconnected') === false) { $workingSlaves[] = Factory::client([ 'host' => $slave[3], 'port' => $slave[5], 'timeout' => $this->timeout, 'persistent' => $this->persistent, 'database' => $this->database, 'password' => $this->getPassword(), ]); } } return $workingSlaves; }
php
public function createSlaveClients($name) { $slaves = $this->slaves($name); $workingSlaves = []; foreach ($slaves as $slave) { if (!isset($slave[9])) { throw new RedisException('Can\' retrieve slave status'); } if (\strpos($slave[9], 's_down') === false && \strpos($slave[9], 'disconnected') === false) { $workingSlaves[] = Factory::client([ 'host' => $slave[3], 'port' => $slave[5], 'timeout' => $this->timeout, 'persistent' => $this->persistent, 'database' => $this->database, 'password' => $this->getPassword(), ]); } } return $workingSlaves; }
[ "public", "function", "createSlaveClients", "(", "$", "name", ")", "{", "$", "slaves", "=", "$", "this", "->", "slaves", "(", "$", "name", ")", ";", "$", "workingSlaves", "=", "[", "]", ";", "foreach", "(", "$", "slaves", "as", "$", "slave", ")", "...
Discover the slave nodes automatically and return an array of Credis_Client objects @param string $name @return RedisInterface[] @throws RedisException
[ "Discover", "the", "slave", "nodes", "automatically", "and", "return", "an", "array", "of", "Credis_Client", "objects" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Redis/Sentinel.php#L169-L190
train
hail-framework/framework
src/Redis/Sentinel.php
Sentinel.getSlaveClients
public function getSlaveClients($name) { if (!isset($this->slaves[$name])) { $this->slaves[$name] = $this->createSlaveClients($name); } return $this->slaves[$name]; }
php
public function getSlaveClients($name) { if (!isset($this->slaves[$name])) { $this->slaves[$name] = $this->createSlaveClients($name); } return $this->slaves[$name]; }
[ "public", "function", "getSlaveClients", "(", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "slaves", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "slaves", "[", "$", "name", "]", "=", "$", "this", "->", "c...
If an array of Credis_Client objects exist for a set of slaves, return them. Otherwise create and return them @param string $name @return Client[] @throws RedisException
[ "If", "an", "array", "of", "Credis_Client", "objects", "exist", "for", "a", "set", "of", "slaves", "return", "them", ".", "Otherwise", "create", "and", "return", "them" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Redis/Sentinel.php#L200-L207
train
hail-framework/framework
src/Redis/Sentinel.php
Sentinel.info
public function info($section = null) { if ($section) { return $this->client->info($section); } return $this->client->info(); }
php
public function info($section = null) { if ($section) { return $this->client->info($section); } return $this->client->info(); }
[ "public", "function", "info", "(", "$", "section", "=", "null", ")", "{", "if", "(", "$", "section", ")", "{", "return", "$", "this", "->", "client", "->", "info", "(", "$", "section", ")", ";", "}", "return", "$", "this", "->", "client", "->", "...
get information block for the sentinel instance @param string|NUll $section @return array
[ "get", "information", "block", "for", "the", "sentinel", "instance" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Redis/Sentinel.php#L232-L239
train
hail-framework/framework
src/Console/CommandTrait.php
CommandTrait.name
public function name(): string { static $name = null; if ($name === null) { // Extract command name from the class name. $class = substr(strrchr(static::class, '\\'), 1); $name = CommandLoader::inverseTranslate($class); } return $name; }
php
public function name(): string { static $name = null; if ($name === null) { // Extract command name from the class name. $class = substr(strrchr(static::class, '\\'), 1); $name = CommandLoader::inverseTranslate($class); } return $name; }
[ "public", "function", "name", "(", ")", ":", "string", "{", "static", "$", "name", "=", "null", ";", "if", "(", "$", "name", "===", "null", ")", "{", "// Extract command name from the class name.", "$", "class", "=", "substr", "(", "strrchr", "(", "static"...
Translate current class name to command name. @return string command name
[ "Translate", "current", "class", "name", "to", "command", "name", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/CommandTrait.php#L132-L142
train
hail-framework/framework
src/Console/CommandTrait.php
CommandTrait.addCommandGroup
public function addCommandGroup($groupName, $commands = []) { $group = new CommandGroup($groupName); foreach ($commands as $val) { $cmd = $this->addCommand($val); $group->addCommand($cmd); } $this->commandGroups[] = $group; return $group; }
php
public function addCommandGroup($groupName, $commands = []) { $group = new CommandGroup($groupName); foreach ($commands as $val) { $cmd = $this->addCommand($val); $group->addCommand($cmd); } $this->commandGroups[] = $group; return $group; }
[ "public", "function", "addCommandGroup", "(", "$", "groupName", ",", "$", "commands", "=", "[", "]", ")", "{", "$", "group", "=", "new", "CommandGroup", "(", "$", "groupName", ")", ";", "foreach", "(", "$", "commands", "as", "$", "val", ")", "{", "$"...
Add a command group and register the commands automatically @param string $groupName The group name @param array $commands Command array combines indexed command names or command class assoc array. @return CommandGroup
[ "Add", "a", "command", "group", "and", "register", "the", "commands", "automatically" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/CommandTrait.php#L161-L171
train
hail-framework/framework
src/Console/CommandTrait.php
CommandTrait.getApplication
public function getApplication(): ?Application { if ($this instanceof Application) { return $this; } if ($p = $this->parent) { return $p->getApplication(); } return null; }
php
public function getApplication(): ?Application { if ($this instanceof Application) { return $this; } if ($p = $this->parent) { return $p->getApplication(); } return null; }
[ "public", "function", "getApplication", "(", ")", ":", "?", "Application", "{", "if", "(", "$", "this", "instanceof", "Application", ")", "{", "return", "$", "this", ";", "}", "if", "(", "$", "p", "=", "$", "this", "->", "parent", ")", "{", "return",...
Get the main application object from parents or the object itself. @return Application|null
[ "Get", "the", "main", "application", "object", "from", "parents", "or", "the", "object", "itself", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/CommandTrait.php#L188-L199
train
hail-framework/framework
src/Console/CommandTrait.php
CommandTrait.connectCommand
public function connectCommand(Command $cmd) { $name = $cmd->name(); $this->commands[$name] = $cmd; // regsiter command aliases to the alias table. $aliases = $cmd->aliases(); if (is_string($aliases)) { $aliases = preg_split('/\s+/', $aliases); } if (!is_array($aliases)) { throw new InvalidArgumentException('Aliases needs to be an array or a space-separated string.'); } foreach ($aliases as $alias) { $this->aliases[$alias] = $cmd; } }
php
public function connectCommand(Command $cmd) { $name = $cmd->name(); $this->commands[$name] = $cmd; // regsiter command aliases to the alias table. $aliases = $cmd->aliases(); if (is_string($aliases)) { $aliases = preg_split('/\s+/', $aliases); } if (!is_array($aliases)) { throw new InvalidArgumentException('Aliases needs to be an array or a space-separated string.'); } foreach ($aliases as $alias) { $this->aliases[$alias] = $cmd; } }
[ "public", "function", "connectCommand", "(", "Command", "$", "cmd", ")", "{", "$", "name", "=", "$", "cmd", "->", "name", "(", ")", ";", "$", "this", "->", "commands", "[", "$", "name", "]", "=", "$", "cmd", ";", "// regsiter command aliases to the alias...
connectCommand connects a command name with a command object. @param Command $cmd
[ "connectCommand", "connects", "a", "command", "name", "with", "a", "command", "object", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/CommandTrait.php#L320-L338
train
hail-framework/framework
src/Console/CommandTrait.php
CommandTrait.aggregate
public function aggregate() { $commands = []; foreach ($this->getVisibleCommands() as $name => $cmd) { $commands[$name] = $cmd; } foreach ($this->commandGroups as $g) { if ($g->isHidden) { continue; } foreach ($g->getCommands() as $name => $cmd) { unset($commands[$name]); } } uasort($this->commandGroups, function ($a, $b) { if ($a->getId() === 'dev') { return 1; } return 0; }); return [ 'groups' => $this->commandGroups, 'commands' => $commands, ]; }
php
public function aggregate() { $commands = []; foreach ($this->getVisibleCommands() as $name => $cmd) { $commands[$name] = $cmd; } foreach ($this->commandGroups as $g) { if ($g->isHidden) { continue; } foreach ($g->getCommands() as $name => $cmd) { unset($commands[$name]); } } uasort($this->commandGroups, function ($a, $b) { if ($a->getId() === 'dev') { return 1; } return 0; }); return [ 'groups' => $this->commandGroups, 'commands' => $commands, ]; }
[ "public", "function", "aggregate", "(", ")", "{", "$", "commands", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getVisibleCommands", "(", ")", "as", "$", "name", "=>", "$", "cmd", ")", "{", "$", "commands", "[", "$", "name", "]", "=", ...
Aggregate command info
[ "Aggregate", "command", "info" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/CommandTrait.php#L344-L372
train
hail-framework/framework
src/Console/CommandTrait.php
CommandTrait.getVisibleCommands
public function getVisibleCommands(): array { $commands = []; foreach ($this->commands as $name => $command) { if ($name[0] === '_') { continue; } $commands[$name] = $command; } return $commands; }
php
public function getVisibleCommands(): array { $commands = []; foreach ($this->commands as $name => $command) { if ($name[0] === '_') { continue; } $commands[$name] = $command; } return $commands; }
[ "public", "function", "getVisibleCommands", "(", ")", ":", "array", "{", "$", "commands", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "commands", "as", "$", "name", "=>", "$", "command", ")", "{", "if", "(", "$", "name", "[", "0", "]", ...
Some commands are not visible. when user runs 'help', we should just show them these visible commands @return string[] CommandBase command map
[ "Some", "commands", "are", "not", "visible", ".", "when", "user", "runs", "help", "we", "should", "just", "show", "them", "these", "visible", "commands" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/CommandTrait.php#L414-L426
train
hail-framework/framework
src/Console/CommandTrait.php
CommandTrait.getCommandNameTraceArray
public function getCommandNameTraceArray() { $cmdStacks = [$this->name()]; $p = $this->parent; while ($p) { if (!$p instanceof Application) { $cmdStacks[] = $p->name(); } $p = $p->parent; } return array_reverse($cmdStacks); }
php
public function getCommandNameTraceArray() { $cmdStacks = [$this->name()]; $p = $this->parent; while ($p) { if (!$p instanceof Application) { $cmdStacks[] = $p->name(); } $p = $p->parent; } return array_reverse($cmdStacks); }
[ "public", "function", "getCommandNameTraceArray", "(", ")", "{", "$", "cmdStacks", "=", "[", "$", "this", "->", "name", "(", ")", "]", ";", "$", "p", "=", "$", "this", "->", "parent", ";", "while", "(", "$", "p", ")", "{", "if", "(", "!", "$", ...
Return the command name stack @return string[]
[ "Return", "the", "command", "name", "stack" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/CommandTrait.php#L446-L458
train
hail-framework/framework
src/Console/CommandTrait.php
CommandTrait.getCommand
public function getCommand($command): Command { if (isset($this->aliases[$command])) { return $this->aliases[$command]; } if (isset($this->commands[$command])) { return $this->commands[$command]; } throw new CommandNotFoundException($this, $command); }
php
public function getCommand($command): Command { if (isset($this->aliases[$command])) { return $this->aliases[$command]; } if (isset($this->commands[$command])) { return $this->commands[$command]; } throw new CommandNotFoundException($this, $command); }
[ "public", "function", "getCommand", "(", "$", "command", ")", ":", "Command", "{", "if", "(", "isset", "(", "$", "this", "->", "aliases", "[", "$", "command", "]", ")", ")", "{", "return", "$", "this", "->", "aliases", "[", "$", "command", "]", ";"...
Get subcommand object from current command by command name. @param string $command @return Command initialized command object. @throws CommandNotFoundException
[ "Get", "subcommand", "object", "from", "current", "command", "by", "command", "name", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/CommandTrait.php#L485-L496
train
hail-framework/framework
src/Console/CommandTrait.php
CommandTrait.getArguments
public function getArguments(): array { // if user not define any arguments, get argument info from method parameters if ($this->arguments === null) { $this->arguments = []; $ro = new \ReflectionObject($this); if (!$ro->hasMethod('execute')) { throw new ExecuteMethodNotDefinedException($this); } $method = $ro->getMethod('execute'); $parameters = $method->getParameters(); foreach ($parameters as $param) { $a = $this->addArgument($param->getName()); if ($param->isOptional()) { $a->optional(); if ($param->isDefaultValueAvailable()) { $a->setValue($param->getDefaultValue()); } } } } return $this->arguments; }
php
public function getArguments(): array { // if user not define any arguments, get argument info from method parameters if ($this->arguments === null) { $this->arguments = []; $ro = new \ReflectionObject($this); if (!$ro->hasMethod('execute')) { throw new ExecuteMethodNotDefinedException($this); } $method = $ro->getMethod('execute'); $parameters = $method->getParameters(); foreach ($parameters as $param) { $a = $this->addArgument($param->getName()); if ($param->isOptional()) { $a->optional(); if ($param->isDefaultValueAvailable()) { $a->setValue($param->getDefaultValue()); } } } } return $this->arguments; }
[ "public", "function", "getArguments", "(", ")", ":", "array", "{", "// if user not define any arguments, get argument info from method parameters", "if", "(", "$", "this", "->", "arguments", "===", "null", ")", "{", "$", "this", "->", "arguments", "=", "[", "]", "...
Return the defined argument info objects. @return Argument[] @throws ExecuteMethodNotDefinedException
[ "Return", "the", "defined", "argument", "info", "objects", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/CommandTrait.php#L659-L686
train
hail-framework/framework
src/Console/CommandTrait.php
CommandTrait.executeWrapper
public function executeWrapper(array $args) { if (!method_exists($this, 'execute')) { $cmd = $this->createCommand(Help::class); $cmd->executeWrapper([$this->name()]); return; } // Validating arguments foreach ($this->getArguments() as $k => $argument) { if (!isset($args[$k])) { if ($argument->isRequired()) { throw new RequireValueException("Argument pos {$k} '{$argument->name()}' requires a value."); } continue; } if (!$argument->validate($args[$k])) { $this->logger->error("Invalid argument {$args[$k]}"); return; } $args[$k] = $argument->getValue(); } $refMethod = new \ReflectionMethod($this, 'execute'); $requiredNumber = $refMethod->getNumberOfRequiredParameters(); $count = count($args); if ($count < $requiredNumber) { throw new CommandArgumentNotEnoughException($this, $count, $requiredNumber); } foreach ($this->extensions as $extension) { $extension->execute(); } $this->execute(...$args); }
php
public function executeWrapper(array $args) { if (!method_exists($this, 'execute')) { $cmd = $this->createCommand(Help::class); $cmd->executeWrapper([$this->name()]); return; } // Validating arguments foreach ($this->getArguments() as $k => $argument) { if (!isset($args[$k])) { if ($argument->isRequired()) { throw new RequireValueException("Argument pos {$k} '{$argument->name()}' requires a value."); } continue; } if (!$argument->validate($args[$k])) { $this->logger->error("Invalid argument {$args[$k]}"); return; } $args[$k] = $argument->getValue(); } $refMethod = new \ReflectionMethod($this, 'execute'); $requiredNumber = $refMethod->getNumberOfRequiredParameters(); $count = count($args); if ($count < $requiredNumber) { throw new CommandArgumentNotEnoughException($this, $count, $requiredNumber); } foreach ($this->extensions as $extension) { $extension->execute(); } $this->execute(...$args); }
[ "public", "function", "executeWrapper", "(", "array", "$", "args", ")", "{", "if", "(", "!", "method_exists", "(", "$", "this", ",", "'execute'", ")", ")", "{", "$", "cmd", "=", "$", "this", "->", "createCommand", "(", "Help", "::", "class", ")", ";"...
Execute command object, this is a wrapper method for execution. In this method, we check the command arguments by the Reflection feature provided by PHP. @param array $args command argument list (not associative array). @throws CommandArgumentNotEnoughException @throws RequireValueException @throws \ReflectionException
[ "Execute", "command", "object", "this", "is", "a", "wrapper", "method", "for", "execution", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/CommandTrait.php#L700-L742
train
hail-framework/framework
src/Http/Middleware/Payload.php
Payload.csvParser
protected static function csvParser(StreamInterface $stream): array { if ($stream->isSeekable()) { $stream->rewind(); } $handle = $stream->detach(); $data = []; while (($row = \fgetcsv($handle)) !== false) { $data[] = $row; } \fclose($handle); return ['body' => $data]; }
php
protected static function csvParser(StreamInterface $stream): array { if ($stream->isSeekable()) { $stream->rewind(); } $handle = $stream->detach(); $data = []; while (($row = \fgetcsv($handle)) !== false) { $data[] = $row; } \fclose($handle); return ['body' => $data]; }
[ "protected", "static", "function", "csvParser", "(", "StreamInterface", "$", "stream", ")", ":", "array", "{", "if", "(", "$", "stream", "->", "isSeekable", "(", ")", ")", "{", "$", "stream", "->", "rewind", "(", ")", ";", "}", "$", "handle", "=", "$...
Parses csv strings. @param StreamInterface $stream @return array @throws \RuntimeException
[ "Parses", "csv", "strings", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Middleware/Payload.php#L177-L191
train
hail-framework/framework
src/Console/Component/Table/Table.php
Table.getNumberOfColumns
private function getNumberOfColumns() { if (null !== $this->numberOfColumns) { return $this->numberOfColumns; } $columns = [\count($this->headers)]; foreach ($this->rows as $row) { $columns[] = \count($row); } return $this->numberOfColumns = \max($columns); }
php
private function getNumberOfColumns() { if (null !== $this->numberOfColumns) { return $this->numberOfColumns; } $columns = [\count($this->headers)]; foreach ($this->rows as $row) { $columns[] = \count($row); } return $this->numberOfColumns = \max($columns); }
[ "private", "function", "getNumberOfColumns", "(", ")", "{", "if", "(", "null", "!==", "$", "this", "->", "numberOfColumns", ")", "{", "return", "$", "this", "->", "numberOfColumns", ";", "}", "$", "columns", "=", "[", "\\", "count", "(", "$", "this", "...
Gets number of columns for this table. @return int
[ "Gets", "number", "of", "columns", "for", "this", "table", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Component/Table/Table.php#L112-L124
train
hiqdev/hipanel-module-dns
src/controllers/RecordController.php
RecordController.actionCreate
public function actionCreate() { $collection = (new Collection([ 'model' => $this->newModel(['scenario' => 'create']), ]))->load(); if ($collection->count() && $collection->save()) { Yii::$app->session->addFlash('success', Yii::t('hipanel:dns', '{0, plural, one{DNS record} other{# DNS records}} created successfully', $collection->count())); return $this->renderZoneView($collection->first->hdomain_id); } elseif ($id = $collection->first->hdomain_id) { return $this->redirect(['@dns/zone/view', 'id' => $id]); } throw new BadRequestHttpException('Bad request'); }
php
public function actionCreate() { $collection = (new Collection([ 'model' => $this->newModel(['scenario' => 'create']), ]))->load(); if ($collection->count() && $collection->save()) { Yii::$app->session->addFlash('success', Yii::t('hipanel:dns', '{0, plural, one{DNS record} other{# DNS records}} created successfully', $collection->count())); return $this->renderZoneView($collection->first->hdomain_id); } elseif ($id = $collection->first->hdomain_id) { return $this->redirect(['@dns/zone/view', 'id' => $id]); } throw new BadRequestHttpException('Bad request'); }
[ "public", "function", "actionCreate", "(", ")", "{", "$", "collection", "=", "(", "new", "Collection", "(", "[", "'model'", "=>", "$", "this", "->", "newModel", "(", "[", "'scenario'", "=>", "'create'", "]", ")", ",", "]", ")", ")", "->", "load", "("...
Created the DNS record. @throws BadRequestHttpException @throws NotFoundHttpException @return string|\yii\web\Response
[ "Created", "the", "DNS", "record", "." ]
7e9199c95d91a979b7bd4fd07fe801dbe9e69183
https://github.com/hiqdev/hipanel-module-dns/blob/7e9199c95d91a979b7bd4fd07fe801dbe9e69183/src/controllers/RecordController.php#L62-L77
train
hiqdev/hipanel-module-dns
src/controllers/RecordController.php
RecordController.actionUpdate
public function actionUpdate($id = null, $hdomain_id = null) { if ($id && $hdomain_id && $model = $this->newModel()->findOne(compact('id', 'hdomain_id'))) { $model->scenario = 'update'; return $this->renderAjax('update', ['model' => $model]); } $collection = (new Collection([ 'model' => $this->newModel(['scenario' => 'update']), ]))->load(); if ($collection->first->id && $collection->save()) { Yii::$app->session->addFlash('success', Yii::t('hipanel:dns', '{0, plural, one{DNS record} other{# DNS records}} updated successfully', $collection->count())); return $this->renderZoneView($collection->first->hdomain_id); } throw new BadRequestHttpException('Bad request'); }
php
public function actionUpdate($id = null, $hdomain_id = null) { if ($id && $hdomain_id && $model = $this->newModel()->findOne(compact('id', 'hdomain_id'))) { $model->scenario = 'update'; return $this->renderAjax('update', ['model' => $model]); } $collection = (new Collection([ 'model' => $this->newModel(['scenario' => 'update']), ]))->load(); if ($collection->first->id && $collection->save()) { Yii::$app->session->addFlash('success', Yii::t('hipanel:dns', '{0, plural, one{DNS record} other{# DNS records}} updated successfully', $collection->count())); return $this->renderZoneView($collection->first->hdomain_id); } throw new BadRequestHttpException('Bad request'); }
[ "public", "function", "actionUpdate", "(", "$", "id", "=", "null", ",", "$", "hdomain_id", "=", "null", ")", "{", "if", "(", "$", "id", "&&", "$", "hdomain_id", "&&", "$", "model", "=", "$", "this", "->", "newModel", "(", ")", "->", "findOne", "(",...
Updates the DNS record. @param integer $id @param integer $hdomain_id @throws BadRequestHttpException @throws NotFoundHttpException @return string
[ "Updates", "the", "DNS", "record", "." ]
7e9199c95d91a979b7bd4fd07fe801dbe9e69183
https://github.com/hiqdev/hipanel-module-dns/blob/7e9199c95d91a979b7bd4fd07fe801dbe9e69183/src/controllers/RecordController.php#L88-L106
train
jormin/aliyun
sdk/aliyun-mq-http-php-sdk/MQClient.php
MQClient.getProducer
public function getProducer($instanceId, $topicName) { if ($topicName == NULL || $topicName == "") { throw new InvalidArgumentException(400, "TopicName is null or empty"); } return new MQProducer($this->client, $instanceId, $topicName); }
php
public function getProducer($instanceId, $topicName) { if ($topicName == NULL || $topicName == "") { throw new InvalidArgumentException(400, "TopicName is null or empty"); } return new MQProducer($this->client, $instanceId, $topicName); }
[ "public", "function", "getProducer", "(", "$", "instanceId", ",", "$", "topicName", ")", "{", "if", "(", "$", "topicName", "==", "NULL", "||", "$", "topicName", "==", "\"\"", ")", "{", "throw", "new", "InvalidArgumentException", "(", "400", ",", "\"TopicNa...
Returns a Producer reference for publish message to topic @param string $instanceId: instance id @param string $topicName: the topic name @return MQProducer $topic: the Producer instance
[ "Returns", "a", "Producer", "reference", "for", "publish", "message", "to", "topic" ]
c0eb19f5c265dba1f463af1db7347acdcfddb240
https://github.com/jormin/aliyun/blob/c0eb19f5c265dba1f463af1db7347acdcfddb240/sdk/aliyun-mq-http-php-sdk/MQClient.php#L46-L52
train
jormin/aliyun
sdk/aliyun-mq-http-php-sdk/MQClient.php
MQClient.getConsumer
public function getConsumer($instanceId, $topicName, $consumer, $messageTag = NULL) { if ($topicName == NULL || $topicName == "") { throw new InvalidArgumentException(400, "TopicName is null or empty"); } if ($consumer == NULL || $consumer == "" ) { throw new InvalidArgumentException(400, "Consumer is null or empty"); } return new MQConsumer($this->client, $instanceId, $topicName, $consumer, $messageTag); }
php
public function getConsumer($instanceId, $topicName, $consumer, $messageTag = NULL) { if ($topicName == NULL || $topicName == "") { throw new InvalidArgumentException(400, "TopicName is null or empty"); } if ($consumer == NULL || $consumer == "" ) { throw new InvalidArgumentException(400, "Consumer is null or empty"); } return new MQConsumer($this->client, $instanceId, $topicName, $consumer, $messageTag); }
[ "public", "function", "getConsumer", "(", "$", "instanceId", ",", "$", "topicName", ",", "$", "consumer", ",", "$", "messageTag", "=", "NULL", ")", "{", "if", "(", "$", "topicName", "==", "NULL", "||", "$", "topicName", "==", "\"\"", ")", "{", "throw",...
Returns a Consumer reference for consume and ack message to topic @param string $instanceId: instance id @param string $topicName: the topic name @param string $consumer: the consumer name / ons cid @param string $messageTag: filter tag for consumer. If not empty, only consume the message which's messageTag is equal to it. @return MQConsumer $topic: the Producer instance
[ "Returns", "a", "Consumer", "reference", "for", "consume", "and", "ack", "message", "to", "topic" ]
c0eb19f5c265dba1f463af1db7347acdcfddb240
https://github.com/jormin/aliyun/blob/c0eb19f5c265dba1f463af1db7347acdcfddb240/sdk/aliyun-mq-http-php-sdk/MQClient.php#L64-L73
train
hail-framework/framework
src/I18n/Gettext/Utils/HeadersExtractorTrait.php
HeadersExtractorTrait.extractHeaders
private static function extractHeaders($headers, Translations $translations) { $headers = explode("\n", $headers); $currentHeader = null; foreach ($headers as $line) { $line = self::convertString($line); if ($line === '') { continue; } if (self::isHeaderDefinition($line)) { $header = \array_map('\trim', \explode(':', $line, 2)); $currentHeader = $header[0]; $translations->setHeader($currentHeader, $header[1]); } else { $entry = $translations->getHeader($currentHeader); $translations->setHeader($currentHeader, $entry.$line); } } }
php
private static function extractHeaders($headers, Translations $translations) { $headers = explode("\n", $headers); $currentHeader = null; foreach ($headers as $line) { $line = self::convertString($line); if ($line === '') { continue; } if (self::isHeaderDefinition($line)) { $header = \array_map('\trim', \explode(':', $line, 2)); $currentHeader = $header[0]; $translations->setHeader($currentHeader, $header[1]); } else { $entry = $translations->getHeader($currentHeader); $translations->setHeader($currentHeader, $entry.$line); } } }
[ "private", "static", "function", "extractHeaders", "(", "$", "headers", ",", "Translations", "$", "translations", ")", "{", "$", "headers", "=", "explode", "(", "\"\\n\"", ",", "$", "headers", ")", ";", "$", "currentHeader", "=", "null", ";", "foreach", "(...
Add the headers found to the translations instance. @param string $headers @param Translations $translations
[ "Add", "the", "headers", "found", "to", "the", "translations", "instance", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Utils/HeadersExtractorTrait.php#L18-L39
train
mcrumm/pecan
src/Console/Output/ConsoleOutput.php
ConsoleOutput.once
public function once($event, callable $listener) { parent::once($event, $listener); $this->stderr->once($event, $listener); }
php
public function once($event, callable $listener) { parent::once($event, $listener); $this->stderr->once($event, $listener); }
[ "public", "function", "once", "(", "$", "event", ",", "callable", "$", "listener", ")", "{", "parent", "::", "once", "(", "$", "event", ",", "$", "listener", ")", ";", "$", "this", "->", "stderr", "->", "once", "(", "$", "event", ",", "$", "listene...
Helper method to proxy event listeners to the wrapped stream. @param $event @param callable $listener
[ "Helper", "method", "to", "proxy", "event", "listeners", "to", "the", "wrapped", "stream", "." ]
f35f01249587a4df45c7d3ab78f3e51919471177
https://github.com/mcrumm/pecan/blob/f35f01249587a4df45c7d3ab78f3e51919471177/src/Console/Output/ConsoleOutput.php#L62-L66
train
jormin/aliyun
sdk/aliyun-mns-php-sdk/AliyunMNS/Client.php
Client.getAccountAttributes
public function getAccountAttributes() { $request = new GetAccountAttributesRequest(); $response = new GetAccountAttributesResponse(); return $this->client->sendRequest($request, $response); }
php
public function getAccountAttributes() { $request = new GetAccountAttributesRequest(); $response = new GetAccountAttributesResponse(); return $this->client->sendRequest($request, $response); }
[ "public", "function", "getAccountAttributes", "(", ")", "{", "$", "request", "=", "new", "GetAccountAttributesRequest", "(", ")", ";", "$", "response", "=", "new", "GetAccountAttributesResponse", "(", ")", ";", "return", "$", "this", "->", "client", "->", "sen...
Query the AccountAttributes @return GetAccountAttributesResponse: the response containing topicNames @throws MnsException if any exception happends
[ "Query", "the", "AccountAttributes" ]
c0eb19f5c265dba1f463af1db7347acdcfddb240
https://github.com/jormin/aliyun/blob/c0eb19f5c265dba1f463af1db7347acdcfddb240/sdk/aliyun-mns-php-sdk/AliyunMNS/Client.php#L210-L215
train
jormin/aliyun
sdk/aliyun-mns-php-sdk/AliyunMNS/Client.php
Client.setAccountAttributes
public function setAccountAttributes(AccountAttributes $attributes) { $request = new SetAccountAttributesRequest($attributes); $response = new SetAccountAttributesResponse(); return $this->client->sendRequest($request, $response); }
php
public function setAccountAttributes(AccountAttributes $attributes) { $request = new SetAccountAttributesRequest($attributes); $response = new SetAccountAttributesResponse(); return $this->client->sendRequest($request, $response); }
[ "public", "function", "setAccountAttributes", "(", "AccountAttributes", "$", "attributes", ")", "{", "$", "request", "=", "new", "SetAccountAttributesRequest", "(", "$", "attributes", ")", ";", "$", "response", "=", "new", "SetAccountAttributesResponse", "(", ")", ...
Set the AccountAttributes @param AccountAttributes $attributes: the AccountAttributes to set @return SetAccountAttributesResponse: the response @throws MnsException if any exception happends
[ "Set", "the", "AccountAttributes" ]
c0eb19f5c265dba1f463af1db7347acdcfddb240
https://github.com/jormin/aliyun/blob/c0eb19f5c265dba1f463af1db7347acdcfddb240/sdk/aliyun-mns-php-sdk/AliyunMNS/Client.php#L233-L238
train
hail-framework/framework
src/I18n/Gettext/Translation.php
Translation.getPluralTranslations
public function getPluralTranslations($size = null) { if ($size === null) { return $this->pluralTranslation; } $current = \count($this->pluralTranslation); if ($size > $current) { return $this->pluralTranslation + \array_fill(0, $size, ''); } if ($size < $current) { return \array_slice($this->pluralTranslation, 0, $size); } return $this->pluralTranslation; }
php
public function getPluralTranslations($size = null) { if ($size === null) { return $this->pluralTranslation; } $current = \count($this->pluralTranslation); if ($size > $current) { return $this->pluralTranslation + \array_fill(0, $size, ''); } if ($size < $current) { return \array_slice($this->pluralTranslation, 0, $size); } return $this->pluralTranslation; }
[ "public", "function", "getPluralTranslations", "(", "$", "size", "=", "null", ")", "{", "if", "(", "$", "size", "===", "null", ")", "{", "return", "$", "this", "->", "pluralTranslation", ";", "}", "$", "current", "=", "\\", "count", "(", "$", "this", ...
Gets all plural translations. @param int $size @return array
[ "Gets", "all", "plural", "translations", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Translation.php#L228-L245
train
hail-framework/framework
src/I18n/Gettext/Translation.php
Translation.hasPluralTranslations
public function hasPluralTranslations($checkContent = false) { if ($checkContent) { return \implode('', $this->pluralTranslation) !== ''; } return !empty($this->pluralTranslation); }
php
public function hasPluralTranslations($checkContent = false) { if ($checkContent) { return \implode('', $this->pluralTranslation) !== ''; } return !empty($this->pluralTranslation); }
[ "public", "function", "hasPluralTranslations", "(", "$", "checkContent", "=", "false", ")", "{", "if", "(", "$", "checkContent", ")", "{", "return", "\\", "implode", "(", "''", ",", "$", "this", "->", "pluralTranslation", ")", "!==", "''", ";", "}", "ret...
Checks if there are any plural translation. @param bool $checkContent @return bool
[ "Checks", "if", "there", "are", "any", "plural", "translation", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Translation.php#L254-L261
train
hail-framework/framework
src/I18n/Gettext/Translation.php
Translation.addExtractedComment
public function addExtractedComment($comment) { if (!\in_array($comment, $this->extractedComments, true)) { $this->extractedComments[] = $comment; } return $this; }
php
public function addExtractedComment($comment) { if (!\in_array($comment, $this->extractedComments, true)) { $this->extractedComments[] = $comment; } return $this; }
[ "public", "function", "addExtractedComment", "(", "$", "comment", ")", "{", "if", "(", "!", "\\", "in_array", "(", "$", "comment", ",", "$", "this", "->", "extractedComments", ",", "true", ")", ")", "{", "$", "this", "->", "extractedComments", "[", "]", ...
Adds a new extracted comment for this translation. @param string $comment @return self
[ "Adds", "a", "new", "extracted", "comment", "for", "this", "translation", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Translation.php#L398-L405
train
htmlburger/wpemerge-cli
src/Helpers/Boolean.php
Boolean.fromString
public static function fromString( $string ) { $values = [ '1' => true, 'y' => true, 'yes' => true, 'true' => true, '0' => false, 'n' => false, 'no' => false, 'false' => false, ]; foreach ( $values as $value => $boolean ) { if ( strtolower( $value ) === strtolower( $string ) ) { return $boolean; } } // rely on PHP's string to boolean conversion in all other cases return (bool) $string; }
php
public static function fromString( $string ) { $values = [ '1' => true, 'y' => true, 'yes' => true, 'true' => true, '0' => false, 'n' => false, 'no' => false, 'false' => false, ]; foreach ( $values as $value => $boolean ) { if ( strtolower( $value ) === strtolower( $string ) ) { return $boolean; } } // rely on PHP's string to boolean conversion in all other cases return (bool) $string; }
[ "public", "static", "function", "fromString", "(", "$", "string", ")", "{", "$", "values", "=", "[", "'1'", "=>", "true", ",", "'y'", "=>", "true", ",", "'yes'", "=>", "true", ",", "'true'", "=>", "true", ",", "'0'", "=>", "false", ",", "'n'", "=>"...
Convert a string to boolean @param string $string @return boolean
[ "Convert", "a", "string", "to", "boolean" ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Helpers/Boolean.php#L12-L33
train
cfxmarkets/php-public-models
src/Brokerage/OrderIntent.php
OrderIntent.serializeAttribute
public function serializeAttribute($name) { if ($name === 'createdOn') { $val = $this->getCreatedOn(); if ($val instanceof \DateTimeInterface) { $val = $val->format("Y-m-d H:i:s"); } return (string)$val; } return parent::serializeAttribute($name); }
php
public function serializeAttribute($name) { if ($name === 'createdOn') { $val = $this->getCreatedOn(); if ($val instanceof \DateTimeInterface) { $val = $val->format("Y-m-d H:i:s"); } return (string)$val; } return parent::serializeAttribute($name); }
[ "public", "function", "serializeAttribute", "(", "$", "name", ")", "{", "if", "(", "$", "name", "===", "'createdOn'", ")", "{", "$", "val", "=", "$", "this", "->", "getCreatedOn", "(", ")", ";", "if", "(", "$", "val", "instanceof", "\\", "DateTimeInter...
Serialize createdOn field to a value that SQL understands We have to do this here because when order intents are serialized that already have a createdOn 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", "createdOn", "field", "to", "a", "value", "that", "SQL", "understands" ]
b91a58f7d9519b98b29c58f0911e976e361a5f65
https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/Brokerage/OrderIntent.php#L448-L458
train
hail-framework/framework
src/Util/Crypto.php
Crypto.encrypt
public static function encrypt( string $plaintext, string $key, string $ad = '', string $format = null, bool $password = false ): string { if (\mb_strlen($key, '8bit') !== self::KEY_BYTE_SIZE) { throw new CryptoException('Bad key length.'); } $salt = \random_bytes(self::SALT_BYTE_SIZE); [$authKey, $encryptKey] = self::deriveKeys($key, $salt, $password); $iv = \random_bytes(self::BLOCK_BYTE_SIZE); $ad = self::getAd($ad); $tag = ''; if (self::$sodium) { $cipherText = \sodium_crypto_aead_aes256gcm_encrypt($plaintext, $ad, $iv, $encryptKey); } else { $cipherText = \openssl_encrypt( $plaintext, self::CIPHER_METHOD, $encryptKey, \OPENSSL_RAW_DATA, $iv, $tag, $ad ); } if ($cipherText === false) { throw new CryptoException('Encrypt failed.'); } $cipherText = self::CURRENT_VERSION . $salt . $iv . $cipherText . $tag; $auth = \hash_hmac(self::HASH_TYPE, $cipherText, $authKey, true); $cipherText .= $auth; return self::fromRaw($cipherText, $format); }
php
public static function encrypt( string $plaintext, string $key, string $ad = '', string $format = null, bool $password = false ): string { if (\mb_strlen($key, '8bit') !== self::KEY_BYTE_SIZE) { throw new CryptoException('Bad key length.'); } $salt = \random_bytes(self::SALT_BYTE_SIZE); [$authKey, $encryptKey] = self::deriveKeys($key, $salt, $password); $iv = \random_bytes(self::BLOCK_BYTE_SIZE); $ad = self::getAd($ad); $tag = ''; if (self::$sodium) { $cipherText = \sodium_crypto_aead_aes256gcm_encrypt($plaintext, $ad, $iv, $encryptKey); } else { $cipherText = \openssl_encrypt( $plaintext, self::CIPHER_METHOD, $encryptKey, \OPENSSL_RAW_DATA, $iv, $tag, $ad ); } if ($cipherText === false) { throw new CryptoException('Encrypt failed.'); } $cipherText = self::CURRENT_VERSION . $salt . $iv . $cipherText . $tag; $auth = \hash_hmac(self::HASH_TYPE, $cipherText, $authKey, true); $cipherText .= $auth; return self::fromRaw($cipherText, $format); }
[ "public", "static", "function", "encrypt", "(", "string", "$", "plaintext", ",", "string", "$", "key", ",", "string", "$", "ad", "=", "''", ",", "string", "$", "format", "=", "null", ",", "bool", "$", "password", "=", "false", ")", ":", "string", "{"...
Encrypts a string with a Key. @param string $plaintext @param string $key @param string $ad @param string $format @param bool $password @throws CryptoException @return string @throws \Exception
[ "Encrypts", "a", "string", "with", "a", "Key", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Crypto.php#L204-L245
train
hail-framework/framework
src/Util/Crypto.php
Crypto.encryptWithPassword
public static function encryptWithPassword( string $plaintext, string $password, string $ad = '', string $format = null ): string { return self::encrypt($plaintext, $password, $ad, $format, true); }
php
public static function encryptWithPassword( string $plaintext, string $password, string $ad = '', string $format = null ): string { return self::encrypt($plaintext, $password, $ad, $format, true); }
[ "public", "static", "function", "encryptWithPassword", "(", "string", "$", "plaintext", ",", "string", "$", "password", ",", "string", "$", "ad", "=", "''", ",", "string", "$", "format", "=", "null", ")", ":", "string", "{", "return", "self", "::", "encr...
Encrypts a string with a password, using a slow key derivation function to make password cracking more expensive. @param string $plaintext @param string $password @param string $ad @param string $format @throws \Exception @return string
[ "Encrypts", "a", "string", "with", "a", "password", "using", "a", "slow", "key", "derivation", "function", "to", "make", "password", "cracking", "more", "expensive", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Crypto.php#L260-L267
train
hail-framework/framework
src/Util/Crypto.php
Crypto.decryptWithPassword
public static function decryptWithPassword( string $cipherText, string $password, string $ad = '', string $format = null ): string { return self::decrypt($cipherText, $password, $ad, $format, true); }
php
public static function decryptWithPassword( string $cipherText, string $password, string $ad = '', string $format = null ): string { return self::decrypt($cipherText, $password, $ad, $format, true); }
[ "public", "static", "function", "decryptWithPassword", "(", "string", "$", "cipherText", ",", "string", "$", "password", ",", "string", "$", "ad", "=", "''", ",", "string", "$", "format", "=", "null", ")", ":", "string", "{", "return", "self", "::", "dec...
Decrypts a ciphertext to a string with a password, using a slow key derivation function to make password cracking more expensive. @param string $cipherText @param string $password @param string $ad @param string $format @throws CryptoException @return string
[ "Decrypts", "a", "ciphertext", "to", "a", "string", "with", "a", "password", "using", "a", "slow", "key", "derivation", "function", "to", "make", "password", "cracking", "more", "expensive", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Crypto.php#L396-L403
train
hail-framework/framework
src/Util/Crypto.php
Crypto.deriveKeys
private static function deriveKeys(string $key, string $salt, bool $password = false) { if ($password) { $preHash = \hash(self::HASH_TYPE, $key, true); $key = self::pbkdf2( self::HASH_TYPE, $preHash, $salt, self::PBKDF2_ITERATIONS, self::KEY_BYTE_SIZE, true ); } $authKey = self::hkdf( self::HASH_TYPE, $key, self::KEY_BYTE_SIZE, self::AUTHENTICATION_INFO_STRING, $salt ); $encryptKey = self::hkdf( self::HASH_TYPE, $key, self::KEY_BYTE_SIZE, self::ENCRYPTION_INFO_STRING, $salt ); return [$authKey, $encryptKey]; }
php
private static function deriveKeys(string $key, string $salt, bool $password = false) { if ($password) { $preHash = \hash(self::HASH_TYPE, $key, true); $key = self::pbkdf2( self::HASH_TYPE, $preHash, $salt, self::PBKDF2_ITERATIONS, self::KEY_BYTE_SIZE, true ); } $authKey = self::hkdf( self::HASH_TYPE, $key, self::KEY_BYTE_SIZE, self::AUTHENTICATION_INFO_STRING, $salt ); $encryptKey = self::hkdf( self::HASH_TYPE, $key, self::KEY_BYTE_SIZE, self::ENCRYPTION_INFO_STRING, $salt ); return [$authKey, $encryptKey]; }
[ "private", "static", "function", "deriveKeys", "(", "string", "$", "key", ",", "string", "$", "salt", ",", "bool", "$", "password", "=", "false", ")", "{", "if", "(", "$", "password", ")", "{", "$", "preHash", "=", "\\", "hash", "(", "self", "::", ...
Derives authentication and encryption keys from the secret, using a slow key derivation function if the secret is a password. @param string $key @param string $salt @param bool $password @throws CryptoException @return array
[ "Derives", "authentication", "and", "encryption", "keys", "from", "the", "secret", "using", "a", "slow", "key", "derivation", "function", "if", "the", "secret", "is", "a", "password", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Crypto.php#L425-L456
train
hail-framework/framework
src/Util/Crypto.php
Crypto.pbkdf2
public static function pbkdf2( string $algorithm, string $password, string $salt, int $count, int $length, bool $raw = false ) { $algorithm = \strtolower($algorithm); // Whitelist, or we could end up with people using CRC32. if (!isset(self::$hashList[$algorithm])) { throw new CryptoException('Algorithm is not a secure cryptographic hash function.'); } if ($count <= 0 || $length <= 0) { throw new CryptoException('Invalid PBKDF2 parameters.'); } // The output length is in NIBBLES (4-bits) if $raw_output is false! if (!$raw) { $length *= 2; } return \hash_pbkdf2($algorithm, $password, $salt, $count, $length, $raw); }
php
public static function pbkdf2( string $algorithm, string $password, string $salt, int $count, int $length, bool $raw = false ) { $algorithm = \strtolower($algorithm); // Whitelist, or we could end up with people using CRC32. if (!isset(self::$hashList[$algorithm])) { throw new CryptoException('Algorithm is not a secure cryptographic hash function.'); } if ($count <= 0 || $length <= 0) { throw new CryptoException('Invalid PBKDF2 parameters.'); } // The output length is in NIBBLES (4-bits) if $raw_output is false! if (!$raw) { $length *= 2; } return \hash_pbkdf2($algorithm, $password, $salt, $count, $length, $raw); }
[ "public", "static", "function", "pbkdf2", "(", "string", "$", "algorithm", ",", "string", "$", "password", ",", "string", "$", "salt", ",", "int", "$", "count", ",", "int", "$", "length", ",", "bool", "$", "raw", "=", "false", ")", "{", "$", "algorit...
Computes the PBKDF2 password-based key derivation function. The PBKDF2 function is defined in RFC 2898. Test vectors can be found in RFC 6070. This implementation of PBKDF2 was originally created by Taylor Hornby, with improvements from http://www.variations-of-shadow.com/. @param string $algorithm The hash algorithm to use. Recommended: SHA256 @param string $password The password. @param string $salt A salt that is unique to the password. @param int $count Iteration count. Higher is better, but slower. Recommended: At least 1000. @param int $length The length of the derived key in bytes. @param bool $raw If true, the key is returned in raw binary format. Hex encoded otherwise. @throws CryptoException @return string A $key_length-byte key derived from the password and salt.
[ "Computes", "the", "PBKDF2", "password", "-", "based", "key", "derivation", "function", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Crypto.php#L581-L605
train
hiqdev/hipanel-module-server
src/models/Consumption.php
Consumption.getTypeLabel
public function getTypeLabel(): string { $provider = Yii::createObject(BillTypesProvider::class); $types = ArrayHelper::index($provider->getTypes(), 'name'); if (!isset($types[$this->type])) { return '--'; } return $types[$this->type]->label; }
php
public function getTypeLabel(): string { $provider = Yii::createObject(BillTypesProvider::class); $types = ArrayHelper::index($provider->getTypes(), 'name'); if (!isset($types[$this->type])) { return '--'; } return $types[$this->type]->label; }
[ "public", "function", "getTypeLabel", "(", ")", ":", "string", "{", "$", "provider", "=", "Yii", "::", "createObject", "(", "BillTypesProvider", "::", "class", ")", ";", "$", "types", "=", "ArrayHelper", "::", "index", "(", "$", "provider", "->", "getTypes...
Get type label. @throws \yii\base\InvalidConfigException @return string
[ "Get", "type", "label", "." ]
e40c3601952cf1fd420ebb97093ee17a33ff3207
https://github.com/hiqdev/hipanel-module-server/blob/e40c3601952cf1fd420ebb97093ee17a33ff3207/src/models/Consumption.php#L51-L60
train
byjg/webrequest
src/WebRequest.php
WebRequest.setCredentials
public function setCredentials($username, $password) { $this->setCurlOption(CURLOPT_HTTPAUTH, CURLAUTH_BASIC); $this->setCurlOption(CURLOPT_USERPWD, $username . ":" . $password); }
php
public function setCredentials($username, $password) { $this->setCurlOption(CURLOPT_HTTPAUTH, CURLAUTH_BASIC); $this->setCurlOption(CURLOPT_USERPWD, $username . ":" . $password); }
[ "public", "function", "setCredentials", "(", "$", "username", ",", "$", "password", ")", "{", "$", "this", "->", "setCurlOption", "(", "CURLOPT_HTTPAUTH", ",", "CURLAUTH_BASIC", ")", ";", "$", "this", "->", "setCurlOption", "(", "CURLOPT_USERPWD", ",", "$", ...
Defines Basic credentials for access the service. @param string $username @param string $password
[ "Defines", "Basic", "credentials", "for", "access", "the", "service", "." ]
779045160a8ca88044ab41a00d30c4dc6201b619
https://github.com/byjg/webrequest/blob/779045160a8ca88044ab41a00d30c4dc6201b619/src/WebRequest.php#L53-L57
train
byjg/webrequest
src/WebRequest.php
WebRequest.setProxy
public function setProxy($url, $username = null, $password = "") { $this->setCurlOption(CURLOPT_PROXY, $url); if (!is_null($username)) { $this->setCurlOption(CURLOPT_PROXYUSERPWD, "$username:$password"); } }
php
public function setProxy($url, $username = null, $password = "") { $this->setCurlOption(CURLOPT_PROXY, $url); if (!is_null($username)) { $this->setCurlOption(CURLOPT_PROXYUSERPWD, "$username:$password"); } }
[ "public", "function", "setProxy", "(", "$", "url", ",", "$", "username", "=", "null", ",", "$", "password", "=", "\"\"", ")", "{", "$", "this", "->", "setCurlOption", "(", "CURLOPT_PROXY", ",", "$", "url", ")", ";", "if", "(", "!", "is_null", "(", ...
Setting the Proxy The full representation of the proxy is scheme://url:port, but the only required is the URL; Some examples: my.proxy.com my.proxy.com:1080 https://my.proxy.com:1080 socks4://my.proxysocks.com socks5://my.proxysocks.com @param string $url The Proxy URL in the format scheme://url:port @param string $username @param string $password
[ "Setting", "the", "Proxy" ]
779045160a8ca88044ab41a00d30c4dc6201b619
https://github.com/byjg/webrequest/blob/779045160a8ca88044ab41a00d30c4dc6201b619/src/WebRequest.php#L193-L199
train
byjg/webrequest
src/WebRequest.php
WebRequest.soapCall
public function soapCall($method, $params = null, $soapOptions = null) { $soapParams = null; if (is_array($params)) { $soapParams = array(); foreach ($params as $key => $value) { $soapParams[] = new SoapParam($value, $key); } } if (!is_array($soapOptions) || (is_null($soapOptions))) { $soapOptions = array( "uri" => "urn:xmethods-delayed-quotes", "soapaction" => "urn:xmethods-delayed-quotes#getQuote" ); } // Chamando método do webservice $result = $this->getSoapClient()->__soapCall( $method, $soapParams, $soapOptions ); return $result; }
php
public function soapCall($method, $params = null, $soapOptions = null) { $soapParams = null; if (is_array($params)) { $soapParams = array(); foreach ($params as $key => $value) { $soapParams[] = new SoapParam($value, $key); } } if (!is_array($soapOptions) || (is_null($soapOptions))) { $soapOptions = array( "uri" => "urn:xmethods-delayed-quotes", "soapaction" => "urn:xmethods-delayed-quotes#getQuote" ); } // Chamando método do webservice $result = $this->getSoapClient()->__soapCall( $method, $soapParams, $soapOptions ); return $result; }
[ "public", "function", "soapCall", "(", "$", "method", ",", "$", "params", "=", "null", ",", "$", "soapOptions", "=", "null", ")", "{", "$", "soapParams", "=", "null", ";", "if", "(", "is_array", "(", "$", "params", ")", ")", "{", "$", "soapParams", ...
Call a Soap client. For example: $webreq = new WebRequest("http://www.byjg.com.br/webservice.php/ws/cep"); $result = $webreq->soapCall("obterCep", new array("cep", "11111233")); @param string $method @param array $params @param array $soapOptions @return string
[ "Call", "a", "Soap", "client", "." ]
779045160a8ca88044ab41a00d30c4dc6201b619
https://github.com/byjg/webrequest/blob/779045160a8ca88044ab41a00d30c4dc6201b619/src/WebRequest.php#L244-L270
train
byjg/webrequest
src/WebRequest.php
WebRequest.defaultCurlOptions
protected function defaultCurlOptions() { $this->curlOptions[CURLOPT_CONNECTTIMEOUT] = 30; $this->curlOptions[CURLOPT_TIMEOUT] = 30; $this->curlOptions[CURLOPT_HEADER] = true; $this->curlOptions[CURLOPT_RETURNTRANSFER] = true; $this->curlOptions[CURLOPT_USERAGENT] = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"; $this->curlOptions[CURLOPT_FOLLOWLOCATION] = true; $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = false; $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = false; }
php
protected function defaultCurlOptions() { $this->curlOptions[CURLOPT_CONNECTTIMEOUT] = 30; $this->curlOptions[CURLOPT_TIMEOUT] = 30; $this->curlOptions[CURLOPT_HEADER] = true; $this->curlOptions[CURLOPT_RETURNTRANSFER] = true; $this->curlOptions[CURLOPT_USERAGENT] = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"; $this->curlOptions[CURLOPT_FOLLOWLOCATION] = true; $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = false; $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = false; }
[ "protected", "function", "defaultCurlOptions", "(", ")", "{", "$", "this", "->", "curlOptions", "[", "CURLOPT_CONNECTTIMEOUT", "]", "=", "30", ";", "$", "this", "->", "curlOptions", "[", "CURLOPT_TIMEOUT", "]", "=", "30", ";", "$", "this", "->", "curlOptions...
Set the default curl options. You can override this method to setup your own default options. You can pass the options to the constructor also;
[ "Set", "the", "default", "curl", "options", ".", "You", "can", "override", "this", "method", "to", "setup", "your", "own", "default", "options", ".", "You", "can", "pass", "the", "options", "to", "the", "constructor", "also", ";" ]
779045160a8ca88044ab41a00d30c4dc6201b619
https://github.com/byjg/webrequest/blob/779045160a8ca88044ab41a00d30c4dc6201b619/src/WebRequest.php#L277-L287
train
byjg/webrequest
src/WebRequest.php
WebRequest.setCurlOption
public function setCurlOption($key, $value) { if (!is_int($key)) { throw new InvalidArgumentException('It is not a CURL_OPT argument'); } if ($key == CURLOPT_HEADER || $key == CURLOPT_RETURNTRANSFER) { throw new InvalidArgumentException('You cannot change CURLOPT_HEADER or CURLOPT_RETURNTRANSFER'); } if (!is_null($value)) { $this->curlOptions[$key] = $value; } else { unset($this->curlOptions[$key]); } }
php
public function setCurlOption($key, $value) { if (!is_int($key)) { throw new InvalidArgumentException('It is not a CURL_OPT argument'); } if ($key == CURLOPT_HEADER || $key == CURLOPT_RETURNTRANSFER) { throw new InvalidArgumentException('You cannot change CURLOPT_HEADER or CURLOPT_RETURNTRANSFER'); } if (!is_null($value)) { $this->curlOptions[$key] = $value; } else { unset($this->curlOptions[$key]); } }
[ "public", "function", "setCurlOption", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "!", "is_int", "(", "$", "key", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'It is not a CURL_OPT argument'", ")", ";", "}", "if", "(", "...
Set a custom CURL option @param int $key @param mixed $value @throws InvalidArgumentException
[ "Set", "a", "custom", "CURL", "option" ]
779045160a8ca88044ab41a00d30c4dc6201b619
https://github.com/byjg/webrequest/blob/779045160a8ca88044ab41a00d30c4dc6201b619/src/WebRequest.php#L296-L310
train
byjg/webrequest
src/WebRequest.php
WebRequest.getCurlOption
public function getCurlOption($key) { return (isset($this->curlOptions[$key]) ? $this->curlOptions[$key] : null); }
php
public function getCurlOption($key) { return (isset($this->curlOptions[$key]) ? $this->curlOptions[$key] : null); }
[ "public", "function", "getCurlOption", "(", "$", "key", ")", "{", "return", "(", "isset", "(", "$", "this", "->", "curlOptions", "[", "$", "key", "]", ")", "?", "$", "this", "->", "curlOptions", "[", "$", "key", "]", ":", "null", ")", ";", "}" ]
Get the current Curl option @param int $key @return mixed
[ "Get", "the", "current", "Curl", "option" ]
779045160a8ca88044ab41a00d30c4dc6201b619
https://github.com/byjg/webrequest/blob/779045160a8ca88044ab41a00d30c4dc6201b619/src/WebRequest.php#L318-L321
train
byjg/webrequest
src/WebRequest.php
WebRequest.curlInit
protected function curlInit() { $curlHandle = curl_init(); curl_setopt($curlHandle, CURLOPT_URL, $this->requestUrl); $this->requestUrl = $this->url; // Reset request URL // Set Curl Options foreach ($this->curlOptions as $key => $value) { curl_setopt($curlHandle, $key, $value); } // Check if have header if (count($this->requestHeader) > 0) { curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $this->requestHeader); $this->requestHeader = []; // Reset request Header } // Add Cookies if (count($this->cookies) > 0) { curl_setopt($curlHandle, CURLOPT_COOKIE, implode(";", $this->cookies)); $this->cookies = []; // Reset request Header } // Set last fetched URL $this->lastFetchedUrl = null; return $curlHandle; }
php
protected function curlInit() { $curlHandle = curl_init(); curl_setopt($curlHandle, CURLOPT_URL, $this->requestUrl); $this->requestUrl = $this->url; // Reset request URL // Set Curl Options foreach ($this->curlOptions as $key => $value) { curl_setopt($curlHandle, $key, $value); } // Check if have header if (count($this->requestHeader) > 0) { curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $this->requestHeader); $this->requestHeader = []; // Reset request Header } // Add Cookies if (count($this->cookies) > 0) { curl_setopt($curlHandle, CURLOPT_COOKIE, implode(";", $this->cookies)); $this->cookies = []; // Reset request Header } // Set last fetched URL $this->lastFetchedUrl = null; return $curlHandle; }
[ "protected", "function", "curlInit", "(", ")", "{", "$", "curlHandle", "=", "curl_init", "(", ")", ";", "curl_setopt", "(", "$", "curlHandle", ",", "CURLOPT_URL", ",", "$", "this", "->", "requestUrl", ")", ";", "$", "this", "->", "requestUrl", "=", "$", ...
Request the method using the CURLOPT defined previously; @return resource
[ "Request", "the", "method", "using", "the", "CURLOPT", "defined", "previously", ";" ]
779045160a8ca88044ab41a00d30c4dc6201b619
https://github.com/byjg/webrequest/blob/779045160a8ca88044ab41a00d30c4dc6201b619/src/WebRequest.php#L372-L398
train
byjg/webrequest
src/WebRequest.php
WebRequest.get
public function get($params = null) { $curlHandle = $this->prepareGet($params); return $this->curlGetResponse($curlHandle); }
php
public function get($params = null) { $curlHandle = $this->prepareGet($params); return $this->curlGetResponse($curlHandle); }
[ "public", "function", "get", "(", "$", "params", "=", "null", ")", "{", "$", "curlHandle", "=", "$", "this", "->", "prepareGet", "(", "$", "params", ")", ";", "return", "$", "this", "->", "curlGetResponse", "(", "$", "curlHandle", ")", ";", "}" ]
Make a REST Get method call @param array|null $params @return string @throws \ByJG\Util\CurlException
[ "Make", "a", "REST", "Get", "method", "call" ]
779045160a8ca88044ab41a00d30c4dc6201b619
https://github.com/byjg/webrequest/blob/779045160a8ca88044ab41a00d30c4dc6201b619/src/WebRequest.php#L488-L492
train
byjg/webrequest
src/WebRequest.php
WebRequest.put
public function put($params = null) { $handle = $this->preparePut($params); return $this->curlGetResponse($handle); }
php
public function put($params = null) { $handle = $this->preparePut($params); return $this->curlGetResponse($handle); }
[ "public", "function", "put", "(", "$", "params", "=", "null", ")", "{", "$", "handle", "=", "$", "this", "->", "preparePut", "(", "$", "params", ")", ";", "return", "$", "this", "->", "curlGetResponse", "(", "$", "handle", ")", ";", "}" ]
Make a REST PUT method call with parameters @param array|string $params @return string @throws \ByJG\Util\CurlException
[ "Make", "a", "REST", "PUT", "method", "call", "with", "parameters" ]
779045160a8ca88044ab41a00d30c4dc6201b619
https://github.com/byjg/webrequest/blob/779045160a8ca88044ab41a00d30c4dc6201b619/src/WebRequest.php#L614-L618
train
byjg/webrequest
src/WebRequest.php
WebRequest.delete
public function delete($params = null) { $handle = $this->prepareDelete($params); return $this->curlGetResponse($handle); }
php
public function delete($params = null) { $handle = $this->prepareDelete($params); return $this->curlGetResponse($handle); }
[ "public", "function", "delete", "(", "$", "params", "=", "null", ")", "{", "$", "handle", "=", "$", "this", "->", "prepareDelete", "(", "$", "params", ")", ";", "return", "$", "this", "->", "curlGetResponse", "(", "$", "handle", ")", ";", "}" ]
Make a REST DELETE method call with parameters @param array|string $params @return string @throws \ByJG\Util\CurlException
[ "Make", "a", "REST", "DELETE", "method", "call", "with", "parameters" ]
779045160a8ca88044ab41a00d30c4dc6201b619
https://github.com/byjg/webrequest/blob/779045160a8ca88044ab41a00d30c4dc6201b619/src/WebRequest.php#L652-L656
train
byjg/webrequest
src/WebRequest.php
WebRequest.deletePayload
public function deletePayload($data = null, $contentType = "text/plain") { $this->addRequestHeader("Content-Type", $contentType); return $this->delete($data); }
php
public function deletePayload($data = null, $contentType = "text/plain") { $this->addRequestHeader("Content-Type", $contentType); return $this->delete($data); }
[ "public", "function", "deletePayload", "(", "$", "data", "=", "null", ",", "$", "contentType", "=", "\"text/plain\"", ")", "{", "$", "this", "->", "addRequestHeader", "(", "\"Content-Type\"", ",", "$", "contentType", ")", ";", "return", "$", "this", "->", ...
Make a REST DELETE method call sending a payload @param string $data @param string $contentType @return string @throws \ByJG\Util\CurlException
[ "Make", "a", "REST", "DELETE", "method", "call", "sending", "a", "payload" ]
779045160a8ca88044ab41a00d30c4dc6201b619
https://github.com/byjg/webrequest/blob/779045160a8ca88044ab41a00d30c4dc6201b619/src/WebRequest.php#L666-L670
train
hail-framework/framework
src/Util/Yaml/Parser.php
Parser.trimTag
private function trimTag(string $value): string { if ('!' === $value[0]) { return \ltrim(\substr($value, 1, \strcspn($value, " \r\n", 1)), ' '); } return $value; }
php
private function trimTag(string $value): string { if ('!' === $value[0]) { return \ltrim(\substr($value, 1, \strcspn($value, " \r\n", 1)), ' '); } return $value; }
[ "private", "function", "trimTag", "(", "string", "$", "value", ")", ":", "string", "{", "if", "(", "'!'", "===", "$", "value", "[", "0", "]", ")", "{", "return", "\\", "ltrim", "(", "\\", "substr", "(", "$", "value", ",", "1", ",", "\\", "strcspn...
Trim the tag on top of the value. Prevent values such as `!foo {quz: bar}` to be considered as a mapping block.
[ "Trim", "the", "tag", "on", "top", "of", "the", "value", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Yaml/Parser.php#L1073-L1080
train
hail-framework/framework
src/Filesystem/Util.php
Util.emulateDirectories
public static function emulateDirectories(array $listing) { $directories = []; $listedDirectories = []; foreach ($listing as $object) { [$directories, $listedDirectories] = static::emulateObjectDirectories($object, $directories, $listedDirectories); } $directories = \array_diff( \array_unique($directories), \array_unique($listedDirectories) ); foreach ($directories as $directory) { $listing[] = static::pathinfo($directory) + ['type' => 'dir']; } return $listing; }
php
public static function emulateDirectories(array $listing) { $directories = []; $listedDirectories = []; foreach ($listing as $object) { [$directories, $listedDirectories] = static::emulateObjectDirectories($object, $directories, $listedDirectories); } $directories = \array_diff( \array_unique($directories), \array_unique($listedDirectories) ); foreach ($directories as $directory) { $listing[] = static::pathinfo($directory) + ['type' => 'dir']; } return $listing; }
[ "public", "static", "function", "emulateDirectories", "(", "array", "$", "listing", ")", "{", "$", "directories", "=", "[", "]", ";", "$", "listedDirectories", "=", "[", "]", ";", "foreach", "(", "$", "listing", "as", "$", "object", ")", "{", "[", "$",...
Emulate directories. @param array $listing @return array listing with emulated directories
[ "Emulate", "directories", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Util.php#L190-L209
train
hail-framework/framework
src/Filesystem/Util.php
Util.emulateObjectDirectories
protected static function emulateObjectDirectories(array $object, array $directories, array $listedDirectories) { if ($object['type'] === 'dir') { $listedDirectories[] = $object['path']; } if (empty($object['dirname'])) { return [$directories, $listedDirectories]; } $parent = $object['dirname']; while (!empty($parent) && !\in_array($parent, $directories, true)) { $directories[] = $parent; $parent = static::dirname($parent); } if (isset($object['type']) && $object['type'] === 'dir') { $listedDirectories[] = $object['path']; return [$directories, $listedDirectories]; } return [$directories, $listedDirectories]; }
php
protected static function emulateObjectDirectories(array $object, array $directories, array $listedDirectories) { if ($object['type'] === 'dir') { $listedDirectories[] = $object['path']; } if (empty($object['dirname'])) { return [$directories, $listedDirectories]; } $parent = $object['dirname']; while (!empty($parent) && !\in_array($parent, $directories, true)) { $directories[] = $parent; $parent = static::dirname($parent); } if (isset($object['type']) && $object['type'] === 'dir') { $listedDirectories[] = $object['path']; return [$directories, $listedDirectories]; } return [$directories, $listedDirectories]; }
[ "protected", "static", "function", "emulateObjectDirectories", "(", "array", "$", "object", ",", "array", "$", "directories", ",", "array", "$", "listedDirectories", ")", "{", "if", "(", "$", "object", "[", "'type'", "]", "===", "'dir'", ")", "{", "$", "li...
Emulate the directories of a single object. @param array $object @param array $directories @param array $listedDirectories @return array
[ "Emulate", "the", "directories", "of", "a", "single", "object", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Util.php#L289-L313
train
netgen-layouts/content-browser-sylius
lib/Repository/ProductRepository.php
ProductRepository.createQueryBuilderWithLocaleCode
private function createQueryBuilderWithLocaleCode(string $localeCode): QueryBuilder { $queryBuilder = $this->createQueryBuilder('o'); $queryBuilder ->addSelect('translation') ->leftJoin('o.translations', 'translation') ->andWhere('translation.locale = :localeCode') ->setParameter('localeCode', $localeCode) ; return $queryBuilder; }
php
private function createQueryBuilderWithLocaleCode(string $localeCode): QueryBuilder { $queryBuilder = $this->createQueryBuilder('o'); $queryBuilder ->addSelect('translation') ->leftJoin('o.translations', 'translation') ->andWhere('translation.locale = :localeCode') ->setParameter('localeCode', $localeCode) ; return $queryBuilder; }
[ "private", "function", "createQueryBuilderWithLocaleCode", "(", "string", "$", "localeCode", ")", ":", "QueryBuilder", "{", "$", "queryBuilder", "=", "$", "this", "->", "createQueryBuilder", "(", "'o'", ")", ";", "$", "queryBuilder", "->", "addSelect", "(", "'tr...
Creates a query builder to filter products by locale.
[ "Creates", "a", "query", "builder", "to", "filter", "products", "by", "locale", "." ]
feb3ab56b584f6fbf4b8b6557ba6398513b116e5
https://github.com/netgen-layouts/content-browser-sylius/blob/feb3ab56b584f6fbf4b8b6557ba6398513b116e5/lib/Repository/ProductRepository.php#L57-L68
train
2amigos/yii2-translateable-behavior
TranslateableBehavior.php
TranslateableBehavior.getAttributeTranslation
private function getAttributeTranslation($attribute, $language) { $seen = []; do { $model = $this->getTranslation($language); $modelLanguage = $language; $fallbackLanguage = $this->getFallbackLanguage($language); $seen[$language] = true; if (isset($seen[$fallbackLanguage])) { // break infinite loop in fallback path return [$model->$attribute, $modelLanguage]; } $language = $fallbackLanguage; } while($model->$attribute === null); return [$model->$attribute, $modelLanguage]; }
php
private function getAttributeTranslation($attribute, $language) { $seen = []; do { $model = $this->getTranslation($language); $modelLanguage = $language; $fallbackLanguage = $this->getFallbackLanguage($language); $seen[$language] = true; if (isset($seen[$fallbackLanguage])) { // break infinite loop in fallback path return [$model->$attribute, $modelLanguage]; } $language = $fallbackLanguage; } while($model->$attribute === null); return [$model->$attribute, $modelLanguage]; }
[ "private", "function", "getAttributeTranslation", "(", "$", "attribute", ",", "$", "language", ")", "{", "$", "seen", "=", "[", "]", ";", "do", "{", "$", "model", "=", "$", "this", "->", "getTranslation", "(", "$", "language", ")", ";", "$", "modelLang...
Retrieve translation for an attribute. @param string $attribute the attribute name. @param string $language the desired translation language. @return array first element is the translation, second element is the language. Language may differ from `$language` when a fallback translation has been used.
[ "Retrieve", "translation", "for", "an", "attribute", "." ]
d50c714d0d63c085a926991ed36c50ed460b8184
https://github.com/2amigos/yii2-translateable-behavior/blob/d50c714d0d63c085a926991ed36c50ed460b8184/TranslateableBehavior.php#L157-L172
train
2amigos/yii2-translateable-behavior
TranslateableBehavior.php
TranslateableBehavior.getFallbackLanguage
public function getFallbackLanguage($forLanguage = null) { if ($this->_fallbackLanguage === null) { $this->_fallbackLanguage = Yii::$app->sourceLanguage; } if ($forLanguage === null) { return $this->_fallbackLanguage; } if ($this->_fallbackLanguage === false) { return $forLanguage; } if (is_array($this->_fallbackLanguage)) { if (isset($this->_fallbackLanguage[$forLanguage])) { return $this->_fallbackLanguage[$forLanguage]; } // check fallback de-DE -> de $fallbackLanguage = substr($forLanguage, 0, 2); if ($forLanguage !== $fallbackLanguage) { return $fallbackLanguage; } // when no fallback is available, use the first defined fallback return reset($this->_fallbackLanguage); } // check fallback de-DE -> de $fallbackLanguage = substr($forLanguage, 0, 2); if ($forLanguage !== $fallbackLanguage) { return $fallbackLanguage; } return $this->_fallbackLanguage; }
php
public function getFallbackLanguage($forLanguage = null) { if ($this->_fallbackLanguage === null) { $this->_fallbackLanguage = Yii::$app->sourceLanguage; } if ($forLanguage === null) { return $this->_fallbackLanguage; } if ($this->_fallbackLanguage === false) { return $forLanguage; } if (is_array($this->_fallbackLanguage)) { if (isset($this->_fallbackLanguage[$forLanguage])) { return $this->_fallbackLanguage[$forLanguage]; } // check fallback de-DE -> de $fallbackLanguage = substr($forLanguage, 0, 2); if ($forLanguage !== $fallbackLanguage) { return $fallbackLanguage; } // when no fallback is available, use the first defined fallback return reset($this->_fallbackLanguage); } // check fallback de-DE -> de $fallbackLanguage = substr($forLanguage, 0, 2); if ($forLanguage !== $fallbackLanguage) { return $fallbackLanguage; } return $this->_fallbackLanguage; }
[ "public", "function", "getFallbackLanguage", "(", "$", "forLanguage", "=", "null", ")", "{", "if", "(", "$", "this", "->", "_fallbackLanguage", "===", "null", ")", "{", "$", "this", "->", "_fallbackLanguage", "=", "Yii", "::", "$", "app", "->", "sourceLang...
Returns current models' fallback language. If null, will return app's configured source language. @return string
[ "Returns", "current", "models", "fallback", "language", ".", "If", "null", "will", "return", "app", "s", "configured", "source", "language", "." ]
d50c714d0d63c085a926991ed36c50ed460b8184
https://github.com/2amigos/yii2-translateable-behavior/blob/d50c714d0d63c085a926991ed36c50ed460b8184/TranslateableBehavior.php#L282-L313
train
2amigos/yii2-translateable-behavior
TranslateableBehavior.php
TranslateableBehavior.modelEqualsFallbackTranslation
private function modelEqualsFallbackTranslation($model, $language) { $fallbackLanguage = $this->getFallbackLanguage($language); foreach($this->translationAttributes as $translationAttribute) { if (isset($model->$translationAttribute)) { list($translation, $transLanguage) = $this->getAttributeTranslation($translationAttribute, $fallbackLanguage); if ($transLanguage === $language || $model->$translationAttribute !== $translation) { return false; } } } return true; }
php
private function modelEqualsFallbackTranslation($model, $language) { $fallbackLanguage = $this->getFallbackLanguage($language); foreach($this->translationAttributes as $translationAttribute) { if (isset($model->$translationAttribute)) { list($translation, $transLanguage) = $this->getAttributeTranslation($translationAttribute, $fallbackLanguage); if ($transLanguage === $language || $model->$translationAttribute !== $translation) { return false; } } } return true; }
[ "private", "function", "modelEqualsFallbackTranslation", "(", "$", "model", ",", "$", "language", ")", "{", "$", "fallbackLanguage", "=", "$", "this", "->", "getFallbackLanguage", "(", "$", "language", ")", ";", "foreach", "(", "$", "this", "->", "translationA...
Check whether translation model has relevant translation data. This will return false if any translation is set and different from the fallback. This method is used to only store translations if they differ from the fallback. @param ActiveRecord $model @param string $language @return bool whether a translation model contains relevant translation data.
[ "Check", "whether", "translation", "model", "has", "relevant", "translation", "data", "." ]
d50c714d0d63c085a926991ed36c50ed460b8184
https://github.com/2amigos/yii2-translateable-behavior/blob/d50c714d0d63c085a926991ed36c50ed460b8184/TranslateableBehavior.php#L375-L387
train
2amigos/yii2-translateable-behavior
TranslateableBehavior.php
TranslateableBehavior.populateTranslations
private function populateTranslations() { //translations $aRelated = $this->owner->getRelatedRecords(); if (isset($aRelated[$this->relation]) && $aRelated[$this->relation] != null) { if (is_array($aRelated[$this->relation])) { foreach ($aRelated[$this->relation] as $model) { $this->_models[$model->getAttribute($this->languageField)] = $model; } } else { $model = $aRelated[$this->relation]; $this->_models[$model->getAttribute($this->languageField)] = $model; } } }
php
private function populateTranslations() { //translations $aRelated = $this->owner->getRelatedRecords(); if (isset($aRelated[$this->relation]) && $aRelated[$this->relation] != null) { if (is_array($aRelated[$this->relation])) { foreach ($aRelated[$this->relation] as $model) { $this->_models[$model->getAttribute($this->languageField)] = $model; } } else { $model = $aRelated[$this->relation]; $this->_models[$model->getAttribute($this->languageField)] = $model; } } }
[ "private", "function", "populateTranslations", "(", ")", "{", "//translations", "$", "aRelated", "=", "$", "this", "->", "owner", "->", "getRelatedRecords", "(", ")", ";", "if", "(", "isset", "(", "$", "aRelated", "[", "$", "this", "->", "relation", "]", ...
Populates already loaded translations
[ "Populates", "already", "loaded", "translations" ]
d50c714d0d63c085a926991ed36c50ed460b8184
https://github.com/2amigos/yii2-translateable-behavior/blob/d50c714d0d63c085a926991ed36c50ed460b8184/TranslateableBehavior.php#L469-L483
train
matthiasmullie/scrapbook
src/Adapters/SQL.php
SQL.unserialize
protected function unserialize($value) { if (is_numeric($value)) { $int = (int) $value; if ((string) $int === $value) { return $int; } $float = (float) $value; if ((string) $float === $value) { return $float; } return $value; } return unserialize($value); }
php
protected function unserialize($value) { if (is_numeric($value)) { $int = (int) $value; if ((string) $int === $value) { return $int; } $float = (float) $value; if ((string) $float === $value) { return $float; } return $value; } return unserialize($value); }
[ "protected", "function", "unserialize", "(", "$", "value", ")", "{", "if", "(", "is_numeric", "(", "$", "value", ")", ")", "{", "$", "int", "=", "(", "int", ")", "$", "value", ";", "if", "(", "(", "string", ")", "$", "int", "===", "$", "value", ...
Numbers aren't serialized for storage size purposes. @param mixed $value @return mixed|int|float
[ "Numbers", "aren", "t", "serialized", "for", "storage", "size", "purposes", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/SQL.php#L496-L513
train
matthiasmullie/scrapbook
src/Adapters/Couchbase.php
Couchbase.assertServerHealhy
protected function assertServerHealhy() { $info = $this->client->manager()->info(); foreach ($info['nodes'] as $node) { if ($node['status'] !== 'healthy') { throw new ServerUnhealthy('Server isn\'t ready yet'); } } }
php
protected function assertServerHealhy() { $info = $this->client->manager()->info(); foreach ($info['nodes'] as $node) { if ($node['status'] !== 'healthy') { throw new ServerUnhealthy('Server isn\'t ready yet'); } } }
[ "protected", "function", "assertServerHealhy", "(", ")", "{", "$", "info", "=", "$", "this", "->", "client", "->", "manager", "(", ")", "->", "info", "(", ")", ";", "foreach", "(", "$", "info", "[", "'nodes'", "]", "as", "$", "node", ")", "{", "if"...
Verify that the server is healthy. @throws ServerUnhealthy
[ "Verify", "that", "the", "server", "is", "healthy", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Couchbase.php#L453-L461
train
matthiasmullie/scrapbook
src/Adapters/Apc.php
Apc.lock
protected function lock($keys) { // both string (single key) and array (multiple) are accepted $keys = (array) $keys; $locked = array(); for ($i = 0; $i < 10; ++$i) { $locked += $this->acquire($keys); $keys = array_diff($keys, $locked); if (empty($keys)) { break; } usleep(1); } return $locked; }
php
protected function lock($keys) { // both string (single key) and array (multiple) are accepted $keys = (array) $keys; $locked = array(); for ($i = 0; $i < 10; ++$i) { $locked += $this->acquire($keys); $keys = array_diff($keys, $locked); if (empty($keys)) { break; } usleep(1); } return $locked; }
[ "protected", "function", "lock", "(", "$", "keys", ")", "{", "// both string (single key) and array (multiple) are accepted", "$", "keys", "=", "(", "array", ")", "$", "keys", ";", "$", "locked", "=", "array", "(", ")", ";", "for", "(", "$", "i", "=", "0",...
Acquire a lock. If we failed to acquire a lock, it'll automatically try again in 1ms, for a maximum of 10 times. APC provides nothing that would allow us to do CAS. To "emulate" CAS, we'll work with locks: all cache writes also briefly create a lock cache entry (yup: #writes * 3, for lock & unlock - luckily, they're not over the network) Writes are disallows when a lock can't be obtained (= locked by another write), which makes it possible for us to first retrieve, compare & then set in a nob-atomic way. However, there's a possibility for interference with direct APC access touching the same keys - e.g. other scripts, not using this class. If CAS is of importance, make sure the only things touching APC on your server is using these classes! @param string|string[] $keys @return array Array of successfully locked keys
[ "Acquire", "a", "lock", ".", "If", "we", "failed", "to", "acquire", "a", "lock", "it", "ll", "automatically", "try", "again", "in", "1ms", "for", "a", "maximum", "of", "10", "times", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Apc.php#L493-L511
train
matthiasmullie/scrapbook
src/Adapters/Apc.php
Apc.acquire
protected function acquire($keys) { $keys = (array) $keys; $values = array(); foreach ($keys as $key) { $values["scrapbook.lock.$key"] = null; } // there's no point in locking longer than max allowed execution time // for this script $ttl = ini_get('max_execution_time'); // lock these keys, then compile a list of successfully locked keys // (using the returned failure array) $result = (array) $this->apcu_add($values, null, $ttl); $failed = array(); foreach ($result as $key => $err) { $failed[] = substr($key, strlen('scrapbook.lock.')); } return array_diff($keys, $failed); }
php
protected function acquire($keys) { $keys = (array) $keys; $values = array(); foreach ($keys as $key) { $values["scrapbook.lock.$key"] = null; } // there's no point in locking longer than max allowed execution time // for this script $ttl = ini_get('max_execution_time'); // lock these keys, then compile a list of successfully locked keys // (using the returned failure array) $result = (array) $this->apcu_add($values, null, $ttl); $failed = array(); foreach ($result as $key => $err) { $failed[] = substr($key, strlen('scrapbook.lock.')); } return array_diff($keys, $failed); }
[ "protected", "function", "acquire", "(", "$", "keys", ")", "{", "$", "keys", "=", "(", "array", ")", "$", "keys", ";", "$", "values", "=", "array", "(", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "values", "[", "\"s...
Acquire a lock - required to provide CAS functionality. @param string|string[] $keys @return string[] Array of successfully locked keys
[ "Acquire", "a", "lock", "-", "required", "to", "provide", "CAS", "functionality", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Apc.php#L520-L542
train
matthiasmullie/scrapbook
src/Adapters/Apc.php
Apc.unlock
protected function unlock($keys) { $keys = (array) $keys; foreach ($keys as $i => $key) { $keys[$i] = "scrapbook.lock.$key"; } $this->apcu_delete($keys); return true; }
php
protected function unlock($keys) { $keys = (array) $keys; foreach ($keys as $i => $key) { $keys[$i] = "scrapbook.lock.$key"; } $this->apcu_delete($keys); return true; }
[ "protected", "function", "unlock", "(", "$", "keys", ")", "{", "$", "keys", "=", "(", "array", ")", "$", "keys", ";", "foreach", "(", "$", "keys", "as", "$", "i", "=>", "$", "key", ")", "{", "$", "keys", "[", "$", "i", "]", "=", "\"scrapbook.lo...
Release a lock. @param string|string[] $keys @return bool
[ "Release", "a", "lock", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Apc.php#L551-L561
train
matthiasmullie/scrapbook
src/Adapters/Apc.php
Apc.expire
protected function expire($key = array(), $ttl = 0) { if ($ttl === 0) { // when storing indefinitely, there's no point in keeping it around, // it won't just expire return; } // $key can be both string (1 key) or array (multiple) $keys = (array) $key; $time = time() + $ttl; foreach ($keys as $key) { $this->expires[$key] = $time; } }
php
protected function expire($key = array(), $ttl = 0) { if ($ttl === 0) { // when storing indefinitely, there's no point in keeping it around, // it won't just expire return; } // $key can be both string (1 key) or array (multiple) $keys = (array) $key; $time = time() + $ttl; foreach ($keys as $key) { $this->expires[$key] = $time; } }
[ "protected", "function", "expire", "(", "$", "key", "=", "array", "(", ")", ",", "$", "ttl", "=", "0", ")", "{", "if", "(", "$", "ttl", "===", "0", ")", "{", "// when storing indefinitely, there's no point in keeping it around,", "// it won't just expire", "retu...
Store the expiration time for items we're setting in this request, to work around APC's behavior of only clearing expires per page request. @see static::$expires @param array|string $key @param int $ttl
[ "Store", "the", "expiration", "time", "for", "items", "we", "re", "setting", "in", "this", "request", "to", "work", "around", "APC", "s", "behavior", "of", "only", "clearing", "expires", "per", "page", "request", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Apc.php#L572-L587
train
matthiasmullie/scrapbook
src/Buffered/TransactionalStore.php
TransactionalStore.commit
public function commit() { if (count($this->transactions) <= 1) { throw new UnbegunTransaction('Attempted to commit without having begun a transaction.'); } /** @var Transaction $transaction */ $transaction = array_pop($this->transactions); return $transaction->commit(); }
php
public function commit() { if (count($this->transactions) <= 1) { throw new UnbegunTransaction('Attempted to commit without having begun a transaction.'); } /** @var Transaction $transaction */ $transaction = array_pop($this->transactions); return $transaction->commit(); }
[ "public", "function", "commit", "(", ")", "{", "if", "(", "count", "(", "$", "this", "->", "transactions", ")", "<=", "1", ")", "{", "throw", "new", "UnbegunTransaction", "(", "'Attempted to commit without having begun a transaction.'", ")", ";", "}", "/** @var ...
Commits all deferred updates to real cache. If the any write fails, all subsequent writes will be aborted & all keys that had already been written to will be deleted. @return bool @throws UnbegunTransaction
[ "Commits", "all", "deferred", "updates", "to", "real", "cache", ".", "If", "the", "any", "write", "fails", "all", "subsequent", "writes", "will", "be", "aborted", "&", "all", "keys", "that", "had", "already", "been", "written", "to", "will", "be", "deleted...
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Buffered/TransactionalStore.php#L85-L95
train
matthiasmullie/scrapbook
src/Buffered/TransactionalStore.php
TransactionalStore.rollback
public function rollback() { if (count($this->transactions) <= 1) { throw new UnbegunTransaction('Attempted to rollback without having begun a transaction.'); } /** @var Transaction $transaction */ $transaction = array_pop($this->transactions); return $transaction->rollback(); }
php
public function rollback() { if (count($this->transactions) <= 1) { throw new UnbegunTransaction('Attempted to rollback without having begun a transaction.'); } /** @var Transaction $transaction */ $transaction = array_pop($this->transactions); return $transaction->rollback(); }
[ "public", "function", "rollback", "(", ")", "{", "if", "(", "count", "(", "$", "this", "->", "transactions", ")", "<=", "1", ")", "{", "throw", "new", "UnbegunTransaction", "(", "'Attempted to rollback without having begun a transaction.'", ")", ";", "}", "/** @...
Roll back all scheduled changes. @return bool @throws UnbegunTransaction
[ "Roll", "back", "all", "scheduled", "changes", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Buffered/TransactionalStore.php#L104-L114
train
matthiasmullie/scrapbook
src/Psr6/Repository.php
Repository.resolve
protected function resolve() { $keys = array_unique(array_values($this->unresolved)); $values = $this->store->getMulti($keys); foreach ($this->unresolved as $unique => $key) { if (!array_key_exists($key, $values)) { // key doesn't exist in cache continue; } /* * In theory, there could've been multiple unresolved requests for * the same cache key. In the case of objects, we'll clone them * to make sure that when the value for 1 item is manipulated, it * doesn't affect the value of the other item (because those objects * would be passed by-ref without the cloning) */ $value = $values[$key]; $value = is_object($value) ? clone $value : $value; $this->resolved[$unique] = $value; } $this->unresolved = array(); }
php
protected function resolve() { $keys = array_unique(array_values($this->unresolved)); $values = $this->store->getMulti($keys); foreach ($this->unresolved as $unique => $key) { if (!array_key_exists($key, $values)) { // key doesn't exist in cache continue; } /* * In theory, there could've been multiple unresolved requests for * the same cache key. In the case of objects, we'll clone them * to make sure that when the value for 1 item is manipulated, it * doesn't affect the value of the other item (because those objects * would be passed by-ref without the cloning) */ $value = $values[$key]; $value = is_object($value) ? clone $value : $value; $this->resolved[$unique] = $value; } $this->unresolved = array(); }
[ "protected", "function", "resolve", "(", ")", "{", "$", "keys", "=", "array_unique", "(", "array_values", "(", "$", "this", "->", "unresolved", ")", ")", ";", "$", "values", "=", "$", "this", "->", "store", "->", "getMulti", "(", "$", "keys", ")", ";...
Resolve all unresolved keys at once.
[ "Resolve", "all", "unresolved", "keys", "at", "once", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Psr6/Repository.php#L102-L127
train
matthiasmullie/scrapbook
src/Adapters/Flysystem.php
Flysystem.lock
protected function lock($key) { $path = $key.'.lock'; for ($i = 0; $i < 25; ++$i) { try { $this->filesystem->write($path, ''); return true; } catch (FileExistsException $e) { usleep(200); } } return false; }
php
protected function lock($key) { $path = $key.'.lock'; for ($i = 0; $i < 25; ++$i) { try { $this->filesystem->write($path, ''); return true; } catch (FileExistsException $e) { usleep(200); } } return false; }
[ "protected", "function", "lock", "(", "$", "key", ")", "{", "$", "path", "=", "$", "key", ".", "'.lock'", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "25", ";", "++", "$", "i", ")", "{", "try", "{", "$", "this", "->", "filesyst...
Obtain a lock for a given key. It'll try to get a lock for a couple of times, but ultimately give up if no lock can be obtained in a reasonable time. @param string $key @return bool
[ "Obtain", "a", "lock", "for", "a", "given", "key", ".", "It", "ll", "try", "to", "get", "a", "lock", "for", "a", "couple", "of", "times", "but", "ultimately", "give", "up", "if", "no", "lock", "can", "be", "obtained", "in", "a", "reasonable", "time",...
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Flysystem.php#L406-L421
train
matthiasmullie/scrapbook
src/Adapters/Flysystem.php
Flysystem.unlock
protected function unlock($key) { $path = $key.'.lock'; try { $this->filesystem->delete($path); } catch (FileNotFoundException $e) { return false; } return true; }
php
protected function unlock($key) { $path = $key.'.lock'; try { $this->filesystem->delete($path); } catch (FileNotFoundException $e) { return false; } return true; }
[ "protected", "function", "unlock", "(", "$", "key", ")", "{", "$", "path", "=", "$", "key", ".", "'.lock'", ";", "try", "{", "$", "this", "->", "filesystem", "->", "delete", "(", "$", "path", ")", ";", "}", "catch", "(", "FileNotFoundException", "$",...
Release the lock for a given key. @param string $key @return bool
[ "Release", "the", "lock", "for", "a", "given", "key", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Flysystem.php#L430-L440
train
matthiasmullie/scrapbook
src/Adapters/Flysystem.php
Flysystem.wrap
protected function wrap($value, $expire) { $expire = $this->normalizeTime($expire); return $expire."\n".serialize($value); }
php
protected function wrap($value, $expire) { $expire = $this->normalizeTime($expire); return $expire."\n".serialize($value); }
[ "protected", "function", "wrap", "(", "$", "value", ",", "$", "expire", ")", "{", "$", "expire", "=", "$", "this", "->", "normalizeTime", "(", "$", "expire", ")", ";", "return", "$", "expire", ".", "\"\\n\"", ".", "serialize", "(", "$", "value", ")",...
Build value, token & expiration time to be stored in cache file. @param string $value @param int $expire @return string
[ "Build", "value", "token", "&", "expiration", "time", "to", "be", "stored", "in", "cache", "file", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Flysystem.php#L478-L483
train
matthiasmullie/scrapbook
src/Adapters/Flysystem.php
Flysystem.read
protected function read($key) { $path = $this->path($key); try { $data = $this->filesystem->read($path); } catch (FileNotFoundException $e) { // unlikely given previous 'exists' check, but let's play safe... // (outside process may have removed it since) return false; } if ($data === false) { // in theory, a file could still be deleted between Flysystem's // assertPresent & the time it actually fetched the content // extremely unlikely though return false; } $data = explode("\n", $data, 2); $data[0] = (int) $data[0]; return $data; }
php
protected function read($key) { $path = $this->path($key); try { $data = $this->filesystem->read($path); } catch (FileNotFoundException $e) { // unlikely given previous 'exists' check, but let's play safe... // (outside process may have removed it since) return false; } if ($data === false) { // in theory, a file could still be deleted between Flysystem's // assertPresent & the time it actually fetched the content // extremely unlikely though return false; } $data = explode("\n", $data, 2); $data[0] = (int) $data[0]; return $data; }
[ "protected", "function", "read", "(", "$", "key", ")", "{", "$", "path", "=", "$", "this", "->", "path", "(", "$", "key", ")", ";", "try", "{", "$", "data", "=", "$", "this", "->", "filesystem", "->", "read", "(", "$", "path", ")", ";", "}", ...
Fetch stored data from cache file. @param string $key @return bool|array
[ "Fetch", "stored", "data", "from", "cache", "file", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Flysystem.php#L492-L514
train
matthiasmullie/scrapbook
src/Adapters/MemoryStore.php
MemoryStore.exists
protected function exists($key) { if (!array_key_exists($key, $this->items)) { // key not in cache return false; } $expire = $this->items[$key][1]; if ($expire !== 0 && $expire < time()) { // not permanent & already expired $this->size -= strlen($this->items[$key][0]); unset($this->items[$key]); return false; } $this->lru($key); return true; }
php
protected function exists($key) { if (!array_key_exists($key, $this->items)) { // key not in cache return false; } $expire = $this->items[$key][1]; if ($expire !== 0 && $expire < time()) { // not permanent & already expired $this->size -= strlen($this->items[$key][0]); unset($this->items[$key]); return false; } $this->lru($key); return true; }
[ "protected", "function", "exists", "(", "$", "key", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "items", ")", ")", "{", "// key not in cache", "return", "false", ";", "}", "$", "expire", "=", "$", "this", "-...
Checks if a value exists in cache and is not yet expired. @param string $key @return bool
[ "Checks", "if", "a", "value", "exists", "in", "cache", "and", "is", "not", "yet", "expired", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/MemoryStore.php#L258-L277
train
matthiasmullie/scrapbook
src/Adapters/MemoryStore.php
MemoryStore.lru
protected function lru($key) { // move key that has just been used to last position in the array $value = $this->items[$key]; unset($this->items[$key]); $this->items[$key] = $value; }
php
protected function lru($key) { // move key that has just been used to last position in the array $value = $this->items[$key]; unset($this->items[$key]); $this->items[$key] = $value; }
[ "protected", "function", "lru", "(", "$", "key", ")", "{", "// move key that has just been used to last position in the array", "$", "value", "=", "$", "this", "->", "items", "[", "$", "key", "]", ";", "unset", "(", "$", "this", "->", "items", "[", "$", "key...
This cache uses least recently used algorithm. This is to be called with the key to be marked as just used.
[ "This", "cache", "uses", "least", "recently", "used", "algorithm", ".", "This", "is", "to", "be", "called", "with", "the", "key", "to", "be", "marked", "as", "just", "used", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/MemoryStore.php#L344-L350
train
matthiasmullie/scrapbook
src/Adapters/MemoryStore.php
MemoryStore.evict
protected function evict() { while ($this->size > $this->limit && !empty($this->items)) { $item = array_shift($this->items); $this->size -= strlen($item[0]); } }
php
protected function evict() { while ($this->size > $this->limit && !empty($this->items)) { $item = array_shift($this->items); $this->size -= strlen($item[0]); } }
[ "protected", "function", "evict", "(", ")", "{", "while", "(", "$", "this", "->", "size", ">", "$", "this", "->", "limit", "&&", "!", "empty", "(", "$", "this", "->", "items", ")", ")", "{", "$", "item", "=", "array_shift", "(", "$", "this", "->"...
Least recently used cache values will be evicted from cache should it fill up too much.
[ "Least", "recently", "used", "cache", "values", "will", "be", "evicted", "from", "cache", "should", "it", "fill", "up", "too", "much", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/MemoryStore.php#L356-L362
train
matthiasmullie/scrapbook
src/Buffered/Utils/BufferCollection.php
BufferCollection.expired
public function expired($key) { if ($this->get($key) !== false) { // returned a value, clearly not yet expired return false; } // a known item, not returned by get, is expired return array_key_exists($key, $this->cache->items); }
php
public function expired($key) { if ($this->get($key) !== false) { // returned a value, clearly not yet expired return false; } // a known item, not returned by get, is expired return array_key_exists($key, $this->cache->items); }
[ "public", "function", "expired", "(", "$", "key", ")", "{", "if", "(", "$", "this", "->", "get", "(", "$", "key", ")", "!==", "false", ")", "{", "// returned a value, clearly not yet expired", "return", "false", ";", "}", "// a known item, not returned by get, i...
Check if a key existed in local storage, but is now expired. Because our local buffer is also just a real cache, expired items will just return nothing, which will lead us to believe no such item exists in that local cache, and we'll reach out to the real cache (where the value may not yet have been expired because that may have been part of an uncommitted write) So we'll want to know when a value is in local cache, but expired! @param string $key @return bool
[ "Check", "if", "a", "key", "existed", "in", "local", "storage", "but", "is", "now", "expired", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Buffered/Utils/BufferCollection.php#L44-L53
train
matthiasmullie/scrapbook
src/Adapters/Memcached.php
Memcached.encode
protected function encode($key) { $regex = '/[^\x21\x22\x24\x26-\x39\x3b-\x7e]+/'; $key = preg_replace_callback($regex, function ($match) { return rawurlencode($match[0]); }, $key); if (strlen($key) > 255) { throw new InvalidKey( "Invalid key: $key. Encoded Memcached keys can not exceed 255 chars." ); } return $key; }
php
protected function encode($key) { $regex = '/[^\x21\x22\x24\x26-\x39\x3b-\x7e]+/'; $key = preg_replace_callback($regex, function ($match) { return rawurlencode($match[0]); }, $key); if (strlen($key) > 255) { throw new InvalidKey( "Invalid key: $key. Encoded Memcached keys can not exceed 255 chars." ); } return $key; }
[ "protected", "function", "encode", "(", "$", "key", ")", "{", "$", "regex", "=", "'/[^\\x21\\x22\\x24\\x26-\\x39\\x3b-\\x7e]+/'", ";", "$", "key", "=", "preg_replace_callback", "(", "$", "regex", ",", "function", "(", "$", "match", ")", "{", "return", "rawurle...
Encode a key for use on the wire inside the memcached protocol. We encode spaces and line breaks to avoid protocol errors. We encode the other control characters for compatibility with libmemcached verify_key. We leave other punctuation alone, to maximise backwards compatibility. @see https://github.com/wikimedia/mediawiki/commit/be76d869#diff-75b7c03970b5e43de95ff95f5faa6ef1R100 @see https://github.com/wikimedia/mediawiki/blob/master/includes/libs/objectcache/MemcachedBagOStuff.php#L116 @param string $key @return string @throws InvalidKey
[ "Encode", "a", "key", "for", "use", "on", "the", "wire", "inside", "the", "memcached", "protocol", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Memcached.php#L374-L388
train
matthiasmullie/scrapbook
src/Adapters/Memcached.php
Memcached.throwExceptionOnClientCallFailure
protected function throwExceptionOnClientCallFailure($result) { if ($result !== false) { return; } throw new OperationFailed( $this->client->getResultMessage(), $this->client->getResultCode() ); }
php
protected function throwExceptionOnClientCallFailure($result) { if ($result !== false) { return; } throw new OperationFailed( $this->client->getResultMessage(), $this->client->getResultCode() ); }
[ "protected", "function", "throwExceptionOnClientCallFailure", "(", "$", "result", ")", "{", "if", "(", "$", "result", "!==", "false", ")", "{", "return", ";", "}", "throw", "new", "OperationFailed", "(", "$", "this", "->", "client", "->", "getResultMessage", ...
Will throw an exception if the returned result from a Memcached call indicates a failure in the operation. The exception will contain debug information about the failure. @param mixed $result @throws OperationFailed
[ "Will", "throw", "an", "exception", "if", "the", "returned", "result", "from", "a", "Memcached", "call", "indicates", "a", "failure", "in", "the", "operation", ".", "The", "exception", "will", "contain", "debug", "information", "about", "the", "failure", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Memcached.php#L445-L455
train
matthiasmullie/scrapbook
src/Buffered/Utils/Defer.php
Defer.commit
public function commit() { list($old, $new) = $this->generateRollback(); $updates = $this->generateUpdates(); $updates = $this->combineUpdates($updates); usort($updates, array($this, 'sortUpdates')); foreach ($updates as $update) { // apply update to cache & receive a simple bool to indicate // success (true) or failure (false) $success = call_user_func_array($update[1], $update[2]); if ($success === false) { $this->rollback($old, $new); return false; } } $this->clear(); return true; }
php
public function commit() { list($old, $new) = $this->generateRollback(); $updates = $this->generateUpdates(); $updates = $this->combineUpdates($updates); usort($updates, array($this, 'sortUpdates')); foreach ($updates as $update) { // apply update to cache & receive a simple bool to indicate // success (true) or failure (false) $success = call_user_func_array($update[1], $update[2]); if ($success === false) { $this->rollback($old, $new); return false; } } $this->clear(); return true; }
[ "public", "function", "commit", "(", ")", "{", "list", "(", "$", "old", ",", "$", "new", ")", "=", "$", "this", "->", "generateRollback", "(", ")", ";", "$", "updates", "=", "$", "this", "->", "generateUpdates", "(", ")", ";", "$", "updates", "=", ...
Commit all deferred writes to cache. When the commit fails, no changes in this transaction will be applied (and those that had already been applied will be undone). False will be returned in that case. @return bool
[ "Commit", "all", "deferred", "writes", "to", "cache", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Buffered/Utils/Defer.php#L352-L373
train
matthiasmullie/scrapbook
src/Buffered/Utils/Defer.php
Defer.rollback
protected function rollback(array $old, array $new) { foreach ($old as $key => $value) { $current = $this->cache->get($key, $token); /* * If the value right now equals the one we planned to write, it * should be restored to what it was before. If it's yet something * else, another process must've stored it and we should leave it * alone. */ if ($current === $new) { /* * CAS the rollback. If it fails, that means another process * has stored in the meantime and we can just leave it alone. * Note that we can't know the original expiration time! */ $this->cas($token, $key, $value, 0); } } $this->clear(); }
php
protected function rollback(array $old, array $new) { foreach ($old as $key => $value) { $current = $this->cache->get($key, $token); /* * If the value right now equals the one we planned to write, it * should be restored to what it was before. If it's yet something * else, another process must've stored it and we should leave it * alone. */ if ($current === $new) { /* * CAS the rollback. If it fails, that means another process * has stored in the meantime and we can just leave it alone. * Note that we can't know the original expiration time! */ $this->cas($token, $key, $value, 0); } } $this->clear(); }
[ "protected", "function", "rollback", "(", "array", "$", "old", ",", "array", "$", "new", ")", "{", "foreach", "(", "$", "old", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "current", "=", "$", "this", "->", "cache", "->", "get", "(", "$",...
Roll the cache back to pre-transaction state by comparing the current cache values with what we planned to set them to. @param array $old @param array $new
[ "Roll", "the", "cache", "back", "to", "pre", "-", "transaction", "state", "by", "comparing", "the", "current", "cache", "values", "with", "what", "we", "planned", "to", "set", "them", "to", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Buffered/Utils/Defer.php#L382-L404
train
matthiasmullie/scrapbook
src/Buffered/Utils/Defer.php
Defer.generateUpdates
protected function generateUpdates() { $updates = array(); if ($this->flush) { $updates[] = array('flush', array($this->cache, 'flush'), array()); } foreach ($this->keys as $key => $data) { $updates[] = $data; } return $updates; }
php
protected function generateUpdates() { $updates = array(); if ($this->flush) { $updates[] = array('flush', array($this->cache, 'flush'), array()); } foreach ($this->keys as $key => $data) { $updates[] = $data; } return $updates; }
[ "protected", "function", "generateUpdates", "(", ")", "{", "$", "updates", "=", "array", "(", ")", ";", "if", "(", "$", "this", "->", "flush", ")", "{", "$", "updates", "[", "]", "=", "array", "(", "'flush'", ",", "array", "(", "$", "this", "->", ...
By storing all updates by key, we've already made sure we don't perform redundant operations on a per-key basis. Now we'll turn those into actual updates. @return array
[ "By", "storing", "all", "updates", "by", "key", "we", "ve", "already", "made", "sure", "we", "don", "t", "perform", "redundant", "operations", "on", "a", "per", "-", "key", "basis", ".", "Now", "we", "ll", "turn", "those", "into", "actual", "updates", ...
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Buffered/Utils/Defer.php#L450-L463
train
matthiasmullie/scrapbook
src/Buffered/Utils/Defer.php
Defer.combineUpdates
protected function combineUpdates($updates) { $setMulti = array(); $deleteMulti = array(); foreach ($updates as $i => $update) { $operation = $update[0]; $args = $update[2]; switch ($operation) { // all set & delete operations can be grouped into setMulti & deleteMulti case 'set': unset($updates[$i]); // only group sets with same expiration $setMulti[$args['expire']][$args['key']] = $args['value']; break; case 'delete': unset($updates[$i]); $deleteMulti[] = $args['key']; break; default: break; } } if (!empty($setMulti)) { $cache = $this->cache; /* * We'll use the return value of all deferred writes to check if they * should be rolled back. * commit() expects a single bool, not a per-key array of success bools. * * @param mixed[] $items * @param int $expire * @return bool */ $callback = function ($items, $expire) use ($cache) { $success = $cache->setMulti($items, $expire); return !in_array(false, $success); }; foreach ($setMulti as $expire => $items) { $updates[] = array('setMulti', $callback, array($items, $expire)); } } if (!empty($deleteMulti)) { $cache = $this->cache; /* * commit() expected a single bool, not an array of success bools. * Besides, deleteMulti() is never cause for failure here: if the * key didn't exist because it has been deleted elsewhere already, * the data isn't corrupt, it's still as we'd expect it. * * @param string[] $keys * @return bool */ $callback = function ($keys) use ($cache) { $cache->deleteMulti($keys); return true; }; $updates[] = array('deleteMulti', $callback, array($deleteMulti)); } return $updates; }
php
protected function combineUpdates($updates) { $setMulti = array(); $deleteMulti = array(); foreach ($updates as $i => $update) { $operation = $update[0]; $args = $update[2]; switch ($operation) { // all set & delete operations can be grouped into setMulti & deleteMulti case 'set': unset($updates[$i]); // only group sets with same expiration $setMulti[$args['expire']][$args['key']] = $args['value']; break; case 'delete': unset($updates[$i]); $deleteMulti[] = $args['key']; break; default: break; } } if (!empty($setMulti)) { $cache = $this->cache; /* * We'll use the return value of all deferred writes to check if they * should be rolled back. * commit() expects a single bool, not a per-key array of success bools. * * @param mixed[] $items * @param int $expire * @return bool */ $callback = function ($items, $expire) use ($cache) { $success = $cache->setMulti($items, $expire); return !in_array(false, $success); }; foreach ($setMulti as $expire => $items) { $updates[] = array('setMulti', $callback, array($items, $expire)); } } if (!empty($deleteMulti)) { $cache = $this->cache; /* * commit() expected a single bool, not an array of success bools. * Besides, deleteMulti() is never cause for failure here: if the * key didn't exist because it has been deleted elsewhere already, * the data isn't corrupt, it's still as we'd expect it. * * @param string[] $keys * @return bool */ $callback = function ($keys) use ($cache) { $cache->deleteMulti($keys); return true; }; $updates[] = array('deleteMulti', $callback, array($deleteMulti)); } return $updates; }
[ "protected", "function", "combineUpdates", "(", "$", "updates", ")", "{", "$", "setMulti", "=", "array", "(", ")", ";", "$", "deleteMulti", "=", "array", "(", ")", ";", "foreach", "(", "$", "updates", "as", "$", "i", "=>", "$", "update", ")", "{", ...
We may have multiple sets & deletes, which can be combined into a single setMulti or deleteMulti operation. @param array $updates @return array
[ "We", "may", "have", "multiple", "sets", "&", "deletes", "which", "can", "be", "combined", "into", "a", "single", "setMulti", "or", "deleteMulti", "operation", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Buffered/Utils/Defer.php#L473-L545
train
matthiasmullie/scrapbook
src/Buffered/Utils/Defer.php
Defer.sortUpdates
protected function sortUpdates(array $a, array $b) { $updateOrder = array( // there's no point in applying this after doing the below updates // we also shouldn't really worry about cas/replace failing after this, // there won't be any after cache having been flushed 'flush', // prone to fail: they depend on certain conditions (token must match // or value must (not) exist) 'cas', 'replace', 'add', // unlikely/impossible to fail, assuming the input is valid 'touch', 'increment', 'decrement', 'set', 'setMulti', 'delete', 'deleteMulti', ); if ($a[0] === $b[0]) { return 0; } return array_search($a[0], $updateOrder) < array_search($b[0], $updateOrder) ? -1 : 1; }
php
protected function sortUpdates(array $a, array $b) { $updateOrder = array( // there's no point in applying this after doing the below updates // we also shouldn't really worry about cas/replace failing after this, // there won't be any after cache having been flushed 'flush', // prone to fail: they depend on certain conditions (token must match // or value must (not) exist) 'cas', 'replace', 'add', // unlikely/impossible to fail, assuming the input is valid 'touch', 'increment', 'decrement', 'set', 'setMulti', 'delete', 'deleteMulti', ); if ($a[0] === $b[0]) { return 0; } return array_search($a[0], $updateOrder) < array_search($b[0], $updateOrder) ? -1 : 1; }
[ "protected", "function", "sortUpdates", "(", "array", "$", "a", ",", "array", "$", "b", ")", "{", "$", "updateOrder", "=", "array", "(", "// there's no point in applying this after doing the below updates", "// we also shouldn't really worry about cas/replace failing after this...
Change the order of the updates in this transaction to ensure we have those most likely to fail first. That'll decrease odds of having to roll back, and make rolling back easier. @param array $a Update, where index 0 is the operation name @param array $b Update, where index 0 is the operation name @return int
[ "Change", "the", "order", "of", "the", "updates", "in", "this", "transaction", "to", "ensure", "we", "have", "those", "most", "likely", "to", "fail", "first", ".", "That", "ll", "decrease", "odds", "of", "having", "to", "roll", "back", "and", "make", "ro...
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Buffered/Utils/Defer.php#L557-L584
train
matthiasmullie/scrapbook
src/Adapters/Redis.php
Redis.getVersion
protected function getVersion() { if ($this->version === null) { $info = $this->client->info(); $this->version = $info['redis_version']; } return $this->version; }
php
protected function getVersion() { if ($this->version === null) { $info = $this->client->info(); $this->version = $info['redis_version']; } return $this->version; }
[ "protected", "function", "getVersion", "(", ")", "{", "if", "(", "$", "this", "->", "version", "===", "null", ")", "{", "$", "info", "=", "$", "this", "->", "client", "->", "info", "(", ")", ";", "$", "this", "->", "version", "=", "$", "info", "[...
Returns the version of the Redis server we're connecting to. @return string
[ "Returns", "the", "version", "of", "the", "Redis", "server", "we", "re", "connecting", "to", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Redis.php#L611-L619
train
deInternetJongens/Lighthouse-Utils
src/Generators/SchemaGenerator.php
SchemaGenerator.generate
public function generate(array $definitionFileDirectories): string { $authEnabled = config('lighthouse-utils.authorization'); if ($authEnabled) { GraphQLSchema::truncate(); } $this->validateFilesPaths($definitionFileDirectories); $schema = $this->getSchemaForFiles($definitionFileDirectories); $definedTypes = $this->getDefinedTypesFromSchema($schema, $definitionFileDirectories); $queries = $this->generateQueriesForDefinedTypes($definedTypes, $definitionFileDirectories); $typesImports = $this->concatSchemaDefinitionFilesFromPath( $this->definitionsParser->getGraphqlDefinitionFilePaths($definitionFileDirectories['types']) ); if ($authEnabled) { event(new GraphQLSchemaGenerated(GraphQLSchema::all())); } //Merge queries and types into one file with required newlines return sprintf("%s\r\n\r\n%s\r\n", $typesImports, $queries); }
php
public function generate(array $definitionFileDirectories): string { $authEnabled = config('lighthouse-utils.authorization'); if ($authEnabled) { GraphQLSchema::truncate(); } $this->validateFilesPaths($definitionFileDirectories); $schema = $this->getSchemaForFiles($definitionFileDirectories); $definedTypes = $this->getDefinedTypesFromSchema($schema, $definitionFileDirectories); $queries = $this->generateQueriesForDefinedTypes($definedTypes, $definitionFileDirectories); $typesImports = $this->concatSchemaDefinitionFilesFromPath( $this->definitionsParser->getGraphqlDefinitionFilePaths($definitionFileDirectories['types']) ); if ($authEnabled) { event(new GraphQLSchemaGenerated(GraphQLSchema::all())); } //Merge queries and types into one file with required newlines return sprintf("%s\r\n\r\n%s\r\n", $typesImports, $queries); }
[ "public", "function", "generate", "(", "array", "$", "definitionFileDirectories", ")", ":", "string", "{", "$", "authEnabled", "=", "config", "(", "'lighthouse-utils.authorization'", ")", ";", "if", "(", "$", "authEnabled", ")", "{", "GraphQLSchema", "::", "trun...
Generates a schema from an array of definition file directories For now, this only supports Types. In the future it should also support Mutations and Queries. @param array $definitionFileDirectories @return string Generated Schema with Types and Queries @throws InvalidConfigurationException @throws \Nuwave\Lighthouse\Exceptions\DirectiveException @throws \Nuwave\Lighthouse\Exceptions\ParseException
[ "Generates", "a", "schema", "from", "an", "array", "of", "definition", "file", "directories", "For", "now", "this", "only", "supports", "Types", ".", "In", "the", "future", "it", "should", "also", "support", "Mutations", "and", "Queries", "." ]
31cd7ffe225f4639f3ecf2fd40c4e6835a145dda
https://github.com/deInternetJongens/Lighthouse-Utils/blob/31cd7ffe225f4639f3ecf2fd40c4e6835a145dda/src/Generators/SchemaGenerator.php#L86-L110
train
deInternetJongens/Lighthouse-Utils
src/Generators/SchemaGenerator.php
SchemaGenerator.validateFilesPaths
private function validateFilesPaths(array $definitionFileDirectories): bool { if (count($definitionFileDirectories) < 1) { throw new InvalidConfigurationException( 'The "schema_paths" config value is empty, it should contain a value with a valid path for the following keys: mutations, queries, types' ); } if (array_diff(array_keys($definitionFileDirectories), $this->requiredSchemaFileKeys)) { throw new InvalidConfigurationException( 'The "schema_paths" config value is incomplete, it should contain a value with a valid path for the following keys: mutations, queries, types' ); } foreach ($definitionFileDirectories as $key => $path) { if (empty($path)) { throw new InvalidConfigurationException( sprintf( 'The "schema_paths" config value for key "%s" is empty, it should contain a value with a valid path', $key ) ); } if (! file_exists($path)) { throw new InvalidConfigurationException( sprintf('The "schema_paths" config value for key "%s" contains a path that does not exist', $key) ); } } return true; }
php
private function validateFilesPaths(array $definitionFileDirectories): bool { if (count($definitionFileDirectories) < 1) { throw new InvalidConfigurationException( 'The "schema_paths" config value is empty, it should contain a value with a valid path for the following keys: mutations, queries, types' ); } if (array_diff(array_keys($definitionFileDirectories), $this->requiredSchemaFileKeys)) { throw new InvalidConfigurationException( 'The "schema_paths" config value is incomplete, it should contain a value with a valid path for the following keys: mutations, queries, types' ); } foreach ($definitionFileDirectories as $key => $path) { if (empty($path)) { throw new InvalidConfigurationException( sprintf( 'The "schema_paths" config value for key "%s" is empty, it should contain a value with a valid path', $key ) ); } if (! file_exists($path)) { throw new InvalidConfigurationException( sprintf('The "schema_paths" config value for key "%s" contains a path that does not exist', $key) ); } } return true; }
[ "private", "function", "validateFilesPaths", "(", "array", "$", "definitionFileDirectories", ")", ":", "bool", "{", "if", "(", "count", "(", "$", "definitionFileDirectories", ")", "<", "1", ")", "{", "throw", "new", "InvalidConfigurationException", "(", "'The \"sc...
Validates if the given defintionFileDirectories contains; - All required keys - Filled values for each key - Existing paths for each key @param array $definitionFileDirectories @return bool @throws InvalidConfigurationException
[ "Validates", "if", "the", "given", "defintionFileDirectories", "contains", ";", "-", "All", "required", "keys", "-", "Filled", "values", "for", "each", "key", "-", "Existing", "paths", "for", "each", "key" ]
31cd7ffe225f4639f3ecf2fd40c4e6835a145dda
https://github.com/deInternetJongens/Lighthouse-Utils/blob/31cd7ffe225f4639f3ecf2fd40c4e6835a145dda/src/Generators/SchemaGenerator.php#L122-L153
train
deInternetJongens/Lighthouse-Utils
src/Generators/SchemaGenerator.php
SchemaGenerator.getSchemaForFiles
private function getSchemaForFiles(array $definitionFileDirectories): Schema { resolve('events')->listen( BuildingAST::class, function () use ($definitionFileDirectories) { $typeDefinitionPaths = $this->definitionsParser->getGraphqlDefinitionFilePaths( $definitionFileDirectories['types'] ); $relativeTypeImports = $this->concatSchemaDefinitionFilesFromPath($typeDefinitionPaths); // Webonyx GraphQL will not generate a schema if there is not at least one query // So just pretend we have one $placeholderQuery = 'type Query{placeholder:String}'; return "$relativeTypeImports\r\n$placeholderQuery"; } ); $schema = graphql()->prepSchema(); return $schema; }
php
private function getSchemaForFiles(array $definitionFileDirectories): Schema { resolve('events')->listen( BuildingAST::class, function () use ($definitionFileDirectories) { $typeDefinitionPaths = $this->definitionsParser->getGraphqlDefinitionFilePaths( $definitionFileDirectories['types'] ); $relativeTypeImports = $this->concatSchemaDefinitionFilesFromPath($typeDefinitionPaths); // Webonyx GraphQL will not generate a schema if there is not at least one query // So just pretend we have one $placeholderQuery = 'type Query{placeholder:String}'; return "$relativeTypeImports\r\n$placeholderQuery"; } ); $schema = graphql()->prepSchema(); return $schema; }
[ "private", "function", "getSchemaForFiles", "(", "array", "$", "definitionFileDirectories", ")", ":", "Schema", "{", "resolve", "(", "'events'", ")", "->", "listen", "(", "BuildingAST", "::", "class", ",", "function", "(", ")", "use", "(", "$", "definitionFile...
Generates a GraphQL schema for a set of definition files Definition files can only be Types at this time In the future this should also support Mutations and Queries @param array $definitionFileDirectories @return Schema @throws \Nuwave\Lighthouse\Exceptions\DirectiveException @throws \Nuwave\Lighthouse\Exceptions\ParseException
[ "Generates", "a", "GraphQL", "schema", "for", "a", "set", "of", "definition", "files", "Definition", "files", "can", "only", "be", "Types", "at", "this", "time", "In", "the", "future", "this", "should", "also", "support", "Mutations", "and", "Queries" ]
31cd7ffe225f4639f3ecf2fd40c4e6835a145dda
https://github.com/deInternetJongens/Lighthouse-Utils/blob/31cd7ffe225f4639f3ecf2fd40c4e6835a145dda/src/Generators/SchemaGenerator.php#L165-L185
train
deInternetJongens/Lighthouse-Utils
src/Generators/SchemaGenerator.php
SchemaGenerator.getDefinedTypesFromSchema
private function getDefinedTypesFromSchema(Schema $schema, array $definitionFileDirectories): array { $definedTypes = $this->definitionsParser->getGraphqlDefinitionFilePaths( $definitionFileDirectories['types'] ); foreach ($definedTypes as $key => $type) { $definedTypes[$key] = str_replace('.graphql', '', basename($type)); } $internalTypes = []; /** * @var string $typeName * @var ObjectType $type */ foreach ($schema->getTypeMap() as $typeName => $type) { if (! in_array($typeName, $definedTypes) || ! method_exists($type, 'getFields')) { continue; } /** * @var string $fieldName * @var FieldDefinition $fieldType */ foreach ($type->getFields() as $fieldName => $fieldType) { $graphQLType = $fieldType->getType(); //Every required field is defined by a parent 'NonNullType' if (method_exists($graphQLType, 'getWrappedType')) { // Clone the field to prevent pass by reference, // because we want to add a config value unique to this field. $graphQLType = clone $graphQLType->getWrappedType(); //We want to know later on wether or not a field is required $graphQLType->config['generator-required'] = true; } if (! in_array(get_class($graphQLType), $this->supportedGraphQLTypes)) { continue; }; // This retrieves the GraphQL type for this field from the webonyx/graphql-php package $internalTypes[$typeName][$fieldName] = $graphQLType; } } return $internalTypes; }
php
private function getDefinedTypesFromSchema(Schema $schema, array $definitionFileDirectories): array { $definedTypes = $this->definitionsParser->getGraphqlDefinitionFilePaths( $definitionFileDirectories['types'] ); foreach ($definedTypes as $key => $type) { $definedTypes[$key] = str_replace('.graphql', '', basename($type)); } $internalTypes = []; /** * @var string $typeName * @var ObjectType $type */ foreach ($schema->getTypeMap() as $typeName => $type) { if (! in_array($typeName, $definedTypes) || ! method_exists($type, 'getFields')) { continue; } /** * @var string $fieldName * @var FieldDefinition $fieldType */ foreach ($type->getFields() as $fieldName => $fieldType) { $graphQLType = $fieldType->getType(); //Every required field is defined by a parent 'NonNullType' if (method_exists($graphQLType, 'getWrappedType')) { // Clone the field to prevent pass by reference, // because we want to add a config value unique to this field. $graphQLType = clone $graphQLType->getWrappedType(); //We want to know later on wether or not a field is required $graphQLType->config['generator-required'] = true; } if (! in_array(get_class($graphQLType), $this->supportedGraphQLTypes)) { continue; }; // This retrieves the GraphQL type for this field from the webonyx/graphql-php package $internalTypes[$typeName][$fieldName] = $graphQLType; } } return $internalTypes; }
[ "private", "function", "getDefinedTypesFromSchema", "(", "Schema", "$", "schema", ",", "array", "$", "definitionFileDirectories", ")", ":", "array", "{", "$", "definedTypes", "=", "$", "this", "->", "definitionsParser", "->", "getGraphqlDefinitionFilePaths", "(", "$...
Parse defined types from a schema into an array with the native GraphQL Scalar types for each field @param Schema $schema @param array $definitionFileDirectories @return Type[]
[ "Parse", "defined", "types", "from", "a", "schema", "into", "an", "array", "with", "the", "native", "GraphQL", "Scalar", "types", "for", "each", "field" ]
31cd7ffe225f4639f3ecf2fd40c4e6835a145dda
https://github.com/deInternetJongens/Lighthouse-Utils/blob/31cd7ffe225f4639f3ecf2fd40c4e6835a145dda/src/Generators/SchemaGenerator.php#L209-L256
train
deInternetJongens/Lighthouse-Utils
src/Generators/SchemaGenerator.php
SchemaGenerator.generateQueriesForDefinedTypes
private function generateQueriesForDefinedTypes(array $definedTypes, array $definitionFileDirectories): string { $queries = []; $mutations = []; $inputTypes = []; /** * @var string $typeName * @var Type $type */ foreach ($definedTypes as $typeName => $type) { $paginateAndAllQuery = PaginateAllQueryGenerator::generate($typeName, $type); if (! empty($paginateAndAllQuery)) { $queries[] = $paginateAndAllQuery; } $findQuery = FindQueryGenerator::generate($typeName, $type); if (! empty($findQuery)) { $queries[] = $findQuery; } $createMutation = createMutationWithInputTypeGenerator::generate($typeName, $type); if ($createMutation->isNotEmpty()) { $mutations[] = $createMutation->getMutation(); $inputTypes[] = $createMutation->getInputType(); } $updateMutation = updateMutationWithInputTypeGenerator::generate($typeName, $type); if ($updateMutation->isNotEmpty()) { $mutations[] = $updateMutation->getMutation(); $inputTypes[] = $updateMutation->getInputType(); } $deleteMutation = DeleteMutationGenerator::generate($typeName, $type); if (! empty($deleteMutation)) { $mutations[] = $deleteMutation; } } $queries = array_merge( $queries, $this->definitionsParser->parseCustomQueriesFrom($definitionFileDirectories['queries']) ); $mutations = array_merge( $mutations, $this->definitionsParser->parseCustomMutationsFrom($definitionFileDirectories['mutations']) ); $return = sprintf("type Query{\r\n%s\r\n}", implode("\r\n", $queries)); $return .= "\r\n\r\n"; $return .= sprintf("type Mutation{\r\n%s\r\n}", implode("\r\n", $mutations)); $return .= "\r\n\r\n"; $return .= implode("\r\n", $inputTypes); return $return; }
php
private function generateQueriesForDefinedTypes(array $definedTypes, array $definitionFileDirectories): string { $queries = []; $mutations = []; $inputTypes = []; /** * @var string $typeName * @var Type $type */ foreach ($definedTypes as $typeName => $type) { $paginateAndAllQuery = PaginateAllQueryGenerator::generate($typeName, $type); if (! empty($paginateAndAllQuery)) { $queries[] = $paginateAndAllQuery; } $findQuery = FindQueryGenerator::generate($typeName, $type); if (! empty($findQuery)) { $queries[] = $findQuery; } $createMutation = createMutationWithInputTypeGenerator::generate($typeName, $type); if ($createMutation->isNotEmpty()) { $mutations[] = $createMutation->getMutation(); $inputTypes[] = $createMutation->getInputType(); } $updateMutation = updateMutationWithInputTypeGenerator::generate($typeName, $type); if ($updateMutation->isNotEmpty()) { $mutations[] = $updateMutation->getMutation(); $inputTypes[] = $updateMutation->getInputType(); } $deleteMutation = DeleteMutationGenerator::generate($typeName, $type); if (! empty($deleteMutation)) { $mutations[] = $deleteMutation; } } $queries = array_merge( $queries, $this->definitionsParser->parseCustomQueriesFrom($definitionFileDirectories['queries']) ); $mutations = array_merge( $mutations, $this->definitionsParser->parseCustomMutationsFrom($definitionFileDirectories['mutations']) ); $return = sprintf("type Query{\r\n%s\r\n}", implode("\r\n", $queries)); $return .= "\r\n\r\n"; $return .= sprintf("type Mutation{\r\n%s\r\n}", implode("\r\n", $mutations)); $return .= "\r\n\r\n"; $return .= implode("\r\n", $inputTypes); return $return; }
[ "private", "function", "generateQueriesForDefinedTypes", "(", "array", "$", "definedTypes", ",", "array", "$", "definitionFileDirectories", ")", ":", "string", "{", "$", "queries", "=", "[", "]", ";", "$", "mutations", "=", "[", "]", ";", "$", "inputTypes", ...
Auto-generates a query for each definedType These queries contain arguments for each field defined in the Type @param array $definedTypes @param array $definitionFileDirectories @return string
[ "Auto", "-", "generates", "a", "query", "for", "each", "definedType", "These", "queries", "contain", "arguments", "for", "each", "field", "defined", "in", "the", "Type" ]
31cd7ffe225f4639f3ecf2fd40c4e6835a145dda
https://github.com/deInternetJongens/Lighthouse-Utils/blob/31cd7ffe225f4639f3ecf2fd40c4e6835a145dda/src/Generators/SchemaGenerator.php#L266-L323
train
deInternetJongens/Lighthouse-Utils
src/Generators/Arguments/RelationArgumentGenerator.php
RelationArgumentGenerator.generate
public static function generate(array $typeFields): array { $arguments = []; foreach ($typeFields as $fieldName => $field) { $config = $field->config; $required = isset($config['generator-required']) ? ($config['generator-required'] ? '!' : '') : ''; $className = get_class($field); if ($className !== ObjectType::class) { continue; } $arguments[] = sprintf('%s_id: ID%s', $fieldName, $required); } return $arguments; }
php
public static function generate(array $typeFields): array { $arguments = []; foreach ($typeFields as $fieldName => $field) { $config = $field->config; $required = isset($config['generator-required']) ? ($config['generator-required'] ? '!' : '') : ''; $className = get_class($field); if ($className !== ObjectType::class) { continue; } $arguments[] = sprintf('%s_id: ID%s', $fieldName, $required); } return $arguments; }
[ "public", "static", "function", "generate", "(", "array", "$", "typeFields", ")", ":", "array", "{", "$", "arguments", "=", "[", "]", ";", "foreach", "(", "$", "typeFields", "as", "$", "fieldName", "=>", "$", "field", ")", "{", "$", "config", "=", "$...
Generates a GraphQL mutation argument for a relation field @param Type[] $typeFields @param bool $required Should the relationship fields be required? @return array
[ "Generates", "a", "GraphQL", "mutation", "argument", "for", "a", "relation", "field" ]
31cd7ffe225f4639f3ecf2fd40c4e6835a145dda
https://github.com/deInternetJongens/Lighthouse-Utils/blob/31cd7ffe225f4639f3ecf2fd40c4e6835a145dda/src/Generators/Arguments/RelationArgumentGenerator.php#L17-L34
train
deInternetJongens/Lighthouse-Utils
src/Generators/Queries/FindQueryGenerator.php
FindQueryGenerator.generate
public static function generate(string $typeName, array $typeFields): string { $arguments = []; //Loop through fields to find the 'ID' field. foreach ($typeFields as $fieldName => $field) { if (false === ($field instanceof IDType)) { continue; } $arguments[] = sprintf('%s: %s! @eq', $fieldName, $field->name); break; } if (count($arguments) < 1) { return ''; } $queryName = lcfirst($typeName); $query = sprintf(' %s(%s)', $queryName, implode(', ', $arguments)); $query .= sprintf(': %1$s @find(model: "%1$s")', $typeName); if (config('lighthouse-utils.authorization')) { $permission = sprintf('find%1$s', $typeName); $query .= sprintf(' @can(if: "%1$s", model: "User")', $permission); } GraphQLSchema::register($queryName, $typeName, 'query', $permission ?? null); return $query; }
php
public static function generate(string $typeName, array $typeFields): string { $arguments = []; //Loop through fields to find the 'ID' field. foreach ($typeFields as $fieldName => $field) { if (false === ($field instanceof IDType)) { continue; } $arguments[] = sprintf('%s: %s! @eq', $fieldName, $field->name); break; } if (count($arguments) < 1) { return ''; } $queryName = lcfirst($typeName); $query = sprintf(' %s(%s)', $queryName, implode(', ', $arguments)); $query .= sprintf(': %1$s @find(model: "%1$s")', $typeName); if (config('lighthouse-utils.authorization')) { $permission = sprintf('find%1$s', $typeName); $query .= sprintf(' @can(if: "%1$s", model: "User")', $permission); } GraphQLSchema::register($queryName, $typeName, 'query', $permission ?? null); return $query; }
[ "public", "static", "function", "generate", "(", "string", "$", "typeName", ",", "array", "$", "typeFields", ")", ":", "string", "{", "$", "arguments", "=", "[", "]", ";", "//Loop through fields to find the 'ID' field.", "foreach", "(", "$", "typeFields", "as", ...
Generates a GraphQL query that returns one entity by ID @param string $typeName @param Type[] $typeFields @return string
[ "Generates", "a", "GraphQL", "query", "that", "returns", "one", "entity", "by", "ID" ]
31cd7ffe225f4639f3ecf2fd40c4e6835a145dda
https://github.com/deInternetJongens/Lighthouse-Utils/blob/31cd7ffe225f4639f3ecf2fd40c4e6835a145dda/src/Generators/Queries/FindQueryGenerator.php#L18-L48
train