id
int32
0
241k
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
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
5,000
sopinet/ApiHelperBundle
Service/ApiHelper.php
ApiHelper.getFormErrors
public function getFormErrors(Form $form, $deep=false,$flatten=true){ // Se parsean los errores que existan en el formulario para devolverlos en el reponse $errors=array(); //Se parsean los posibles errores generales del formulario(incluyendo los asserts a nivel de entidad) foreach ($form->getErrors($deep, $flatten) as $key => $error) { if ($form->isRoot()) { $errors['form'][] = $error->getMessage(); } else { $errors[] = $error->getMessage(); } } $childs=$form->getIterator(); //Se parsean los posibles errores de cada campo del formulario /** @var Form $child */ foreach($childs as $child ){ $fieldErrors=$child->getErrors(); while($fieldErrors->current()!=null){ $errors[$child->getName()][]=$fieldErrors->current()->getMessage(); $fieldErrors->next(); } } return $errors; }
php
public function getFormErrors(Form $form, $deep=false,$flatten=true){ // Se parsean los errores que existan en el formulario para devolverlos en el reponse $errors=array(); //Se parsean los posibles errores generales del formulario(incluyendo los asserts a nivel de entidad) foreach ($form->getErrors($deep, $flatten) as $key => $error) { if ($form->isRoot()) { $errors['form'][] = $error->getMessage(); } else { $errors[] = $error->getMessage(); } } $childs=$form->getIterator(); //Se parsean los posibles errores de cada campo del formulario /** @var Form $child */ foreach($childs as $child ){ $fieldErrors=$child->getErrors(); while($fieldErrors->current()!=null){ $errors[$child->getName()][]=$fieldErrors->current()->getMessage(); $fieldErrors->next(); } } return $errors; }
[ "public", "function", "getFormErrors", "(", "Form", "$", "form", ",", "$", "deep", "=", "false", ",", "$", "flatten", "=", "true", ")", "{", "// Se parsean los errores que existan en el formulario para devolverlos en el reponse", "$", "errors", "=", "array", "(", ")", ";", "//Se parsean los posibles errores generales del formulario(incluyendo los asserts a nivel de entidad)", "foreach", "(", "$", "form", "->", "getErrors", "(", "$", "deep", ",", "$", "flatten", ")", "as", "$", "key", "=>", "$", "error", ")", "{", "if", "(", "$", "form", "->", "isRoot", "(", ")", ")", "{", "$", "errors", "[", "'form'", "]", "[", "]", "=", "$", "error", "->", "getMessage", "(", ")", ";", "}", "else", "{", "$", "errors", "[", "]", "=", "$", "error", "->", "getMessage", "(", ")", ";", "}", "}", "$", "childs", "=", "$", "form", "->", "getIterator", "(", ")", ";", "//Se parsean los posibles errores de cada campo del formulario", "/** @var Form $child */", "foreach", "(", "$", "childs", "as", "$", "child", ")", "{", "$", "fieldErrors", "=", "$", "child", "->", "getErrors", "(", ")", ";", "while", "(", "$", "fieldErrors", "->", "current", "(", ")", "!=", "null", ")", "{", "$", "errors", "[", "$", "child", "->", "getName", "(", ")", "]", "[", "]", "=", "$", "fieldErrors", "->", "current", "(", ")", "->", "getMessage", "(", ")", ";", "$", "fieldErrors", "->", "next", "(", ")", ";", "}", "}", "return", "$", "errors", ";", "}" ]
Dado un formulario se devuelven sus errores parseados @param Form $form @param bool $deep option for Form getErrors method @param bool $flatten option for Form getErrors method @return array
[ "Dado", "un", "formulario", "se", "devuelven", "sus", "errores", "parseados" ]
878dd397445f5289afaa8ee1b1752dc111b557de
https://github.com/sopinet/ApiHelperBundle/blob/878dd397445f5289afaa8ee1b1752dc111b557de/Service/ApiHelper.php#L124-L146
5,001
slushie/middleware
src/Slushie/Middleware/Loader.php
Loader.register
public function register() { $this->registerMiddleware(); $this->app->before($this->createBeforeFilter()); $this->app->after($this->createAfterFilter()); }
php
public function register() { $this->registerMiddleware(); $this->app->before($this->createBeforeFilter()); $this->app->after($this->createAfterFilter()); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "registerMiddleware", "(", ")", ";", "$", "this", "->", "app", "->", "before", "(", "$", "this", "->", "createBeforeFilter", "(", ")", ")", ";", "$", "this", "->", "app", "->", "after", "(", "$", "this", "->", "createAfterFilter", "(", ")", ")", ";", "}" ]
Register all configured middleware classes with the appropriate App-level events.
[ "Register", "all", "configured", "middleware", "classes", "with", "the", "appropriate", "App", "-", "level", "events", "." ]
e2c7bd4c932b5ce4dc7900a7532a032e4f7862bf
https://github.com/slushie/middleware/blob/e2c7bd4c932b5ce4dc7900a7532a032e4f7862bf/src/Slushie/Middleware/Loader.php#L33-L38
5,002
slushie/middleware
src/Slushie/Middleware/Loader.php
Loader.registerMiddleware
protected function registerMiddleware() { $middleware = $this->app['config']['app.middleware']; foreach ($middleware as $class_name) { $filter = app($class_name); if ($filter instanceof BeforeInterface) { array_push($this->before, $filter); } if ($filter instanceof AfterInterface) { array_push($this->after, $filter); } } }
php
protected function registerMiddleware() { $middleware = $this->app['config']['app.middleware']; foreach ($middleware as $class_name) { $filter = app($class_name); if ($filter instanceof BeforeInterface) { array_push($this->before, $filter); } if ($filter instanceof AfterInterface) { array_push($this->after, $filter); } } }
[ "protected", "function", "registerMiddleware", "(", ")", "{", "$", "middleware", "=", "$", "this", "->", "app", "[", "'config'", "]", "[", "'app.middleware'", "]", ";", "foreach", "(", "$", "middleware", "as", "$", "class_name", ")", "{", "$", "filter", "=", "app", "(", "$", "class_name", ")", ";", "if", "(", "$", "filter", "instanceof", "BeforeInterface", ")", "{", "array_push", "(", "$", "this", "->", "before", ",", "$", "filter", ")", ";", "}", "if", "(", "$", "filter", "instanceof", "AfterInterface", ")", "{", "array_push", "(", "$", "this", "->", "after", ",", "$", "filter", ")", ";", "}", "}", "}" ]
Create middleware instances from the array of class names in the "app.middleware" config key.
[ "Create", "middleware", "instances", "from", "the", "array", "of", "class", "names", "in", "the", "app", ".", "middleware", "config", "key", "." ]
e2c7bd4c932b5ce4dc7900a7532a032e4f7862bf
https://github.com/slushie/middleware/blob/e2c7bd4c932b5ce4dc7900a7532a032e4f7862bf/src/Slushie/Middleware/Loader.php#L44-L56
5,003
slushie/middleware
src/Slushie/Middleware/Loader.php
Loader.createBeforeFilter
protected function createBeforeFilter() { $before = $this->before; // closure that iterates over all before filters return function ($request) use ($before) { foreach ($before as $filter) { $response = $filter->onBefore($request); if (!is_null($response)) { return $response; } } return null; }; }
php
protected function createBeforeFilter() { $before = $this->before; // closure that iterates over all before filters return function ($request) use ($before) { foreach ($before as $filter) { $response = $filter->onBefore($request); if (!is_null($response)) { return $response; } } return null; }; }
[ "protected", "function", "createBeforeFilter", "(", ")", "{", "$", "before", "=", "$", "this", "->", "before", ";", "// closure that iterates over all before filters", "return", "function", "(", "$", "request", ")", "use", "(", "$", "before", ")", "{", "foreach", "(", "$", "before", "as", "$", "filter", ")", "{", "$", "response", "=", "$", "filter", "->", "onBefore", "(", "$", "request", ")", ";", "if", "(", "!", "is_null", "(", "$", "response", ")", ")", "{", "return", "$", "response", ";", "}", "}", "return", "null", ";", "}", ";", "}" ]
Generate a callback function that iterates over all BeforeInterface middleware. @return callable
[ "Generate", "a", "callback", "function", "that", "iterates", "over", "all", "BeforeInterface", "middleware", "." ]
e2c7bd4c932b5ce4dc7900a7532a032e4f7862bf
https://github.com/slushie/middleware/blob/e2c7bd4c932b5ce4dc7900a7532a032e4f7862bf/src/Slushie/Middleware/Loader.php#L64-L78
5,004
slushie/middleware
src/Slushie/Middleware/Loader.php
Loader.createAfterFilter
protected function createAfterFilter() { $after = $this->after; return function ($request, $response) use ($after) { foreach ($after as $filter) { $filter->onAfter($request, $response); } }; }
php
protected function createAfterFilter() { $after = $this->after; return function ($request, $response) use ($after) { foreach ($after as $filter) { $filter->onAfter($request, $response); } }; }
[ "protected", "function", "createAfterFilter", "(", ")", "{", "$", "after", "=", "$", "this", "->", "after", ";", "return", "function", "(", "$", "request", ",", "$", "response", ")", "use", "(", "$", "after", ")", "{", "foreach", "(", "$", "after", "as", "$", "filter", ")", "{", "$", "filter", "->", "onAfter", "(", "$", "request", ",", "$", "response", ")", ";", "}", "}", ";", "}" ]
Generate a callback function that iterates over all AfterInterface middleware. @return callable
[ "Generate", "a", "callback", "function", "that", "iterates", "over", "all", "AfterInterface", "middleware", "." ]
e2c7bd4c932b5ce4dc7900a7532a032e4f7862bf
https://github.com/slushie/middleware/blob/e2c7bd4c932b5ce4dc7900a7532a032e4f7862bf/src/Slushie/Middleware/Loader.php#L86-L94
5,005
RowlandOti/ooglee-core
src/OoGlee/Domain/Providers/LaravelServiceProvider.php
LaravelServiceProvider.getConfig
public function getConfig($key = null) { if (isLaravel5()) { $configNameSpace = 'vendor.'.$this->packageVendor.'.'.$this->packageName.'.'; //question ? result if true :(result is false) $key = $configNameSpace . ($key ? '.'.$key : ''); return $this->app['config']->get($key); } }
php
public function getConfig($key = null) { if (isLaravel5()) { $configNameSpace = 'vendor.'.$this->packageVendor.'.'.$this->packageName.'.'; //question ? result if true :(result is false) $key = $configNameSpace . ($key ? '.'.$key : ''); return $this->app['config']->get($key); } }
[ "public", "function", "getConfig", "(", "$", "key", "=", "null", ")", "{", "if", "(", "isLaravel5", "(", ")", ")", "{", "$", "configNameSpace", "=", "'vendor.'", ".", "$", "this", "->", "packageVendor", ".", "'.'", ".", "$", "this", "->", "packageName", ".", "'.'", ";", "//question ? result if true :(result is false)", "$", "key", "=", "$", "configNameSpace", ".", "(", "$", "key", "?", "'.'", ".", "$", "key", ":", "''", ")", ";", "return", "$", "this", "->", "app", "[", "'config'", "]", "->", "get", "(", "$", "key", ")", ";", "}", "}" ]
Get a configuration value @param string $key @return mixed
[ "Get", "a", "configuration", "value" ]
6cd8a8e58e37749e1c58e99063ea72c9d37a98bc
https://github.com/RowlandOti/ooglee-core/blob/6cd8a8e58e37749e1c58e99063ea72c9d37a98bc/src/OoGlee/Domain/Providers/LaravelServiceProvider.php#L253-L263
5,006
trivialsense/php-framework-common
src/TrivialSense/FrameworkCommon/Container/ContainerHelperTrait.php
ContainerHelperTrait.persistAndFlush
public function persistAndFlush($entity, $persistAll = false, $entityManager = null) { $entityManager = $this->getEntityManager($entityManager); $entityManager->persist($entity); $entityManager->flush($persistAll ? null : $entity); }
php
public function persistAndFlush($entity, $persistAll = false, $entityManager = null) { $entityManager = $this->getEntityManager($entityManager); $entityManager->persist($entity); $entityManager->flush($persistAll ? null : $entity); }
[ "public", "function", "persistAndFlush", "(", "$", "entity", ",", "$", "persistAll", "=", "false", ",", "$", "entityManager", "=", "null", ")", "{", "$", "entityManager", "=", "$", "this", "->", "getEntityManager", "(", "$", "entityManager", ")", ";", "$", "entityManager", "->", "persist", "(", "$", "entity", ")", ";", "$", "entityManager", "->", "flush", "(", "$", "persistAll", "?", "null", ":", "$", "entity", ")", ";", "}" ]
Persist and flush a given entity @param $entity @param string $entityManager
[ "Persist", "and", "flush", "a", "given", "entity" ]
3cb769c62df7badaeae557306c8f738252adaa28
https://github.com/trivialsense/php-framework-common/blob/3cb769c62df7badaeae557306c8f738252adaa28/src/TrivialSense/FrameworkCommon/Container/ContainerHelperTrait.php#L98-L104
5,007
trivialsense/php-framework-common
src/TrivialSense/FrameworkCommon/Container/ContainerHelperTrait.php
ContainerHelperTrait.deleteAndFlush
public function deleteAndFlush($entity, $entityManager = null) { $entityManager = $this->getEntityManager($entityManager); $entityManager->remove($entity); $entityManager->flush($entity); }
php
public function deleteAndFlush($entity, $entityManager = null) { $entityManager = $this->getEntityManager($entityManager); $entityManager->remove($entity); $entityManager->flush($entity); }
[ "public", "function", "deleteAndFlush", "(", "$", "entity", ",", "$", "entityManager", "=", "null", ")", "{", "$", "entityManager", "=", "$", "this", "->", "getEntityManager", "(", "$", "entityManager", ")", ";", "$", "entityManager", "->", "remove", "(", "$", "entity", ")", ";", "$", "entityManager", "->", "flush", "(", "$", "entity", ")", ";", "}" ]
Remove and flush a given entity @param $entity @param string $entityManager
[ "Remove", "and", "flush", "a", "given", "entity" ]
3cb769c62df7badaeae557306c8f738252adaa28
https://github.com/trivialsense/php-framework-common/blob/3cb769c62df7badaeae557306c8f738252adaa28/src/TrivialSense/FrameworkCommon/Container/ContainerHelperTrait.php#L123-L129
5,008
unyx/utils
Platform.php
Platform.isUnix
public static function isUnix() : bool { // Return the cached result if it's already available. if (null !== static::$type) { return static::$type === self::TYPE_UNIX; } return static::getType() === self::TYPE_UNIX; }
php
public static function isUnix() : bool { // Return the cached result if it's already available. if (null !== static::$type) { return static::$type === self::TYPE_UNIX; } return static::getType() === self::TYPE_UNIX; }
[ "public", "static", "function", "isUnix", "(", ")", ":", "bool", "{", "// Return the cached result if it's already available.", "if", "(", "null", "!==", "static", "::", "$", "type", ")", "{", "return", "static", "::", "$", "type", "===", "self", "::", "TYPE_UNIX", ";", "}", "return", "static", "::", "getType", "(", ")", "===", "self", "::", "TYPE_UNIX", ";", "}" ]
Checks whether PHP is running on a Unix platform @return bool True when PHP is running on a Unix platform, false otherwise.
[ "Checks", "whether", "PHP", "is", "running", "on", "a", "Unix", "platform" ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Platform.php#L96-L104
5,009
unyx/utils
Platform.php
Platform.isWindows
public static function isWindows() : bool { // Return the cached result if it's already available. if (null !== static::$type) { return static::$type === self::TYPE_WINDOWS; } return static::getType() === self::TYPE_WINDOWS; }
php
public static function isWindows() : bool { // Return the cached result if it's already available. if (null !== static::$type) { return static::$type === self::TYPE_WINDOWS; } return static::getType() === self::TYPE_WINDOWS; }
[ "public", "static", "function", "isWindows", "(", ")", ":", "bool", "{", "// Return the cached result if it's already available.", "if", "(", "null", "!==", "static", "::", "$", "type", ")", "{", "return", "static", "::", "$", "type", "===", "self", "::", "TYPE_WINDOWS", ";", "}", "return", "static", "::", "getType", "(", ")", "===", "self", "::", "TYPE_WINDOWS", ";", "}" ]
Checks whether PHP is running on a Windows platform @return bool True when PHP is running on a Windows platform, false otherwise.
[ "Checks", "whether", "PHP", "is", "running", "on", "a", "Windows", "platform" ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Platform.php#L111-L119
5,010
unyx/utils
Platform.php
Platform.isBsd
public static function isBsd() : bool { // Return the cached result if it's already available. if (null !== static::$type) { return static::$type === self::TYPE_BSD; } return static::getType() === self::TYPE_BSD; }
php
public static function isBsd() : bool { // Return the cached result if it's already available. if (null !== static::$type) { return static::$type === self::TYPE_BSD; } return static::getType() === self::TYPE_BSD; }
[ "public", "static", "function", "isBsd", "(", ")", ":", "bool", "{", "// Return the cached result if it's already available.", "if", "(", "null", "!==", "static", "::", "$", "type", ")", "{", "return", "static", "::", "$", "type", "===", "self", "::", "TYPE_BSD", ";", "}", "return", "static", "::", "getType", "(", ")", "===", "self", "::", "TYPE_BSD", ";", "}" ]
Checks whether PHP is running on a BSD platform @return bool True when PHP is running on a BSD platform, false otherwise.
[ "Checks", "whether", "PHP", "is", "running", "on", "a", "BSD", "platform" ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Platform.php#L126-L134
5,011
unyx/utils
Platform.php
Platform.isDarwin
public static function isDarwin() : bool { // Return the cached result if it's already available. if (null !== static::$type) { return static::$type === self::TYPE_DARWIN; } return static::getType() === self::TYPE_DARWIN; }
php
public static function isDarwin() : bool { // Return the cached result if it's already available. if (null !== static::$type) { return static::$type === self::TYPE_DARWIN; } return static::getType() === self::TYPE_DARWIN; }
[ "public", "static", "function", "isDarwin", "(", ")", ":", "bool", "{", "// Return the cached result if it's already available.", "if", "(", "null", "!==", "static", "::", "$", "type", ")", "{", "return", "static", "::", "$", "type", "===", "self", "::", "TYPE_DARWIN", ";", "}", "return", "static", "::", "getType", "(", ")", "===", "self", "::", "TYPE_DARWIN", ";", "}" ]
Checks whether PHP is running on a Darwin platform @return bool True when PHP is running on a Darwin platform, false otherwise.
[ "Checks", "whether", "PHP", "is", "running", "on", "a", "Darwin", "platform" ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Platform.php#L141-L149
5,012
unyx/utils
Platform.php
Platform.isCygwin
public static function isCygwin() : bool { // Return the cached result if it's already available. if (null !== static::$type) { return static::$type === self::TYPE_CYGWIN; } return static::getType() === self::TYPE_CYGWIN; }
php
public static function isCygwin() : bool { // Return the cached result if it's already available. if (null !== static::$type) { return static::$type === self::TYPE_CYGWIN; } return static::getType() === self::TYPE_CYGWIN; }
[ "public", "static", "function", "isCygwin", "(", ")", ":", "bool", "{", "// Return the cached result if it's already available.", "if", "(", "null", "!==", "static", "::", "$", "type", ")", "{", "return", "static", "::", "$", "type", "===", "self", "::", "TYPE_CYGWIN", ";", "}", "return", "static", "::", "getType", "(", ")", "===", "self", "::", "TYPE_CYGWIN", ";", "}" ]
Checks whether PHP is running on a Cygwin platform @return bool True when PHP is running on a Cygwin platform, false otherwise.
[ "Checks", "whether", "PHP", "is", "running", "on", "a", "Cygwin", "platform" ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Platform.php#L156-L164
5,013
unyx/utils
Platform.php
Platform.hasStty
public static function hasStty() : bool { // Return the cached result if it's already available. if (static::$hasStty !== null) { return static::$hasStty; } // Definitely no Stty on Windows. if (static::isWindows()) { return static::$hasStty = false; } // Run a simple exec() call and check whether it returned with an error code. exec('/usr/bin/env stty', $output, $exitCode); return static::$hasStty = $exitCode === 0; }
php
public static function hasStty() : bool { // Return the cached result if it's already available. if (static::$hasStty !== null) { return static::$hasStty; } // Definitely no Stty on Windows. if (static::isWindows()) { return static::$hasStty = false; } // Run a simple exec() call and check whether it returned with an error code. exec('/usr/bin/env stty', $output, $exitCode); return static::$hasStty = $exitCode === 0; }
[ "public", "static", "function", "hasStty", "(", ")", ":", "bool", "{", "// Return the cached result if it's already available.", "if", "(", "static", "::", "$", "hasStty", "!==", "null", ")", "{", "return", "static", "::", "$", "hasStty", ";", "}", "// Definitely no Stty on Windows.", "if", "(", "static", "::", "isWindows", "(", ")", ")", "{", "return", "static", "::", "$", "hasStty", "=", "false", ";", "}", "// Run a simple exec() call and check whether it returned with an error code.", "exec", "(", "'/usr/bin/env stty'", ",", "$", "output", ",", "$", "exitCode", ")", ";", "return", "static", "::", "$", "hasStty", "=", "$", "exitCode", "===", "0", ";", "}" ]
Checks whether this platform has the 'stty' binary. @return bool True when 'stty' is available on this platform, false otherwise (always false on Windows).
[ "Checks", "whether", "this", "platform", "has", "the", "stty", "binary", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Platform.php#L232-L248
5,014
vinala/kernel
src/Processes/Router.php
Router.post
public static function post($route) { $content = self::traitPost($route); // self::addRoute($content); return true; }
php
public static function post($route) { $content = self::traitPost($route); // self::addRoute($content); return true; }
[ "public", "static", "function", "post", "(", "$", "route", ")", "{", "$", "content", "=", "self", "::", "traitPost", "(", "$", "route", ")", ";", "//", "self", "::", "addRoute", "(", "$", "content", ")", ";", "return", "true", ";", "}" ]
function to generate Post Route. @param string $route @return bool
[ "function", "to", "generate", "Post", "Route", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/Processes/Router.php#L28-L35
5,015
vinala/kernel
src/Processes/Router.php
Router.target
public static function target($route, $controller, $method) { $content = self::traitTarget($route, $controller, $method); // self::addRoute($content); return true; }
php
public static function target($route, $controller, $method) { $content = self::traitTarget($route, $controller, $method); // self::addRoute($content); return true; }
[ "public", "static", "function", "target", "(", "$", "route", ",", "$", "controller", ",", "$", "method", ")", "{", "$", "content", "=", "self", "::", "traitTarget", "(", "$", "route", ",", "$", "controller", ",", "$", "method", ")", ";", "//", "self", "::", "addRoute", "(", "$", "content", ")", ";", "return", "true", ";", "}" ]
function to generate target Route. @param string $route @param string $controller @param string $method @return bool
[ "function", "to", "generate", "target", "Route", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/Processes/Router.php#L46-L53
5,016
vinala/kernel
src/Processes/Router.php
Router.traitPost
protected static function traitPost($route) { $content = ''; // $content .= "\n\n".self::funcPost($route).' '; $content .= '{'."\n"; $content .= "\t".'// TODO : '."\n"; $content .= '});'; // return $content; }
php
protected static function traitPost($route) { $content = ''; // $content .= "\n\n".self::funcPost($route).' '; $content .= '{'."\n"; $content .= "\t".'// TODO : '."\n"; $content .= '});'; // return $content; }
[ "protected", "static", "function", "traitPost", "(", "$", "route", ")", "{", "$", "content", "=", "''", ";", "//", "$", "content", ".=", "\"\\n\\n\"", ".", "self", "::", "funcPost", "(", "$", "route", ")", ".", "' '", ";", "$", "content", ".=", "'{'", ".", "\"\\n\"", ";", "$", "content", ".=", "\"\\t\"", ".", "'// TODO : '", ".", "\"\\n\"", ";", "$", "content", ".=", "'});'", ";", "//", "return", "$", "content", ";", "}" ]
generate Post Route script. @param string $route @return string
[ "generate", "Post", "Route", "script", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/Processes/Router.php#L74-L84
5,017
vinala/kernel
src/Processes/Router.php
Router.addRoute
protected static function addRoute($content) { $Root = Process::root; $RouterFile = $Root.'app/http/Routes.php'; // file_put_contents($RouterFile, $content, FILE_APPEND | LOCK_EX); }
php
protected static function addRoute($content) { $Root = Process::root; $RouterFile = $Root.'app/http/Routes.php'; // file_put_contents($RouterFile, $content, FILE_APPEND | LOCK_EX); }
[ "protected", "static", "function", "addRoute", "(", "$", "content", ")", "{", "$", "Root", "=", "Process", "::", "root", ";", "$", "RouterFile", "=", "$", "Root", ".", "'app/http/Routes.php'", ";", "//", "file_put_contents", "(", "$", "RouterFile", ",", "$", "content", ",", "FILE_APPEND", "|", "LOCK_EX", ")", ";", "}" ]
Add callable to the route file.
[ "Add", "callable", "to", "the", "route", "file", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/Processes/Router.php#L105-L111
5,018
vinala/kernel
src/Processes/Router.php
Router.formatParams
protected static function formatParams($params) { $reslt = ''; // for ($i = 0; $i < count($params); $i++) { $reslt .= '$'.$params[$i]; if ($i < count($params) - 1) { $reslt .= ','; } } return $reslt; }
php
protected static function formatParams($params) { $reslt = ''; // for ($i = 0; $i < count($params); $i++) { $reslt .= '$'.$params[$i]; if ($i < count($params) - 1) { $reslt .= ','; } } return $reslt; }
[ "protected", "static", "function", "formatParams", "(", "$", "params", ")", "{", "$", "reslt", "=", "''", ";", "//", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "params", ")", ";", "$", "i", "++", ")", "{", "$", "reslt", ".=", "'$'", ".", "$", "params", "[", "$", "i", "]", ";", "if", "(", "$", "i", "<", "count", "(", "$", "params", ")", "-", "1", ")", "{", "$", "reslt", ".=", "','", ";", "}", "}", "return", "$", "reslt", ";", "}" ]
Concat the paramters.
[ "Concat", "the", "paramters", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/Processes/Router.php#L146-L158
5,019
vinala/kernel
src/Processes/Router.php
Router.dynamic
protected static function dynamic($route) { $parms = []; $param = ''; $open = false; // for ($i = 0; $i < Strings::length($route); $i++) { if ($open && $route[$i] != '}') { $param .= $route[$i]; } // if ($route[$i] == '{' && !$open) { $open = true; } // elseif ($route[$i] == '}' && $open) { $open = !true; $parms[] = $param; $param = ''; } } // return $parms; }
php
protected static function dynamic($route) { $parms = []; $param = ''; $open = false; // for ($i = 0; $i < Strings::length($route); $i++) { if ($open && $route[$i] != '}') { $param .= $route[$i]; } // if ($route[$i] == '{' && !$open) { $open = true; } // elseif ($route[$i] == '}' && $open) { $open = !true; $parms[] = $param; $param = ''; } } // return $parms; }
[ "protected", "static", "function", "dynamic", "(", "$", "route", ")", "{", "$", "parms", "=", "[", "]", ";", "$", "param", "=", "''", ";", "$", "open", "=", "false", ";", "//", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "Strings", "::", "length", "(", "$", "route", ")", ";", "$", "i", "++", ")", "{", "if", "(", "$", "open", "&&", "$", "route", "[", "$", "i", "]", "!=", "'}'", ")", "{", "$", "param", ".=", "$", "route", "[", "$", "i", "]", ";", "}", "//", "if", "(", "$", "route", "[", "$", "i", "]", "==", "'{'", "&&", "!", "$", "open", ")", "{", "$", "open", "=", "true", ";", "}", "//", "elseif", "(", "$", "route", "[", "$", "i", "]", "==", "'}'", "&&", "$", "open", ")", "{", "$", "open", "=", "!", "true", ";", "$", "parms", "[", "]", "=", "$", "param", ";", "$", "param", "=", "''", ";", "}", "}", "//", "return", "$", "parms", ";", "}" ]
Get the dynamic paramteres from route string.
[ "Get", "the", "dynamic", "paramteres", "from", "route", "string", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/Processes/Router.php#L163-L185
5,020
donbidon/core
src/Registry/Recursive.php
Recursive.replaceRefs
protected function replaceRefs($key, &$scope) { if (is_array($scope)) { foreach (array_keys($scope) as $subkey) { $this->replaceRefs( implode($this->delimiter, [$key, $subkey]), $scope[$subkey] ); } } else { $this->getByRef($key, $scope); } }
php
protected function replaceRefs($key, &$scope) { if (is_array($scope)) { foreach (array_keys($scope) as $subkey) { $this->replaceRefs( implode($this->delimiter, [$key, $subkey]), $scope[$subkey] ); } } else { $this->getByRef($key, $scope); } }
[ "protected", "function", "replaceRefs", "(", "$", "key", ",", "&", "$", "scope", ")", "{", "if", "(", "is_array", "(", "$", "scope", ")", ")", "{", "foreach", "(", "array_keys", "(", "$", "scope", ")", "as", "$", "subkey", ")", "{", "$", "this", "->", "replaceRefs", "(", "implode", "(", "$", "this", "->", "delimiter", ",", "[", "$", "key", ",", "$", "subkey", "]", ")", ",", "$", "scope", "[", "$", "subkey", "]", ")", ";", "}", "}", "else", "{", "$", "this", "->", "getByRef", "(", "$", "key", ",", "$", "scope", ")", ";", "}", "}" ]
Replaces references recursively. @param string $key @param mixed $scope @return void @throws \ReflectionException @internal
[ "Replaces", "references", "recursively", "." ]
a22030c98ffb2dcbb8eb7a12f0498d88fb7531fe
https://github.com/donbidon/core/blob/a22030c98ffb2dcbb8eb7a12f0498d88fb7531fe/src/Registry/Recursive.php#L177-L189
5,021
donbidon/core
src/Registry/Recursive.php
Recursive.setScope
protected function setScope(&$key, $create = false) { $this->scope = &$this->fullScope; if (false === strpos($key, $this->delimiter)) { return; } /** @noinspection PhpInternalEntityUsedInspection */ $this->key = $key; $keys = explode($this->delimiter, $key); $lastKey = array_pop($keys); $lastIndex = sizeof($keys) - 1; foreach ($keys as $index => $key) { if (!isset($this->scope[$key]) || !is_array($this->scope[$key])) { if ($create) { $this->scope[$key] = []; } else if (!isset($this->scope[$key]) && $index == $lastIndex) { return; } } if ( $this->checkRefs && $this->isRef($this->scope[$key],false) ) { $key = $this->scope[$key]; $this->isRef($key); $this->setScope($key, $create); } $this->scope = &$this->scope[$key]; } $key = $lastKey; }
php
protected function setScope(&$key, $create = false) { $this->scope = &$this->fullScope; if (false === strpos($key, $this->delimiter)) { return; } /** @noinspection PhpInternalEntityUsedInspection */ $this->key = $key; $keys = explode($this->delimiter, $key); $lastKey = array_pop($keys); $lastIndex = sizeof($keys) - 1; foreach ($keys as $index => $key) { if (!isset($this->scope[$key]) || !is_array($this->scope[$key])) { if ($create) { $this->scope[$key] = []; } else if (!isset($this->scope[$key]) && $index == $lastIndex) { return; } } if ( $this->checkRefs && $this->isRef($this->scope[$key],false) ) { $key = $this->scope[$key]; $this->isRef($key); $this->setScope($key, $create); } $this->scope = &$this->scope[$key]; } $key = $lastKey; }
[ "protected", "function", "setScope", "(", "&", "$", "key", ",", "$", "create", "=", "false", ")", "{", "$", "this", "->", "scope", "=", "&", "$", "this", "->", "fullScope", ";", "if", "(", "false", "===", "strpos", "(", "$", "key", ",", "$", "this", "->", "delimiter", ")", ")", "{", "return", ";", "}", "/** @noinspection PhpInternalEntityUsedInspection */", "$", "this", "->", "key", "=", "$", "key", ";", "$", "keys", "=", "explode", "(", "$", "this", "->", "delimiter", ",", "$", "key", ")", ";", "$", "lastKey", "=", "array_pop", "(", "$", "keys", ")", ";", "$", "lastIndex", "=", "sizeof", "(", "$", "keys", ")", "-", "1", ";", "foreach", "(", "$", "keys", "as", "$", "index", "=>", "$", "key", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "scope", "[", "$", "key", "]", ")", "||", "!", "is_array", "(", "$", "this", "->", "scope", "[", "$", "key", "]", ")", ")", "{", "if", "(", "$", "create", ")", "{", "$", "this", "->", "scope", "[", "$", "key", "]", "=", "[", "]", ";", "}", "else", "if", "(", "!", "isset", "(", "$", "this", "->", "scope", "[", "$", "key", "]", ")", "&&", "$", "index", "==", "$", "lastIndex", ")", "{", "return", ";", "}", "}", "if", "(", "$", "this", "->", "checkRefs", "&&", "$", "this", "->", "isRef", "(", "$", "this", "->", "scope", "[", "$", "key", "]", ",", "false", ")", ")", "{", "$", "key", "=", "$", "this", "->", "scope", "[", "$", "key", "]", ";", "$", "this", "->", "isRef", "(", "$", "key", ")", ";", "$", "this", "->", "setScope", "(", "$", "key", ",", "$", "create", ")", ";", "}", "$", "this", "->", "scope", "=", "&", "$", "this", "->", "scope", "[", "$", "key", "]", ";", "}", "$", "key", "=", "$", "lastKey", ";", "}" ]
Shifts scope according to complex key. @param string $key <b>[by ref]</b> @param bool $create @return void @internal
[ "Shifts", "scope", "according", "to", "complex", "key", "." ]
a22030c98ffb2dcbb8eb7a12f0498d88fb7531fe
https://github.com/donbidon/core/blob/a22030c98ffb2dcbb8eb7a12f0498d88fb7531fe/src/Registry/Recursive.php#L199-L230
5,022
nano7/Database
src/Model/HasAttributes.php
HasAttributes.getAttributeFromArray
public function getAttributeFromArray($key, $default = null) { return isset($this->attributes[$key]) ? $this->attributes[$key] : $default; }
php
public function getAttributeFromArray($key, $default = null) { return isset($this->attributes[$key]) ? $this->attributes[$key] : $default; }
[ "public", "function", "getAttributeFromArray", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "return", "isset", "(", "$", "this", "->", "attributes", "[", "$", "key", "]", ")", "?", "$", "this", "->", "attributes", "[", "$", "key", "]", ":", "$", "default", ";", "}" ]
Get an attribute from the array in model. @param string $key @param mixed $default @return mixed
[ "Get", "an", "attribute", "from", "the", "array", "in", "model", "." ]
7d8c10af415c469a317f40471f657104e4d5b52a
https://github.com/nano7/Database/blob/7d8c10af415c469a317f40471f657104e4d5b52a/src/Model/HasAttributes.php#L83-L86
5,023
nano7/Database
src/Model/HasAttributes.php
HasAttributes.setAttributeToArray
public function setAttributeToArray($key, $value) { // Marcar key como alterado $this->changed[$key] = true; // Setar no array de atributos $this->attributes[$key] = $value; return $this; }
php
public function setAttributeToArray($key, $value) { // Marcar key como alterado $this->changed[$key] = true; // Setar no array de atributos $this->attributes[$key] = $value; return $this; }
[ "public", "function", "setAttributeToArray", "(", "$", "key", ",", "$", "value", ")", "{", "// Marcar key como alterado", "$", "this", "->", "changed", "[", "$", "key", "]", "=", "true", ";", "// Setar no array de atributos", "$", "this", "->", "attributes", "[", "$", "key", "]", "=", "$", "value", ";", "return", "$", "this", ";", "}" ]
Set an attribute to the array in model. @param string $key @param mixed $value @return $this
[ "Set", "an", "attribute", "to", "the", "array", "in", "model", "." ]
7d8c10af415c469a317f40471f657104e4d5b52a
https://github.com/nano7/Database/blob/7d8c10af415c469a317f40471f657104e4d5b52a/src/Model/HasAttributes.php#L147-L156
5,024
nano7/Database
src/Model/HasAttributes.php
HasAttributes.mergeRawAttributes
public function mergeRawAttributes(array $attributes, $sync = false, $force = false) { foreach ($attributes as $key => $value) { if ($force || ((! $force) && (! $this->hasAttribute($key)))) { $this->setAttribute($key, $value); } } if ($sync) { $this->syncOriginal(); } return $this; }
php
public function mergeRawAttributes(array $attributes, $sync = false, $force = false) { foreach ($attributes as $key => $value) { if ($force || ((! $force) && (! $this->hasAttribute($key)))) { $this->setAttribute($key, $value); } } if ($sync) { $this->syncOriginal(); } return $this; }
[ "public", "function", "mergeRawAttributes", "(", "array", "$", "attributes", ",", "$", "sync", "=", "false", ",", "$", "force", "=", "false", ")", "{", "foreach", "(", "$", "attributes", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "force", "||", "(", "(", "!", "$", "force", ")", "&&", "(", "!", "$", "this", "->", "hasAttribute", "(", "$", "key", ")", ")", ")", ")", "{", "$", "this", "->", "setAttribute", "(", "$", "key", ",", "$", "value", ")", ";", "}", "}", "if", "(", "$", "sync", ")", "{", "$", "this", "->", "syncOriginal", "(", ")", ";", "}", "return", "$", "this", ";", "}" ]
Set the array of model attributes. @param array $attributes @param bool $sync @param bool $force Force change value if exists. @return $this
[ "Set", "the", "array", "of", "model", "attributes", "." ]
7d8c10af415c469a317f40471f657104e4d5b52a
https://github.com/nano7/Database/blob/7d8c10af415c469a317f40471f657104e4d5b52a/src/Model/HasAttributes.php#L184-L197
5,025
nano7/Database
src/Model/HasAttributes.php
HasAttributes.hasChanged
public function hasChanged($attribute = false) { $changes = $this->getChanged(); // Verificar se atributo foi alterado if ($attribute !== false) { $attribute = (array) $attribute; foreach ($attribute as $attr) { if (array_key_exists($attr, $changes)) { return true; } } return false; } return count($changes) > 0; }
php
public function hasChanged($attribute = false) { $changes = $this->getChanged(); // Verificar se atributo foi alterado if ($attribute !== false) { $attribute = (array) $attribute; foreach ($attribute as $attr) { if (array_key_exists($attr, $changes)) { return true; } } return false; } return count($changes) > 0; }
[ "public", "function", "hasChanged", "(", "$", "attribute", "=", "false", ")", "{", "$", "changes", "=", "$", "this", "->", "getChanged", "(", ")", ";", "// Verificar se atributo foi alterado", "if", "(", "$", "attribute", "!==", "false", ")", "{", "$", "attribute", "=", "(", "array", ")", "$", "attribute", ";", "foreach", "(", "$", "attribute", "as", "$", "attr", ")", "{", "if", "(", "array_key_exists", "(", "$", "attr", ",", "$", "changes", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", "return", "count", "(", "$", "changes", ")", ">", "0", ";", "}" ]
Verifica e retorna se ha alguma alteracao para ser salva. @param bool|string|array $attribute @return bool
[ "Verifica", "e", "retorna", "se", "ha", "alguma", "alteracao", "para", "ser", "salva", "." ]
7d8c10af415c469a317f40471f657104e4d5b52a
https://github.com/nano7/Database/blob/7d8c10af415c469a317f40471f657104e4d5b52a/src/Model/HasAttributes.php#L258-L275
5,026
uberboom/oauth2-basecamp
src/Provider/Basecamp.php
Basecamp.getBasecampAccounts
public function getBasecampAccounts(AccessToken $token) { $response = $this->fetchUserDetails($token); $details = json_decode($response); return $details->accounts; }
php
public function getBasecampAccounts(AccessToken $token) { $response = $this->fetchUserDetails($token); $details = json_decode($response); return $details->accounts; }
[ "public", "function", "getBasecampAccounts", "(", "AccessToken", "$", "token", ")", "{", "$", "response", "=", "$", "this", "->", "fetchUserDetails", "(", "$", "token", ")", ";", "$", "details", "=", "json_decode", "(", "$", "response", ")", ";", "return", "$", "details", "->", "accounts", ";", "}" ]
Get basecamp accounts @return array
[ "Get", "basecamp", "accounts" ]
337e21572f2f554930f824d5cb48a9b031557a43
https://github.com/uberboom/oauth2-basecamp/blob/337e21572f2f554930f824d5cb48a9b031557a43/src/Provider/Basecamp.php#L76-L81
5,027
bkdotcom/Toolbox
src/Gzip.php
Gzip.compressFile
public static function compressFile($filepathSrc, $filepathDst = null, $level = 9) { if (!isset($filepathDst)) { $filepathDst = $filepathSrc.'.gz'; } $return = $filepathDst; $mode = 'wb'.$level; if ($fpOut = gzopen($filepathDst, $mode)) { if ($fpIn = fopen($filepathSrc, 'rb')) { while (!feof($fpIn)) { gzwrite($fpOut, fread($fpIn, 1024*512)); } fclose($fpIn); } else { $return = false; } gzclose($fpOut); } else { $return = false; } return $return; }
php
public static function compressFile($filepathSrc, $filepathDst = null, $level = 9) { if (!isset($filepathDst)) { $filepathDst = $filepathSrc.'.gz'; } $return = $filepathDst; $mode = 'wb'.$level; if ($fpOut = gzopen($filepathDst, $mode)) { if ($fpIn = fopen($filepathSrc, 'rb')) { while (!feof($fpIn)) { gzwrite($fpOut, fread($fpIn, 1024*512)); } fclose($fpIn); } else { $return = false; } gzclose($fpOut); } else { $return = false; } return $return; }
[ "public", "static", "function", "compressFile", "(", "$", "filepathSrc", ",", "$", "filepathDst", "=", "null", ",", "$", "level", "=", "9", ")", "{", "if", "(", "!", "isset", "(", "$", "filepathDst", ")", ")", "{", "$", "filepathDst", "=", "$", "filepathSrc", ".", "'.gz'", ";", "}", "$", "return", "=", "$", "filepathDst", ";", "$", "mode", "=", "'wb'", ".", "$", "level", ";", "if", "(", "$", "fpOut", "=", "gzopen", "(", "$", "filepathDst", ",", "$", "mode", ")", ")", "{", "if", "(", "$", "fpIn", "=", "fopen", "(", "$", "filepathSrc", ",", "'rb'", ")", ")", "{", "while", "(", "!", "feof", "(", "$", "fpIn", ")", ")", "{", "gzwrite", "(", "$", "fpOut", ",", "fread", "(", "$", "fpIn", ",", "1024", "*", "512", ")", ")", ";", "}", "fclose", "(", "$", "fpIn", ")", ";", "}", "else", "{", "$", "return", "=", "false", ";", "}", "gzclose", "(", "$", "fpOut", ")", ";", "}", "else", "{", "$", "return", "=", "false", ";", "}", "return", "$", "return", ";", "}" ]
Compress a file Removes original @param string $filepathSrc input file @param string $filepathDst optional output file (optional) @param integer $level compression level (optional) @return string|false
[ "Compress", "a", "file", "Removes", "original" ]
2f9d34fd57bd8382baee4c29aac13a6710e3a994
https://github.com/bkdotcom/Toolbox/blob/2f9d34fd57bd8382baee4c29aac13a6710e3a994/src/Gzip.php#L20-L41
5,028
bkdotcom/Toolbox
src/Gzip.php
Gzip.uncompressFile
public static function uncompressFile($filepathSrc, $filepathDst = null) { if (!isset($filepathDst)) { $regex = '#^(.+).gz$#'; $filepathDst = preg_replace($regex, '$1', $filepathSrc); } elseif (is_dir($filepathDst)) { $pathInfo = pathinfo($filepathSrc); $filename = preg_replace($filename, '$1', $pathInfo['filename']); $filepathDst = $pathInfo['dirname'].'/'.$filename; } $return = $filepathDst; if ($filepathDst == $filepathSrc) { // @todo $return = false; } elseif ($fpIn = gzopen($filepathSrc, 'rb')) { if ($fpOut = fopen($filepathDst, 'wb')) { while (!gzeof($fpIn)) { fwrite($fpOut, gzread($fpIn, 1024*512)); } } else { $return = false; } } else { $return = false; } return $return; }
php
public static function uncompressFile($filepathSrc, $filepathDst = null) { if (!isset($filepathDst)) { $regex = '#^(.+).gz$#'; $filepathDst = preg_replace($regex, '$1', $filepathSrc); } elseif (is_dir($filepathDst)) { $pathInfo = pathinfo($filepathSrc); $filename = preg_replace($filename, '$1', $pathInfo['filename']); $filepathDst = $pathInfo['dirname'].'/'.$filename; } $return = $filepathDst; if ($filepathDst == $filepathSrc) { // @todo $return = false; } elseif ($fpIn = gzopen($filepathSrc, 'rb')) { if ($fpOut = fopen($filepathDst, 'wb')) { while (!gzeof($fpIn)) { fwrite($fpOut, gzread($fpIn, 1024*512)); } } else { $return = false; } } else { $return = false; } return $return; }
[ "public", "static", "function", "uncompressFile", "(", "$", "filepathSrc", ",", "$", "filepathDst", "=", "null", ")", "{", "if", "(", "!", "isset", "(", "$", "filepathDst", ")", ")", "{", "$", "regex", "=", "'#^(.+).gz$#'", ";", "$", "filepathDst", "=", "preg_replace", "(", "$", "regex", ",", "'$1'", ",", "$", "filepathSrc", ")", ";", "}", "elseif", "(", "is_dir", "(", "$", "filepathDst", ")", ")", "{", "$", "pathInfo", "=", "pathinfo", "(", "$", "filepathSrc", ")", ";", "$", "filename", "=", "preg_replace", "(", "$", "filename", ",", "'$1'", ",", "$", "pathInfo", "[", "'filename'", "]", ")", ";", "$", "filepathDst", "=", "$", "pathInfo", "[", "'dirname'", "]", ".", "'/'", ".", "$", "filename", ";", "}", "$", "return", "=", "$", "filepathDst", ";", "if", "(", "$", "filepathDst", "==", "$", "filepathSrc", ")", "{", "// @todo", "$", "return", "=", "false", ";", "}", "elseif", "(", "$", "fpIn", "=", "gzopen", "(", "$", "filepathSrc", ",", "'rb'", ")", ")", "{", "if", "(", "$", "fpOut", "=", "fopen", "(", "$", "filepathDst", ",", "'wb'", ")", ")", "{", "while", "(", "!", "gzeof", "(", "$", "fpIn", ")", ")", "{", "fwrite", "(", "$", "fpOut", ",", "gzread", "(", "$", "fpIn", ",", "1024", "*", "512", ")", ")", ";", "}", "}", "else", "{", "$", "return", "=", "false", ";", "}", "}", "else", "{", "$", "return", "=", "false", ";", "}", "return", "$", "return", ";", "}" ]
Uncompress gziped file @param string $filepathSrc input file @param string $filepathDst optional output file (or output directory) @return string|false path to uncomperssed file
[ "Uncompress", "gziped", "file" ]
2f9d34fd57bd8382baee4c29aac13a6710e3a994
https://github.com/bkdotcom/Toolbox/blob/2f9d34fd57bd8382baee4c29aac13a6710e3a994/src/Gzip.php#L56-L82
5,029
xmlsquad/gsheet-to-xml
src/Model/Service/InventoryXmlSerializer.php
InventoryXmlSerializer.processDomainGSheetObjects
public function processDomainGSheetObjects(array $inventories) { $dom = new DomDocument("1.0", "UTF-8"); $products = $dom->createElement('Products'); /** @var Inventory $inventory */ foreach ($inventories as $inventory) { $product = $dom->createElement('Product'); $inventoryXmlElement = $this->buildInventoryElement($dom, $inventory); $product->appendChild($inventoryXmlElement); $products->appendChild($product); } $dom->appendChild($products); return $this->outputFormattedXml($dom); }
php
public function processDomainGSheetObjects(array $inventories) { $dom = new DomDocument("1.0", "UTF-8"); $products = $dom->createElement('Products'); /** @var Inventory $inventory */ foreach ($inventories as $inventory) { $product = $dom->createElement('Product'); $inventoryXmlElement = $this->buildInventoryElement($dom, $inventory); $product->appendChild($inventoryXmlElement); $products->appendChild($product); } $dom->appendChild($products); return $this->outputFormattedXml($dom); }
[ "public", "function", "processDomainGSheetObjects", "(", "array", "$", "inventories", ")", "{", "$", "dom", "=", "new", "DomDocument", "(", "\"1.0\"", ",", "\"UTF-8\"", ")", ";", "$", "products", "=", "$", "dom", "->", "createElement", "(", "'Products'", ")", ";", "/** @var Inventory $inventory */", "foreach", "(", "$", "inventories", "as", "$", "inventory", ")", "{", "$", "product", "=", "$", "dom", "->", "createElement", "(", "'Product'", ")", ";", "$", "inventoryXmlElement", "=", "$", "this", "->", "buildInventoryElement", "(", "$", "dom", ",", "$", "inventory", ")", ";", "$", "product", "->", "appendChild", "(", "$", "inventoryXmlElement", ")", ";", "$", "products", "->", "appendChild", "(", "$", "product", ")", ";", "}", "$", "dom", "->", "appendChild", "(", "$", "products", ")", ";", "return", "$", "this", "->", "outputFormattedXml", "(", "$", "dom", ")", ";", "}" ]
Satisfies interface method. Invoked in XmlSquad\Library\Application\Service\GoogleDriveProcessService
[ "Satisfies", "interface", "method", ".", "Invoked", "in", "XmlSquad", "\\", "Library", "\\", "Application", "\\", "Service", "\\", "GoogleDriveProcessService" ]
069539b533160e384562044ca9744162f5cf4eb9
https://github.com/xmlsquad/gsheet-to-xml/blob/069539b533160e384562044ca9744162f5cf4eb9/src/Model/Service/InventoryXmlSerializer.php#L26-L42
5,030
FrenzelGmbH/cm-categories
controllers/CategoriesController.php
CategoriesController.actionCreate
public function actionCreate() { $model = new Categories; if ($model->load(Yii::$app->request->post()) && $model->save()) { if (Yii::$app->request->isAjax) { header('Content-type: application/json'); echo Json::encode(['status'=>'DONE','model'=>$model]); exit(); } else { return $this->redirect(['view', 'id' => $model->id]); } } return $this->render('create', [ 'model' => $model, ]); }
php
public function actionCreate() { $model = new Categories; if ($model->load(Yii::$app->request->post()) && $model->save()) { if (Yii::$app->request->isAjax) { header('Content-type: application/json'); echo Json::encode(['status'=>'DONE','model'=>$model]); exit(); } else { return $this->redirect(['view', 'id' => $model->id]); } } return $this->render('create', [ 'model' => $model, ]); }
[ "public", "function", "actionCreate", "(", ")", "{", "$", "model", "=", "new", "Categories", ";", "if", "(", "$", "model", "->", "load", "(", "Yii", "::", "$", "app", "->", "request", "->", "post", "(", ")", ")", "&&", "$", "model", "->", "save", "(", ")", ")", "{", "if", "(", "Yii", "::", "$", "app", "->", "request", "->", "isAjax", ")", "{", "header", "(", "'Content-type: application/json'", ")", ";", "echo", "Json", "::", "encode", "(", "[", "'status'", "=>", "'DONE'", ",", "'model'", "=>", "$", "model", "]", ")", ";", "exit", "(", ")", ";", "}", "else", "{", "return", "$", "this", "->", "redirect", "(", "[", "'view'", ",", "'id'", "=>", "$", "model", "->", "id", "]", ")", ";", "}", "}", "return", "$", "this", "->", "render", "(", "'create'", ",", "[", "'model'", "=>", "$", "model", ",", "]", ")", ";", "}" ]
Creates a new Categories model. If creation is successful, the browser will be redirected to the 'view' page. @return mixed
[ "Creates", "a", "new", "Categories", "model", ".", "If", "creation", "is", "successful", "the", "browser", "will", "be", "redirected", "to", "the", "view", "page", "." ]
e66780295229bc775e5ab3af43b59529024a5c58
https://github.com/FrenzelGmbH/cm-categories/blob/e66780295229bc775e5ab3af43b59529024a5c58/controllers/CategoriesController.php#L68-L87
5,031
FrenzelGmbH/cm-categories
controllers/CategoriesController.php
CategoriesController.actionJsoncategories
public function actionJsoncategories() { header('Content-type: application/json'); $out = []; if(isset($_POST['depdrop_parents'])) { $parents = $_POST['depdrop_parents']; if($parents != null) { $mod_table = $parents[0]; $out = Categories::jsCategories($mod_table); echo Json::encode(['output'=>$out,'selected'=>'']); return; } } echo Json::encode(['output'=>'','selected'=>'']); exit; }
php
public function actionJsoncategories() { header('Content-type: application/json'); $out = []; if(isset($_POST['depdrop_parents'])) { $parents = $_POST['depdrop_parents']; if($parents != null) { $mod_table = $parents[0]; $out = Categories::jsCategories($mod_table); echo Json::encode(['output'=>$out,'selected'=>'']); return; } } echo Json::encode(['output'=>'','selected'=>'']); exit; }
[ "public", "function", "actionJsoncategories", "(", ")", "{", "header", "(", "'Content-type: application/json'", ")", ";", "$", "out", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "_POST", "[", "'depdrop_parents'", "]", ")", ")", "{", "$", "parents", "=", "$", "_POST", "[", "'depdrop_parents'", "]", ";", "if", "(", "$", "parents", "!=", "null", ")", "{", "$", "mod_table", "=", "$", "parents", "[", "0", "]", ";", "$", "out", "=", "Categories", "::", "jsCategories", "(", "$", "mod_table", ")", ";", "echo", "Json", "::", "encode", "(", "[", "'output'", "=>", "$", "out", ",", "'selected'", "=>", "''", "]", ")", ";", "return", ";", "}", "}", "echo", "Json", "::", "encode", "(", "[", "'output'", "=>", "''", ",", "'selected'", "=>", "''", "]", ")", ";", "exit", ";", "}" ]
this produces an json array with the available categories for the passed over module.
[ "this", "produces", "an", "json", "array", "with", "the", "available", "categories", "for", "the", "passed", "over", "module", "." ]
e66780295229bc775e5ab3af43b59529024a5c58
https://github.com/FrenzelGmbH/cm-categories/blob/e66780295229bc775e5ab3af43b59529024a5c58/controllers/CategoriesController.php#L167-L184
5,032
asbsoft/yii2module-news_1b_160430
controllers/AdminController.php
AdminController.actionIndex
public function actionIndex($page = 1, $id = 0) { $searchModel = new NewsSearch(); $params = Yii::$app->request->queryParams; if (!Yii::$app->user->can('roleNewsModerator') && Yii::$app->user->can('roleNewsAuthor')) { $params[$searchModel->formName()]['owner_id'] = Yii::$app->user->id; }//var_dump($params); $dataProvider = $searchModel->search($params); $pager = $dataProvider->getPagination(); $pager->pageSize = $this->module->params['pageSizeAdmin']; $pager->totalCount = $dataProvider->getTotalCount(); // page number correction: //if ($pager->totalCount <= $pager->pageSize || $page > ceil($pager->totalCount / $pager->pageSize) ) { // $pager->page = 0; //goto 1st page if shortage records $maxPage = ceil($pager->totalCount / $pager->pageSize); if ($page > $maxPage) { $pager->page = $maxPage - 1; } else { $pager->page = $page - 1; //! from 0 }//var_dump($page);var_dump($pager->page); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'currentId' => $id, ]); }
php
public function actionIndex($page = 1, $id = 0) { $searchModel = new NewsSearch(); $params = Yii::$app->request->queryParams; if (!Yii::$app->user->can('roleNewsModerator') && Yii::$app->user->can('roleNewsAuthor')) { $params[$searchModel->formName()]['owner_id'] = Yii::$app->user->id; }//var_dump($params); $dataProvider = $searchModel->search($params); $pager = $dataProvider->getPagination(); $pager->pageSize = $this->module->params['pageSizeAdmin']; $pager->totalCount = $dataProvider->getTotalCount(); // page number correction: //if ($pager->totalCount <= $pager->pageSize || $page > ceil($pager->totalCount / $pager->pageSize) ) { // $pager->page = 0; //goto 1st page if shortage records $maxPage = ceil($pager->totalCount / $pager->pageSize); if ($page > $maxPage) { $pager->page = $maxPage - 1; } else { $pager->page = $page - 1; //! from 0 }//var_dump($page);var_dump($pager->page); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'currentId' => $id, ]); }
[ "public", "function", "actionIndex", "(", "$", "page", "=", "1", ",", "$", "id", "=", "0", ")", "{", "$", "searchModel", "=", "new", "NewsSearch", "(", ")", ";", "$", "params", "=", "Yii", "::", "$", "app", "->", "request", "->", "queryParams", ";", "if", "(", "!", "Yii", "::", "$", "app", "->", "user", "->", "can", "(", "'roleNewsModerator'", ")", "&&", "Yii", "::", "$", "app", "->", "user", "->", "can", "(", "'roleNewsAuthor'", ")", ")", "{", "$", "params", "[", "$", "searchModel", "->", "formName", "(", ")", "]", "[", "'owner_id'", "]", "=", "Yii", "::", "$", "app", "->", "user", "->", "id", ";", "}", "//var_dump($params);", "$", "dataProvider", "=", "$", "searchModel", "->", "search", "(", "$", "params", ")", ";", "$", "pager", "=", "$", "dataProvider", "->", "getPagination", "(", ")", ";", "$", "pager", "->", "pageSize", "=", "$", "this", "->", "module", "->", "params", "[", "'pageSizeAdmin'", "]", ";", "$", "pager", "->", "totalCount", "=", "$", "dataProvider", "->", "getTotalCount", "(", ")", ";", "// page number correction:", "//if ($pager->totalCount <= $pager->pageSize || $page > ceil($pager->totalCount / $pager->pageSize) ) {", "// $pager->page = 0; //goto 1st page if shortage records", "$", "maxPage", "=", "ceil", "(", "$", "pager", "->", "totalCount", "/", "$", "pager", "->", "pageSize", ")", ";", "if", "(", "$", "page", ">", "$", "maxPage", ")", "{", "$", "pager", "->", "page", "=", "$", "maxPage", "-", "1", ";", "}", "else", "{", "$", "pager", "->", "page", "=", "$", "page", "-", "1", ";", "//! from 0", "}", "//var_dump($page);var_dump($pager->page);", "return", "$", "this", "->", "render", "(", "'index'", ",", "[", "'searchModel'", "=>", "$", "searchModel", ",", "'dataProvider'", "=>", "$", "dataProvider", ",", "'currentId'", "=>", "$", "id", ",", "]", ")", ";", "}" ]
Lists all News models. @return mixed
[ "Lists", "all", "News", "models", "." ]
ce64b1e70c5a57b572921945cc51384087905461
https://github.com/asbsoft/yii2module-news_1b_160430/blob/ce64b1e70c5a57b572921945cc51384087905461/controllers/AdminController.php#L103-L131
5,033
asbsoft/yii2module-news_1b_160430
controllers/AdminController.php
AdminController.actionView
public function actionView($id) { $model = $this->findModel($id); $modelsI18n = $model::prepareI18nModels($model); if ($model->pageSize > 0) { $model->orderBy = $model->defaultOrderBy; $model->page = $model->calcPage();//echo __METHOD__.": calcPage(id={$id},pageSize={$model->pageSize})={$model->page}<br>";exit; } return $this->render('view', [ 'model' => $model, 'modelsI18n' => $modelsI18n, ]); }
php
public function actionView($id) { $model = $this->findModel($id); $modelsI18n = $model::prepareI18nModels($model); if ($model->pageSize > 0) { $model->orderBy = $model->defaultOrderBy; $model->page = $model->calcPage();//echo __METHOD__.": calcPage(id={$id},pageSize={$model->pageSize})={$model->page}<br>";exit; } return $this->render('view', [ 'model' => $model, 'modelsI18n' => $modelsI18n, ]); }
[ "public", "function", "actionView", "(", "$", "id", ")", "{", "$", "model", "=", "$", "this", "->", "findModel", "(", "$", "id", ")", ";", "$", "modelsI18n", "=", "$", "model", "::", "prepareI18nModels", "(", "$", "model", ")", ";", "if", "(", "$", "model", "->", "pageSize", ">", "0", ")", "{", "$", "model", "->", "orderBy", "=", "$", "model", "->", "defaultOrderBy", ";", "$", "model", "->", "page", "=", "$", "model", "->", "calcPage", "(", ")", ";", "//echo __METHOD__.\": calcPage(id={$id},pageSize={$model->pageSize})={$model->page}<br>\";exit;", "}", "return", "$", "this", "->", "render", "(", "'view'", ",", "[", "'model'", "=>", "$", "model", ",", "'modelsI18n'", "=>", "$", "modelsI18n", ",", "]", ")", ";", "}" ]
Displays a single News model. @param integer $id @return mixed
[ "Displays", "a", "single", "News", "model", "." ]
ce64b1e70c5a57b572921945cc51384087905461
https://github.com/asbsoft/yii2module-news_1b_160430/blob/ce64b1e70c5a57b572921945cc51384087905461/controllers/AdminController.php#L138-L152
5,034
asbsoft/yii2module-news_1b_160430
controllers/AdminController.php
AdminController.actionCreate
public function actionCreate() {//echo __METHOD__."@{$this->module->className()}"; //$model = new News(); $model = $this->module->model('News');//var_dump($model->className()); $model = $model->loadDefaultValues(); //$modelsI18n = News::prepareI18nModels($model); $modelsI18n = $model::prepareI18nModels($model);//var_dump($modelsI18n);exit; $activeTab = $this->langCodeMain; $created = $this->savePost($model, $modelsI18n); if (!$created) { return $this->render('create', [ 'model' => $model, 'modelsI18n' => $modelsI18n, 'activeTab' => $activeTab, ]); } else if ($activeTab = $this->modelsHaveErrors($model, $modelsI18n)) { // main record created but exist another errors Yii::$app->session->setFlash('warning', Yii::t($this->tcModule, 'Record create but partially')); if ($activeTab === true) $activeTab = $this->langCodeMain; $errors = $model->errors; foreach($modelsI18n as $langCode => $modelI18n) { if ($modelI18n->hasErrors()) { $errors += $modelI18n->errors; $activeTab = $langCode; break; } } $error = array_shift($errors); // get only first error if (isset($error[0])) { Yii::$app->session->setFlash('error', $error[0]); } return $this->redirect(['update', 'id' => $model->id, 'activeTab' => $activeTab, ]); } else { Yii::$app->session->setFlash('success', Yii::t($this->tcModule, 'Record create success')); if ($model->aftersave == $model::AFTERSAVE_VIEW) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->redirect(['index', 'page' => $model->page, 'id' => $model->id, 'sort' => $model->orderBy, //'lang' => Yii::$app->language, ]); } } }
php
public function actionCreate() {//echo __METHOD__."@{$this->module->className()}"; //$model = new News(); $model = $this->module->model('News');//var_dump($model->className()); $model = $model->loadDefaultValues(); //$modelsI18n = News::prepareI18nModels($model); $modelsI18n = $model::prepareI18nModels($model);//var_dump($modelsI18n);exit; $activeTab = $this->langCodeMain; $created = $this->savePost($model, $modelsI18n); if (!$created) { return $this->render('create', [ 'model' => $model, 'modelsI18n' => $modelsI18n, 'activeTab' => $activeTab, ]); } else if ($activeTab = $this->modelsHaveErrors($model, $modelsI18n)) { // main record created but exist another errors Yii::$app->session->setFlash('warning', Yii::t($this->tcModule, 'Record create but partially')); if ($activeTab === true) $activeTab = $this->langCodeMain; $errors = $model->errors; foreach($modelsI18n as $langCode => $modelI18n) { if ($modelI18n->hasErrors()) { $errors += $modelI18n->errors; $activeTab = $langCode; break; } } $error = array_shift($errors); // get only first error if (isset($error[0])) { Yii::$app->session->setFlash('error', $error[0]); } return $this->redirect(['update', 'id' => $model->id, 'activeTab' => $activeTab, ]); } else { Yii::$app->session->setFlash('success', Yii::t($this->tcModule, 'Record create success')); if ($model->aftersave == $model::AFTERSAVE_VIEW) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->redirect(['index', 'page' => $model->page, 'id' => $model->id, 'sort' => $model->orderBy, //'lang' => Yii::$app->language, ]); } } }
[ "public", "function", "actionCreate", "(", ")", "{", "//echo __METHOD__.\"@{$this->module->className()}\";", "//$model = new News();", "$", "model", "=", "$", "this", "->", "module", "->", "model", "(", "'News'", ")", ";", "//var_dump($model->className());", "$", "model", "=", "$", "model", "->", "loadDefaultValues", "(", ")", ";", "//$modelsI18n = News::prepareI18nModels($model);", "$", "modelsI18n", "=", "$", "model", "::", "prepareI18nModels", "(", "$", "model", ")", ";", "//var_dump($modelsI18n);exit;", "$", "activeTab", "=", "$", "this", "->", "langCodeMain", ";", "$", "created", "=", "$", "this", "->", "savePost", "(", "$", "model", ",", "$", "modelsI18n", ")", ";", "if", "(", "!", "$", "created", ")", "{", "return", "$", "this", "->", "render", "(", "'create'", ",", "[", "'model'", "=>", "$", "model", ",", "'modelsI18n'", "=>", "$", "modelsI18n", ",", "'activeTab'", "=>", "$", "activeTab", ",", "]", ")", ";", "}", "else", "if", "(", "$", "activeTab", "=", "$", "this", "->", "modelsHaveErrors", "(", "$", "model", ",", "$", "modelsI18n", ")", ")", "{", "// main record created but exist another errors", "Yii", "::", "$", "app", "->", "session", "->", "setFlash", "(", "'warning'", ",", "Yii", "::", "t", "(", "$", "this", "->", "tcModule", ",", "'Record create but partially'", ")", ")", ";", "if", "(", "$", "activeTab", "===", "true", ")", "$", "activeTab", "=", "$", "this", "->", "langCodeMain", ";", "$", "errors", "=", "$", "model", "->", "errors", ";", "foreach", "(", "$", "modelsI18n", "as", "$", "langCode", "=>", "$", "modelI18n", ")", "{", "if", "(", "$", "modelI18n", "->", "hasErrors", "(", ")", ")", "{", "$", "errors", "+=", "$", "modelI18n", "->", "errors", ";", "$", "activeTab", "=", "$", "langCode", ";", "break", ";", "}", "}", "$", "error", "=", "array_shift", "(", "$", "errors", ")", ";", "// get only first error", "if", "(", "isset", "(", "$", "error", "[", "0", "]", ")", ")", "{", "Yii", "::", "$", "app", "->", "session", "->", "setFlash", "(", "'error'", ",", "$", "error", "[", "0", "]", ")", ";", "}", "return", "$", "this", "->", "redirect", "(", "[", "'update'", ",", "'id'", "=>", "$", "model", "->", "id", ",", "'activeTab'", "=>", "$", "activeTab", ",", "]", ")", ";", "}", "else", "{", "Yii", "::", "$", "app", "->", "session", "->", "setFlash", "(", "'success'", ",", "Yii", "::", "t", "(", "$", "this", "->", "tcModule", ",", "'Record create success'", ")", ")", ";", "if", "(", "$", "model", "->", "aftersave", "==", "$", "model", "::", "AFTERSAVE_VIEW", ")", "{", "return", "$", "this", "->", "redirect", "(", "[", "'view'", ",", "'id'", "=>", "$", "model", "->", "id", "]", ")", ";", "}", "else", "{", "return", "$", "this", "->", "redirect", "(", "[", "'index'", ",", "'page'", "=>", "$", "model", "->", "page", ",", "'id'", "=>", "$", "model", "->", "id", ",", "'sort'", "=>", "$", "model", "->", "orderBy", ",", "//'lang' => Yii::$app->language,", "]", ")", ";", "}", "}", "}" ]
Creates a new News model. If creation is successful, the browser will be redirected to the 'view' page. @return mixed
[ "Creates", "a", "new", "News", "model", ".", "If", "creation", "is", "successful", "the", "browser", "will", "be", "redirected", "to", "the", "view", "page", "." ]
ce64b1e70c5a57b572921945cc51384087905461
https://github.com/asbsoft/yii2module-news_1b_160430/blob/ce64b1e70c5a57b572921945cc51384087905461/controllers/AdminController.php#L159-L208
5,035
asbsoft/yii2module-news_1b_160430
controllers/AdminController.php
AdminController.actionUpdate
public function actionUpdate($id, $activeTab = null) { $model = $this->findModel($id); if (!Yii::$app->user->can('roleNewsModerator') // user is not moderator && Yii::$app->user->can('roleNewsAuthor') // but is author ... && !Yii::$app->user->can('updateOwnNews', [ // ... can edit only own post 'news' => $model, // - if post unvisible - always can 'canEditVisible' // - but if not visible - see this param => $this->canAuthorEditOwnVisibleArticle, ]) ) { if ($this->canAuthorEditOwnVisibleArticle) { throw new ForbiddenHttpException(Yii::t($this->tc, 'You can update only your own post')); } else { throw new ForbiddenHttpException(Yii::t($this->tc, 'You can update only your own post still unvisible')); } } //$modelsI18n = News::prepareI18nModels($model); $modelsI18n = $this->module->model('News')->prepareI18nModels($model); if (empty($activeTab)) $activeTab = $this->langCodeMain; $created = $this->savePost($model, $modelsI18n); if (!$created || ($activeTab = $this->modelsHaveErrors($model, $modelsI18n))) { return $this->render('update', [ 'model' => $model, 'modelsI18n' => $modelsI18n, 'activeTab' => $activeTab, ]); } else { Yii::$app->session->setFlash('success', Yii::t($this->tcModule, 'Record save success')); if ($model->aftersave == $model::AFTERSAVE_VIEW) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->redirect(['index', 'page' => $model->page, 'id' => $model->id, 'sort' => $model->orderBy, //'lang' => Yii::$app->language, ]); } } }
php
public function actionUpdate($id, $activeTab = null) { $model = $this->findModel($id); if (!Yii::$app->user->can('roleNewsModerator') // user is not moderator && Yii::$app->user->can('roleNewsAuthor') // but is author ... && !Yii::$app->user->can('updateOwnNews', [ // ... can edit only own post 'news' => $model, // - if post unvisible - always can 'canEditVisible' // - but if not visible - see this param => $this->canAuthorEditOwnVisibleArticle, ]) ) { if ($this->canAuthorEditOwnVisibleArticle) { throw new ForbiddenHttpException(Yii::t($this->tc, 'You can update only your own post')); } else { throw new ForbiddenHttpException(Yii::t($this->tc, 'You can update only your own post still unvisible')); } } //$modelsI18n = News::prepareI18nModels($model); $modelsI18n = $this->module->model('News')->prepareI18nModels($model); if (empty($activeTab)) $activeTab = $this->langCodeMain; $created = $this->savePost($model, $modelsI18n); if (!$created || ($activeTab = $this->modelsHaveErrors($model, $modelsI18n))) { return $this->render('update', [ 'model' => $model, 'modelsI18n' => $modelsI18n, 'activeTab' => $activeTab, ]); } else { Yii::$app->session->setFlash('success', Yii::t($this->tcModule, 'Record save success')); if ($model->aftersave == $model::AFTERSAVE_VIEW) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->redirect(['index', 'page' => $model->page, 'id' => $model->id, 'sort' => $model->orderBy, //'lang' => Yii::$app->language, ]); } } }
[ "public", "function", "actionUpdate", "(", "$", "id", ",", "$", "activeTab", "=", "null", ")", "{", "$", "model", "=", "$", "this", "->", "findModel", "(", "$", "id", ")", ";", "if", "(", "!", "Yii", "::", "$", "app", "->", "user", "->", "can", "(", "'roleNewsModerator'", ")", "// user is not moderator", "&&", "Yii", "::", "$", "app", "->", "user", "->", "can", "(", "'roleNewsAuthor'", ")", "// but is author ...", "&&", "!", "Yii", "::", "$", "app", "->", "user", "->", "can", "(", "'updateOwnNews'", ",", "[", "// ... can edit only own post", "'news'", "=>", "$", "model", ",", "// - if post unvisible - always can", "'canEditVisible'", "// - but if not visible - see this param", "=>", "$", "this", "->", "canAuthorEditOwnVisibleArticle", ",", "]", ")", ")", "{", "if", "(", "$", "this", "->", "canAuthorEditOwnVisibleArticle", ")", "{", "throw", "new", "ForbiddenHttpException", "(", "Yii", "::", "t", "(", "$", "this", "->", "tc", ",", "'You can update only your own post'", ")", ")", ";", "}", "else", "{", "throw", "new", "ForbiddenHttpException", "(", "Yii", "::", "t", "(", "$", "this", "->", "tc", ",", "'You can update only your own post still unvisible'", ")", ")", ";", "}", "}", "//$modelsI18n = News::prepareI18nModels($model);", "$", "modelsI18n", "=", "$", "this", "->", "module", "->", "model", "(", "'News'", ")", "->", "prepareI18nModels", "(", "$", "model", ")", ";", "if", "(", "empty", "(", "$", "activeTab", ")", ")", "$", "activeTab", "=", "$", "this", "->", "langCodeMain", ";", "$", "created", "=", "$", "this", "->", "savePost", "(", "$", "model", ",", "$", "modelsI18n", ")", ";", "if", "(", "!", "$", "created", "||", "(", "$", "activeTab", "=", "$", "this", "->", "modelsHaveErrors", "(", "$", "model", ",", "$", "modelsI18n", ")", ")", ")", "{", "return", "$", "this", "->", "render", "(", "'update'", ",", "[", "'model'", "=>", "$", "model", ",", "'modelsI18n'", "=>", "$", "modelsI18n", ",", "'activeTab'", "=>", "$", "activeTab", ",", "]", ")", ";", "}", "else", "{", "Yii", "::", "$", "app", "->", "session", "->", "setFlash", "(", "'success'", ",", "Yii", "::", "t", "(", "$", "this", "->", "tcModule", ",", "'Record save success'", ")", ")", ";", "if", "(", "$", "model", "->", "aftersave", "==", "$", "model", "::", "AFTERSAVE_VIEW", ")", "{", "return", "$", "this", "->", "redirect", "(", "[", "'view'", ",", "'id'", "=>", "$", "model", "->", "id", "]", ")", ";", "}", "else", "{", "return", "$", "this", "->", "redirect", "(", "[", "'index'", ",", "'page'", "=>", "$", "model", "->", "page", ",", "'id'", "=>", "$", "model", "->", "id", ",", "'sort'", "=>", "$", "model", "->", "orderBy", ",", "//'lang' => Yii::$app->language,", "]", ")", ";", "}", "}", "}" ]
Updates an existing News model. If update is successful, the browser will be redirected to the 'view' page. @param integer $id @return mixed @throws ForbiddenHttpException if user can't edit this news
[ "Updates", "an", "existing", "News", "model", ".", "If", "update", "is", "successful", "the", "browser", "will", "be", "redirected", "to", "the", "view", "page", "." ]
ce64b1e70c5a57b572921945cc51384087905461
https://github.com/asbsoft/yii2module-news_1b_160430/blob/ce64b1e70c5a57b572921945cc51384087905461/controllers/AdminController.php#L217-L262
5,036
asbsoft/yii2module-news_1b_160430
controllers/AdminController.php
AdminController.timeCorrection
protected function timeCorrection($model, $attribute) {//echo __METHOD__."(model,'$attribute')";var_dump($model->$attribute); $resultFormat = 'Y-m-d H:i'; $dateFormats = [ 'Y-m-d H:i', 'Y-m-d G:i', 'Y-m-j H:i', 'Y-m-j G:i', 'Y-n-d H:i', 'Y-n-d G:i', 'Y-n-j H:i', 'Y-n-j G:i', //'Y-m-d', 'Y-m-j', 'Y-n-d', 'Y-n-j', // do not use - will add current time, not 00:00 ]; // correct if empty time //$model->$attribute = rtrim($model->$attribute, " :"); $needCorrection = true; if (':' == substr($model->$attribute, -1)) { $model->$attribute = rtrim($model->$attribute, ':'); $model->$attribute .= '00:00'; $needCorrection = false; } foreach($dateFormats as $dateFormat) { $datetime = \DateTime::createFromFormat($dateFormat, $model->$attribute); if (!empty($datetime)) break; } if ($needCorrection && !empty($datetime) && !empty($model->timezoneshift)) { $unixDatetime = $datetime->getTimestamp(); $unixDatetime += 60 * intval($model->timezoneshift); $datetime->setTimestamp($unixDatetime); $model->$attribute = $datetime->format($resultFormat); }//var_dump($model->$attribute);exit; }
php
protected function timeCorrection($model, $attribute) {//echo __METHOD__."(model,'$attribute')";var_dump($model->$attribute); $resultFormat = 'Y-m-d H:i'; $dateFormats = [ 'Y-m-d H:i', 'Y-m-d G:i', 'Y-m-j H:i', 'Y-m-j G:i', 'Y-n-d H:i', 'Y-n-d G:i', 'Y-n-j H:i', 'Y-n-j G:i', //'Y-m-d', 'Y-m-j', 'Y-n-d', 'Y-n-j', // do not use - will add current time, not 00:00 ]; // correct if empty time //$model->$attribute = rtrim($model->$attribute, " :"); $needCorrection = true; if (':' == substr($model->$attribute, -1)) { $model->$attribute = rtrim($model->$attribute, ':'); $model->$attribute .= '00:00'; $needCorrection = false; } foreach($dateFormats as $dateFormat) { $datetime = \DateTime::createFromFormat($dateFormat, $model->$attribute); if (!empty($datetime)) break; } if ($needCorrection && !empty($datetime) && !empty($model->timezoneshift)) { $unixDatetime = $datetime->getTimestamp(); $unixDatetime += 60 * intval($model->timezoneshift); $datetime->setTimestamp($unixDatetime); $model->$attribute = $datetime->format($resultFormat); }//var_dump($model->$attribute);exit; }
[ "protected", "function", "timeCorrection", "(", "$", "model", ",", "$", "attribute", ")", "{", "//echo __METHOD__.\"(model,'$attribute')\";var_dump($model->$attribute);", "$", "resultFormat", "=", "'Y-m-d H:i'", ";", "$", "dateFormats", "=", "[", "'Y-m-d H:i'", ",", "'Y-m-d G:i'", ",", "'Y-m-j H:i'", ",", "'Y-m-j G:i'", ",", "'Y-n-d H:i'", ",", "'Y-n-d G:i'", ",", "'Y-n-j H:i'", ",", "'Y-n-j G:i'", ",", "//'Y-m-d', 'Y-m-j', 'Y-n-d', 'Y-n-j', // do not use - will add current time, not 00:00", "]", ";", "// correct if empty time", "//$model->$attribute = rtrim($model->$attribute, \" :\");", "$", "needCorrection", "=", "true", ";", "if", "(", "':'", "==", "substr", "(", "$", "model", "->", "$", "attribute", ",", "-", "1", ")", ")", "{", "$", "model", "->", "$", "attribute", "=", "rtrim", "(", "$", "model", "->", "$", "attribute", ",", "':'", ")", ";", "$", "model", "->", "$", "attribute", ".=", "'00:00'", ";", "$", "needCorrection", "=", "false", ";", "}", "foreach", "(", "$", "dateFormats", "as", "$", "dateFormat", ")", "{", "$", "datetime", "=", "\\", "DateTime", "::", "createFromFormat", "(", "$", "dateFormat", ",", "$", "model", "->", "$", "attribute", ")", ";", "if", "(", "!", "empty", "(", "$", "datetime", ")", ")", "break", ";", "}", "if", "(", "$", "needCorrection", "&&", "!", "empty", "(", "$", "datetime", ")", "&&", "!", "empty", "(", "$", "model", "->", "timezoneshift", ")", ")", "{", "$", "unixDatetime", "=", "$", "datetime", "->", "getTimestamp", "(", ")", ";", "$", "unixDatetime", "+=", "60", "*", "intval", "(", "$", "model", "->", "timezoneshift", ")", ";", "$", "datetime", "->", "setTimestamp", "(", "$", "unixDatetime", ")", ";", "$", "model", "->", "$", "attribute", "=", "$", "datetime", "->", "format", "(", "$", "resultFormat", ")", ";", "}", "//var_dump($model->$attribute);exit;", "}" ]
Correct datetime field according to timezone
[ "Correct", "datetime", "field", "according", "to", "timezone" ]
ce64b1e70c5a57b572921945cc51384087905461
https://github.com/asbsoft/yii2module-news_1b_160430/blob/ce64b1e70c5a57b572921945cc51384087905461/controllers/AdminController.php#L265-L300
5,037
asbsoft/yii2module-news_1b_160430
controllers/AdminController.php
AdminController.saveImage
protected function saveImage($model) { //$subdir = News::getImageSubdir($model->id); $subdir = $this->module->model('News')->getImageSubdir($model->id); FileHelper::createDirectory($this->uploadsNewsDir . '/' . $subdir); //$baseMainImageName = $model->imagefile->baseName; // don't use original file name $baseMainImageName = $model->id . '-' . $this->baseMainImageName; // image name should be standard $path = $subdir . '/' . $baseMainImageName . '.' . $model->imagefile->extension; $newImagePath = $this->uploadsNewsDir . '/' . $path; $oldImagePath = $this->uploadsNewsDir . '/' . $model->image; if ($newImagePath !== $oldImagePath && is_file($newImagePath)) { // names collision //! do not overwrite: it can be file uploaded by image manager //$model->addError('imagefile', 'Such image already exists: ' . $newImagePath); return false; //error can't solve problem rename($newImagePath, $newImagePath . '-' . uniqid()); // rename exists old file with 'new' name for save } if (is_file($oldImagePath)) { @unlink($oldImagePath); // always delete old main news image - need when change file extension } try { $model->imagefile->saveAs($newImagePath); } catch(ErrorException $e) { $model->addError('imagefile', $error = $e->getMessage()); $path = false; } return $path; }
php
protected function saveImage($model) { //$subdir = News::getImageSubdir($model->id); $subdir = $this->module->model('News')->getImageSubdir($model->id); FileHelper::createDirectory($this->uploadsNewsDir . '/' . $subdir); //$baseMainImageName = $model->imagefile->baseName; // don't use original file name $baseMainImageName = $model->id . '-' . $this->baseMainImageName; // image name should be standard $path = $subdir . '/' . $baseMainImageName . '.' . $model->imagefile->extension; $newImagePath = $this->uploadsNewsDir . '/' . $path; $oldImagePath = $this->uploadsNewsDir . '/' . $model->image; if ($newImagePath !== $oldImagePath && is_file($newImagePath)) { // names collision //! do not overwrite: it can be file uploaded by image manager //$model->addError('imagefile', 'Such image already exists: ' . $newImagePath); return false; //error can't solve problem rename($newImagePath, $newImagePath . '-' . uniqid()); // rename exists old file with 'new' name for save } if (is_file($oldImagePath)) { @unlink($oldImagePath); // always delete old main news image - need when change file extension } try { $model->imagefile->saveAs($newImagePath); } catch(ErrorException $e) { $model->addError('imagefile', $error = $e->getMessage()); $path = false; } return $path; }
[ "protected", "function", "saveImage", "(", "$", "model", ")", "{", "//$subdir = News::getImageSubdir($model->id);", "$", "subdir", "=", "$", "this", "->", "module", "->", "model", "(", "'News'", ")", "->", "getImageSubdir", "(", "$", "model", "->", "id", ")", ";", "FileHelper", "::", "createDirectory", "(", "$", "this", "->", "uploadsNewsDir", ".", "'/'", ".", "$", "subdir", ")", ";", "//$baseMainImageName = $model->imagefile->baseName; // don't use original file name", "$", "baseMainImageName", "=", "$", "model", "->", "id", ".", "'-'", ".", "$", "this", "->", "baseMainImageName", ";", "// image name should be standard", "$", "path", "=", "$", "subdir", ".", "'/'", ".", "$", "baseMainImageName", ".", "'.'", ".", "$", "model", "->", "imagefile", "->", "extension", ";", "$", "newImagePath", "=", "$", "this", "->", "uploadsNewsDir", ".", "'/'", ".", "$", "path", ";", "$", "oldImagePath", "=", "$", "this", "->", "uploadsNewsDir", ".", "'/'", ".", "$", "model", "->", "image", ";", "if", "(", "$", "newImagePath", "!==", "$", "oldImagePath", "&&", "is_file", "(", "$", "newImagePath", ")", ")", "{", "// names collision", "//! do not overwrite: it can be file uploaded by image manager", "//$model->addError('imagefile', 'Such image already exists: ' . $newImagePath); return false; //error can't solve problem", "rename", "(", "$", "newImagePath", ",", "$", "newImagePath", ".", "'-'", ".", "uniqid", "(", ")", ")", ";", "// rename exists old file with 'new' name for save", "}", "if", "(", "is_file", "(", "$", "oldImagePath", ")", ")", "{", "@", "unlink", "(", "$", "oldImagePath", ")", ";", "// always delete old main news image - need when change file extension", "}", "try", "{", "$", "model", "->", "imagefile", "->", "saveAs", "(", "$", "newImagePath", ")", ";", "}", "catch", "(", "ErrorException", "$", "e", ")", "{", "$", "model", "->", "addError", "(", "'imagefile'", ",", "$", "error", "=", "$", "e", "->", "getMessage", "(", ")", ")", ";", "$", "path", "=", "false", ";", "}", "return", "$", "path", ";", "}" ]
Save image file. Replace if exists. @return string relative path to file without main upload dir prefix
[ "Save", "image", "file", ".", "Replace", "if", "exists", "." ]
ce64b1e70c5a57b572921945cc51384087905461
https://github.com/asbsoft/yii2module-news_1b_160430/blob/ce64b1e70c5a57b572921945cc51384087905461/controllers/AdminController.php#L379-L408
5,038
asbsoft/yii2module-news_1b_160430
controllers/AdminController.php
AdminController.actionDelete
public function actionDelete($id, $page = 1) { $model = $this->findModel($id); /* moved to model: $subdir = $this->module->model('News')->getImageSubdir($model->id); $fullDir = $this->uploadsNewsDir . '/' . $subdir;//var_dump($fullDir);exit; if (is_dir($fullDir)) { @FileHelper::removeDirectory($fullDir); } */ $model->delete(); // images and i18n-deletions also in main model Yii::$app->session->setFlash('success', Yii::t($this->tcModule, 'Record with ID={id} delete success', ['id' => $id])); $searchFormName = basename(NewsSearch::className()); $paramSort = Yii::$app->request->get($searchFormName, []); foreach ($paramSort as $key => $val) { if (empty($val)) unset($paramSort[$key]); } return $this->redirect(['index', 'page' => $page, $searchFormName => $paramSort, 'sort' => $model->orderBy, ]); }
php
public function actionDelete($id, $page = 1) { $model = $this->findModel($id); /* moved to model: $subdir = $this->module->model('News')->getImageSubdir($model->id); $fullDir = $this->uploadsNewsDir . '/' . $subdir;//var_dump($fullDir);exit; if (is_dir($fullDir)) { @FileHelper::removeDirectory($fullDir); } */ $model->delete(); // images and i18n-deletions also in main model Yii::$app->session->setFlash('success', Yii::t($this->tcModule, 'Record with ID={id} delete success', ['id' => $id])); $searchFormName = basename(NewsSearch::className()); $paramSort = Yii::$app->request->get($searchFormName, []); foreach ($paramSort as $key => $val) { if (empty($val)) unset($paramSort[$key]); } return $this->redirect(['index', 'page' => $page, $searchFormName => $paramSort, 'sort' => $model->orderBy, ]); }
[ "public", "function", "actionDelete", "(", "$", "id", ",", "$", "page", "=", "1", ")", "{", "$", "model", "=", "$", "this", "->", "findModel", "(", "$", "id", ")", ";", "/* moved to model:\n $subdir = $this->module->model('News')->getImageSubdir($model->id);\n $fullDir = $this->uploadsNewsDir . '/' . $subdir;//var_dump($fullDir);exit;\n if (is_dir($fullDir)) {\n @FileHelper::removeDirectory($fullDir);\n }\n*/", "$", "model", "->", "delete", "(", ")", ";", "// images and i18n-deletions also in main model", "Yii", "::", "$", "app", "->", "session", "->", "setFlash", "(", "'success'", ",", "Yii", "::", "t", "(", "$", "this", "->", "tcModule", ",", "'Record with ID={id} delete success'", ",", "[", "'id'", "=>", "$", "id", "]", ")", ")", ";", "$", "searchFormName", "=", "basename", "(", "NewsSearch", "::", "className", "(", ")", ")", ";", "$", "paramSort", "=", "Yii", "::", "$", "app", "->", "request", "->", "get", "(", "$", "searchFormName", ",", "[", "]", ")", ";", "foreach", "(", "$", "paramSort", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "empty", "(", "$", "val", ")", ")", "unset", "(", "$", "paramSort", "[", "$", "key", "]", ")", ";", "}", "return", "$", "this", "->", "redirect", "(", "[", "'index'", ",", "'page'", "=>", "$", "page", ",", "$", "searchFormName", "=>", "$", "paramSort", ",", "'sort'", "=>", "$", "model", "->", "orderBy", ",", "]", ")", ";", "}" ]
Deletes an existing News model. If deletion is successful, the browser will be redirected to the 'index' page. @param integer $id @return mixed
[ "Deletes", "an", "existing", "News", "model", ".", "If", "deletion", "is", "successful", "the", "browser", "will", "be", "redirected", "to", "the", "index", "page", "." ]
ce64b1e70c5a57b572921945cc51384087905461
https://github.com/asbsoft/yii2module-news_1b_160430/blob/ce64b1e70c5a57b572921945cc51384087905461/controllers/AdminController.php#L416-L440
5,039
asbsoft/yii2module-news_1b_160430
controllers/AdminController.php
AdminController.findModel
protected function findModel($id) { //$model = News::findOne($id); $model = $this->module->model('News')->findOne($id); if ($model !== null) { return $model; } else { throw new NotFoundHttpException(Yii::t($this->tc,'The requested news does not exist')); } }
php
protected function findModel($id) { //$model = News::findOne($id); $model = $this->module->model('News')->findOne($id); if ($model !== null) { return $model; } else { throw new NotFoundHttpException(Yii::t($this->tc,'The requested news does not exist')); } }
[ "protected", "function", "findModel", "(", "$", "id", ")", "{", "//$model = News::findOne($id);", "$", "model", "=", "$", "this", "->", "module", "->", "model", "(", "'News'", ")", "->", "findOne", "(", "$", "id", ")", ";", "if", "(", "$", "model", "!==", "null", ")", "{", "return", "$", "model", ";", "}", "else", "{", "throw", "new", "NotFoundHttpException", "(", "Yii", "::", "t", "(", "$", "this", "->", "tc", ",", "'The requested news does not exist'", ")", ")", ";", "}", "}" ]
Finds the News model based on its primary key value. If the model is not found, a 404 HTTP exception will be thrown. @param integer $id @return News the loaded model @throws NotFoundHttpException if the model cannot be found
[ "Finds", "the", "News", "model", "based", "on", "its", "primary", "key", "value", ".", "If", "the", "model", "is", "not", "found", "a", "404", "HTTP", "exception", "will", "be", "thrown", "." ]
ce64b1e70c5a57b572921945cc51384087905461
https://github.com/asbsoft/yii2module-news_1b_160430/blob/ce64b1e70c5a57b572921945cc51384087905461/controllers/AdminController.php#L449-L458
5,040
extendsframework/extends-shell
src/ShellBuilder.php
ShellBuilder.addCommand
public function addCommand( string $name, string $description, array $operands = null, array $options = null, array $parameters = null ): ShellBuilder { $definition = new Definition(); foreach ($operands ?? [] as $operand) { $definition->addOperand( new Operand($operand['name']) ); } foreach ($options ?? [] as $option) { $definition->addOption( new Option( $option['name'], $option['description'], $option['short'] ?? null, $option['long'] ?? null, $option['flag'] ?? null, $option['multiple'] ?? null ) ); } $this->commands[] = new Command( $name, $description, $definition, $parameters ); return $this; }
php
public function addCommand( string $name, string $description, array $operands = null, array $options = null, array $parameters = null ): ShellBuilder { $definition = new Definition(); foreach ($operands ?? [] as $operand) { $definition->addOperand( new Operand($operand['name']) ); } foreach ($options ?? [] as $option) { $definition->addOption( new Option( $option['name'], $option['description'], $option['short'] ?? null, $option['long'] ?? null, $option['flag'] ?? null, $option['multiple'] ?? null ) ); } $this->commands[] = new Command( $name, $description, $definition, $parameters ); return $this; }
[ "public", "function", "addCommand", "(", "string", "$", "name", ",", "string", "$", "description", ",", "array", "$", "operands", "=", "null", ",", "array", "$", "options", "=", "null", ",", "array", "$", "parameters", "=", "null", ")", ":", "ShellBuilder", "{", "$", "definition", "=", "new", "Definition", "(", ")", ";", "foreach", "(", "$", "operands", "??", "[", "]", "as", "$", "operand", ")", "{", "$", "definition", "->", "addOperand", "(", "new", "Operand", "(", "$", "operand", "[", "'name'", "]", ")", ")", ";", "}", "foreach", "(", "$", "options", "??", "[", "]", "as", "$", "option", ")", "{", "$", "definition", "->", "addOption", "(", "new", "Option", "(", "$", "option", "[", "'name'", "]", ",", "$", "option", "[", "'description'", "]", ",", "$", "option", "[", "'short'", "]", "??", "null", ",", "$", "option", "[", "'long'", "]", "??", "null", ",", "$", "option", "[", "'flag'", "]", "??", "null", ",", "$", "option", "[", "'multiple'", "]", "??", "null", ")", ")", ";", "}", "$", "this", "->", "commands", "[", "]", "=", "new", "Command", "(", "$", "name", ",", "$", "description", ",", "$", "definition", ",", "$", "parameters", ")", ";", "return", "$", "this", ";", "}" ]
Add command to shell. @param string $name @param string $description @param array|null $operands @param array|null $options @param array|null $parameters @return ShellBuilder
[ "Add", "command", "to", "shell", "." ]
115a38dd7e2af82d56d15407d7955da2d382521b
https://github.com/extendsframework/extends-shell/blob/115a38dd7e2af82d56d15407d7955da2d382521b/src/ShellBuilder.php#L106-L141
5,041
extendsframework/extends-shell
src/ShellBuilder.php
ShellBuilder.reset
protected function reset(): ShellBuilder { $this->name = $this->program = $this->version = $this->descriptor = $this->suggester = $this->parser = null; $this->commands = []; return $this; }
php
protected function reset(): ShellBuilder { $this->name = $this->program = $this->version = $this->descriptor = $this->suggester = $this->parser = null; $this->commands = []; return $this; }
[ "protected", "function", "reset", "(", ")", ":", "ShellBuilder", "{", "$", "this", "->", "name", "=", "$", "this", "->", "program", "=", "$", "this", "->", "version", "=", "$", "this", "->", "descriptor", "=", "$", "this", "->", "suggester", "=", "$", "this", "->", "parser", "=", "null", ";", "$", "this", "->", "commands", "=", "[", "]", ";", "return", "$", "this", ";", "}" ]
Reset builder after build. @return ShellBuilder
[ "Reset", "builder", "after", "build", "." ]
115a38dd7e2af82d56d15407d7955da2d382521b
https://github.com/extendsframework/extends-shell/blob/115a38dd7e2af82d56d15407d7955da2d382521b/src/ShellBuilder.php#L296-L302
5,042
ekyna/UserBundle
Mailer/Mailer.php
Mailer.sendSuccessfulLoginEmailMessage
public function sendSuccessfulLoginEmailMessage(UserInterface $user) { /** @var \Ekyna\Bundle\UserBundle\Model\UserInterface $user */ $siteName = $this->settingsManager->getParameter('general.site_name'); $userName = sprintf('%s %s', $user->getFirstName(), $user->getLastName()); $rendered = $this->templating->render( 'EkynaUserBundle:Security:login_success_email.html.twig', [ 'username' => $userName, 'sitename' => $siteName, 'date' => new \DateTime() ] ); $subject = $this->translator->trans( 'ekyna_user.email.login_success.subject', ['%sitename%' => $siteName] ); $this->sendEmail($rendered, $user->getEmail(), $userName, $subject); }
php
public function sendSuccessfulLoginEmailMessage(UserInterface $user) { /** @var \Ekyna\Bundle\UserBundle\Model\UserInterface $user */ $siteName = $this->settingsManager->getParameter('general.site_name'); $userName = sprintf('%s %s', $user->getFirstName(), $user->getLastName()); $rendered = $this->templating->render( 'EkynaUserBundle:Security:login_success_email.html.twig', [ 'username' => $userName, 'sitename' => $siteName, 'date' => new \DateTime() ] ); $subject = $this->translator->trans( 'ekyna_user.email.login_success.subject', ['%sitename%' => $siteName] ); $this->sendEmail($rendered, $user->getEmail(), $userName, $subject); }
[ "public", "function", "sendSuccessfulLoginEmailMessage", "(", "UserInterface", "$", "user", ")", "{", "/** @var \\Ekyna\\Bundle\\UserBundle\\Model\\UserInterface $user */", "$", "siteName", "=", "$", "this", "->", "settingsManager", "->", "getParameter", "(", "'general.site_name'", ")", ";", "$", "userName", "=", "sprintf", "(", "'%s %s'", ",", "$", "user", "->", "getFirstName", "(", ")", ",", "$", "user", "->", "getLastName", "(", ")", ")", ";", "$", "rendered", "=", "$", "this", "->", "templating", "->", "render", "(", "'EkynaUserBundle:Security:login_success_email.html.twig'", ",", "[", "'username'", "=>", "$", "userName", ",", "'sitename'", "=>", "$", "siteName", ",", "'date'", "=>", "new", "\\", "DateTime", "(", ")", "]", ")", ";", "$", "subject", "=", "$", "this", "->", "translator", "->", "trans", "(", "'ekyna_user.email.login_success.subject'", ",", "[", "'%sitename%'", "=>", "$", "siteName", "]", ")", ";", "$", "this", "->", "sendEmail", "(", "$", "rendered", ",", "$", "user", "->", "getEmail", "(", ")", ",", "$", "userName", ",", "$", "subject", ")", ";", "}" ]
Sends an email to the user to warn about successful login. @param UserInterface $user
[ "Sends", "an", "email", "to", "the", "user", "to", "warn", "about", "successful", "login", "." ]
e38d56aee978148a312a923b9e70bdaad1a381bf
https://github.com/ekyna/UserBundle/blob/e38d56aee978148a312a923b9e70bdaad1a381bf/Mailer/Mailer.php#L90-L111
5,043
ekyna/UserBundle
Mailer/Mailer.php
Mailer.sendCreationEmailMessage
public function sendCreationEmailMessage(UserInterface $user, $password) { /** @var \Ekyna\Bundle\UserBundle\Model\UserInterface $user */ $siteName = $this->settingsManager->getParameter('general.site_name'); $userName = sprintf('%s %s', $user->getFirstName(), $user->getLastName()); $login = $user->getUsername(); if (0 === strlen($password)) { return 0; } if (null === $loginUrl = $this->getLoginUrl($user)) { return 0; } $rendered = $this->templating->render( 'EkynaUserBundle:Admin/User:creation_email.html.twig', [ 'username' => $userName, 'sitename' => $siteName, 'login_url' => $loginUrl, 'login' => $login, 'password' => $password, ] ); $subject = $this->translator->trans( 'ekyna_user.email.creation.subject', ['%sitename%' => $siteName] ); return $this->sendEmail($rendered, $user->getEmail(), $userName, $subject); }
php
public function sendCreationEmailMessage(UserInterface $user, $password) { /** @var \Ekyna\Bundle\UserBundle\Model\UserInterface $user */ $siteName = $this->settingsManager->getParameter('general.site_name'); $userName = sprintf('%s %s', $user->getFirstName(), $user->getLastName()); $login = $user->getUsername(); if (0 === strlen($password)) { return 0; } if (null === $loginUrl = $this->getLoginUrl($user)) { return 0; } $rendered = $this->templating->render( 'EkynaUserBundle:Admin/User:creation_email.html.twig', [ 'username' => $userName, 'sitename' => $siteName, 'login_url' => $loginUrl, 'login' => $login, 'password' => $password, ] ); $subject = $this->translator->trans( 'ekyna_user.email.creation.subject', ['%sitename%' => $siteName] ); return $this->sendEmail($rendered, $user->getEmail(), $userName, $subject); }
[ "public", "function", "sendCreationEmailMessage", "(", "UserInterface", "$", "user", ",", "$", "password", ")", "{", "/** @var \\Ekyna\\Bundle\\UserBundle\\Model\\UserInterface $user */", "$", "siteName", "=", "$", "this", "->", "settingsManager", "->", "getParameter", "(", "'general.site_name'", ")", ";", "$", "userName", "=", "sprintf", "(", "'%s %s'", ",", "$", "user", "->", "getFirstName", "(", ")", ",", "$", "user", "->", "getLastName", "(", ")", ")", ";", "$", "login", "=", "$", "user", "->", "getUsername", "(", ")", ";", "if", "(", "0", "===", "strlen", "(", "$", "password", ")", ")", "{", "return", "0", ";", "}", "if", "(", "null", "===", "$", "loginUrl", "=", "$", "this", "->", "getLoginUrl", "(", "$", "user", ")", ")", "{", "return", "0", ";", "}", "$", "rendered", "=", "$", "this", "->", "templating", "->", "render", "(", "'EkynaUserBundle:Admin/User:creation_email.html.twig'", ",", "[", "'username'", "=>", "$", "userName", ",", "'sitename'", "=>", "$", "siteName", ",", "'login_url'", "=>", "$", "loginUrl", ",", "'login'", "=>", "$", "login", ",", "'password'", "=>", "$", "password", ",", "]", ")", ";", "$", "subject", "=", "$", "this", "->", "translator", "->", "trans", "(", "'ekyna_user.email.creation.subject'", ",", "[", "'%sitename%'", "=>", "$", "siteName", "]", ")", ";", "return", "$", "this", "->", "sendEmail", "(", "$", "rendered", ",", "$", "user", "->", "getEmail", "(", ")", ",", "$", "userName", ",", "$", "subject", ")", ";", "}" ]
Sends an email to the user to warn about account creation. @param UserInterface $user @param string $password @return integer
[ "Sends", "an", "email", "to", "the", "user", "to", "warn", "about", "account", "creation", "." ]
e38d56aee978148a312a923b9e70bdaad1a381bf
https://github.com/ekyna/UserBundle/blob/e38d56aee978148a312a923b9e70bdaad1a381bf/Mailer/Mailer.php#L120-L152
5,044
ekyna/UserBundle
Mailer/Mailer.php
Mailer.getLoginUrl
protected function getLoginUrl(UserInterface $user) { $token = new UsernamePasswordToken($user, 'none', 'none', $user->getRoles()); if ($this->accessDecisionManager->decide($token, ['ROLE_ADMIN'])) { return $this->router->generate('ekyna_admin_security_login', [], UrlGeneratorInterface::ABSOLUTE_URL); } else if ($this->config['account']['enable']) { return $this->router->generate('fos_user_security_login', [], UrlGeneratorInterface::ABSOLUTE_URL); } return null; }
php
protected function getLoginUrl(UserInterface $user) { $token = new UsernamePasswordToken($user, 'none', 'none', $user->getRoles()); if ($this->accessDecisionManager->decide($token, ['ROLE_ADMIN'])) { return $this->router->generate('ekyna_admin_security_login', [], UrlGeneratorInterface::ABSOLUTE_URL); } else if ($this->config['account']['enable']) { return $this->router->generate('fos_user_security_login', [], UrlGeneratorInterface::ABSOLUTE_URL); } return null; }
[ "protected", "function", "getLoginUrl", "(", "UserInterface", "$", "user", ")", "{", "$", "token", "=", "new", "UsernamePasswordToken", "(", "$", "user", ",", "'none'", ",", "'none'", ",", "$", "user", "->", "getRoles", "(", ")", ")", ";", "if", "(", "$", "this", "->", "accessDecisionManager", "->", "decide", "(", "$", "token", ",", "[", "'ROLE_ADMIN'", "]", ")", ")", "{", "return", "$", "this", "->", "router", "->", "generate", "(", "'ekyna_admin_security_login'", ",", "[", "]", ",", "UrlGeneratorInterface", "::", "ABSOLUTE_URL", ")", ";", "}", "else", "if", "(", "$", "this", "->", "config", "[", "'account'", "]", "[", "'enable'", "]", ")", "{", "return", "$", "this", "->", "router", "->", "generate", "(", "'fos_user_security_login'", ",", "[", "]", ",", "UrlGeneratorInterface", "::", "ABSOLUTE_URL", ")", ";", "}", "return", "null", ";", "}" ]
Returns the login url. @param UserInterface $user @return null|string
[ "Returns", "the", "login", "url", "." ]
e38d56aee978148a312a923b9e70bdaad1a381bf
https://github.com/ekyna/UserBundle/blob/e38d56aee978148a312a923b9e70bdaad1a381bf/Mailer/Mailer.php#L251-L260
5,045
Flowpack/Flowpack.SingleSignOn.Server
Classes/Flowpack/SingleSignOn/Server/Domain/Model/SsoClient.php
SsoClient.destroySession
public function destroySession(SsoServer $ssoServer, $sessionId) { $signedRequest = $this->buildDestroySessionRequest($ssoServer, $sessionId); $response = $this->requestEngine->sendRequest($signedRequest); if ($response->getStatusCode() === 404 && $response->getHeader('Content-Type') === 'application/json') { $data = json_decode($response->getContent(), TRUE); if (is_array($data) && isset($data['error']) && $data['error'] === 'SessionNotFound') { return; } } if ($response->getStatusCode() !== 200) { throw new Exception('Unexpected status code for destroy session when calling "' . (string)$signedRequest->getUri() . '": "' . $response->getStatus() . '"', 1354132939); } }
php
public function destroySession(SsoServer $ssoServer, $sessionId) { $signedRequest = $this->buildDestroySessionRequest($ssoServer, $sessionId); $response = $this->requestEngine->sendRequest($signedRequest); if ($response->getStatusCode() === 404 && $response->getHeader('Content-Type') === 'application/json') { $data = json_decode($response->getContent(), TRUE); if (is_array($data) && isset($data['error']) && $data['error'] === 'SessionNotFound') { return; } } if ($response->getStatusCode() !== 200) { throw new Exception('Unexpected status code for destroy session when calling "' . (string)$signedRequest->getUri() . '": "' . $response->getStatus() . '"', 1354132939); } }
[ "public", "function", "destroySession", "(", "SsoServer", "$", "ssoServer", ",", "$", "sessionId", ")", "{", "$", "signedRequest", "=", "$", "this", "->", "buildDestroySessionRequest", "(", "$", "ssoServer", ",", "$", "sessionId", ")", ";", "$", "response", "=", "$", "this", "->", "requestEngine", "->", "sendRequest", "(", "$", "signedRequest", ")", ";", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", "===", "404", "&&", "$", "response", "->", "getHeader", "(", "'Content-Type'", ")", "===", "'application/json'", ")", "{", "$", "data", "=", "json_decode", "(", "$", "response", "->", "getContent", "(", ")", ",", "TRUE", ")", ";", "if", "(", "is_array", "(", "$", "data", ")", "&&", "isset", "(", "$", "data", "[", "'error'", "]", ")", "&&", "$", "data", "[", "'error'", "]", "===", "'SessionNotFound'", ")", "{", "return", ";", "}", "}", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", "!==", "200", ")", "{", "throw", "new", "Exception", "(", "'Unexpected status code for destroy session when calling \"'", ".", "(", "string", ")", "$", "signedRequest", "->", "getUri", "(", ")", ".", "'\": \"'", ".", "$", "response", "->", "getStatus", "(", ")", ".", "'\"'", ",", "1354132939", ")", ";", "}", "}" ]
Destroy a client session with the given session id The client expects a local session id and not a global session id from the SSO server. TODO Move code to SimpleSsoClientNotififer and only leave buildDestroySessionRequest in client @param \Flowpack\SingleSignOn\Server\Domain\Model\SsoServer $ssoServer @param string $sessionId @return void
[ "Destroy", "a", "client", "session", "with", "the", "given", "session", "id" ]
b1fa014f31d0d101a79cb95d5585b9973f35347d
https://github.com/Flowpack/Flowpack.SingleSignOn.Server/blob/b1fa014f31d0d101a79cb95d5585b9973f35347d/Classes/Flowpack/SingleSignOn/Server/Domain/Model/SsoClient.php#L62-L77
5,046
Flowpack/Flowpack.SingleSignOn.Server
Classes/Flowpack/SingleSignOn/Server/Domain/Model/SsoClient.php
SsoClient.buildDestroySessionRequest
public function buildDestroySessionRequest(SsoServer $ssoServer, $sessionId) { $serviceUri = new Uri(rtrim($this->serviceBaseUri, '/') . '/session/' . urlencode($sessionId) . '/destroy'); $serviceUri->setQuery(http_build_query(array('serverIdentifier' => $ssoServer->getServiceBaseUri()))); $request = \TYPO3\Flow\Http\Request::create($serviceUri, 'DELETE'); $request->setContent(''); return $this->requestSigner->signRequest($request, $ssoServer->getKeyPairFingerprint(), $ssoServer->getKeyPairFingerprint()); }
php
public function buildDestroySessionRequest(SsoServer $ssoServer, $sessionId) { $serviceUri = new Uri(rtrim($this->serviceBaseUri, '/') . '/session/' . urlencode($sessionId) . '/destroy'); $serviceUri->setQuery(http_build_query(array('serverIdentifier' => $ssoServer->getServiceBaseUri()))); $request = \TYPO3\Flow\Http\Request::create($serviceUri, 'DELETE'); $request->setContent(''); return $this->requestSigner->signRequest($request, $ssoServer->getKeyPairFingerprint(), $ssoServer->getKeyPairFingerprint()); }
[ "public", "function", "buildDestroySessionRequest", "(", "SsoServer", "$", "ssoServer", ",", "$", "sessionId", ")", "{", "$", "serviceUri", "=", "new", "Uri", "(", "rtrim", "(", "$", "this", "->", "serviceBaseUri", ",", "'/'", ")", ".", "'/session/'", ".", "urlencode", "(", "$", "sessionId", ")", ".", "'/destroy'", ")", ";", "$", "serviceUri", "->", "setQuery", "(", "http_build_query", "(", "array", "(", "'serverIdentifier'", "=>", "$", "ssoServer", "->", "getServiceBaseUri", "(", ")", ")", ")", ")", ";", "$", "request", "=", "\\", "TYPO3", "\\", "Flow", "\\", "Http", "\\", "Request", "::", "create", "(", "$", "serviceUri", ",", "'DELETE'", ")", ";", "$", "request", "->", "setContent", "(", "''", ")", ";", "return", "$", "this", "->", "requestSigner", "->", "signRequest", "(", "$", "request", ",", "$", "ssoServer", "->", "getKeyPairFingerprint", "(", ")", ",", "$", "ssoServer", "->", "getKeyPairFingerprint", "(", ")", ")", ";", "}" ]
Builds a request for calling the destroy session webservice on this client @param \Flowpack\SingleSignOn\Server\Domain\Model\SsoServer $ssoServer @param string $sessionId @return \TYPO3\Flow\Http\Request
[ "Builds", "a", "request", "for", "calling", "the", "destroy", "session", "webservice", "on", "this", "client" ]
b1fa014f31d0d101a79cb95d5585b9973f35347d
https://github.com/Flowpack/Flowpack.SingleSignOn.Server/blob/b1fa014f31d0d101a79cb95d5585b9973f35347d/Classes/Flowpack/SingleSignOn/Server/Domain/Model/SsoClient.php#L86-L93
5,047
rafflesargentina/l5-user-action
src/Observers/BaseObserver.php
BaseObserver.getDiff
protected function getDiff($model) { $dirty = $model->getDirty(); $fresh = $model->fresh() ? $model->fresh()->toArray() : []; $after = json_encode($dirty); $before = json_encode(array_intersect_key($fresh, $dirty)); return compact('before', 'after'); }
php
protected function getDiff($model) { $dirty = $model->getDirty(); $fresh = $model->fresh() ? $model->fresh()->toArray() : []; $after = json_encode($dirty); $before = json_encode(array_intersect_key($fresh, $dirty)); return compact('before', 'after'); }
[ "protected", "function", "getDiff", "(", "$", "model", ")", "{", "$", "dirty", "=", "$", "model", "->", "getDirty", "(", ")", ";", "$", "fresh", "=", "$", "model", "->", "fresh", "(", ")", "?", "$", "model", "->", "fresh", "(", ")", "->", "toArray", "(", ")", ":", "[", "]", ";", "$", "after", "=", "json_encode", "(", "$", "dirty", ")", ";", "$", "before", "=", "json_encode", "(", "array_intersect_key", "(", "$", "fresh", ",", "$", "dirty", ")", ")", ";", "return", "compact", "(", "'before'", ",", "'after'", ")", ";", "}" ]
Get diff between dirty and fresh model attributes. @param \Illuminate\Database\Eloquent\Model $model The Eloquent model. @return void
[ "Get", "diff", "between", "dirty", "and", "fresh", "model", "attributes", "." ]
eb13dd46bf8b45e498104bd14527afa0625f7ee1
https://github.com/rafflesargentina/l5-user-action/blob/eb13dd46bf8b45e498104bd14527afa0625f7ee1/src/Observers/BaseObserver.php#L25-L33
5,048
rafflesargentina/l5-user-action
src/Observers/BaseObserver.php
BaseObserver.handleEventsLogging
protected function handleEventsLogging($model) { if (config($this->package.'.log_events_to_file') === true) { $this->logEventsToFile($model); } if (config($this->package.'.log_events_to_db') === true) { $this->logEventsToDB($model); } }
php
protected function handleEventsLogging($model) { if (config($this->package.'.log_events_to_file') === true) { $this->logEventsToFile($model); } if (config($this->package.'.log_events_to_db') === true) { $this->logEventsToDB($model); } }
[ "protected", "function", "handleEventsLogging", "(", "$", "model", ")", "{", "if", "(", "config", "(", "$", "this", "->", "package", ".", "'.log_events_to_file'", ")", "===", "true", ")", "{", "$", "this", "->", "logEventsToFile", "(", "$", "model", ")", ";", "}", "if", "(", "config", "(", "$", "this", "->", "package", ".", "'.log_events_to_db'", ")", "===", "true", ")", "{", "$", "this", "->", "logEventsToDB", "(", "$", "model", ")", ";", "}", "}" ]
Handle events logging. @param $model The Eloquent model. @return void
[ "Handle", "events", "logging", "." ]
eb13dd46bf8b45e498104bd14527afa0625f7ee1
https://github.com/rafflesargentina/l5-user-action/blob/eb13dd46bf8b45e498104bd14527afa0625f7ee1/src/Observers/BaseObserver.php#L84-L93
5,049
rafflesargentina/l5-user-action
src/Observers/BaseObserver.php
BaseObserver.logEventsToDB
private function logEventsToDB($model) { $user = auth()->user(); $class = get_class($model); $trace = debug_backtrace(); $event = $trace[2] ? $trace[2]['function'] : "Unknown event"; try { UserAction::create( array_merge($this->getDiff($model), [ 'model' => $class, 'action' => $event, 'user_id' => $user ? $user->id : null, 'model_id' => $model->id, ]) ); } catch (\Exception $e) { $message = $e->getMessage(); Log::error("Could not record user action to db: '{$message}'"); } }
php
private function logEventsToDB($model) { $user = auth()->user(); $class = get_class($model); $trace = debug_backtrace(); $event = $trace[2] ? $trace[2]['function'] : "Unknown event"; try { UserAction::create( array_merge($this->getDiff($model), [ 'model' => $class, 'action' => $event, 'user_id' => $user ? $user->id : null, 'model_id' => $model->id, ]) ); } catch (\Exception $e) { $message = $e->getMessage(); Log::error("Could not record user action to db: '{$message}'"); } }
[ "private", "function", "logEventsToDB", "(", "$", "model", ")", "{", "$", "user", "=", "auth", "(", ")", "->", "user", "(", ")", ";", "$", "class", "=", "get_class", "(", "$", "model", ")", ";", "$", "trace", "=", "debug_backtrace", "(", ")", ";", "$", "event", "=", "$", "trace", "[", "2", "]", "?", "$", "trace", "[", "2", "]", "[", "'function'", "]", ":", "\"Unknown event\"", ";", "try", "{", "UserAction", "::", "create", "(", "array_merge", "(", "$", "this", "->", "getDiff", "(", "$", "model", ")", ",", "[", "'model'", "=>", "$", "class", ",", "'action'", "=>", "$", "event", ",", "'user_id'", "=>", "$", "user", "?", "$", "user", "->", "id", ":", "null", ",", "'model_id'", "=>", "$", "model", "->", "id", ",", "]", ")", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "message", "=", "$", "e", "->", "getMessage", "(", ")", ";", "Log", "::", "error", "(", "\"Could not record user action to db: '{$message}'\"", ")", ";", "}", "}" ]
Log Events to DB. @param $model The Eloquent model.
[ "Log", "Events", "to", "DB", "." ]
eb13dd46bf8b45e498104bd14527afa0625f7ee1
https://github.com/rafflesargentina/l5-user-action/blob/eb13dd46bf8b45e498104bd14527afa0625f7ee1/src/Observers/BaseObserver.php#L101-L121
5,050
rafflesargentina/l5-user-action
src/Observers/BaseObserver.php
BaseObserver.logEventsToFile
private function logEventsToFile($model) { $user = auth()->user(); $class = class_basename($model); $trace = debug_backtrace(); $event = $trace[2] ? $trace[2]['function'] : "Unknown event"; if (auth()->check()) { Log::info("{$class} id {$model->id} {$event} by user id {$user->id} ({$user->email})."); } else { Log::info("{$class} id {$model->id} {$event} by unknown user."); } }
php
private function logEventsToFile($model) { $user = auth()->user(); $class = class_basename($model); $trace = debug_backtrace(); $event = $trace[2] ? $trace[2]['function'] : "Unknown event"; if (auth()->check()) { Log::info("{$class} id {$model->id} {$event} by user id {$user->id} ({$user->email})."); } else { Log::info("{$class} id {$model->id} {$event} by unknown user."); } }
[ "private", "function", "logEventsToFile", "(", "$", "model", ")", "{", "$", "user", "=", "auth", "(", ")", "->", "user", "(", ")", ";", "$", "class", "=", "class_basename", "(", "$", "model", ")", ";", "$", "trace", "=", "debug_backtrace", "(", ")", ";", "$", "event", "=", "$", "trace", "[", "2", "]", "?", "$", "trace", "[", "2", "]", "[", "'function'", "]", ":", "\"Unknown event\"", ";", "if", "(", "auth", "(", ")", "->", "check", "(", ")", ")", "{", "Log", "::", "info", "(", "\"{$class} id {$model->id} {$event} by user id {$user->id} ({$user->email}).\"", ")", ";", "}", "else", "{", "Log", "::", "info", "(", "\"{$class} id {$model->id} {$event} by unknown user.\"", ")", ";", "}", "}" ]
Log Events to file. @param $model The Eloquent model.
[ "Log", "Events", "to", "file", "." ]
eb13dd46bf8b45e498104bd14527afa0625f7ee1
https://github.com/rafflesargentina/l5-user-action/blob/eb13dd46bf8b45e498104bd14527afa0625f7ee1/src/Observers/BaseObserver.php#L129-L141
5,051
Ara95/user
src/Admin/AdminController.php
AdminController.getIndex
public function getIndex() { $this->di->get("auth")->isAdmin(true); $user = new User(); $user->setDb($this->di->get("db")); $title = "Min sida"; $view = $this->di->get("view"); $pageRender = $this->di->get("pageRender"); $data = [ "title" => $title, "users" => $user->findAll(), ]; $view->add("admin/index", $data); $pageRender->renderPage(["title" => $title]); }
php
public function getIndex() { $this->di->get("auth")->isAdmin(true); $user = new User(); $user->setDb($this->di->get("db")); $title = "Min sida"; $view = $this->di->get("view"); $pageRender = $this->di->get("pageRender"); $data = [ "title" => $title, "users" => $user->findAll(), ]; $view->add("admin/index", $data); $pageRender->renderPage(["title" => $title]); }
[ "public", "function", "getIndex", "(", ")", "{", "$", "this", "->", "di", "->", "get", "(", "\"auth\"", ")", "->", "isAdmin", "(", "true", ")", ";", "$", "user", "=", "new", "User", "(", ")", ";", "$", "user", "->", "setDb", "(", "$", "this", "->", "di", "->", "get", "(", "\"db\"", ")", ")", ";", "$", "title", "=", "\"Min sida\"", ";", "$", "view", "=", "$", "this", "->", "di", "->", "get", "(", "\"view\"", ")", ";", "$", "pageRender", "=", "$", "this", "->", "di", "->", "get", "(", "\"pageRender\"", ")", ";", "$", "data", "=", "[", "\"title\"", "=>", "$", "title", ",", "\"users\"", "=>", "$", "user", "->", "findAll", "(", ")", ",", "]", ";", "$", "view", "->", "add", "(", "\"admin/index\"", ",", "$", "data", ")", ";", "$", "pageRender", "->", "renderPage", "(", "[", "\"title\"", "=>", "$", "title", "]", ")", ";", "}" ]
Get the Admin indexpage. @throws Exception @return void
[ "Get", "the", "Admin", "indexpage", "." ]
96e15a19906562a689abedf6bcf4818ad8437a3b
https://github.com/Ara95/user/blob/96e15a19906562a689abedf6bcf4818ad8437a3b/src/Admin/AdminController.php#L32-L52
5,052
Ara95/user
src/Admin/AdminController.php
AdminController.getPostEditAdmin
public function getPostEditAdmin($id) { $this->di->get("auth")->isAdmin(true); $title = "Admin - Redigera profil"; $card = "Redigera"; $view = $this->di->get("view"); $pageRender = $this->di->get("pageRender"); $form = new EditAdminForm($this->di, $id); $form->check(); $data = [ "form" => $form->getHTML(), "card" => $card, "title" => $title, ]; $view->add("admin/edit", $data); $pageRender->renderPage(["title" => $title]); }
php
public function getPostEditAdmin($id) { $this->di->get("auth")->isAdmin(true); $title = "Admin - Redigera profil"; $card = "Redigera"; $view = $this->di->get("view"); $pageRender = $this->di->get("pageRender"); $form = new EditAdminForm($this->di, $id); $form->check(); $data = [ "form" => $form->getHTML(), "card" => $card, "title" => $title, ]; $view->add("admin/edit", $data); $pageRender->renderPage(["title" => $title]); }
[ "public", "function", "getPostEditAdmin", "(", "$", "id", ")", "{", "$", "this", "->", "di", "->", "get", "(", "\"auth\"", ")", "->", "isAdmin", "(", "true", ")", ";", "$", "title", "=", "\"Admin - Redigera profil\"", ";", "$", "card", "=", "\"Redigera\"", ";", "$", "view", "=", "$", "this", "->", "di", "->", "get", "(", "\"view\"", ")", ";", "$", "pageRender", "=", "$", "this", "->", "di", "->", "get", "(", "\"pageRender\"", ")", ";", "$", "form", "=", "new", "EditAdminForm", "(", "$", "this", "->", "di", ",", "$", "id", ")", ";", "$", "form", "->", "check", "(", ")", ";", "$", "data", "=", "[", "\"form\"", "=>", "$", "form", "->", "getHTML", "(", ")", ",", "\"card\"", "=>", "$", "card", ",", "\"title\"", "=>", "$", "title", ",", "]", ";", "$", "view", "->", "add", "(", "\"admin/edit\"", ",", "$", "data", ")", ";", "$", "pageRender", "->", "renderPage", "(", "[", "\"title\"", "=>", "$", "title", "]", ")", ";", "}" ]
Edit a user as admin. @return void
[ "Edit", "a", "user", "as", "admin", "." ]
96e15a19906562a689abedf6bcf4818ad8437a3b
https://github.com/Ara95/user/blob/96e15a19906562a689abedf6bcf4818ad8437a3b/src/Admin/AdminController.php#L87-L108
5,053
CatLabInteractive/Neuron
src/Neuron/URLBuilder.php
URLBuilder.guessAbsoluteURL
private static function guessAbsoluteURL () { $scheme = 'http'; $host = 'localhost'; if (isset($_SERVER['REQUEST_SCHEME'])) { $scheme = $_SERVER['REQUEST_SCHEME']; } if (isset($_SERVER['HTTP_HOST'])) { $host = $_SERVER['HTTP_HOST']; } return $scheme . '://' . $host . '/'; }
php
private static function guessAbsoluteURL () { $scheme = 'http'; $host = 'localhost'; if (isset($_SERVER['REQUEST_SCHEME'])) { $scheme = $_SERVER['REQUEST_SCHEME']; } if (isset($_SERVER['HTTP_HOST'])) { $host = $_SERVER['HTTP_HOST']; } return $scheme . '://' . $host . '/'; }
[ "private", "static", "function", "guessAbsoluteURL", "(", ")", "{", "$", "scheme", "=", "'http'", ";", "$", "host", "=", "'localhost'", ";", "if", "(", "isset", "(", "$", "_SERVER", "[", "'REQUEST_SCHEME'", "]", ")", ")", "{", "$", "scheme", "=", "$", "_SERVER", "[", "'REQUEST_SCHEME'", "]", ";", "}", "if", "(", "isset", "(", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ")", ")", "{", "$", "host", "=", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ";", "}", "return", "$", "scheme", ".", "'://'", ".", "$", "host", ".", "'/'", ";", "}" ]
Guest absolute url from server variables. @return string
[ "Guest", "absolute", "url", "from", "server", "variables", "." ]
67dca5349891e23b31a96dcdead893b9491a1b8b
https://github.com/CatLabInteractive/Neuron/blob/67dca5349891e23b31a96dcdead893b9491a1b8b/src/Neuron/URLBuilder.php#L72-L85
5,054
onesimus-systems/osrouter
src/Route.php
Route.patternMatch
private function patternMatch($url) { $url = explode('/', $url); $pattern = explode('/', $this->pattern); $matches = true; if (count($url) > count($pattern)) { return false; } foreach ($pattern as $pkey => $pvalue) { if (!isset($url[$pkey])) { if (substr($pvalue, 0, 2) === '{?') { // Piece not in URL but is optional continue; } else { // Piece not in URL and is required return false; } } if ($pvalue != $url[$pkey] && substr($pvalue, 0, 1) != '{') { // Doesn't contain a required part return false; } } return $matches; }
php
private function patternMatch($url) { $url = explode('/', $url); $pattern = explode('/', $this->pattern); $matches = true; if (count($url) > count($pattern)) { return false; } foreach ($pattern as $pkey => $pvalue) { if (!isset($url[$pkey])) { if (substr($pvalue, 0, 2) === '{?') { // Piece not in URL but is optional continue; } else { // Piece not in URL and is required return false; } } if ($pvalue != $url[$pkey] && substr($pvalue, 0, 1) != '{') { // Doesn't contain a required part return false; } } return $matches; }
[ "private", "function", "patternMatch", "(", "$", "url", ")", "{", "$", "url", "=", "explode", "(", "'/'", ",", "$", "url", ")", ";", "$", "pattern", "=", "explode", "(", "'/'", ",", "$", "this", "->", "pattern", ")", ";", "$", "matches", "=", "true", ";", "if", "(", "count", "(", "$", "url", ")", ">", "count", "(", "$", "pattern", ")", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "pattern", "as", "$", "pkey", "=>", "$", "pvalue", ")", "{", "if", "(", "!", "isset", "(", "$", "url", "[", "$", "pkey", "]", ")", ")", "{", "if", "(", "substr", "(", "$", "pvalue", ",", "0", ",", "2", ")", "===", "'{?'", ")", "{", "// Piece not in URL but is optional", "continue", ";", "}", "else", "{", "// Piece not in URL and is required", "return", "false", ";", "}", "}", "if", "(", "$", "pvalue", "!=", "$", "url", "[", "$", "pkey", "]", "&&", "substr", "(", "$", "pvalue", ",", "0", ",", "1", ")", "!=", "'{'", ")", "{", "// Doesn't contain a required part", "return", "false", ";", "}", "}", "return", "$", "matches", ";", "}" ]
Determines if this route matches a variable path @param string $url Url to attemt match @return bool
[ "Determines", "if", "this", "route", "matches", "a", "variable", "path" ]
1b87b0b91c227752cc6d3e09cc02d9d2bb4bc7de
https://github.com/onesimus-systems/osrouter/blob/1b87b0b91c227752cc6d3e09cc02d9d2bb4bc7de/src/Route.php#L123-L151
5,055
kambo-1st/KamboRouter
src/Route/Builder/Base.php
Base.build
public function build(string $method, string $url, $handler) : Route { return new BaseRoute($method, $url, $handler); }
php
public function build(string $method, string $url, $handler) : Route { return new BaseRoute($method, $url, $handler); }
[ "public", "function", "build", "(", "string", "$", "method", ",", "string", "$", "url", ",", "$", "handler", ")", ":", "Route", "{", "return", "new", "BaseRoute", "(", "$", "method", ",", "$", "url", ",", "$", "handler", ")", ";", "}" ]
Build instance of the route @param string $method Route method - GET, POST, etc... @param string $url route definition @param mixed $handler handler which will be executed if the url match the route @return \Kambo\Router\Route\Route\Base Base route
[ "Build", "instance", "of", "the", "route" ]
32ad63ab1c5483714868d5acbbc67beb2f0b1cda
https://github.com/kambo-1st/KamboRouter/blob/32ad63ab1c5483714868d5acbbc67beb2f0b1cda/src/Route/Builder/Base.php#L29-L32
5,056
affinitidev/silex-config
Source/Loader/LoaderFactory.php
LoaderFactory.newInstance
public function newInstance() { // Set the file locators in each loader instance. foreach($this->loaders as $loader) { if(false === $loader instanceof LoaderInterface) { throw new \InvalidArgumentException("Loaders must implement Affiniti\Config\Loader\LoaderInterface."); } $loader->setLocator($this->fileLocator); } return new DelegatingLoader(new LoaderResolver($this->loaders)); }
php
public function newInstance() { // Set the file locators in each loader instance. foreach($this->loaders as $loader) { if(false === $loader instanceof LoaderInterface) { throw new \InvalidArgumentException("Loaders must implement Affiniti\Config\Loader\LoaderInterface."); } $loader->setLocator($this->fileLocator); } return new DelegatingLoader(new LoaderResolver($this->loaders)); }
[ "public", "function", "newInstance", "(", ")", "{", "// Set the file locators in each loader instance.", "foreach", "(", "$", "this", "->", "loaders", "as", "$", "loader", ")", "{", "if", "(", "false", "===", "$", "loader", "instanceof", "LoaderInterface", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Loaders must implement Affiniti\\Config\\Loader\\LoaderInterface.\"", ")", ";", "}", "$", "loader", "->", "setLocator", "(", "$", "this", "->", "fileLocator", ")", ";", "}", "return", "new", "DelegatingLoader", "(", "new", "LoaderResolver", "(", "$", "this", "->", "loaders", ")", ")", ";", "}" ]
Returns a new DelegatingLoader which allows multiple loaders to be managed. @return \Symfony\Component\Config\Loader\DelegatingLoader The DelegatingLoader which contains all other defined loaders. @throws \InvalidArgumentException
[ "Returns", "a", "new", "DelegatingLoader", "which", "allows", "multiple", "loaders", "to", "be", "managed", "." ]
6c9cd170b26a6d30f31334ccfaca203304ad8f72
https://github.com/affinitidev/silex-config/blob/6c9cd170b26a6d30f31334ccfaca203304ad8f72/Source/Loader/LoaderFactory.php#L51-L63
5,057
mikegibson/sentient
src/Asset/AssetFactory.php
AssetFactory.addPath
public function addPath($namespace, $path, $prepend = false) { if($namespace === null) { $namespace = '_'; } if(!isset($this->paths[$namespace])) { $this->paths[$namespace] = []; } if($prepend) { array_unshift($this->paths[$namespace], $path); } else { array_push($this->paths[$namespace], $path); } }
php
public function addPath($namespace, $path, $prepend = false) { if($namespace === null) { $namespace = '_'; } if(!isset($this->paths[$namespace])) { $this->paths[$namespace] = []; } if($prepend) { array_unshift($this->paths[$namespace], $path); } else { array_push($this->paths[$namespace], $path); } }
[ "public", "function", "addPath", "(", "$", "namespace", ",", "$", "path", ",", "$", "prepend", "=", "false", ")", "{", "if", "(", "$", "namespace", "===", "null", ")", "{", "$", "namespace", "=", "'_'", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "paths", "[", "$", "namespace", "]", ")", ")", "{", "$", "this", "->", "paths", "[", "$", "namespace", "]", "=", "[", "]", ";", "}", "if", "(", "$", "prepend", ")", "{", "array_unshift", "(", "$", "this", "->", "paths", "[", "$", "namespace", "]", ",", "$", "path", ")", ";", "}", "else", "{", "array_push", "(", "$", "this", "->", "paths", "[", "$", "namespace", "]", ",", "$", "path", ")", ";", "}", "}" ]
Register a namespaced path to search for asset files. @param $namespace @param $path @param bool $prepend
[ "Register", "a", "namespaced", "path", "to", "search", "for", "asset", "files", "." ]
05aaaa0cd8e649d2b526df52a59c9fb53c114338
https://github.com/mikegibson/sentient/blob/05aaaa0cd8e649d2b526df52a59c9fb53c114338/src/Asset/AssetFactory.php#L125-L137
5,058
YiMAproject/yimaJquery
src/yimaJquery/View/Helper/jQuery.php
jQuery.enable
public function enable($ver = null) { if ($ver == null) { $ver = ($this->getVersion()) ?$this->getVersion() :$this->defVersion; } if ($this->isEnabled() && $this->getVersion() == $ver) { return $this; } $ver = (string) $ver; $this->enabled = $ver; return $this; }
php
public function enable($ver = null) { if ($ver == null) { $ver = ($this->getVersion()) ?$this->getVersion() :$this->defVersion; } if ($this->isEnabled() && $this->getVersion() == $ver) { return $this; } $ver = (string) $ver; $this->enabled = $ver; return $this; }
[ "public", "function", "enable", "(", "$", "ver", "=", "null", ")", "{", "if", "(", "$", "ver", "==", "null", ")", "{", "$", "ver", "=", "(", "$", "this", "->", "getVersion", "(", ")", ")", "?", "$", "this", "->", "getVersion", "(", ")", ":", "$", "this", "->", "defVersion", ";", "}", "if", "(", "$", "this", "->", "isEnabled", "(", ")", "&&", "$", "this", "->", "getVersion", "(", ")", "==", "$", "ver", ")", "{", "return", "$", "this", ";", "}", "$", "ver", "=", "(", "string", ")", "$", "ver", ";", "$", "this", "->", "enabled", "=", "$", "ver", ";", "return", "$", "this", ";", "}" ]
Enable jQ by minimum version required @param null|string $ver minimum version of jQ required @return $this @throws \Exception
[ "Enable", "jQ", "by", "minimum", "version", "required" ]
5c19fc17397a57c74e3c9f5ff4ff067a3beaf2cc
https://github.com/YiMAproject/yimaJquery/blob/5c19fc17397a57c74e3c9f5ff4ff067a3beaf2cc/src/yimaJquery/View/Helper/jQuery.php#L76-L92
5,059
YiMAproject/yimaJquery
src/yimaJquery/View/Helper/jQuery.php
jQuery.append
protected function append(array $item) { if (!$this->isEnabled()) { $this->enable(); } $this->getContainer()->append($item); }
php
protected function append(array $item) { if (!$this->isEnabled()) { $this->enable(); } $this->getContainer()->append($item); }
[ "protected", "function", "append", "(", "array", "$", "item", ")", "{", "if", "(", "!", "$", "this", "->", "isEnabled", "(", ")", ")", "{", "$", "this", "->", "enable", "(", ")", ";", "}", "$", "this", "->", "getContainer", "(", ")", "->", "append", "(", "$", "item", ")", ";", "}" ]
Append data to container @param array $item Created Data
[ "Append", "data", "to", "container" ]
5c19fc17397a57c74e3c9f5ff4ff067a3beaf2cc
https://github.com/YiMAproject/yimaJquery/blob/5c19fc17397a57c74e3c9f5ff4ff067a3beaf2cc/src/yimaJquery/View/Helper/jQuery.php#L239-L246
5,060
YiMAproject/yimaJquery
src/yimaJquery/View/Helper/jQuery.php
jQuery.prepend
protected function prepend(array $item) { if (! $this->isEnabled()) { $this->enable(); } $container = $this->getContainer(); $currentArr = $container->getArrayCopy(); array_unshift($currentArr, $item); $container->exchangeArray($currentArr); }
php
protected function prepend(array $item) { if (! $this->isEnabled()) { $this->enable(); } $container = $this->getContainer(); $currentArr = $container->getArrayCopy(); array_unshift($currentArr, $item); $container->exchangeArray($currentArr); }
[ "protected", "function", "prepend", "(", "array", "$", "item", ")", "{", "if", "(", "!", "$", "this", "->", "isEnabled", "(", ")", ")", "{", "$", "this", "->", "enable", "(", ")", ";", "}", "$", "container", "=", "$", "this", "->", "getContainer", "(", ")", ";", "$", "currentArr", "=", "$", "container", "->", "getArrayCopy", "(", ")", ";", "array_unshift", "(", "$", "currentArr", ",", "$", "item", ")", ";", "$", "container", "->", "exchangeArray", "(", "$", "currentArr", ")", ";", "}" ]
Prepend data to container @param array $item Created Data
[ "Prepend", "data", "to", "container" ]
5c19fc17397a57c74e3c9f5ff4ff067a3beaf2cc
https://github.com/YiMAproject/yimaJquery/blob/5c19fc17397a57c74e3c9f5ff4ff067a3beaf2cc/src/yimaJquery/View/Helper/jQuery.php#L253-L264
5,061
YiMAproject/yimaJquery
src/yimaJquery/View/Helper/jQuery.php
jQuery.getDecorator
public function getDecorator() { if (! $this->decorator) { $this->decorator = new DefaultDecorator(); } // set options used to render scripts $this->decorator->no_conflict_mode = $this->isNoConflict(); $this->decorator->base_library = $this->getLibSrc(); $this->decorator->no_conflict_handler = $this->getNoConflictHandler(); return $this->decorator; }
php
public function getDecorator() { if (! $this->decorator) { $this->decorator = new DefaultDecorator(); } // set options used to render scripts $this->decorator->no_conflict_mode = $this->isNoConflict(); $this->decorator->base_library = $this->getLibSrc(); $this->decorator->no_conflict_handler = $this->getNoConflictHandler(); return $this->decorator; }
[ "public", "function", "getDecorator", "(", ")", "{", "if", "(", "!", "$", "this", "->", "decorator", ")", "{", "$", "this", "->", "decorator", "=", "new", "DefaultDecorator", "(", ")", ";", "}", "// set options used to render scripts", "$", "this", "->", "decorator", "->", "no_conflict_mode", "=", "$", "this", "->", "isNoConflict", "(", ")", ";", "$", "this", "->", "decorator", "->", "base_library", "=", "$", "this", "->", "getLibSrc", "(", ")", ";", "$", "this", "->", "decorator", "->", "no_conflict_handler", "=", "$", "this", "->", "getNoConflictHandler", "(", ")", ";", "return", "$", "this", "->", "decorator", ";", "}" ]
Get decorator for rendering data in container @return AbstractDecorator
[ "Get", "decorator", "for", "rendering", "data", "in", "container" ]
5c19fc17397a57c74e3c9f5ff4ff067a3beaf2cc
https://github.com/YiMAproject/yimaJquery/blob/5c19fc17397a57c74e3c9f5ff4ff067a3beaf2cc/src/yimaJquery/View/Helper/jQuery.php#L286-L298
5,062
YiMAproject/yimaJquery
src/yimaJquery/View/Helper/jQuery.php
jQuery.getContainer
public function getContainer() { if (! $this->container) { $this->container = new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS); } return $this->container; }
php
public function getContainer() { if (! $this->container) { $this->container = new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS); } return $this->container; }
[ "public", "function", "getContainer", "(", ")", "{", "if", "(", "!", "$", "this", "->", "container", ")", "{", "$", "this", "->", "container", "=", "new", "ArrayObject", "(", "array", "(", ")", ",", "ArrayObject", "::", "ARRAY_AS_PROPS", ")", ";", "}", "return", "$", "this", "->", "container", ";", "}" ]
Get container for scripts @return ArrayObject
[ "Get", "container", "for", "scripts" ]
5c19fc17397a57c74e3c9f5ff4ff067a3beaf2cc
https://github.com/YiMAproject/yimaJquery/blob/5c19fc17397a57c74e3c9f5ff4ff067a3beaf2cc/src/yimaJquery/View/Helper/jQuery.php#L317-L324
5,063
YiMAproject/yimaJquery
src/yimaJquery/View/Helper/jQuery.php
jQuery.getLibSrc
public function getLibSrc($ver = null) { if ($ver == null) { $ver = $this->getVersion(); } if (!$ver) { $ver = $this->defVersion; } $return = false; /** @var $service InterfaceDelivery */ foreach ($this->getLibDelivers() as $name => $service) { $return = $service->getLibSrc($ver); if ($return) { break; } } if (!$return) { throw new \Exception('Can`t resolve to library.'); } return $return; }
php
public function getLibSrc($ver = null) { if ($ver == null) { $ver = $this->getVersion(); } if (!$ver) { $ver = $this->defVersion; } $return = false; /** @var $service InterfaceDelivery */ foreach ($this->getLibDelivers() as $name => $service) { $return = $service->getLibSrc($ver); if ($return) { break; } } if (!$return) { throw new \Exception('Can`t resolve to library.'); } return $return; }
[ "public", "function", "getLibSrc", "(", "$", "ver", "=", "null", ")", "{", "if", "(", "$", "ver", "==", "null", ")", "{", "$", "ver", "=", "$", "this", "->", "getVersion", "(", ")", ";", "}", "if", "(", "!", "$", "ver", ")", "{", "$", "ver", "=", "$", "this", "->", "defVersion", ";", "}", "$", "return", "=", "false", ";", "/** @var $service InterfaceDelivery */", "foreach", "(", "$", "this", "->", "getLibDelivers", "(", ")", "as", "$", "name", "=>", "$", "service", ")", "{", "$", "return", "=", "$", "service", "->", "getLibSrc", "(", "$", "ver", ")", ";", "if", "(", "$", "return", ")", "{", "break", ";", "}", "}", "if", "(", "!", "$", "return", ")", "{", "throw", "new", "\\", "Exception", "(", "'Can`t resolve to library.'", ")", ";", "}", "return", "$", "return", ";", "}" ]
Get jquery lib src from deliveries @return string
[ "Get", "jquery", "lib", "src", "from", "deliveries" ]
5c19fc17397a57c74e3c9f5ff4ff067a3beaf2cc
https://github.com/YiMAproject/yimaJquery/blob/5c19fc17397a57c74e3c9f5ff4ff067a3beaf2cc/src/yimaJquery/View/Helper/jQuery.php#L351-L376
5,064
YiMAproject/yimaJquery
src/yimaJquery/View/Helper/jQuery.php
jQuery.addLibDeliver
public function addLibDeliver(InterfaceDelivery $deliverance) { $name = $deliverance->getName(); $this->delivLibs[$name] = $deliverance; return $this; }
php
public function addLibDeliver(InterfaceDelivery $deliverance) { $name = $deliverance->getName(); $this->delivLibs[$name] = $deliverance; return $this; }
[ "public", "function", "addLibDeliver", "(", "InterfaceDelivery", "$", "deliverance", ")", "{", "$", "name", "=", "$", "deliverance", "->", "getName", "(", ")", ";", "$", "this", "->", "delivLibs", "[", "$", "name", "]", "=", "$", "deliverance", ";", "return", "$", "this", ";", "}" ]
Add a deliverance of library @param InterfaceDelivery $deliverance
[ "Add", "a", "deliverance", "of", "library" ]
5c19fc17397a57c74e3c9f5ff4ff067a3beaf2cc
https://github.com/YiMAproject/yimaJquery/blob/5c19fc17397a57c74e3c9f5ff4ff067a3beaf2cc/src/yimaJquery/View/Helper/jQuery.php#L383-L390
5,065
YiMAproject/yimaJquery
src/yimaJquery/View/Helper/jQuery.php
jQuery.createData
protected function createData($mode, $content = null, array $attributes = array()) { $data = array(); $data['mode'] = $mode; $data['content'] = $content; $data['attributes'] = array_merge($attributes, array('type' => 'text/javascript')); return $data; }
php
protected function createData($mode, $content = null, array $attributes = array()) { $data = array(); $data['mode'] = $mode; $data['content'] = $content; $data['attributes'] = array_merge($attributes, array('type' => 'text/javascript')); return $data; }
[ "protected", "function", "createData", "(", "$", "mode", ",", "$", "content", "=", "null", ",", "array", "$", "attributes", "=", "array", "(", ")", ")", "{", "$", "data", "=", "array", "(", ")", ";", "$", "data", "[", "'mode'", "]", "=", "$", "mode", ";", "$", "data", "[", "'content'", "]", "=", "$", "content", ";", "$", "data", "[", "'attributes'", "]", "=", "array_merge", "(", "$", "attributes", ",", "array", "(", "'type'", "=>", "'text/javascript'", ")", ")", ";", "return", "$", "data", ";", "}" ]
Create data item containing all necessary components of script @param string $mode Type of data script|file|link.... @param array $attributes Attributes of data @param string $content Content of data @return Array
[ "Create", "data", "item", "containing", "all", "necessary", "components", "of", "script" ]
5c19fc17397a57c74e3c9f5ff4ff067a3beaf2cc
https://github.com/YiMAproject/yimaJquery/blob/5c19fc17397a57c74e3c9f5ff4ff067a3beaf2cc/src/yimaJquery/View/Helper/jQuery.php#L415-L424
5,066
unyx/utils
Func.php
Func.compose
public static function compose(callable ...$callables) : \Closure { // Reverse the order of the given callables outside of the Closure. With the assumption // the Closure may get invoked n > 1 times, this shaves off some execution time. $callables = array_reverse($callables); return function(...$args) use ($callables) { foreach ($callables as $callable) { $args = [$callable(...$args)]; } return current($args); }; }
php
public static function compose(callable ...$callables) : \Closure { // Reverse the order of the given callables outside of the Closure. With the assumption // the Closure may get invoked n > 1 times, this shaves off some execution time. $callables = array_reverse($callables); return function(...$args) use ($callables) { foreach ($callables as $callable) { $args = [$callable(...$args)]; } return current($args); }; }
[ "public", "static", "function", "compose", "(", "callable", "...", "$", "callables", ")", ":", "\\", "Closure", "{", "// Reverse the order of the given callables outside of the Closure. With the assumption", "// the Closure may get invoked n > 1 times, this shaves off some execution time.", "$", "callables", "=", "array_reverse", "(", "$", "callables", ")", ";", "return", "function", "(", "...", "$", "args", ")", "use", "(", "$", "callables", ")", "{", "foreach", "(", "$", "callables", "as", "$", "callable", ")", "{", "$", "args", "=", "[", "$", "callable", "(", "...", "$", "args", ")", "]", ";", "}", "return", "current", "(", "$", "args", ")", ";", "}", ";", "}" ]
Returns a Closure which, once invoked, applies each given callable to the result of the previous callable, in right-to-left order. As such, the arguments passed to the Closure are passed through to the last callable given to the composition. Example: Func::compose(f, g, h)(x) is the equivalent of f(g(h(x))). @param callable[] ...$callables The callables to compose. @return \Closure
[ "Returns", "a", "Closure", "which", "once", "invoked", "applies", "each", "given", "callable", "to", "the", "result", "of", "the", "previous", "callable", "in", "right", "-", "to", "-", "left", "order", ".", "As", "such", "the", "arguments", "passed", "to", "the", "Closure", "are", "passed", "through", "to", "the", "last", "callable", "given", "to", "the", "composition", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Func.php#L82-L95
5,067
unyx/utils
Func.php
Func.memoize
public static function memoize(callable $callback, $key = null) : \Closure { return function(...$args) use ($callback, $key) { // Determine which cache key to use. $key = null === $key ? static::hash($callback, $args) : (string) (is_callable($key) ? $key($callback, ...$args) : $key); // If we don't already have a hit for the cache key, populate it with the result of invocation. if (!array_key_exists($key, static::$memory)) { static::$memory[$key] = $callback(...$args); } return static::$memory[$key]; }; }
php
public static function memoize(callable $callback, $key = null) : \Closure { return function(...$args) use ($callback, $key) { // Determine which cache key to use. $key = null === $key ? static::hash($callback, $args) : (string) (is_callable($key) ? $key($callback, ...$args) : $key); // If we don't already have a hit for the cache key, populate it with the result of invocation. if (!array_key_exists($key, static::$memory)) { static::$memory[$key] = $callback(...$args); } return static::$memory[$key]; }; }
[ "public", "static", "function", "memoize", "(", "callable", "$", "callback", ",", "$", "key", "=", "null", ")", ":", "\\", "Closure", "{", "return", "function", "(", "...", "$", "args", ")", "use", "(", "$", "callback", ",", "$", "key", ")", "{", "// Determine which cache key to use.", "$", "key", "=", "null", "===", "$", "key", "?", "static", "::", "hash", "(", "$", "callback", ",", "$", "args", ")", ":", "(", "string", ")", "(", "is_callable", "(", "$", "key", ")", "?", "$", "key", "(", "$", "callback", ",", "...", "$", "args", ")", ":", "$", "key", ")", ";", "// If we don't already have a hit for the cache key, populate it with the result of invocation.", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "static", "::", "$", "memory", ")", ")", "{", "static", "::", "$", "memory", "[", "$", "key", "]", "=", "$", "callback", "(", "...", "$", "args", ")", ";", "}", "return", "static", "::", "$", "memory", "[", "$", "key", "]", ";", "}", ";", "}" ]
Creates a Closure that memoizes the result of the wrapped callable and returns it once the wrapper gets called. @param callable $callback The callable to wrap. @param callable|string $key - When a (resolver) callable is given, it will be invoked with 1 or more arguments: the wrapped callable and any arguments passed to the wrapped callable (variadic). Its return value will be cast to a string and used as the cache key for the result. - When any other value except for null is given, it will be cast to a string and used as the cache key. - When not given, self::hash() will be used to create a hash of the call signature to use as key. @return \Closure The wrapper. @todo Expose the cached result inside the callable (limited to the same callable?) @todo Use the first argument for the callable as cache key if not given?
[ "Creates", "a", "Closure", "that", "memoizes", "the", "result", "of", "the", "wrapped", "callable", "and", "returns", "it", "once", "the", "wrapper", "gets", "called", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Func.php#L133-L149
5,068
unyx/utils
Func.php
Func.partial
public static function partial(callable $callback, ...$prependedArgs) : \Closure { return function(...$args) use ($callback, $prependedArgs) { return $callback(...$prependedArgs, ...$args); }; }
php
public static function partial(callable $callback, ...$prependedArgs) : \Closure { return function(...$args) use ($callback, $prependedArgs) { return $callback(...$prependedArgs, ...$args); }; }
[ "public", "static", "function", "partial", "(", "callable", "$", "callback", ",", "...", "$", "prependedArgs", ")", ":", "\\", "Closure", "{", "return", "function", "(", "...", "$", "args", ")", "use", "(", "$", "callback", ",", "$", "prependedArgs", ")", "{", "return", "$", "callback", "(", "...", "$", "prependedArgs", ",", "...", "$", "args", ")", ";", "}", ";", "}" ]
Creates a Closure that, when called, invokes the wrapped callable with any additional partial arguments prepended to those provided to the new Closure. @param callable $callback The callable to wrap. @param mixed ...$prependedArgs The arguments to prepend to the callback. @return \Closure The wrapper.
[ "Creates", "a", "Closure", "that", "when", "called", "invokes", "the", "wrapped", "callable", "with", "any", "additional", "partial", "arguments", "prepended", "to", "those", "provided", "to", "the", "new", "Closure", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Func.php#L190-L195
5,069
unyx/utils
Func.php
Func.partialRight
public static function partialRight(callable $callback, ...$appendedArgs) : \Closure { return function(...$args) use ($callback, $appendedArgs) { return $callback(...$args, ...$appendedArgs); }; }
php
public static function partialRight(callable $callback, ...$appendedArgs) : \Closure { return function(...$args) use ($callback, $appendedArgs) { return $callback(...$args, ...$appendedArgs); }; }
[ "public", "static", "function", "partialRight", "(", "callable", "$", "callback", ",", "...", "$", "appendedArgs", ")", ":", "\\", "Closure", "{", "return", "function", "(", "...", "$", "args", ")", "use", "(", "$", "callback", ",", "$", "appendedArgs", ")", "{", "return", "$", "callback", "(", "...", "$", "args", ",", "...", "$", "appendedArgs", ")", ";", "}", ";", "}" ]
Creates a Closure that, when called, invokes the wrapped callable with any additional partial arguments appended to those provided to the new Closure. @param callable $callback The callable to wrap. @param mixed ...$appendedArgs The arguments to append to the callback. @return \Closure The wrapper.
[ "Creates", "a", "Closure", "that", "when", "called", "invokes", "the", "wrapped", "callable", "with", "any", "additional", "partial", "arguments", "appended", "to", "those", "provided", "to", "the", "new", "Closure", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Func.php#L205-L210
5,070
jasand-pereza/frontend-loader
src/FrontendLoader.php
FrontendLoader.getAssetFolderName
public static function getAssetFolderName($file_name) { $file_extension = strtolower(substr(strrchr($file_name,"."), 1)); if (preg_match('/jpg|jpeg|gif|png|ico/', $file_extension)) { return 'img'; } if ($file_extension === 'js') { return 'js'; } if ($file_extension === 'css') { return 'css'; } if ($file_extension === 'pdf') { return 'pdf'; } return false; }
php
public static function getAssetFolderName($file_name) { $file_extension = strtolower(substr(strrchr($file_name,"."), 1)); if (preg_match('/jpg|jpeg|gif|png|ico/', $file_extension)) { return 'img'; } if ($file_extension === 'js') { return 'js'; } if ($file_extension === 'css') { return 'css'; } if ($file_extension === 'pdf') { return 'pdf'; } return false; }
[ "public", "static", "function", "getAssetFolderName", "(", "$", "file_name", ")", "{", "$", "file_extension", "=", "strtolower", "(", "substr", "(", "strrchr", "(", "$", "file_name", ",", "\".\"", ")", ",", "1", ")", ")", ";", "if", "(", "preg_match", "(", "'/jpg|jpeg|gif|png|ico/'", ",", "$", "file_extension", ")", ")", "{", "return", "'img'", ";", "}", "if", "(", "$", "file_extension", "===", "'js'", ")", "{", "return", "'js'", ";", "}", "if", "(", "$", "file_extension", "===", "'css'", ")", "{", "return", "'css'", ";", "}", "if", "(", "$", "file_extension", "===", "'pdf'", ")", "{", "return", "'pdf'", ";", "}", "return", "false", ";", "}" ]
Return the folder name for a given file @param string $file_name @return string bool
[ "Return", "the", "folder", "name", "for", "a", "given", "file" ]
ca4ea71a13ff78daf84398426324cef368bf9f4d
https://github.com/jasand-pereza/frontend-loader/blob/ca4ea71a13ff78daf84398426324cef368bf9f4d/src/FrontendLoader.php#L135-L151
5,071
jasand-pereza/frontend-loader
src/FrontendLoader.php
FrontendLoader.getAssetPath
public function getAssetPath() { $url_frags = parse_url($_SERVER['REQUEST_URI']); if (!array_key_exists('query', $url_frags)) return false; parse_str($url_frags['query'], $query_vars); if (!array_key_exists('asset', $query_vars)) return false; $folder_name = self::getAssetFolderName($query_vars['asset']); $file_name = sprintf( $this->actual_path.'/assets/%s/%s', $folder_name, $query_vars['asset'] ); if (file_exists($file_name)) { return $file_name; } return $false; }
php
public function getAssetPath() { $url_frags = parse_url($_SERVER['REQUEST_URI']); if (!array_key_exists('query', $url_frags)) return false; parse_str($url_frags['query'], $query_vars); if (!array_key_exists('asset', $query_vars)) return false; $folder_name = self::getAssetFolderName($query_vars['asset']); $file_name = sprintf( $this->actual_path.'/assets/%s/%s', $folder_name, $query_vars['asset'] ); if (file_exists($file_name)) { return $file_name; } return $false; }
[ "public", "function", "getAssetPath", "(", ")", "{", "$", "url_frags", "=", "parse_url", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ")", ";", "if", "(", "!", "array_key_exists", "(", "'query'", ",", "$", "url_frags", ")", ")", "return", "false", ";", "parse_str", "(", "$", "url_frags", "[", "'query'", "]", ",", "$", "query_vars", ")", ";", "if", "(", "!", "array_key_exists", "(", "'asset'", ",", "$", "query_vars", ")", ")", "return", "false", ";", "$", "folder_name", "=", "self", "::", "getAssetFolderName", "(", "$", "query_vars", "[", "'asset'", "]", ")", ";", "$", "file_name", "=", "sprintf", "(", "$", "this", "->", "actual_path", ".", "'/assets/%s/%s'", ",", "$", "folder_name", ",", "$", "query_vars", "[", "'asset'", "]", ")", ";", "if", "(", "file_exists", "(", "$", "file_name", ")", ")", "{", "return", "$", "file_name", ";", "}", "return", "$", "false", ";", "}" ]
Determine the path for an asset using the query string @return string bool
[ "Determine", "the", "path", "for", "an", "asset", "using", "the", "query", "string" ]
ca4ea71a13ff78daf84398426324cef368bf9f4d
https://github.com/jasand-pereza/frontend-loader/blob/ca4ea71a13ff78daf84398426324cef368bf9f4d/src/FrontendLoader.php#L158-L175
5,072
jasand-pereza/frontend-loader
src/FrontendLoader.php
FrontendLoader.getAssetFileName
public static function getAssetFileName() { $url_frags = parse_url($_SERVER['REQUEST_URI']); if (!array_key_exists('query', $url_frags)) return false; parse_str($url_frags['query'], $query_vars); if (!array_key_exists('asset', $query_vars)) return false; return $query_vars['asset']; }
php
public static function getAssetFileName() { $url_frags = parse_url($_SERVER['REQUEST_URI']); if (!array_key_exists('query', $url_frags)) return false; parse_str($url_frags['query'], $query_vars); if (!array_key_exists('asset', $query_vars)) return false; return $query_vars['asset']; }
[ "public", "static", "function", "getAssetFileName", "(", ")", "{", "$", "url_frags", "=", "parse_url", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ")", ";", "if", "(", "!", "array_key_exists", "(", "'query'", ",", "$", "url_frags", ")", ")", "return", "false", ";", "parse_str", "(", "$", "url_frags", "[", "'query'", "]", ",", "$", "query_vars", ")", ";", "if", "(", "!", "array_key_exists", "(", "'asset'", ",", "$", "query_vars", ")", ")", "return", "false", ";", "return", "$", "query_vars", "[", "'asset'", "]", ";", "}" ]
Get the file from a the query string @return string bool
[ "Get", "the", "file", "from", "a", "the", "query", "string" ]
ca4ea71a13ff78daf84398426324cef368bf9f4d
https://github.com/jasand-pereza/frontend-loader/blob/ca4ea71a13ff78daf84398426324cef368bf9f4d/src/FrontendLoader.php#L182-L189
5,073
jasand-pereza/frontend-loader
src/FrontendLoader.php
FrontendLoader.fileServe
public function fileServe($query, $callback=null) { if (!array_key_exists('REQUEST_URI', $_SERVER)) return $query; $path_prefix = $this->getPathPrefix(); if (!preg_match("/$path_prefix\/assets\/(.*)$/i", $_SERVER['REQUEST_URI'])) return $query; $file_path = self::getAssetPath(); if (!$file_path) return $query; // check if this file is whitelisted if (!$this->shouldLoadFile($this->getAssetFileName())) return $query; $content_type = self::getContentType($file_path); header('Content-type: ' . $content_type); header('Content-Length: ' . filesize($file_path)); http_response_code(200); readfile($file_path); if ($callback) { $callback(); } exit; return $query; }
php
public function fileServe($query, $callback=null) { if (!array_key_exists('REQUEST_URI', $_SERVER)) return $query; $path_prefix = $this->getPathPrefix(); if (!preg_match("/$path_prefix\/assets\/(.*)$/i", $_SERVER['REQUEST_URI'])) return $query; $file_path = self::getAssetPath(); if (!$file_path) return $query; // check if this file is whitelisted if (!$this->shouldLoadFile($this->getAssetFileName())) return $query; $content_type = self::getContentType($file_path); header('Content-type: ' . $content_type); header('Content-Length: ' . filesize($file_path)); http_response_code(200); readfile($file_path); if ($callback) { $callback(); } exit; return $query; }
[ "public", "function", "fileServe", "(", "$", "query", ",", "$", "callback", "=", "null", ")", "{", "if", "(", "!", "array_key_exists", "(", "'REQUEST_URI'", ",", "$", "_SERVER", ")", ")", "return", "$", "query", ";", "$", "path_prefix", "=", "$", "this", "->", "getPathPrefix", "(", ")", ";", "if", "(", "!", "preg_match", "(", "\"/$path_prefix\\/assets\\/(.*)$/i\"", ",", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ")", ")", "return", "$", "query", ";", "$", "file_path", "=", "self", "::", "getAssetPath", "(", ")", ";", "if", "(", "!", "$", "file_path", ")", "return", "$", "query", ";", "// check if this file is whitelisted", "if", "(", "!", "$", "this", "->", "shouldLoadFile", "(", "$", "this", "->", "getAssetFileName", "(", ")", ")", ")", "return", "$", "query", ";", "$", "content_type", "=", "self", "::", "getContentType", "(", "$", "file_path", ")", ";", "header", "(", "'Content-type: '", ".", "$", "content_type", ")", ";", "header", "(", "'Content-Length: '", ".", "filesize", "(", "$", "file_path", ")", ")", ";", "http_response_code", "(", "200", ")", ";", "readfile", "(", "$", "file_path", ")", ";", "if", "(", "$", "callback", ")", "{", "$", "callback", "(", ")", ";", "}", "exit", ";", "return", "$", "query", ";", "}" ]
Return a file given the query string @param array $query - wordpress passes this in and it must be returned @return file
[ "Return", "a", "file", "given", "the", "query", "string" ]
ca4ea71a13ff78daf84398426324cef368bf9f4d
https://github.com/jasand-pereza/frontend-loader/blob/ca4ea71a13ff78daf84398426324cef368bf9f4d/src/FrontendLoader.php#L208-L233
5,074
phn-io/compilation
spec/Phn/Compilation/CompilerSpec.php
CompilerSpec.it_compiles_nodes_using_a_generic_solution
function it_compiles_nodes_using_a_generic_solution($node) { $node->compile($this)->will(function ($args) { $args[0]->write('echo $message'); }); $this->repr($node)->getSource()->shouldMatch('/echo \$message/'); }
php
function it_compiles_nodes_using_a_generic_solution($node) { $node->compile($this)->will(function ($args) { $args[0]->write('echo $message'); }); $this->repr($node)->getSource()->shouldMatch('/echo \$message/'); }
[ "function", "it_compiles_nodes_using_a_generic_solution", "(", "$", "node", ")", "{", "$", "node", "->", "compile", "(", "$", "this", ")", "->", "will", "(", "function", "(", "$", "args", ")", "{", "$", "args", "[", "0", "]", "->", "write", "(", "'echo $message'", ")", ";", "}", ")", ";", "$", "this", "->", "repr", "(", "$", "node", ")", "->", "getSource", "(", ")", "->", "shouldMatch", "(", "'/echo \\$message/'", ")", ";", "}" ]
It compiles nodes using a generic solution. @param \Phn\Compilation\NodeInterface $node
[ "It", "compiles", "nodes", "using", "a", "generic", "solution", "." ]
202e1816cc0039c08ad7ab3eb914e91e51d77320
https://github.com/phn-io/compilation/blob/202e1816cc0039c08ad7ab3eb914e91e51d77320/spec/Phn/Compilation/CompilerSpec.php#L146-L153
5,075
phn-io/compilation
spec/Phn/Compilation/CompilerSpec.php
CompilerSpec.it_compiles_nodes
function it_compiles_nodes($node) { $node->compile($this)->will(function ($args) { $args[0]->write('echo $message'); }); $this->compile($node)->getSource()->shouldMatch('/\Recho \$message/'); }
php
function it_compiles_nodes($node) { $node->compile($this)->will(function ($args) { $args[0]->write('echo $message'); }); $this->compile($node)->getSource()->shouldMatch('/\Recho \$message/'); }
[ "function", "it_compiles_nodes", "(", "$", "node", ")", "{", "$", "node", "->", "compile", "(", "$", "this", ")", "->", "will", "(", "function", "(", "$", "args", ")", "{", "$", "args", "[", "0", "]", "->", "write", "(", "'echo $message'", ")", ";", "}", ")", ";", "$", "this", "->", "compile", "(", "$", "node", ")", "->", "getSource", "(", ")", "->", "shouldMatch", "(", "'/\\Recho \\$message/'", ")", ";", "}" ]
It compiles nodes. @param \Phn\Compilation\NodeInterface $node
[ "It", "compiles", "nodes", "." ]
202e1816cc0039c08ad7ab3eb914e91e51d77320
https://github.com/phn-io/compilation/blob/202e1816cc0039c08ad7ab3eb914e91e51d77320/spec/Phn/Compilation/CompilerSpec.php#L176-L183
5,076
phn-io/compilation
spec/Phn/Compilation/CompilerSpec.php
CompilerSpec.it_can_execute_functions_conditionally_to_not_break_the_fluent_interface
function it_can_execute_functions_conditionally_to_not_break_the_fluent_interface() { $this ->runIf(false, function() { $this->write('echo $message'); }) ->getSource() ->shouldReturn('<?php'.PHP_EOL) ; $this ->runIf(true, function() { $this->write('echo $message'); }) ->getSource() ->shouldMatch('/\Recho \$message/') ; }
php
function it_can_execute_functions_conditionally_to_not_break_the_fluent_interface() { $this ->runIf(false, function() { $this->write('echo $message'); }) ->getSource() ->shouldReturn('<?php'.PHP_EOL) ; $this ->runIf(true, function() { $this->write('echo $message'); }) ->getSource() ->shouldMatch('/\Recho \$message/') ; }
[ "function", "it_can_execute_functions_conditionally_to_not_break_the_fluent_interface", "(", ")", "{", "$", "this", "->", "runIf", "(", "false", ",", "function", "(", ")", "{", "$", "this", "->", "write", "(", "'echo $message'", ")", ";", "}", ")", "->", "getSource", "(", ")", "->", "shouldReturn", "(", "'<?php'", ".", "PHP_EOL", ")", ";", "$", "this", "->", "runIf", "(", "true", ",", "function", "(", ")", "{", "$", "this", "->", "write", "(", "'echo $message'", ")", ";", "}", ")", "->", "getSource", "(", ")", "->", "shouldMatch", "(", "'/\\Recho \\$message/'", ")", ";", "}" ]
It can execute functions conditionally to not break the fluent interface.
[ "It", "can", "execute", "functions", "conditionally", "to", "not", "break", "the", "fluent", "interface", "." ]
202e1816cc0039c08ad7ab3eb914e91e51d77320
https://github.com/phn-io/compilation/blob/202e1816cc0039c08ad7ab3eb914e91e51d77320/spec/Phn/Compilation/CompilerSpec.php#L202-L219
5,077
phn-io/compilation
spec/Phn/Compilation/CompilerSpec.php
CompilerSpec.it_can_execute_functions_for_each_item_in_a_collection
function it_can_execute_functions_for_each_item_in_a_collection() { $collection = [1, 2, 3]; $this ->each($collection, function($item) { $this->raw($item); }) ->getSource() ->shouldMatch('/123/') ; }
php
function it_can_execute_functions_for_each_item_in_a_collection() { $collection = [1, 2, 3]; $this ->each($collection, function($item) { $this->raw($item); }) ->getSource() ->shouldMatch('/123/') ; }
[ "function", "it_can_execute_functions_for_each_item_in_a_collection", "(", ")", "{", "$", "collection", "=", "[", "1", ",", "2", ",", "3", "]", ";", "$", "this", "->", "each", "(", "$", "collection", ",", "function", "(", "$", "item", ")", "{", "$", "this", "->", "raw", "(", "$", "item", ")", ";", "}", ")", "->", "getSource", "(", ")", "->", "shouldMatch", "(", "'/123/'", ")", ";", "}" ]
It can execute functions for each item in a collection.
[ "It", "can", "execute", "functions", "for", "each", "item", "in", "a", "collection", "." ]
202e1816cc0039c08ad7ab3eb914e91e51d77320
https://github.com/phn-io/compilation/blob/202e1816cc0039c08ad7ab3eb914e91e51d77320/spec/Phn/Compilation/CompilerSpec.php#L224-L235
5,078
anklimsk/cakephp-basic-functions
Vendor/langcode-conv/zendframework/zend-stdlib/src/StringWrapper/MbString.php
MbString.getSupportedEncodings
public static function getSupportedEncodings() { if (static::$encodings === null) { static::$encodings = array_map('strtoupper', mb_list_encodings()); // FIXME: Converting € (UTF-8) to ISO-8859-16 gives a wrong result $indexIso885916 = array_search('ISO-8859-16', static::$encodings, true); if ($indexIso885916 !== false) { unset(static::$encodings[$indexIso885916]); } } return static::$encodings; }
php
public static function getSupportedEncodings() { if (static::$encodings === null) { static::$encodings = array_map('strtoupper', mb_list_encodings()); // FIXME: Converting € (UTF-8) to ISO-8859-16 gives a wrong result $indexIso885916 = array_search('ISO-8859-16', static::$encodings, true); if ($indexIso885916 !== false) { unset(static::$encodings[$indexIso885916]); } } return static::$encodings; }
[ "public", "static", "function", "getSupportedEncodings", "(", ")", "{", "if", "(", "static", "::", "$", "encodings", "===", "null", ")", "{", "static", "::", "$", "encodings", "=", "array_map", "(", "'strtoupper'", ",", "mb_list_encodings", "(", ")", ")", ";", "// FIXME: Converting € (UTF-8) to ISO-8859-16 gives a wrong result", "$", "indexIso885916", "=", "array_search", "(", "'ISO-8859-16'", ",", "static", "::", "$", "encodings", ",", "true", ")", ";", "if", "(", "$", "indexIso885916", "!==", "false", ")", "{", "unset", "(", "static", "::", "$", "encodings", "[", "$", "indexIso885916", "]", ")", ";", "}", "}", "return", "static", "::", "$", "encodings", ";", "}" ]
Get a list of supported character encodings @return string[]
[ "Get", "a", "list", "of", "supported", "character", "encodings" ]
7554e8b0b420fd3155593af7bf76b7ccbdc8701e
https://github.com/anklimsk/cakephp-basic-functions/blob/7554e8b0b420fd3155593af7bf76b7ccbdc8701e/Vendor/langcode-conv/zendframework/zend-stdlib/src/StringWrapper/MbString.php#L29-L42
5,079
anklimsk/cakephp-basic-functions
Vendor/langcode-conv/zendframework/zend-stdlib/src/StringWrapper/MbString.php
MbString.convert
public function convert($str, $reverse = false) { $encoding = $this->getEncoding(); $convertEncoding = $this->getConvertEncoding(); if ($convertEncoding === null) { throw new Exception\LogicException( 'No convert encoding defined' ); } if ($encoding === $convertEncoding) { return $str; } $fromEncoding = $reverse ? $convertEncoding : $encoding; $toEncoding = $reverse ? $encoding : $convertEncoding; return mb_convert_encoding($str, $toEncoding, $fromEncoding); }
php
public function convert($str, $reverse = false) { $encoding = $this->getEncoding(); $convertEncoding = $this->getConvertEncoding(); if ($convertEncoding === null) { throw new Exception\LogicException( 'No convert encoding defined' ); } if ($encoding === $convertEncoding) { return $str; } $fromEncoding = $reverse ? $convertEncoding : $encoding; $toEncoding = $reverse ? $encoding : $convertEncoding; return mb_convert_encoding($str, $toEncoding, $fromEncoding); }
[ "public", "function", "convert", "(", "$", "str", ",", "$", "reverse", "=", "false", ")", "{", "$", "encoding", "=", "$", "this", "->", "getEncoding", "(", ")", ";", "$", "convertEncoding", "=", "$", "this", "->", "getConvertEncoding", "(", ")", ";", "if", "(", "$", "convertEncoding", "===", "null", ")", "{", "throw", "new", "Exception", "\\", "LogicException", "(", "'No convert encoding defined'", ")", ";", "}", "if", "(", "$", "encoding", "===", "$", "convertEncoding", ")", "{", "return", "$", "str", ";", "}", "$", "fromEncoding", "=", "$", "reverse", "?", "$", "convertEncoding", ":", "$", "encoding", ";", "$", "toEncoding", "=", "$", "reverse", "?", "$", "encoding", ":", "$", "convertEncoding", ";", "return", "mb_convert_encoding", "(", "$", "str", ",", "$", "toEncoding", ",", "$", "fromEncoding", ")", ";", "}" ]
Convert a string from defined encoding to the defined convert encoding @param string $str @param bool $reverse @return string|false
[ "Convert", "a", "string", "from", "defined", "encoding", "to", "the", "defined", "convert", "encoding" ]
7554e8b0b420fd3155593af7bf76b7ccbdc8701e
https://github.com/anklimsk/cakephp-basic-functions/blob/7554e8b0b420fd3155593af7bf76b7ccbdc8701e/Vendor/langcode-conv/zendframework/zend-stdlib/src/StringWrapper/MbString.php#L102-L120
5,080
tenside/core
src/Util/JsonArray.php
JsonArray.splitPath
protected function splitPath($path) { $chunks = array_map( [$this, 'unescape'], preg_split('#(?<!\\\)\/#', ltrim($path, '/')) ); if (empty($chunks) || (array_filter($chunks) !== $chunks)) { throw new \InvalidArgumentException('Invalid path provided:' . $path); } return $chunks; }
php
protected function splitPath($path) { $chunks = array_map( [$this, 'unescape'], preg_split('#(?<!\\\)\/#', ltrim($path, '/')) ); if (empty($chunks) || (array_filter($chunks) !== $chunks)) { throw new \InvalidArgumentException('Invalid path provided:' . $path); } return $chunks; }
[ "protected", "function", "splitPath", "(", "$", "path", ")", "{", "$", "chunks", "=", "array_map", "(", "[", "$", "this", ",", "'unescape'", "]", ",", "preg_split", "(", "'#(?<!\\\\\\)\\/#'", ",", "ltrim", "(", "$", "path", ",", "'/'", ")", ")", ")", ";", "if", "(", "empty", "(", "$", "chunks", ")", "||", "(", "array_filter", "(", "$", "chunks", ")", "!==", "$", "chunks", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Invalid path provided:'", ".", "$", "path", ")", ";", "}", "return", "$", "chunks", ";", "}" ]
Split the path into chunks. @param string $path The path to split. @return array @throws \InvalidArgumentException When the path is invalid.
[ "Split", "the", "path", "into", "chunks", "." ]
56422fa8cdecf03cb431bb6654c2942ade39bf7b
https://github.com/tenside/core/blob/56422fa8cdecf03cb431bb6654c2942ade39bf7b/src/Util/JsonArray.php#L119-L131
5,081
tenside/core
src/Util/JsonArray.php
JsonArray.get
public function get($path, $forceArray = false) { // special case, root element. if ($path === '/') { return $this->data; } $chunks = $this->splitPath($path); $scope = $this->data; while (null !== ($sub = array_shift($chunks))) { if (isset($scope[$sub])) { if ($forceArray) { $scope = (array) $scope[$sub]; } else { $scope = $scope[$sub]; } } else { if ($forceArray) { return []; } else { return null; } } } return $scope; }
php
public function get($path, $forceArray = false) { // special case, root element. if ($path === '/') { return $this->data; } $chunks = $this->splitPath($path); $scope = $this->data; while (null !== ($sub = array_shift($chunks))) { if (isset($scope[$sub])) { if ($forceArray) { $scope = (array) $scope[$sub]; } else { $scope = $scope[$sub]; } } else { if ($forceArray) { return []; } else { return null; } } } return $scope; }
[ "public", "function", "get", "(", "$", "path", ",", "$", "forceArray", "=", "false", ")", "{", "// special case, root element.", "if", "(", "$", "path", "===", "'/'", ")", "{", "return", "$", "this", "->", "data", ";", "}", "$", "chunks", "=", "$", "this", "->", "splitPath", "(", "$", "path", ")", ";", "$", "scope", "=", "$", "this", "->", "data", ";", "while", "(", "null", "!==", "(", "$", "sub", "=", "array_shift", "(", "$", "chunks", ")", ")", ")", "{", "if", "(", "isset", "(", "$", "scope", "[", "$", "sub", "]", ")", ")", "{", "if", "(", "$", "forceArray", ")", "{", "$", "scope", "=", "(", "array", ")", "$", "scope", "[", "$", "sub", "]", ";", "}", "else", "{", "$", "scope", "=", "$", "scope", "[", "$", "sub", "]", ";", "}", "}", "else", "{", "if", "(", "$", "forceArray", ")", "{", "return", "[", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}", "}", "return", "$", "scope", ";", "}" ]
Retrieve a value. @param string $path The path of the value. @param bool $forceArray Flag if the result shall be casted to array. @return array|string|int|null
[ "Retrieve", "a", "value", "." ]
56422fa8cdecf03cb431bb6654c2942ade39bf7b
https://github.com/tenside/core/blob/56422fa8cdecf03cb431bb6654c2942ade39bf7b/src/Util/JsonArray.php#L166-L192
5,082
tenside/core
src/Util/JsonArray.php
JsonArray.has
public function has($path) { $chunks = $this->splitPath($path); $scope = $this->data; while (null !== ($sub = array_shift($chunks))) { if (isset($scope[$sub])) { $scope = $scope[$sub]; } else { return false; } } return true; }
php
public function has($path) { $chunks = $this->splitPath($path); $scope = $this->data; while (null !== ($sub = array_shift($chunks))) { if (isset($scope[$sub])) { $scope = $scope[$sub]; } else { return false; } } return true; }
[ "public", "function", "has", "(", "$", "path", ")", "{", "$", "chunks", "=", "$", "this", "->", "splitPath", "(", "$", "path", ")", ";", "$", "scope", "=", "$", "this", "->", "data", ";", "while", "(", "null", "!==", "(", "$", "sub", "=", "array_shift", "(", "$", "chunks", ")", ")", ")", "{", "if", "(", "isset", "(", "$", "scope", "[", "$", "sub", "]", ")", ")", "{", "$", "scope", "=", "$", "scope", "[", "$", "sub", "]", ";", "}", "else", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Check if a value exists. @param string $path The path of the value. @return bool
[ "Check", "if", "a", "value", "exists", "." ]
56422fa8cdecf03cb431bb6654c2942ade39bf7b
https://github.com/tenside/core/blob/56422fa8cdecf03cb431bb6654c2942ade39bf7b/src/Util/JsonArray.php#L246-L260
5,083
tenside/core
src/Util/JsonArray.php
JsonArray.getEntries
public function getEntries($path) { $entries = $this->get($path); $result = []; $prefix = trim($path, '/'); if (strlen($prefix)) { $prefix .= '/'; } if (is_array($entries)) { foreach (array_keys($entries) as $key) { $result[] = $prefix . $this->escape($key); } } return $result; }
php
public function getEntries($path) { $entries = $this->get($path); $result = []; $prefix = trim($path, '/'); if (strlen($prefix)) { $prefix .= '/'; } if (is_array($entries)) { foreach (array_keys($entries) as $key) { $result[] = $prefix . $this->escape($key); } } return $result; }
[ "public", "function", "getEntries", "(", "$", "path", ")", "{", "$", "entries", "=", "$", "this", "->", "get", "(", "$", "path", ")", ";", "$", "result", "=", "[", "]", ";", "$", "prefix", "=", "trim", "(", "$", "path", ",", "'/'", ")", ";", "if", "(", "strlen", "(", "$", "prefix", ")", ")", "{", "$", "prefix", ".=", "'/'", ";", "}", "if", "(", "is_array", "(", "$", "entries", ")", ")", "{", "foreach", "(", "array_keys", "(", "$", "entries", ")", "as", "$", "key", ")", "{", "$", "result", "[", "]", "=", "$", "prefix", ".", "$", "this", "->", "escape", "(", "$", "key", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Retrieve the contained keys at the given path. @param string $path The sub path to be examined. @return string[]
[ "Retrieve", "the", "contained", "keys", "at", "the", "given", "path", "." ]
56422fa8cdecf03cb431bb6654c2942ade39bf7b
https://github.com/tenside/core/blob/56422fa8cdecf03cb431bb6654c2942ade39bf7b/src/Util/JsonArray.php#L293-L308
5,084
tenside/core
src/Util/JsonArray.php
JsonArray.uasort
public function uasort($callback, $path = '/') { $value = $this->get($path); if (null === $value || !is_array($value)) { return; } uasort($value, $callback); $this->set($path, $value); }
php
public function uasort($callback, $path = '/') { $value = $this->get($path); if (null === $value || !is_array($value)) { return; } uasort($value, $callback); $this->set($path, $value); }
[ "public", "function", "uasort", "(", "$", "callback", ",", "$", "path", "=", "'/'", ")", "{", "$", "value", "=", "$", "this", "->", "get", "(", "$", "path", ")", ";", "if", "(", "null", "===", "$", "value", "||", "!", "is_array", "(", "$", "value", ")", ")", "{", "return", ";", "}", "uasort", "(", "$", "value", ",", "$", "callback", ")", ";", "$", "this", "->", "set", "(", "$", "path", ",", "$", "value", ")", ";", "}" ]
Sort the array by the provided user function. @param callable $callback The callback function to use. @param string $path The sub path to be sorted. @return void
[ "Sort", "the", "array", "by", "the", "provided", "user", "function", "." ]
56422fa8cdecf03cb431bb6654c2942ade39bf7b
https://github.com/tenside/core/blob/56422fa8cdecf03cb431bb6654c2942ade39bf7b/src/Util/JsonArray.php#L319-L329
5,085
unyx/utils
Str.php
Str.collapse
public static function collapse(string $str, string $encoding = null) : string { $encoding = $encoding ?: static::encoding($str); return static::trim(static::replace($str, '[[:space:]]+', ' ', 'msr', $encoding), null, $encoding); }
php
public static function collapse(string $str, string $encoding = null) : string { $encoding = $encoding ?: static::encoding($str); return static::trim(static::replace($str, '[[:space:]]+', ' ', 'msr', $encoding), null, $encoding); }
[ "public", "static", "function", "collapse", "(", "string", "$", "str", ",", "string", "$", "encoding", "=", "null", ")", ":", "string", "{", "$", "encoding", "=", "$", "encoding", "?", ":", "static", "::", "encoding", "(", "$", "str", ")", ";", "return", "static", "::", "trim", "(", "static", "::", "replace", "(", "$", "str", ",", "'[[:space:]]+'", ",", "' '", ",", "'msr'", ",", "$", "encoding", ")", ",", "null", ",", "$", "encoding", ")", ";", "}" ]
Trims the given string and replaces multiple consecutive whitespaces with a single whitespace. Note: This includes multi-byte whitespace characters, tabs and newlines, which effectively means that the string may also be collapsed down. This is mostly a utility for processing natural language user input for displaying. @param string $str The string to collapse. @param string|null $encoding The encoding to use. @return string The resulting string.
[ "Trims", "the", "given", "string", "and", "replaces", "multiple", "consecutive", "whitespaces", "with", "a", "single", "whitespace", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Str.php#L191-L196
5,086
unyx/utils
Str.php
Str.eachLine
public static function eachLine(string $str, callable $callable, ...$args) : string { if ($str === '') { return $str; } $lines = mb_split('[\r\n]{1,2}', $str); foreach ($lines as $number => &$line) { $lines[$number] = (string) call_user_func($callable, $line, $number, ...$args); } return implode("\n", $lines); }
php
public static function eachLine(string $str, callable $callable, ...$args) : string { if ($str === '') { return $str; } $lines = mb_split('[\r\n]{1,2}', $str); foreach ($lines as $number => &$line) { $lines[$number] = (string) call_user_func($callable, $line, $number, ...$args); } return implode("\n", $lines); }
[ "public", "static", "function", "eachLine", "(", "string", "$", "str", ",", "callable", "$", "callable", ",", "...", "$", "args", ")", ":", "string", "{", "if", "(", "$", "str", "===", "''", ")", "{", "return", "$", "str", ";", "}", "$", "lines", "=", "mb_split", "(", "'[\\r\\n]{1,2}'", ",", "$", "str", ")", ";", "foreach", "(", "$", "lines", "as", "$", "number", "=>", "&", "$", "line", ")", "{", "$", "lines", "[", "$", "number", "]", "=", "(", "string", ")", "call_user_func", "(", "$", "callable", ",", "$", "line", ",", "$", "number", ",", "...", "$", "args", ")", ";", "}", "return", "implode", "(", "\"\\n\"", ",", "$", "lines", ")", ";", "}" ]
Runs the given callable over each line of the given string and returns the resulting string. The callable should accept two arguments (in this order): the contents of the line (string) and the line's number (int). Additional arguments may also be added and will be appended to the callable in the order given. The callable should return a string or a value castable to a string. @param string $str The string over which to run the callable. @param callable $callable The callable to apply. @param mixed ...$args Additional arguments to pass to the callable. @return string The string after applying the callable to each of its lines.
[ "Runs", "the", "given", "callable", "over", "each", "line", "of", "the", "given", "string", "and", "returns", "the", "resulting", "string", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Str.php#L269-L282
5,087
unyx/utils
Str.php
Str.encoding
public static function encoding(string $str = null) : string { // If a string was given, we attempt to detect the encoding of the string if we are told to do so. // If we succeed, just return the determined type. if (true === static::$autoDetectEncoding && null !== $str && false !== $encoding = mb_detect_encoding($str)) { return $encoding; } // Otherwise let's return one of the defaults. return static::$encoding ?: 'utf-8'; }
php
public static function encoding(string $str = null) : string { // If a string was given, we attempt to detect the encoding of the string if we are told to do so. // If we succeed, just return the determined type. if (true === static::$autoDetectEncoding && null !== $str && false !== $encoding = mb_detect_encoding($str)) { return $encoding; } // Otherwise let's return one of the defaults. return static::$encoding ?: 'utf-8'; }
[ "public", "static", "function", "encoding", "(", "string", "$", "str", "=", "null", ")", ":", "string", "{", "// If a string was given, we attempt to detect the encoding of the string if we are told to do so.", "// If we succeed, just return the determined type.", "if", "(", "true", "===", "static", "::", "$", "autoDetectEncoding", "&&", "null", "!==", "$", "str", "&&", "false", "!==", "$", "encoding", "=", "mb_detect_encoding", "(", "$", "str", ")", ")", "{", "return", "$", "encoding", ";", "}", "// Otherwise let's return one of the defaults.", "return", "static", "::", "$", "encoding", "?", ":", "'utf-8'", ";", "}" ]
Attempts to determine the encoding of a string if a string is given. Upon failure or when no string is given, returns the static encoding set in this class or if that is not set, the hardcoded default of 'utf-8'. @param string|null $str @return string
[ "Attempts", "to", "determine", "the", "encoding", "of", "a", "string", "if", "a", "string", "is", "given", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Str.php#L293-L303
5,088
unyx/utils
Str.php
Str.length
public static function length(string $str, string $encoding = null) : int { return mb_strlen($str, $encoding ?: static::encoding($str)); }
php
public static function length(string $str, string $encoding = null) : int { return mb_strlen($str, $encoding ?: static::encoding($str)); }
[ "public", "static", "function", "length", "(", "string", "$", "str", ",", "string", "$", "encoding", "=", "null", ")", ":", "int", "{", "return", "mb_strlen", "(", "$", "str", ",", "$", "encoding", "?", ":", "static", "::", "encoding", "(", "$", "str", ")", ")", ";", "}" ]
Determines the length of a given string. Counts multi-byte characters as single characters. @param string $str The string to count characters in. @param string $encoding The encoding to use. @return int The length of the string.
[ "Determines", "the", "length", "of", "a", "given", "string", ".", "Counts", "multi", "-", "byte", "characters", "as", "single", "characters", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Str.php#L469-L472
5,089
unyx/utils
Str.php
Str.matches
public static function matches(string $str, string $pattern) : bool { if ($pattern === $str) { return true; } return (bool) preg_match('#^'.str_replace('\*', '.*', preg_quote($pattern, '#')).'\z'.'#', $str); }
php
public static function matches(string $str, string $pattern) : bool { if ($pattern === $str) { return true; } return (bool) preg_match('#^'.str_replace('\*', '.*', preg_quote($pattern, '#')).'\z'.'#', $str); }
[ "public", "static", "function", "matches", "(", "string", "$", "str", ",", "string", "$", "pattern", ")", ":", "bool", "{", "if", "(", "$", "pattern", "===", "$", "str", ")", "{", "return", "true", ";", "}", "return", "(", "bool", ")", "preg_match", "(", "'#^'", ".", "str_replace", "(", "'\\*'", ",", "'.*'", ",", "preg_quote", "(", "$", "pattern", ",", "'#'", ")", ")", ".", "'\\z'", ".", "'#'", ",", "$", "str", ")", ";", "}" ]
Determines whether the given string matches the given pattern. Asterisks are translated into zero or more regexp wildcards, allowing for glob-style patterns. @param string $str The string to match. @param string $pattern The pattern to match the string against. @return bool
[ "Determines", "whether", "the", "given", "string", "matches", "the", "given", "pattern", ".", "Asterisks", "are", "translated", "into", "zero", "or", "more", "regexp", "wildcards", "allowing", "for", "glob", "-", "style", "patterns", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Str.php#L496-L503
5,090
unyx/utils
Str.php
Str.slug
public static function slug(string $str, string $delimiter = '-') : string { $str = static::toAscii($str); // Remove all characters that are neither alphanumeric, nor the separator nor a whitespace. $str = preg_replace('![^'.preg_quote($delimiter).'\pL\pN\s]+!u', '', mb_strtolower($str)); // Standardize the separator. $flip = $delimiter == '-' ? '_' : '-'; $str = preg_replace('!['.preg_quote($flip).']+!u', $delimiter, $str); // Replace all separator characters and whitespace by a single separator. $str = preg_replace('!['.preg_quote($delimiter).'\s]+!u', $delimiter, $str); return trim($str, $delimiter); }
php
public static function slug(string $str, string $delimiter = '-') : string { $str = static::toAscii($str); // Remove all characters that are neither alphanumeric, nor the separator nor a whitespace. $str = preg_replace('![^'.preg_quote($delimiter).'\pL\pN\s]+!u', '', mb_strtolower($str)); // Standardize the separator. $flip = $delimiter == '-' ? '_' : '-'; $str = preg_replace('!['.preg_quote($flip).']+!u', $delimiter, $str); // Replace all separator characters and whitespace by a single separator. $str = preg_replace('!['.preg_quote($delimiter).'\s]+!u', $delimiter, $str); return trim($str, $delimiter); }
[ "public", "static", "function", "slug", "(", "string", "$", "str", ",", "string", "$", "delimiter", "=", "'-'", ")", ":", "string", "{", "$", "str", "=", "static", "::", "toAscii", "(", "$", "str", ")", ";", "// Remove all characters that are neither alphanumeric, nor the separator nor a whitespace.", "$", "str", "=", "preg_replace", "(", "'![^'", ".", "preg_quote", "(", "$", "delimiter", ")", ".", "'\\pL\\pN\\s]+!u'", ",", "''", ",", "mb_strtolower", "(", "$", "str", ")", ")", ";", "// Standardize the separator.", "$", "flip", "=", "$", "delimiter", "==", "'-'", "?", "'_'", ":", "'-'", ";", "$", "str", "=", "preg_replace", "(", "'!['", ".", "preg_quote", "(", "$", "flip", ")", ".", "']+!u'", ",", "$", "delimiter", ",", "$", "str", ")", ";", "// Replace all separator characters and whitespace by a single separator.", "$", "str", "=", "preg_replace", "(", "'!['", ".", "preg_quote", "(", "$", "delimiter", ")", ".", "'\\s]+!u'", ",", "$", "delimiter", ",", "$", "str", ")", ";", "return", "trim", "(", "$", "str", ",", "$", "delimiter", ")", ";", "}" ]
Generates a URL-friendly slug from the given string. @param string $str The string to slugify. @param string $delimiter The delimiter to replace non-alphanumeric characters with. @return string The resulting slug.
[ "Generates", "a", "URL", "-", "friendly", "slug", "from", "the", "given", "string", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Str.php#L878-L893
5,091
unyx/utils
Str.php
Str.toAscii
public static function toAscii(string $str) : string { if (preg_match("/[\x80-\xFF]/", $str)) { // Grab the transliteration table since we'll need it. if (null === static::$ascii) { static::$ascii = unserialize(file_get_contents(__DIR__ . '/str/resources/transliteration_table.ser')); } $str = \Normalizer::normalize($str, \Normalizer::NFKD); $str = preg_replace('/\p{Mn}+/u', '', $str); $str = str_replace(static::$ascii[0], static::$ascii[1], $str); $str = iconv('UTF-8', 'ASCII' . ('glibc' !== ICONV_IMPL ? '//IGNORE' : '') . '//TRANSLIT', $str); } return $str; }
php
public static function toAscii(string $str) : string { if (preg_match("/[\x80-\xFF]/", $str)) { // Grab the transliteration table since we'll need it. if (null === static::$ascii) { static::$ascii = unserialize(file_get_contents(__DIR__ . '/str/resources/transliteration_table.ser')); } $str = \Normalizer::normalize($str, \Normalizer::NFKD); $str = preg_replace('/\p{Mn}+/u', '', $str); $str = str_replace(static::$ascii[0], static::$ascii[1], $str); $str = iconv('UTF-8', 'ASCII' . ('glibc' !== ICONV_IMPL ? '//IGNORE' : '') . '//TRANSLIT', $str); } return $str; }
[ "public", "static", "function", "toAscii", "(", "string", "$", "str", ")", ":", "string", "{", "if", "(", "preg_match", "(", "\"/[\\x80-\\xFF]/\"", ",", "$", "str", ")", ")", "{", "// Grab the transliteration table since we'll need it.", "if", "(", "null", "===", "static", "::", "$", "ascii", ")", "{", "static", "::", "$", "ascii", "=", "unserialize", "(", "file_get_contents", "(", "__DIR__", ".", "'/str/resources/transliteration_table.ser'", ")", ")", ";", "}", "$", "str", "=", "\\", "Normalizer", "::", "normalize", "(", "$", "str", ",", "\\", "Normalizer", "::", "NFKD", ")", ";", "$", "str", "=", "preg_replace", "(", "'/\\p{Mn}+/u'", ",", "''", ",", "$", "str", ")", ";", "$", "str", "=", "str_replace", "(", "static", "::", "$", "ascii", "[", "0", "]", ",", "static", "::", "$", "ascii", "[", "1", "]", ",", "$", "str", ")", ";", "$", "str", "=", "iconv", "(", "'UTF-8'", ",", "'ASCII'", ".", "(", "'glibc'", "!==", "ICONV_IMPL", "?", "'//IGNORE'", ":", "''", ")", ".", "'//TRANSLIT'", ",", "$", "str", ")", ";", "}", "return", "$", "str", ";", "}" ]
Transliterates an UTF-8 encoded string to its ASCII equivalent. @param string $str The UTF-8 encoded string to transliterate. @return string The ASCII equivalent of the input string.
[ "Transliterates", "an", "UTF", "-", "8", "encoded", "string", "to", "its", "ASCII", "equivalent", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Str.php#L991-L1006
5,092
unyx/utils
Str.php
Str.toBool
public static function toBool(string $str, string $encoding = null) : bool { static $map = [ 'true' => true, 'false' => false, '1' => true, '0' => false, 'on' => true, 'off' => false, 'yes' => true, 'no' => false, 'y' => true, 'n' => false ]; $encoding = $encoding ?: static::encoding($str); return $map[mb_strtolower($str, $encoding)] ?? (bool) static::replace($str, '[[:space:]]', '', 'msr', $encoding); }
php
public static function toBool(string $str, string $encoding = null) : bool { static $map = [ 'true' => true, 'false' => false, '1' => true, '0' => false, 'on' => true, 'off' => false, 'yes' => true, 'no' => false, 'y' => true, 'n' => false ]; $encoding = $encoding ?: static::encoding($str); return $map[mb_strtolower($str, $encoding)] ?? (bool) static::replace($str, '[[:space:]]', '', 'msr', $encoding); }
[ "public", "static", "function", "toBool", "(", "string", "$", "str", ",", "string", "$", "encoding", "=", "null", ")", ":", "bool", "{", "static", "$", "map", "=", "[", "'true'", "=>", "true", ",", "'false'", "=>", "false", ",", "'1'", "=>", "true", ",", "'0'", "=>", "false", ",", "'on'", "=>", "true", ",", "'off'", "=>", "false", ",", "'yes'", "=>", "true", ",", "'no'", "=>", "false", ",", "'y'", "=>", "true", ",", "'n'", "=>", "false", "]", ";", "$", "encoding", "=", "$", "encoding", "?", ":", "static", "::", "encoding", "(", "$", "str", ")", ";", "return", "$", "map", "[", "mb_strtolower", "(", "$", "str", ",", "$", "encoding", ")", "]", "??", "(", "bool", ")", "static", "::", "replace", "(", "$", "str", ",", "'[[:space:]]'", ",", "''", ",", "'msr'", ",", "$", "encoding", ")", ";", "}" ]
Checks whether the given string represents a boolean value. Case insensitive. Works different than simply casting a string to a bool in that strings like "yes"/"no", "y"/"n", "on"/"off", "1"/"0" and "true"/"false" are interpreted based on the natural language value they represent. Numeric strings are left as in native PHP typecasting, ie. only 0 represents false. Every other numeric string, including negative numbers, will be treated as a truthy value. Non-empty strings containing only whitespaces, tabs or newlines will also be interpreted as empty (false) strings. Other than that normal typecasting rules apply. @param string $str The string to check. @param string|null $encoding The encoding to use. @return bool True when the string represents a boolean value, false otherwise. @todo Grab the map from a separate method to allow easier extending with locale specific values? @todo Rename to asBool() to make a more explicit distinction between this and normal typecasting?
[ "Checks", "whether", "the", "given", "string", "represents", "a", "boolean", "value", ".", "Case", "insensitive", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Str.php#L1027-L1045
5,093
unyx/utils
Str.php
Str.words
public static function words(string $str, int $words = 100, string $encoding = null, string $end = '...') : string { $encoding = $encoding ?: static::encoding($str); preg_match('/^\s*+(?:\S++\s*+){1,'.$words.'}/u', $str, $matches); if (!isset($matches[0]) || mb_strlen($str, $encoding) === mb_strlen($matches[0], $encoding)) { return $str; } return rtrim($matches[0]).$end; }
php
public static function words(string $str, int $words = 100, string $encoding = null, string $end = '...') : string { $encoding = $encoding ?: static::encoding($str); preg_match('/^\s*+(?:\S++\s*+){1,'.$words.'}/u', $str, $matches); if (!isset($matches[0]) || mb_strlen($str, $encoding) === mb_strlen($matches[0], $encoding)) { return $str; } return rtrim($matches[0]).$end; }
[ "public", "static", "function", "words", "(", "string", "$", "str", ",", "int", "$", "words", "=", "100", ",", "string", "$", "encoding", "=", "null", ",", "string", "$", "end", "=", "'...'", ")", ":", "string", "{", "$", "encoding", "=", "$", "encoding", "?", ":", "static", "::", "encoding", "(", "$", "str", ")", ";", "preg_match", "(", "'/^\\s*+(?:\\S++\\s*+){1,'", ".", "$", "words", ".", "'}/u'", ",", "$", "str", ",", "$", "matches", ")", ";", "if", "(", "!", "isset", "(", "$", "matches", "[", "0", "]", ")", "||", "mb_strlen", "(", "$", "str", ",", "$", "encoding", ")", "===", "mb_strlen", "(", "$", "matches", "[", "0", "]", ",", "$", "encoding", ")", ")", "{", "return", "$", "str", ";", "}", "return", "rtrim", "(", "$", "matches", "[", "0", "]", ")", ".", "$", "end", ";", "}" ]
Limits the number of words in the given string. @param string $str The string to limit. @param int $words The maximal number of words to be contained in the string, not counting the replacement. @param string|null $encoding The encoding to use. @param string $end The replacement for the whole of the cut off string (if any). @return string The resulting string.
[ "Limits", "the", "number", "of", "words", "in", "the", "given", "string", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/Str.php#L1185-L1196
5,094
sgtlambda/fieldwork
src/fieldwork/Form.php
Form.reset
public function reset () { $this->isUserSubmitted = false; $this->isProcessed = false; $this->isCallbacksubmitted = false; parent::reset(); }
php
public function reset () { $this->isUserSubmitted = false; $this->isProcessed = false; $this->isCallbacksubmitted = false; parent::reset(); }
[ "public", "function", "reset", "(", ")", "{", "$", "this", "->", "isUserSubmitted", "=", "false", ";", "$", "this", "->", "isProcessed", "=", "false", ";", "$", "this", "->", "isCallbacksubmitted", "=", "false", ";", "parent", "::", "reset", "(", ")", ";", "}" ]
Resets state and field values. DOES NOT remove validators and callbacks
[ "Resets", "state", "and", "field", "values", ".", "DOES", "NOT", "remove", "validators", "and", "callbacks" ]
ba18939c9822db4dc84947d90979cfb0da072cb0
https://github.com/sgtlambda/fieldwork/blob/ba18939c9822db4dc84947d90979cfb0da072cb0/src/fieldwork/Form.php#L56-L62
5,095
sgtlambda/fieldwork
src/fieldwork/Form.php
Form.f
public function f ($query, $includeInactiveFields = false) { $minLength = -1; $match = null; foreach ($this->getFields($includeInactiveFields) as $field) /* @var $field Field */ if (preg_match("/^(.*)" . preg_quote($query) . "$/", $field->getGlobalSlug(), $matches)) { $l = strlen($matches[1]); if ($l < $minLength || $minLength == -1) { $minLength = $l; $match = $field; } } return $match; }
php
public function f ($query, $includeInactiveFields = false) { $minLength = -1; $match = null; foreach ($this->getFields($includeInactiveFields) as $field) /* @var $field Field */ if (preg_match("/^(.*)" . preg_quote($query) . "$/", $field->getGlobalSlug(), $matches)) { $l = strlen($matches[1]); if ($l < $minLength || $minLength == -1) { $minLength = $l; $match = $field; } } return $match; }
[ "public", "function", "f", "(", "$", "query", ",", "$", "includeInactiveFields", "=", "false", ")", "{", "$", "minLength", "=", "-", "1", ";", "$", "match", "=", "null", ";", "foreach", "(", "$", "this", "->", "getFields", "(", "$", "includeInactiveFields", ")", "as", "$", "field", ")", "/* @var $field Field */", "if", "(", "preg_match", "(", "\"/^(.*)\"", ".", "preg_quote", "(", "$", "query", ")", ".", "\"$/\"", ",", "$", "field", "->", "getGlobalSlug", "(", ")", ",", "$", "matches", ")", ")", "{", "$", "l", "=", "strlen", "(", "$", "matches", "[", "1", "]", ")", ";", "if", "(", "$", "l", "<", "$", "minLength", "||", "$", "minLength", "==", "-", "1", ")", "{", "$", "minLength", "=", "$", "l", ";", "$", "match", "=", "$", "field", ";", "}", "}", "return", "$", "match", ";", "}" ]
Searches form fields @param string $query ID to search for @param bool $includeInactiveFields Whether to include inactive fields in the search @return null|Field closest match or null if not found
[ "Searches", "form", "fields" ]
ba18939c9822db4dc84947d90979cfb0da072cb0
https://github.com/sgtlambda/fieldwork/blob/ba18939c9822db4dc84947d90979cfb0da072cb0/src/fieldwork/Form.php#L82-L96
5,096
sgtlambda/fieldwork
src/fieldwork/Form.php
Form.v
public function v ($query, $default = '') { $f = $this->f($query); if ($f !== null) return $f->getValue(); else return $default; }
php
public function v ($query, $default = '') { $f = $this->f($query); if ($f !== null) return $f->getValue(); else return $default; }
[ "public", "function", "v", "(", "$", "query", ",", "$", "default", "=", "''", ")", "{", "$", "f", "=", "$", "this", "->", "f", "(", "$", "query", ")", ";", "if", "(", "$", "f", "!==", "null", ")", "return", "$", "f", "->", "getValue", "(", ")", ";", "else", "return", "$", "default", ";", "}" ]
Searches form fields and returns its value @param string $query id to search for @param string $default default value @return string value of closest match or default value if field not found
[ "Searches", "form", "fields", "and", "returns", "its", "value" ]
ba18939c9822db4dc84947d90979cfb0da072cb0
https://github.com/sgtlambda/fieldwork/blob/ba18939c9822db4dc84947d90979cfb0da072cb0/src/fieldwork/Form.php#L106-L113
5,097
sgtlambda/fieldwork
src/fieldwork/Form.php
Form.c
public function c () { $fields = array(); foreach ($this->getFields() as $field) /* @var $field Field */ if ($field->getCollectData()) $fields[] = $field; return $fields; }
php
public function c () { $fields = array(); foreach ($this->getFields() as $field) /* @var $field Field */ if ($field->getCollectData()) $fields[] = $field; return $fields; }
[ "public", "function", "c", "(", ")", "{", "$", "fields", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "getFields", "(", ")", "as", "$", "field", ")", "/* @var $field Field */", "if", "(", "$", "field", "->", "getCollectData", "(", ")", ")", "$", "fields", "[", "]", "=", "$", "field", ";", "return", "$", "fields", ";", "}" ]
Returns an array of fields of which data is to be collected @return Field[]
[ "Returns", "an", "array", "of", "fields", "of", "which", "data", "is", "to", "be", "collected" ]
ba18939c9822db4dc84947d90979cfb0da072cb0
https://github.com/sgtlambda/fieldwork/blob/ba18939c9822db4dc84947d90979cfb0da072cb0/src/fieldwork/Form.php#L119-L127
5,098
sgtlambda/fieldwork
src/fieldwork/Form.php
Form.addValidator
public function addValidator (FormValidator $validator, $unshift = false) { if ($unshift) array_unshift($this->validators, $validator); else $this->validators[] = $validator; return $this; }
php
public function addValidator (FormValidator $validator, $unshift = false) { if ($unshift) array_unshift($this->validators, $validator); else $this->validators[] = $validator; return $this; }
[ "public", "function", "addValidator", "(", "FormValidator", "$", "validator", ",", "$", "unshift", "=", "false", ")", "{", "if", "(", "$", "unshift", ")", "array_unshift", "(", "$", "this", "->", "validators", ",", "$", "validator", ")", ";", "else", "$", "this", "->", "validators", "[", "]", "=", "$", "validator", ";", "return", "$", "this", ";", "}" ]
Adds a new form-level validator @param FormValidator $validator validator @param boolean $unshift Whether to add the validator to the front of the array @return static
[ "Adds", "a", "new", "form", "-", "level", "validator" ]
ba18939c9822db4dc84947d90979cfb0da072cb0
https://github.com/sgtlambda/fieldwork/blob/ba18939c9822db4dc84947d90979cfb0da072cb0/src/fieldwork/Form.php#L137-L144
5,099
sgtlambda/fieldwork
src/fieldwork/Form.php
Form.getField
public function getField ($localSlug) { foreach ($this->getFields() as $field) /* @var $field Field */ if ($field->getLocalSlug() == $localSlug) return $field; return null; }
php
public function getField ($localSlug) { foreach ($this->getFields() as $field) /* @var $field Field */ if ($field->getLocalSlug() == $localSlug) return $field; return null; }
[ "public", "function", "getField", "(", "$", "localSlug", ")", "{", "foreach", "(", "$", "this", "->", "getFields", "(", ")", "as", "$", "field", ")", "/* @var $field Field */", "if", "(", "$", "field", "->", "getLocalSlug", "(", ")", "==", "$", "localSlug", ")", "return", "$", "field", ";", "return", "null", ";", "}" ]
Finds a field by its localslug value @param $localSlug @return Field|null
[ "Finds", "a", "field", "by", "its", "localslug", "value" ]
ba18939c9822db4dc84947d90979cfb0da072cb0
https://github.com/sgtlambda/fieldwork/blob/ba18939c9822db4dc84947d90979cfb0da072cb0/src/fieldwork/Form.php#L163-L170