repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
acacha/adminlte-laravel
src/Console/MakeRoute.php
MakeRoute.createMenu
protected function createMenu() { try { $this->warnIfSpatieMenuIsNotInstalled(); } catch (\Exception $e) { //Skip installation of menu $this->error($e->getMessage()); return; } Artisan::call('make:menu', [ 'link' => $link = undot_path($this->argument('link')), 'name' => ucfirst($link), ]); $this->info('Menu entry ' . $link .' added to config/menu.php file.'); }
php
protected function createMenu() { try { $this->warnIfSpatieMenuIsNotInstalled(); } catch (\Exception $e) { //Skip installation of menu $this->error($e->getMessage()); return; } Artisan::call('make:menu', [ 'link' => $link = undot_path($this->argument('link')), 'name' => ucfirst($link), ]); $this->info('Menu entry ' . $link .' added to config/menu.php file.'); }
[ "protected", "function", "createMenu", "(", ")", "{", "try", "{", "$", "this", "->", "warnIfSpatieMenuIsNotInstalled", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "//Skip installation of menu", "$", "this", "->", "error", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "return", ";", "}", "Artisan", "::", "call", "(", "'make:menu'", ",", "[", "'link'", "=>", "$", "link", "=", "undot_path", "(", "$", "this", "->", "argument", "(", "'link'", ")", ")", ",", "'name'", "=>", "ucfirst", "(", "$", "link", ")", ",", "]", ")", ";", "$", "this", "->", "info", "(", "'Menu entry '", ".", "$", "link", ".", "' added to config/menu.php file.'", ")", ";", "}" ]
Create menu.
[ "Create", "menu", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/MakeRoute.php#L337-L351
train
acacha/adminlte-laravel
src/Console/MakeRoute.php
MakeRoute.createView
protected function createView($name = null) { if ($name == null) { $name = $this->action(); } Artisan::call('make:view', [ 'name' => $name ]); $this->info('View ' . undot_path($name) .'.blade.php created.'); }
php
protected function createView($name = null) { if ($name == null) { $name = $this->action(); } Artisan::call('make:view', [ 'name' => $name ]); $this->info('View ' . undot_path($name) .'.blade.php created.'); }
[ "protected", "function", "createView", "(", "$", "name", "=", "null", ")", "{", "if", "(", "$", "name", "==", "null", ")", "{", "$", "name", "=", "$", "this", "->", "action", "(", ")", ";", "}", "Artisan", "::", "call", "(", "'make:view'", ",", "[", "'name'", "=>", "$", "name", "]", ")", ";", "$", "this", "->", "info", "(", "'View '", ".", "undot_path", "(", "$", "name", ")", ".", "'.blade.php created.'", ")", ";", "}" ]
Create View. @param null $name
[ "Create", "View", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/MakeRoute.php#L384-L393
train
acacha/adminlte-laravel
src/Console/MakeRoute.php
MakeRoute.createController
protected function createController() { Artisan::call('make:controller', [ 'name' => $controller = $this->controllerWithoutMethod($this->action()) ]); $this->addMethodToController($controller, $this->controllerMethod($this->action())); $this->info('Controller ' . $controller .' created.'); $this->createView($this->argument('link')); }
php
protected function createController() { Artisan::call('make:controller', [ 'name' => $controller = $this->controllerWithoutMethod($this->action()) ]); $this->addMethodToController($controller, $this->controllerMethod($this->action())); $this->info('Controller ' . $controller .' created.'); $this->createView($this->argument('link')); }
[ "protected", "function", "createController", "(", ")", "{", "Artisan", "::", "call", "(", "'make:controller'", ",", "[", "'name'", "=>", "$", "controller", "=", "$", "this", "->", "controllerWithoutMethod", "(", "$", "this", "->", "action", "(", ")", ")", "]", ")", ";", "$", "this", "->", "addMethodToController", "(", "$", "controller", ",", "$", "this", "->", "controllerMethod", "(", "$", "this", "->", "action", "(", ")", ")", ")", ";", "$", "this", "->", "info", "(", "'Controller '", ".", "$", "controller", ".", "' created.'", ")", ";", "$", "this", "->", "createView", "(", "$", "this", "->", "argument", "(", "'link'", ")", ")", ";", "}" ]
Create regular controller.
[ "Create", "regular", "controller", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/MakeRoute.php#L398-L406
train
acacha/adminlte-laravel
src/Console/MakeRoute.php
MakeRoute.createResourceController
protected function createResourceController() { Artisan::call('make:controller', [ 'name' => $controller = $this->controllerWithoutMethod($this->action()), '--resource' => true ]); $this->info('Resource Controller ' . $controller .' created.'); $this->createView($this->argument('link')); }
php
protected function createResourceController() { Artisan::call('make:controller', [ 'name' => $controller = $this->controllerWithoutMethod($this->action()), '--resource' => true ]); $this->info('Resource Controller ' . $controller .' created.'); $this->createView($this->argument('link')); }
[ "protected", "function", "createResourceController", "(", ")", "{", "Artisan", "::", "call", "(", "'make:controller'", ",", "[", "'name'", "=>", "$", "controller", "=", "$", "this", "->", "controllerWithoutMethod", "(", "$", "this", "->", "action", "(", ")", ")", ",", "'--resource'", "=>", "true", "]", ")", ";", "$", "this", "->", "info", "(", "'Resource Controller '", ".", "$", "controller", ".", "' created.'", ")", ";", "$", "this", "->", "createView", "(", "$", "this", "->", "argument", "(", "'link'", ")", ")", ";", "}" ]
Create resource controller.
[ "Create", "resource", "controller", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/MakeRoute.php#L411-L419
train
acacha/adminlte-laravel
src/Console/MakeRoute.php
MakeRoute.addMethodToController
protected function addMethodToController($controller, $controllerMethod) { $tmpfile = $this->createTmpFileWithMethod($controllerMethod); $path = $this->getPath($tmpfile); add_file_into_file('\/\/', $path, app_path('Http/Controllers/' . $controller . '.php')); }
php
protected function addMethodToController($controller, $controllerMethod) { $tmpfile = $this->createTmpFileWithMethod($controllerMethod); $path = $this->getPath($tmpfile); add_file_into_file('\/\/', $path, app_path('Http/Controllers/' . $controller . '.php')); }
[ "protected", "function", "addMethodToController", "(", "$", "controller", ",", "$", "controllerMethod", ")", "{", "$", "tmpfile", "=", "$", "this", "->", "createTmpFileWithMethod", "(", "$", "controllerMethod", ")", ";", "$", "path", "=", "$", "this", "->", "getPath", "(", "$", "tmpfile", ")", ";", "add_file_into_file", "(", "'\\/\\/'", ",", "$", "path", ",", "app_path", "(", "'Http/Controllers/'", ".", "$", "controller", ".", "'.php'", ")", ")", ";", "}" ]
Add method to controller. @param $controller @param $controllerMethod *
[ "Add", "method", "to", "controller", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/MakeRoute.php#L427-L432
train
acacha/adminlte-laravel
src/Console/MakeRoute.php
MakeRoute.createTmpFileWithMethod
protected function createTmpFileWithMethod($controllerMethod) { $temp = tmpfile(); fwrite($temp, $this->getMethodCode($controllerMethod)); return $temp; }
php
protected function createTmpFileWithMethod($controllerMethod) { $temp = tmpfile(); fwrite($temp, $this->getMethodCode($controllerMethod)); return $temp; }
[ "protected", "function", "createTmpFileWithMethod", "(", "$", "controllerMethod", ")", "{", "$", "temp", "=", "tmpfile", "(", ")", ";", "fwrite", "(", "$", "temp", ",", "$", "this", "->", "getMethodCode", "(", "$", "controllerMethod", ")", ")", ";", "return", "$", "temp", ";", "}" ]
Crete tmp file with route to add. @param $controllerMethod @return mixed
[ "Crete", "tmp", "file", "with", "route", "to", "add", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/MakeRoute.php#L440-L445
train
acacha/adminlte-laravel
src/Console/Routes/Route.php
Route.code
public function code() { return $this->compiler->compile( $this->filesystem->get($this->getStubPath()), $this->obtainReplacements() ); }
php
public function code() { return $this->compiler->compile( $this->filesystem->get($this->getStubPath()), $this->obtainReplacements() ); }
[ "public", "function", "code", "(", ")", "{", "return", "$", "this", "->", "compiler", "->", "compile", "(", "$", "this", "->", "filesystem", "->", "get", "(", "$", "this", "->", "getStubPath", "(", ")", ")", ",", "$", "this", "->", "obtainReplacements", "(", ")", ")", ";", "}" ]
Generate route code.
[ "Generate", "route", "code", "." ]
abcf6f5f63e3337275715b1f55f6faf185f4e6e7
https://github.com/acacha/adminlte-laravel/blob/abcf6f5f63e3337275715b1f55f6faf185f4e6e7/src/Console/Routes/Route.php#L68-L74
train
agentejo/cockpit
lib/MongoLite/Collection.php
Collection.findOne
public function findOne($criteria = null, $projection = null) { $items = $this->find($criteria, $projection)->limit(1)->toArray(); return isset($items[0]) ? $items[0]:null; }
php
public function findOne($criteria = null, $projection = null) { $items = $this->find($criteria, $projection)->limit(1)->toArray(); return isset($items[0]) ? $items[0]:null; }
[ "public", "function", "findOne", "(", "$", "criteria", "=", "null", ",", "$", "projection", "=", "null", ")", "{", "$", "items", "=", "$", "this", "->", "find", "(", "$", "criteria", ",", "$", "projection", ")", "->", "limit", "(", "1", ")", "->", "toArray", "(", ")", ";", "return", "isset", "(", "$", "items", "[", "0", "]", ")", "?", "$", "items", "[", "0", "]", ":", "null", ";", "}" ]
Find one document @param mixed $criteria @return array
[ "Find", "one", "document" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/MongoLite/Collection.php#L186-L191
train
agentejo/cockpit
lib/Lime/App.php
App.service
public function service($name, $callable) { $this->registry[$name] = function($c) use($callable) { static $object; if (null === $object) { $object = $callable($c); } return $object; }; return $this; }
php
public function service($name, $callable) { $this->registry[$name] = function($c) use($callable) { static $object; if (null === $object) { $object = $callable($c); } return $object; }; return $this; }
[ "public", "function", "service", "(", "$", "name", ",", "$", "callable", ")", "{", "$", "this", "->", "registry", "[", "$", "name", "]", "=", "function", "(", "$", "c", ")", "use", "(", "$", "callable", ")", "{", "static", "$", "object", ";", "if", "(", "null", "===", "$", "object", ")", "{", "$", "object", "=", "$", "callable", "(", "$", "c", ")", ";", "}", "return", "$", "object", ";", "}", ";", "return", "$", "this", ";", "}" ]
Returns a closure that stores the result of the given closure @param String $name @param \Closure $callable @return Object
[ "Returns", "a", "closure", "that", "stores", "the", "result", "of", "the", "given", "closure" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/App.php#L272-L285
train
agentejo/cockpit
lib/Lime/App.php
App.baseUrl
public function baseUrl($path) { $url = ''; if (\strpos($path, ':')===false) { /* if ($this->registry['base_port'] != '80') { $url .= $this->registry['site_url']; } */ $url .= $this->registry['base_url'].'/'.\ltrim($path, '/'); } else { $url = $this->pathToUrl($path); } return $url; }
php
public function baseUrl($path) { $url = ''; if (\strpos($path, ':')===false) { /* if ($this->registry['base_port'] != '80') { $url .= $this->registry['site_url']; } */ $url .= $this->registry['base_url'].'/'.\ltrim($path, '/'); } else { $url = $this->pathToUrl($path); } return $url; }
[ "public", "function", "baseUrl", "(", "$", "path", ")", "{", "$", "url", "=", "''", ";", "if", "(", "\\", "strpos", "(", "$", "path", ",", "':'", ")", "===", "false", ")", "{", "/*\n if ($this->registry['base_port'] != '80') {\n $url .= $this->registry['site_url'];\n }\n */", "$", "url", ".=", "$", "this", "->", "registry", "[", "'base_url'", "]", ".", "'/'", ".", "\\", "ltrim", "(", "$", "path", ",", "'/'", ")", ";", "}", "else", "{", "$", "url", "=", "$", "this", "->", "pathToUrl", "(", "$", "path", ")", ";", "}", "return", "$", "url", ";", "}" ]
Returns link based on the base url of the app @param String $path e.g. /js/myscript.js @return String Link
[ "Returns", "link", "based", "on", "the", "base", "url", "of", "the", "app" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/App.php#L333-L352
train
agentejo/cockpit
lib/Lime/App.php
App.set
public function set($key, $value) { $keys = \explode('/',$key); if (\count($keys)>5) return false; switch (\count($keys)){ case 1: $this->registry[$keys[0]] = $value; break; case 2: $this->registry[$keys[0]][$keys[1]] = $value; break; case 3: $this->registry[$keys[0]][$keys[1]][$keys[2]] = $value; break; case 4: $this->registry[$keys[0]][$keys[1]][$keys[2]][$keys[3]] = $value; break; case 5: $this->registry[$keys[0]][$keys[1]][$keys[2]][$keys[3]][$keys[4]] = $value; break; } return $this; }
php
public function set($key, $value) { $keys = \explode('/',$key); if (\count($keys)>5) return false; switch (\count($keys)){ case 1: $this->registry[$keys[0]] = $value; break; case 2: $this->registry[$keys[0]][$keys[1]] = $value; break; case 3: $this->registry[$keys[0]][$keys[1]][$keys[2]] = $value; break; case 4: $this->registry[$keys[0]][$keys[1]][$keys[2]][$keys[3]] = $value; break; case 5: $this->registry[$keys[0]][$keys[1]][$keys[2]][$keys[3]][$keys[4]] = $value; break; } return $this; }
[ "public", "function", "set", "(", "$", "key", ",", "$", "value", ")", "{", "$", "keys", "=", "\\", "explode", "(", "'/'", ",", "$", "key", ")", ";", "if", "(", "\\", "count", "(", "$", "keys", ")", ">", "5", ")", "return", "false", ";", "switch", "(", "\\", "count", "(", "$", "keys", ")", ")", "{", "case", "1", ":", "$", "this", "->", "registry", "[", "$", "keys", "[", "0", "]", "]", "=", "$", "value", ";", "break", ";", "case", "2", ":", "$", "this", "->", "registry", "[", "$", "keys", "[", "0", "]", "]", "[", "$", "keys", "[", "1", "]", "]", "=", "$", "value", ";", "break", ";", "case", "3", ":", "$", "this", "->", "registry", "[", "$", "keys", "[", "0", "]", "]", "[", "$", "keys", "[", "1", "]", "]", "[", "$", "keys", "[", "2", "]", "]", "=", "$", "value", ";", "break", ";", "case", "4", ":", "$", "this", "->", "registry", "[", "$", "keys", "[", "0", "]", "]", "[", "$", "keys", "[", "1", "]", "]", "[", "$", "keys", "[", "2", "]", "]", "[", "$", "keys", "[", "3", "]", "]", "=", "$", "value", ";", "break", ";", "case", "5", ":", "$", "this", "->", "registry", "[", "$", "keys", "[", "0", "]", "]", "[", "$", "keys", "[", "1", "]", "]", "[", "$", "keys", "[", "2", "]", "]", "[", "$", "keys", "[", "3", "]", "]", "[", "$", "keys", "[", "4", "]", "]", "=", "$", "value", ";", "break", ";", "}", "return", "$", "this", ";", "}" ]
Put a value in the Lime registry @param String $key Key name @param Mixed $value Value
[ "Put", "a", "value", "in", "the", "Lime", "registry" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/App.php#L412-L442
train
agentejo/cockpit
lib/Lime/App.php
App.path
public function path(){ $args = \func_get_args(); switch (\count($args)){ case 1: $file = $args[0]; if ($this->isAbsolutePath($file) && \file_exists($file)) { return $file; } $parts = \explode(':', $file, 2); if (count($parts)==2){ if (!isset($this->paths[$parts[0]])) return false; foreach ($this->paths[$parts[0]] as &$path){ if (\file_exists($path.$parts[1])){ return $path.$parts[1]; } } } return false; case 2: if (!isset($this->paths[$args[0]])) { $this->paths[$args[0]] = []; } \array_unshift($this->paths[$args[0]], \rtrim(\str_replace(DIRECTORY_SEPARATOR, '/', $args[1]), '/').'/'); return $this; } return null; }
php
public function path(){ $args = \func_get_args(); switch (\count($args)){ case 1: $file = $args[0]; if ($this->isAbsolutePath($file) && \file_exists($file)) { return $file; } $parts = \explode(':', $file, 2); if (count($parts)==2){ if (!isset($this->paths[$parts[0]])) return false; foreach ($this->paths[$parts[0]] as &$path){ if (\file_exists($path.$parts[1])){ return $path.$parts[1]; } } } return false; case 2: if (!isset($this->paths[$args[0]])) { $this->paths[$args[0]] = []; } \array_unshift($this->paths[$args[0]], \rtrim(\str_replace(DIRECTORY_SEPARATOR, '/', $args[1]), '/').'/'); return $this; } return null; }
[ "public", "function", "path", "(", ")", "{", "$", "args", "=", "\\", "func_get_args", "(", ")", ";", "switch", "(", "\\", "count", "(", "$", "args", ")", ")", "{", "case", "1", ":", "$", "file", "=", "$", "args", "[", "0", "]", ";", "if", "(", "$", "this", "->", "isAbsolutePath", "(", "$", "file", ")", "&&", "\\", "file_exists", "(", "$", "file", ")", ")", "{", "return", "$", "file", ";", "}", "$", "parts", "=", "\\", "explode", "(", "':'", ",", "$", "file", ",", "2", ")", ";", "if", "(", "count", "(", "$", "parts", ")", "==", "2", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "paths", "[", "$", "parts", "[", "0", "]", "]", ")", ")", "return", "false", ";", "foreach", "(", "$", "this", "->", "paths", "[", "$", "parts", "[", "0", "]", "]", "as", "&", "$", "path", ")", "{", "if", "(", "\\", "file_exists", "(", "$", "path", ".", "$", "parts", "[", "1", "]", ")", ")", "{", "return", "$", "path", ".", "$", "parts", "[", "1", "]", ";", "}", "}", "}", "return", "false", ";", "case", "2", ":", "if", "(", "!", "isset", "(", "$", "this", "->", "paths", "[", "$", "args", "[", "0", "]", "]", ")", ")", "{", "$", "this", "->", "paths", "[", "$", "args", "[", "0", "]", "]", "=", "[", "]", ";", "}", "\\", "array_unshift", "(", "$", "this", "->", "paths", "[", "$", "args", "[", "0", "]", "]", ",", "\\", "rtrim", "(", "\\", "str_replace", "(", "DIRECTORY_SEPARATOR", ",", "'/'", ",", "$", "args", "[", "1", "]", ")", ",", "'/'", ")", ".", "'/'", ")", ";", "return", "$", "this", ";", "}", "return", "null", ";", "}" ]
Path helper method @return Mixed
[ "Path", "helper", "method" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/App.php#L459-L498
train
agentejo/cockpit
lib/Lime/App.php
App.cache
public function cache(){ $args = \func_get_args(); switch(\count($args)){ case 1: return $this->helper('cache')->read($args[0]); case 2: return $this->helper('cache')->write($args[0], $args[1]); } return null; }
php
public function cache(){ $args = \func_get_args(); switch(\count($args)){ case 1: return $this->helper('cache')->read($args[0]); case 2: return $this->helper('cache')->write($args[0], $args[1]); } return null; }
[ "public", "function", "cache", "(", ")", "{", "$", "args", "=", "\\", "func_get_args", "(", ")", ";", "switch", "(", "\\", "count", "(", "$", "args", ")", ")", "{", "case", "1", ":", "return", "$", "this", "->", "helper", "(", "'cache'", ")", "->", "read", "(", "$", "args", "[", "0", "]", ")", ";", "case", "2", ":", "return", "$", "this", "->", "helper", "(", "'cache'", ")", "->", "write", "(", "$", "args", "[", "0", "]", ",", "$", "args", "[", "1", "]", ")", ";", "}", "return", "null", ";", "}" ]
Cache helper method @return Mixed
[ "Cache", "helper", "method" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/App.php#L541-L553
train
agentejo/cockpit
lib/Lime/App.php
App.block
public function block($name, $options=[]) { if (!isset($this->blocks[$name])) return null; $options = \array_merge([ 'print' => true ], $options); $block = \implode("\n", $this->blocks[$name]); if ($options['print']){ echo $block; } return $block; }
php
public function block($name, $options=[]) { if (!isset($this->blocks[$name])) return null; $options = \array_merge([ 'print' => true ], $options); $block = \implode("\n", $this->blocks[$name]); if ($options['print']){ echo $block; } return $block; }
[ "public", "function", "block", "(", "$", "name", ",", "$", "options", "=", "[", "]", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "blocks", "[", "$", "name", "]", ")", ")", "return", "null", ";", "$", "options", "=", "\\", "array_merge", "(", "[", "'print'", "=>", "true", "]", ",", "$", "options", ")", ";", "$", "block", "=", "\\", "implode", "(", "\"\\n\"", ",", "$", "this", "->", "blocks", "[", "$", "name", "]", ")", ";", "if", "(", "$", "options", "[", "'print'", "]", ")", "{", "echo", "$", "block", ";", "}", "return", "$", "block", ";", "}" ]
Get block content @param String $name @param array $options @return String
[ "Get", "block", "content" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/App.php#L707-L722
train
agentejo/cockpit
lib/Lime/App.php
App.param
public function param($index=null, $default = null, $source = null) { $src = $source ? $source : $_REQUEST; $cast = null; if (\strpos($index, ':') !== false) { list($index, $cast) = \explode(':', $index, 2); } $value = fetch_from_array($src, $index, $default); if ($cast) { if (\in_array($cast, ['bool', 'boolean']) && \is_string($value) && \in_array($cast, ['true', 'false'])) { $value = $value == 'true' ? true : false; } \settype($value, $cast); } return $value; }
php
public function param($index=null, $default = null, $source = null) { $src = $source ? $source : $_REQUEST; $cast = null; if (\strpos($index, ':') !== false) { list($index, $cast) = \explode(':', $index, 2); } $value = fetch_from_array($src, $index, $default); if ($cast) { if (\in_array($cast, ['bool', 'boolean']) && \is_string($value) && \in_array($cast, ['true', 'false'])) { $value = $value == 'true' ? true : false; } \settype($value, $cast); } return $value; }
[ "public", "function", "param", "(", "$", "index", "=", "null", ",", "$", "default", "=", "null", ",", "$", "source", "=", "null", ")", "{", "$", "src", "=", "$", "source", "?", "$", "source", ":", "$", "_REQUEST", ";", "$", "cast", "=", "null", ";", "if", "(", "\\", "strpos", "(", "$", "index", ",", "':'", ")", "!==", "false", ")", "{", "list", "(", "$", "index", ",", "$", "cast", ")", "=", "\\", "explode", "(", "':'", ",", "$", "index", ",", "2", ")", ";", "}", "$", "value", "=", "fetch_from_array", "(", "$", "src", ",", "$", "index", ",", "$", "default", ")", ";", "if", "(", "$", "cast", ")", "{", "if", "(", "\\", "in_array", "(", "$", "cast", ",", "[", "'bool'", ",", "'boolean'", "]", ")", "&&", "\\", "is_string", "(", "$", "value", ")", "&&", "\\", "in_array", "(", "$", "cast", ",", "[", "'true'", ",", "'false'", "]", ")", ")", "{", "$", "value", "=", "$", "value", "==", "'true'", "?", "true", ":", "false", ";", "}", "\\", "settype", "(", "$", "value", ",", "$", "cast", ")", ";", "}", "return", "$", "value", ";", "}" ]
Get request variables @param String $index @param Mixed $default @param Array $source @return Mixed
[ "Get", "request", "variables" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/App.php#L746-L767
train
agentejo/cockpit
lib/Lime/App.php
App.get
public function get($path, $callback, $condition = true){ if (!$this->req_is('get')) return; $this->bind($path, $callback, $condition); }
php
public function get($path, $callback, $condition = true){ if (!$this->req_is('get')) return; $this->bind($path, $callback, $condition); }
[ "public", "function", "get", "(", "$", "path", ",", "$", "callback", ",", "$", "condition", "=", "true", ")", "{", "if", "(", "!", "$", "this", "->", "req_is", "(", "'get'", ")", ")", "return", ";", "$", "this", "->", "bind", "(", "$", "path", ",", "$", "callback", ",", "$", "condition", ")", ";", "}" ]
Bind GET request to route @param String $path @param \Closure $callback @param Boolean $condition @return void
[ "Bind", "GET", "request", "to", "route" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/App.php#L852-L855
train
agentejo/cockpit
lib/Lime/App.php
App.post
public function post($path, $callback, $condition = true){ if (!$this->req_is('post')) return; $this->bind($path, $callback, $condition); }
php
public function post($path, $callback, $condition = true){ if (!$this->req_is('post')) return; $this->bind($path, $callback, $condition); }
[ "public", "function", "post", "(", "$", "path", ",", "$", "callback", ",", "$", "condition", "=", "true", ")", "{", "if", "(", "!", "$", "this", "->", "req_is", "(", "'post'", ")", ")", "return", ";", "$", "this", "->", "bind", "(", "$", "path", ",", "$", "callback", ",", "$", "condition", ")", ";", "}" ]
Bind POST request to route @param String $path @param \Closure $callback @param Boolean $condition @return void
[ "Bind", "POST", "request", "to", "route" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/App.php#L864-L867
train
agentejo/cockpit
lib/Lime/App.php
App.bindClass
public function bindClass($class, $alias = false) { $self = $this; $clean = $alias ? $alias : \trim(\strtolower(\str_replace("\\", "/", $class)), "\\"); $this->bind('/'.$clean.'/*', function() use($self, $class, $clean) { $parts = \explode('/', \trim(\preg_replace("#$clean#","",$self["route"],1),'/')); $action = isset($parts[0]) ? $parts[0]:"index"; $params = \count($parts)>1 ? \array_slice($parts, 1):[]; return $self->invoke($class,$action, $params); }); $this->bind('/'.$clean, function() use($self, $class) { return $self->invoke($class, 'index', []); }); }
php
public function bindClass($class, $alias = false) { $self = $this; $clean = $alias ? $alias : \trim(\strtolower(\str_replace("\\", "/", $class)), "\\"); $this->bind('/'.$clean.'/*', function() use($self, $class, $clean) { $parts = \explode('/', \trim(\preg_replace("#$clean#","",$self["route"],1),'/')); $action = isset($parts[0]) ? $parts[0]:"index"; $params = \count($parts)>1 ? \array_slice($parts, 1):[]; return $self->invoke($class,$action, $params); }); $this->bind('/'.$clean, function() use($self, $class) { return $self->invoke($class, 'index', []); }); }
[ "public", "function", "bindClass", "(", "$", "class", ",", "$", "alias", "=", "false", ")", "{", "$", "self", "=", "$", "this", ";", "$", "clean", "=", "$", "alias", "?", "$", "alias", ":", "\\", "trim", "(", "\\", "strtolower", "(", "\\", "str_replace", "(", "\"\\\\\"", ",", "\"/\"", ",", "$", "class", ")", ")", ",", "\"\\\\\"", ")", ";", "$", "this", "->", "bind", "(", "'/'", ".", "$", "clean", ".", "'/*'", ",", "function", "(", ")", "use", "(", "$", "self", ",", "$", "class", ",", "$", "clean", ")", "{", "$", "parts", "=", "\\", "explode", "(", "'/'", ",", "\\", "trim", "(", "\\", "preg_replace", "(", "\"#$clean#\"", ",", "\"\"", ",", "$", "self", "[", "\"route\"", "]", ",", "1", ")", ",", "'/'", ")", ")", ";", "$", "action", "=", "isset", "(", "$", "parts", "[", "0", "]", ")", "?", "$", "parts", "[", "0", "]", ":", "\"index\"", ";", "$", "params", "=", "\\", "count", "(", "$", "parts", ")", ">", "1", "?", "\\", "array_slice", "(", "$", "parts", ",", "1", ")", ":", "[", "]", ";", "return", "$", "self", "->", "invoke", "(", "$", "class", ",", "$", "action", ",", "$", "params", ")", ";", "}", ")", ";", "$", "this", "->", "bind", "(", "'/'", ".", "$", "clean", ",", "function", "(", ")", "use", "(", "$", "self", ",", "$", "class", ")", "{", "return", "$", "self", "->", "invoke", "(", "$", "class", ",", "'index'", ",", "[", "]", ")", ";", "}", ")", ";", "}" ]
Bind Class to routes @param String $class @return void
[ "Bind", "Class", "to", "routes" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/App.php#L874-L891
train
agentejo/cockpit
lib/Lime/App.php
App.bind
public function bind($path, $callback, $condition = true) { if (!$condition) return; if (!isset($this->routes[$path])) { $this->routes[$path] = []; } // make $this available in closures if (\is_object($callback) && $callback instanceof \Closure) { $callback = $callback->bindTo($this, $this); } // autou-register for /route/* also /route if (\substr($path, -2) == '/*' && !isset($this->routes[\substr($path, 0, -2)])) { $this->bind(\substr($path, 0, -2), $callback, $condition); } $this->routes[$path] = $callback; }
php
public function bind($path, $callback, $condition = true) { if (!$condition) return; if (!isset($this->routes[$path])) { $this->routes[$path] = []; } // make $this available in closures if (\is_object($callback) && $callback instanceof \Closure) { $callback = $callback->bindTo($this, $this); } // autou-register for /route/* also /route if (\substr($path, -2) == '/*' && !isset($this->routes[\substr($path, 0, -2)])) { $this->bind(\substr($path, 0, -2), $callback, $condition); } $this->routes[$path] = $callback; }
[ "public", "function", "bind", "(", "$", "path", ",", "$", "callback", ",", "$", "condition", "=", "true", ")", "{", "if", "(", "!", "$", "condition", ")", "return", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "routes", "[", "$", "path", "]", ")", ")", "{", "$", "this", "->", "routes", "[", "$", "path", "]", "=", "[", "]", ";", "}", "// make $this available in closures", "if", "(", "\\", "is_object", "(", "$", "callback", ")", "&&", "$", "callback", "instanceof", "\\", "Closure", ")", "{", "$", "callback", "=", "$", "callback", "->", "bindTo", "(", "$", "this", ",", "$", "this", ")", ";", "}", "// autou-register for /route/* also /route", "if", "(", "\\", "substr", "(", "$", "path", ",", "-", "2", ")", "==", "'/*'", "&&", "!", "isset", "(", "$", "this", "->", "routes", "[", "\\", "substr", "(", "$", "path", ",", "0", ",", "-", "2", ")", "]", ")", ")", "{", "$", "this", "->", "bind", "(", "\\", "substr", "(", "$", "path", ",", "0", ",", "-", "2", ")", ",", "$", "callback", ",", "$", "condition", ")", ";", "}", "$", "this", "->", "routes", "[", "$", "path", "]", "=", "$", "callback", ";", "}" ]
Bind request to route @param String $path @param \Closure $callback @param Boolean $condition @return void
[ "Bind", "request", "to", "route" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/App.php#L928-L947
train
agentejo/cockpit
lib/Lime/App.php
App.render_route
protected function render_route($route, $params = []) { $output = false; if (isset($this->routes[$route])) { $ret = null; if (\is_callable($this->routes[$route])){ $ret = \call_user_func($this->routes[$route], $params); } if (!is_null($ret)){ return $ret; } } return $output; }
php
protected function render_route($route, $params = []) { $output = false; if (isset($this->routes[$route])) { $ret = null; if (\is_callable($this->routes[$route])){ $ret = \call_user_func($this->routes[$route], $params); } if (!is_null($ret)){ return $ret; } } return $output; }
[ "protected", "function", "render_route", "(", "$", "route", ",", "$", "params", "=", "[", "]", ")", "{", "$", "output", "=", "false", ";", "if", "(", "isset", "(", "$", "this", "->", "routes", "[", "$", "route", "]", ")", ")", "{", "$", "ret", "=", "null", ";", "if", "(", "\\", "is_callable", "(", "$", "this", "->", "routes", "[", "$", "route", "]", ")", ")", "{", "$", "ret", "=", "\\", "call_user_func", "(", "$", "this", "->", "routes", "[", "$", "route", "]", ",", "$", "params", ")", ";", "}", "if", "(", "!", "is_null", "(", "$", "ret", ")", ")", "{", "return", "$", "ret", ";", "}", "}", "return", "$", "output", ";", "}" ]
Render dispatched route @param [type] $route @param array $params @return String
[ "Render", "dispatched", "route" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/App.php#L1066-L1084
train
agentejo/cockpit
lib/Lime/App.php
App.invoke
public function invoke($class, $action="index", $params=[]) { $controller = new $class($this); return \method_exists($controller, $action) && \is_callable([$controller, $action]) ? \call_user_func_array([$controller,$action], $params) : false; }
php
public function invoke($class, $action="index", $params=[]) { $controller = new $class($this); return \method_exists($controller, $action) && \is_callable([$controller, $action]) ? \call_user_func_array([$controller,$action], $params) : false; }
[ "public", "function", "invoke", "(", "$", "class", ",", "$", "action", "=", "\"index\"", ",", "$", "params", "=", "[", "]", ")", "{", "$", "controller", "=", "new", "$", "class", "(", "$", "this", ")", ";", "return", "\\", "method_exists", "(", "$", "controller", ",", "$", "action", ")", "&&", "\\", "is_callable", "(", "[", "$", "controller", ",", "$", "action", "]", ")", "?", "\\", "call_user_func_array", "(", "[", "$", "controller", ",", "$", "action", "]", ",", "$", "params", ")", ":", "false", ";", "}" ]
Invoke Class as controller @param String $class @param String $action @param Array $params @return Mixed
[ "Invoke", "Class", "as", "controller" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/App.php#L1094-L1101
train
agentejo/cockpit
lib/Lime/App.php
App.getClientIp
public function getClientIp(){ if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){ // Use the forwarded IP address, typically set when the // client is using a proxy server. return $_SERVER['HTTP_X_FORWARDED_FOR']; }elseif (isset($_SERVER['HTTP_CLIENT_IP'])){ // Use the forwarded IP address, typically set when the // client is using a proxy server. return $_SERVER['HTTP_CLIENT_IP']; } elseif (isset($_SERVER['REMOTE_ADDR'])){ // The remote IP address return $_SERVER['REMOTE_ADDR']; } return null; }
php
public function getClientIp(){ if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){ // Use the forwarded IP address, typically set when the // client is using a proxy server. return $_SERVER['HTTP_X_FORWARDED_FOR']; }elseif (isset($_SERVER['HTTP_CLIENT_IP'])){ // Use the forwarded IP address, typically set when the // client is using a proxy server. return $_SERVER['HTTP_CLIENT_IP']; } elseif (isset($_SERVER['REMOTE_ADDR'])){ // The remote IP address return $_SERVER['REMOTE_ADDR']; } return null; }
[ "public", "function", "getClientIp", "(", ")", "{", "if", "(", "isset", "(", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_FOR'", "]", ")", ")", "{", "// Use the forwarded IP address, typically set when the", "// client is using a proxy server.", "return", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_FOR'", "]", ";", "}", "elseif", "(", "isset", "(", "$", "_SERVER", "[", "'HTTP_CLIENT_IP'", "]", ")", ")", "{", "// Use the forwarded IP address, typically set when the", "// client is using a proxy server.", "return", "$", "_SERVER", "[", "'HTTP_CLIENT_IP'", "]", ";", "}", "elseif", "(", "isset", "(", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ")", ")", "{", "// The remote IP address", "return", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ";", "}", "return", "null", ";", "}" ]
Get client ip. @return String
[ "Get", "client", "ip", "." ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/App.php#L1158-L1175
train
agentejo/cockpit
lib/Lime/Helper/Utils.php
Utils.resolveDependencies
public function resolveDependencies(array $data) { $new_data = array(); $original_count = \count($data); while (\count($new_data) < $original_count) { foreach ($data as $name => $dependencies) { if (!\count($dependencies)) { $new_data[] = $name; unset($data[$name]); continue; } foreach ($dependencies as $key => $dependency) { if (\in_array($dependency, $new_data)) { unset($data[$name][$key]); } } } } return $new_data; }
php
public function resolveDependencies(array $data) { $new_data = array(); $original_count = \count($data); while (\count($new_data) < $original_count) { foreach ($data as $name => $dependencies) { if (!\count($dependencies)) { $new_data[] = $name; unset($data[$name]); continue; } foreach ($dependencies as $key => $dependency) { if (\in_array($dependency, $new_data)) { unset($data[$name][$key]); } } } } return $new_data; }
[ "public", "function", "resolveDependencies", "(", "array", "$", "data", ")", "{", "$", "new_data", "=", "array", "(", ")", ";", "$", "original_count", "=", "\\", "count", "(", "$", "data", ")", ";", "while", "(", "\\", "count", "(", "$", "new_data", ")", "<", "$", "original_count", ")", "{", "foreach", "(", "$", "data", "as", "$", "name", "=>", "$", "dependencies", ")", "{", "if", "(", "!", "\\", "count", "(", "$", "dependencies", ")", ")", "{", "$", "new_data", "[", "]", "=", "$", "name", ";", "unset", "(", "$", "data", "[", "$", "name", "]", ")", ";", "continue", ";", "}", "foreach", "(", "$", "dependencies", "as", "$", "key", "=>", "$", "dependency", ")", "{", "if", "(", "\\", "in_array", "(", "$", "dependency", ",", "$", "new_data", ")", ")", "{", "unset", "(", "$", "data", "[", "$", "name", "]", "[", "$", "key", "]", ")", ";", "}", "}", "}", "}", "return", "$", "new_data", ";", "}" ]
resolves complicated dependencies to determine what order something can run in start with an array like: array( 'a' => array('b', 'c'), 'b' => array(), 'c' => array('b') ) a depends on b and c, c depends on b, and b depends on nobody in this case we would return array('b', 'c', 'a') @param array $data @return array
[ "resolves", "complicated", "dependencies", "to", "determine", "what", "order", "something", "can", "run", "in" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/Helper/Utils.php#L158-L178
train
agentejo/cockpit
lib/Lime/Helper/Utils.php
Utils.url_get_contents
public function url_get_contents($url) { $content = ''; if (\function_exists('curl_exec')){ $conn = \curl_init($url); \curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, true); \curl_setopt($conn, CURLOPT_FRESH_CONNECT, true); \curl_setopt($conn, CURLOPT_RETURNTRANSFER, 1); \curl_setopt($conn,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17'); \curl_setopt($conn, CURLOPT_AUTOREFERER, true); \curl_setopt($conn, CURLOPT_FOLLOWLOCATION, 1); \curl_setopt($conn, CURLOPT_VERBOSE, 0); $content = (\curl_exec($conn)); \curl_close($conn); } if (!$content && \function_exists('file_get_contents')){ $content = @\file_get_contents($url); } if (!$content && \function_exists('fopen') && function_exists('stream_get_contents')){ $handle = @\fopen ($url, "r"); $content = @\stream_get_contents($handle); } return $content; }
php
public function url_get_contents($url) { $content = ''; if (\function_exists('curl_exec')){ $conn = \curl_init($url); \curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, true); \curl_setopt($conn, CURLOPT_FRESH_CONNECT, true); \curl_setopt($conn, CURLOPT_RETURNTRANSFER, 1); \curl_setopt($conn,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17'); \curl_setopt($conn, CURLOPT_AUTOREFERER, true); \curl_setopt($conn, CURLOPT_FOLLOWLOCATION, 1); \curl_setopt($conn, CURLOPT_VERBOSE, 0); $content = (\curl_exec($conn)); \curl_close($conn); } if (!$content && \function_exists('file_get_contents')){ $content = @\file_get_contents($url); } if (!$content && \function_exists('fopen') && function_exists('stream_get_contents')){ $handle = @\fopen ($url, "r"); $content = @\stream_get_contents($handle); } return $content; }
[ "public", "function", "url_get_contents", "(", "$", "url", ")", "{", "$", "content", "=", "''", ";", "if", "(", "\\", "function_exists", "(", "'curl_exec'", ")", ")", "{", "$", "conn", "=", "\\", "curl_init", "(", "$", "url", ")", ";", "\\", "curl_setopt", "(", "$", "conn", ",", "CURLOPT_SSL_VERIFYPEER", ",", "true", ")", ";", "\\", "curl_setopt", "(", "$", "conn", ",", "CURLOPT_FRESH_CONNECT", ",", "true", ")", ";", "\\", "curl_setopt", "(", "$", "conn", ",", "CURLOPT_RETURNTRANSFER", ",", "1", ")", ";", "\\", "curl_setopt", "(", "$", "conn", ",", "CURLOPT_USERAGENT", ",", "'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17'", ")", ";", "\\", "curl_setopt", "(", "$", "conn", ",", "CURLOPT_AUTOREFERER", ",", "true", ")", ";", "\\", "curl_setopt", "(", "$", "conn", ",", "CURLOPT_FOLLOWLOCATION", ",", "1", ")", ";", "\\", "curl_setopt", "(", "$", "conn", ",", "CURLOPT_VERBOSE", ",", "0", ")", ";", "$", "content", "=", "(", "\\", "curl_exec", "(", "$", "conn", ")", ")", ";", "\\", "curl_close", "(", "$", "conn", ")", ";", "}", "if", "(", "!", "$", "content", "&&", "\\", "function_exists", "(", "'file_get_contents'", ")", ")", "{", "$", "content", "=", "@", "\\", "file_get_contents", "(", "$", "url", ")", ";", "}", "if", "(", "!", "$", "content", "&&", "\\", "function_exists", "(", "'fopen'", ")", "&&", "function_exists", "(", "'stream_get_contents'", ")", ")", "{", "$", "handle", "=", "@", "\\", "fopen", "(", "$", "url", ",", "\"r\"", ")", ";", "$", "content", "=", "@", "\\", "stream_get_contents", "(", "$", "handle", ")", ";", "}", "return", "$", "content", ";", "}" ]
Get content from url source. @param string $url @return string
[ "Get", "content", "from", "url", "source", "." ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/Helper/Utils.php#L235-L259
train
agentejo/cockpit
lib/Lime/Helper/Utils.php
Utils.isEmail
public function isEmail($email) { if (\function_exists('idn_to_ascii')) { $email = @\idn_to_ascii($email); } return (bool) \filter_var($email, FILTER_VALIDATE_EMAIL); }
php
public function isEmail($email) { if (\function_exists('idn_to_ascii')) { $email = @\idn_to_ascii($email); } return (bool) \filter_var($email, FILTER_VALIDATE_EMAIL); }
[ "public", "function", "isEmail", "(", "$", "email", ")", "{", "if", "(", "\\", "function_exists", "(", "'idn_to_ascii'", ")", ")", "{", "$", "email", "=", "@", "\\", "idn_to_ascii", "(", "$", "email", ")", ";", "}", "return", "(", "bool", ")", "\\", "filter_var", "(", "$", "email", ",", "FILTER_VALIDATE_EMAIL", ")", ";", "}" ]
Check if string is valid email @param string $email @return boolean
[ "Check", "if", "string", "is", "valid", "email" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/Helper/Utils.php#L376-L383
train
agentejo/cockpit
lib/Lime/Helper/Utils.php
Utils.fixStringBooleanValues
public function fixStringBooleanValues(&$input) { if (!\is_array($input)) { if (\is_string($input) && ($input === 'true' || $input === 'false')) { $input = filter_var($input, FILTER_VALIDATE_BOOLEAN); } return $input; } foreach ($input as $k => $v) { if (\is_array($input[$k])) { $input[$k] = $this->fixStringBooleanValues($input[$k]); } if (\is_string($v) && ($v === 'true' || $v === 'false')) { $v = \filter_var($v, FILTER_VALIDATE_BOOLEAN); } $input[$k] = $v; } return $input; }
php
public function fixStringBooleanValues(&$input) { if (!\is_array($input)) { if (\is_string($input) && ($input === 'true' || $input === 'false')) { $input = filter_var($input, FILTER_VALIDATE_BOOLEAN); } return $input; } foreach ($input as $k => $v) { if (\is_array($input[$k])) { $input[$k] = $this->fixStringBooleanValues($input[$k]); } if (\is_string($v) && ($v === 'true' || $v === 'false')) { $v = \filter_var($v, FILTER_VALIDATE_BOOLEAN); } $input[$k] = $v; } return $input; }
[ "public", "function", "fixStringBooleanValues", "(", "&", "$", "input", ")", "{", "if", "(", "!", "\\", "is_array", "(", "$", "input", ")", ")", "{", "if", "(", "\\", "is_string", "(", "$", "input", ")", "&&", "(", "$", "input", "===", "'true'", "||", "$", "input", "===", "'false'", ")", ")", "{", "$", "input", "=", "filter_var", "(", "$", "input", ",", "FILTER_VALIDATE_BOOLEAN", ")", ";", "}", "return", "$", "input", ";", "}", "foreach", "(", "$", "input", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "\\", "is_array", "(", "$", "input", "[", "$", "k", "]", ")", ")", "{", "$", "input", "[", "$", "k", "]", "=", "$", "this", "->", "fixStringBooleanValues", "(", "$", "input", "[", "$", "k", "]", ")", ";", "}", "if", "(", "\\", "is_string", "(", "$", "v", ")", "&&", "(", "$", "v", "===", "'true'", "||", "$", "v", "===", "'false'", ")", ")", "{", "$", "v", "=", "\\", "filter_var", "(", "$", "v", ",", "FILTER_VALIDATE_BOOLEAN", ")", ";", "}", "$", "input", "[", "$", "k", "]", "=", "$", "v", ";", "}", "return", "$", "input", ";", "}" ]
Cast boolean string values to boolean @param mixed $input @return mixed
[ "Cast", "boolean", "string", "values", "to", "boolean" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/Helper/Utils.php#L390-L414
train
agentejo/cockpit
lib/Lime/Helper/Utils.php
Utils.fixStringNumericValues
public function fixStringNumericValues(&$input) { if (!\is_array($input)) { if (\is_string($input) && \is_numeric($input)) { $input += 0; } return $input; } foreach ($input as $k => $v) { if (\is_array($input[$k])) { $input[$k] = $this->fixStringNumericValues($input[$k]); } if (\is_string($v) && \is_numeric($v)) { $v += 0; } $input[$k] = $v; } return $input; }
php
public function fixStringNumericValues(&$input) { if (!\is_array($input)) { if (\is_string($input) && \is_numeric($input)) { $input += 0; } return $input; } foreach ($input as $k => $v) { if (\is_array($input[$k])) { $input[$k] = $this->fixStringNumericValues($input[$k]); } if (\is_string($v) && \is_numeric($v)) { $v += 0; } $input[$k] = $v; } return $input; }
[ "public", "function", "fixStringNumericValues", "(", "&", "$", "input", ")", "{", "if", "(", "!", "\\", "is_array", "(", "$", "input", ")", ")", "{", "if", "(", "\\", "is_string", "(", "$", "input", ")", "&&", "\\", "is_numeric", "(", "$", "input", ")", ")", "{", "$", "input", "+=", "0", ";", "}", "return", "$", "input", ";", "}", "foreach", "(", "$", "input", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "\\", "is_array", "(", "$", "input", "[", "$", "k", "]", ")", ")", "{", "$", "input", "[", "$", "k", "]", "=", "$", "this", "->", "fixStringNumericValues", "(", "$", "input", "[", "$", "k", "]", ")", ";", "}", "if", "(", "\\", "is_string", "(", "$", "v", ")", "&&", "\\", "is_numeric", "(", "$", "v", ")", ")", "{", "$", "v", "+=", "0", ";", "}", "$", "input", "[", "$", "k", "]", "=", "$", "v", ";", "}", "return", "$", "input", ";", "}" ]
Cast numeric string values to numbers @param mixed $input @return mixed
[ "Cast", "numeric", "string", "values", "to", "numbers" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/Helper/Utils.php#L421-L445
train
agentejo/cockpit
lib/Lime/Helper/Utils.php
Utils.retry
public function retry($times, callable $fn) { retrybeginning: try { return $fn(); } catch (\Exception $e) { if (!$times) { throw new \Exception('', 0, $e); } $times--; goto retrybeginning; } }
php
public function retry($times, callable $fn) { retrybeginning: try { return $fn(); } catch (\Exception $e) { if (!$times) { throw new \Exception('', 0, $e); } $times--; goto retrybeginning; } }
[ "public", "function", "retry", "(", "$", "times", ",", "callable", "$", "fn", ")", "{", "retrybeginning", ":", "try", "{", "return", "$", "fn", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "if", "(", "!", "$", "times", ")", "{", "throw", "new", "\\", "Exception", "(", "''", ",", "0", ",", "$", "e", ")", ";", "}", "$", "times", "--", ";", "goto", "retrybeginning", ";", "}", "}" ]
Execute callable with retry if it fails @param int $times @param callable $fn @return null
[ "Execute", "callable", "with", "retry", "if", "it", "fails" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/Helper/Utils.php#L453-L465
train
agentejo/cockpit
lib/Lime/Helper/Assets.php
Assets.style
public function style($assets, $name, $path="", $cache=0, $version=false) { $path = $this->path($path); if(!$path) return null; $href = rtrim($this->pathToUrl($path), '/')."/{$name}.css".($version ? "?ver={$version}":""); $path.= "/{$name}.css"; $tag = '<link href="'.$href.'" type="text/css" rel="stylesheet" />'."\n"; if($cache && file_exists($path) && (time() - filemtime($path)) < $cache) { return $tag; } $result = $this->compile($assets, "css"); if ($result) { file_put_contents($path, $result); return $tag; } return null; }
php
public function style($assets, $name, $path="", $cache=0, $version=false) { $path = $this->path($path); if(!$path) return null; $href = rtrim($this->pathToUrl($path), '/')."/{$name}.css".($version ? "?ver={$version}":""); $path.= "/{$name}.css"; $tag = '<link href="'.$href.'" type="text/css" rel="stylesheet" />'."\n"; if($cache && file_exists($path) && (time() - filemtime($path)) < $cache) { return $tag; } $result = $this->compile($assets, "css"); if ($result) { file_put_contents($path, $result); return $tag; } return null; }
[ "public", "function", "style", "(", "$", "assets", ",", "$", "name", ",", "$", "path", "=", "\"\"", ",", "$", "cache", "=", "0", ",", "$", "version", "=", "false", ")", "{", "$", "path", "=", "$", "this", "->", "path", "(", "$", "path", ")", ";", "if", "(", "!", "$", "path", ")", "return", "null", ";", "$", "href", "=", "rtrim", "(", "$", "this", "->", "pathToUrl", "(", "$", "path", ")", ",", "'/'", ")", ".", "\"/{$name}.css\"", ".", "(", "$", "version", "?", "\"?ver={$version}\"", ":", "\"\"", ")", ";", "$", "path", ".=", "\"/{$name}.css\"", ";", "$", "tag", "=", "'<link href=\"'", ".", "$", "href", ".", "'\" type=\"text/css\" rel=\"stylesheet\" />'", ".", "\"\\n\"", ";", "if", "(", "$", "cache", "&&", "file_exists", "(", "$", "path", ")", "&&", "(", "time", "(", ")", "-", "filemtime", "(", "$", "path", ")", ")", "<", "$", "cache", ")", "{", "return", "$", "tag", ";", "}", "$", "result", "=", "$", "this", "->", "compile", "(", "$", "assets", ",", "\"css\"", ")", ";", "if", "(", "$", "result", ")", "{", "file_put_contents", "(", "$", "path", ",", "$", "result", ")", ";", "return", "$", "tag", ";", "}", "return", "null", ";", "}" ]
Compile styles and return in a link tag @param Array $assets @param String $name @param String $path @param Float $cache @param Boolean $version @return String
[ "Compile", "styles", "and", "return", "in", "a", "link", "tag" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/Helper/Assets.php#L28-L49
train
agentejo/cockpit
lib/Lime/Helper/Assets.php
Assets.style_and_script
public function style_and_script($assets, $name, $path="", $cache=0, $version=false) { echo $this->script($assets, $name, $path, $cache, $version); echo $this->style($assets, $name, $path, $cache, $version); }
php
public function style_and_script($assets, $name, $path="", $cache=0, $version=false) { echo $this->script($assets, $name, $path, $cache, $version); echo $this->style($assets, $name, $path, $cache, $version); }
[ "public", "function", "style_and_script", "(", "$", "assets", ",", "$", "name", ",", "$", "path", "=", "\"\"", ",", "$", "cache", "=", "0", ",", "$", "version", "=", "false", ")", "{", "echo", "$", "this", "->", "script", "(", "$", "assets", ",", "$", "name", ",", "$", "path", ",", "$", "cache", ",", "$", "version", ")", ";", "echo", "$", "this", "->", "style", "(", "$", "assets", ",", "$", "name", ",", "$", "path", ",", "$", "cache", ",", "$", "version", ")", ";", "}" ]
Echo tags for scripts and styles @param Array $assets @param String $name @param String $path @param Float $cache @param Boolean $version @return void
[ "Echo", "tags", "for", "scripts", "and", "styles" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/Helper/Assets.php#L94-L97
train
agentejo/cockpit
lib/Lexy.php
Lexy.compile_default_structures
protected function compile_default_structures($value) { $value = preg_replace('/(?(R)\((?:[^\(\)]|(?R))*\)|(?<!\w)(\s*)@(if|foreach|for|while)(\s*(?R)+))/', '$1<?php $2 $3 { ?>', $value); $value = preg_replace('/(\s*)@elseif(\s*\(.*\))/', '$1<?php } elseif$2 { ?>', $value); $value = preg_replace('/(\s*)@(endif|endforeach|endfor|endwhile)(\s*)/', '$1<?php } ?>$3', $value); $value = preg_replace('/(\s*)@(end)(\s*)/', '$1<?php } ?>$3', $value); return $value; }
php
protected function compile_default_structures($value) { $value = preg_replace('/(?(R)\((?:[^\(\)]|(?R))*\)|(?<!\w)(\s*)@(if|foreach|for|while)(\s*(?R)+))/', '$1<?php $2 $3 { ?>', $value); $value = preg_replace('/(\s*)@elseif(\s*\(.*\))/', '$1<?php } elseif$2 { ?>', $value); $value = preg_replace('/(\s*)@(endif|endforeach|endfor|endwhile)(\s*)/', '$1<?php } ?>$3', $value); $value = preg_replace('/(\s*)@(end)(\s*)/', '$1<?php } ?>$3', $value); return $value; }
[ "protected", "function", "compile_default_structures", "(", "$", "value", ")", "{", "$", "value", "=", "preg_replace", "(", "'/(?(R)\\((?:[^\\(\\)]|(?R))*\\)|(?<!\\w)(\\s*)@(if|foreach|for|while)(\\s*(?R)+))/'", ",", "'$1<?php $2 $3 { ?>'", ",", "$", "value", ")", ";", "$", "value", "=", "preg_replace", "(", "'/(\\s*)@elseif(\\s*\\(.*\\))/'", ",", "'$1<?php } elseif$2 { ?>'", ",", "$", "value", ")", ";", "$", "value", "=", "preg_replace", "(", "'/(\\s*)@(endif|endforeach|endfor|endwhile)(\\s*)/'", ",", "'$1<?php } ?>$3'", ",", "$", "value", ")", ";", "$", "value", "=", "preg_replace", "(", "'/(\\s*)@(end)(\\s*)/'", ",", "'$1<?php } ?>$3'", ",", "$", "value", ")", ";", "return", "$", "value", ";", "}" ]
Rewrites Lexi's structure openings into PHP structure openings. @param string $value @return string
[ "Rewrites", "Lexi", "s", "structure", "openings", "into", "PHP", "structure", "openings", "." ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lexy.php#L373-L381
train
agentejo/cockpit
lib/RedisLite.php
RedisLite.keys
public function keys($pattern = null) { $keys = array(); $stmt = $this->connection->query("SELECT `key` FROM ".$this->table." ORDER BY `key`;"); $res = $stmt->fetchAll(\PDO::FETCH_ASSOC); if (!$pattern) { foreach ($res as $record) { $keys[] = $record["key"]; } } else { $matcher = function_exists('fnmatch') ? 'fnmatch': function($pattern, $string){ return preg_match("#^".strtr(preg_quote($pattern, '#'), array('\*' => '.*', '\?' => '.'))."$#i", $string); }; foreach ($res as $record) { if($matcher($pattern, $record["key"])) { $keys[] = $record["key"]; } } } return $keys; }
php
public function keys($pattern = null) { $keys = array(); $stmt = $this->connection->query("SELECT `key` FROM ".$this->table." ORDER BY `key`;"); $res = $stmt->fetchAll(\PDO::FETCH_ASSOC); if (!$pattern) { foreach ($res as $record) { $keys[] = $record["key"]; } } else { $matcher = function_exists('fnmatch') ? 'fnmatch': function($pattern, $string){ return preg_match("#^".strtr(preg_quote($pattern, '#'), array('\*' => '.*', '\?' => '.'))."$#i", $string); }; foreach ($res as $record) { if($matcher($pattern, $record["key"])) { $keys[] = $record["key"]; } } } return $keys; }
[ "public", "function", "keys", "(", "$", "pattern", "=", "null", ")", "{", "$", "keys", "=", "array", "(", ")", ";", "$", "stmt", "=", "$", "this", "->", "connection", "->", "query", "(", "\"SELECT `key` FROM \"", ".", "$", "this", "->", "table", ".", "\" ORDER BY `key`;\"", ")", ";", "$", "res", "=", "$", "stmt", "->", "fetchAll", "(", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "if", "(", "!", "$", "pattern", ")", "{", "foreach", "(", "$", "res", "as", "$", "record", ")", "{", "$", "keys", "[", "]", "=", "$", "record", "[", "\"key\"", "]", ";", "}", "}", "else", "{", "$", "matcher", "=", "function_exists", "(", "'fnmatch'", ")", "?", "'fnmatch'", ":", "function", "(", "$", "pattern", ",", "$", "string", ")", "{", "return", "preg_match", "(", "\"#^\"", ".", "strtr", "(", "preg_quote", "(", "$", "pattern", ",", "'#'", ")", ",", "array", "(", "'\\*'", "=>", "'.*'", ",", "'\\?'", "=>", "'.'", ")", ")", ".", "\"$#i\"", ",", "$", "string", ")", ";", "}", ";", "foreach", "(", "$", "res", "as", "$", "record", ")", "{", "if", "(", "$", "matcher", "(", "$", "pattern", ",", "$", "record", "[", "\"key\"", "]", ")", ")", "{", "$", "keys", "[", "]", "=", "$", "record", "[", "\"key\"", "]", ";", "}", "}", "}", "return", "$", "keys", ";", "}" ]
Get all keys matching a pattern @param string $pattern @return array
[ "Get", "all", "keys", "matching", "a", "pattern" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/RedisLite.php#L120-L146
train
agentejo/cockpit
lib/MongoLite/Database.php
Database.registerCriteriaFunction
public function registerCriteriaFunction($criteria) { $id = \uniqid('criteria'); if (\is_callable($criteria)) { $this->document_criterias[$id] = $criteria; return $id; } if (is_array($criteria)) { $fn = null; eval('$fn = function($document) { return '.UtilArrayQuery::buildCondition($criteria).'; };'); $this->document_criterias[$id] = $fn; return $id; } return null; }
php
public function registerCriteriaFunction($criteria) { $id = \uniqid('criteria'); if (\is_callable($criteria)) { $this->document_criterias[$id] = $criteria; return $id; } if (is_array($criteria)) { $fn = null; eval('$fn = function($document) { return '.UtilArrayQuery::buildCondition($criteria).'; };'); $this->document_criterias[$id] = $fn; return $id; } return null; }
[ "public", "function", "registerCriteriaFunction", "(", "$", "criteria", ")", "{", "$", "id", "=", "\\", "uniqid", "(", "'criteria'", ")", ";", "if", "(", "\\", "is_callable", "(", "$", "criteria", ")", ")", "{", "$", "this", "->", "document_criterias", "[", "$", "id", "]", "=", "$", "criteria", ";", "return", "$", "id", ";", "}", "if", "(", "is_array", "(", "$", "criteria", ")", ")", "{", "$", "fn", "=", "null", ";", "eval", "(", "'$fn = function($document) { return '", ".", "UtilArrayQuery", "::", "buildCondition", "(", "$", "criteria", ")", ".", "'; };'", ")", ";", "$", "this", "->", "document_criterias", "[", "$", "id", "]", "=", "$", "fn", ";", "return", "$", "id", ";", "}", "return", "null", ";", "}" ]
Register Criteria function @param mixed $criteria @return mixed
[ "Register", "Criteria", "function" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/MongoLite/Database.php#L99-L120
train
agentejo/cockpit
lib/MongoLite/Database.php
Database.callCriteriaFunction
public function callCriteriaFunction($id, $document) { return isset($this->document_criterias[$id]) ? $this->document_criterias[$id]($document):false; }
php
public function callCriteriaFunction($id, $document) { return isset($this->document_criterias[$id]) ? $this->document_criterias[$id]($document):false; }
[ "public", "function", "callCriteriaFunction", "(", "$", "id", ",", "$", "document", ")", "{", "return", "isset", "(", "$", "this", "->", "document_criterias", "[", "$", "id", "]", ")", "?", "$", "this", "->", "document_criterias", "[", "$", "id", "]", "(", "$", "document", ")", ":", "false", ";", "}" ]
Execute registred criteria function @param string $id @param array $document @return boolean
[ "Execute", "registred", "criteria", "function" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/MongoLite/Database.php#L129-L132
train
agentejo/cockpit
lib/MongoLite/Database.php
Database.getCollectionNames
public function getCollectionNames() { $stmt = $this->connection->query("SELECT name FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence';"); $tables = $stmt->fetchAll( \PDO::FETCH_ASSOC); $names = []; foreach ($tables as $table) { $names[] = $table['name']; } return $names; }
php
public function getCollectionNames() { $stmt = $this->connection->query("SELECT name FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence';"); $tables = $stmt->fetchAll( \PDO::FETCH_ASSOC); $names = []; foreach ($tables as $table) { $names[] = $table['name']; } return $names; }
[ "public", "function", "getCollectionNames", "(", ")", "{", "$", "stmt", "=", "$", "this", "->", "connection", "->", "query", "(", "\"SELECT name FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence';\"", ")", ";", "$", "tables", "=", "$", "stmt", "->", "fetchAll", "(", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "$", "names", "=", "[", "]", ";", "foreach", "(", "$", "tables", "as", "$", "table", ")", "{", "$", "names", "[", "]", "=", "$", "table", "[", "'name'", "]", ";", "}", "return", "$", "names", ";", "}" ]
Get all collection names in the database @return array
[ "Get", "all", "collection", "names", "in", "the", "database" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/MongoLite/Database.php#L173-L184
train
agentejo/cockpit
lib/MongoLite/Database.php
Database.listCollections
public function listCollections() { foreach ($this->getCollectionNames() as $name) { if(!isset($this->collections[$name])) { $this->collections[$name] = new Collection($name, $this); } } return $this->collections; }
php
public function listCollections() { foreach ($this->getCollectionNames() as $name) { if(!isset($this->collections[$name])) { $this->collections[$name] = new Collection($name, $this); } } return $this->collections; }
[ "public", "function", "listCollections", "(", ")", "{", "foreach", "(", "$", "this", "->", "getCollectionNames", "(", ")", "as", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "collections", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "collections", "[", "$", "name", "]", "=", "new", "Collection", "(", "$", "name", ",", "$", "this", ")", ";", "}", "}", "return", "$", "this", "->", "collections", ";", "}" ]
Get all collections in the database @return array
[ "Get", "all", "collections", "in", "the", "database" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/MongoLite/Database.php#L191-L200
train
agentejo/cockpit
lib/Lime/Helper/Cookie.php
Cookie.set
public function set($name, $value, $ttl = 86400 /* 1 day */, $path = '/', $domain = '', $secure = false, $http_only = false) { $this->_cookies[$name] = $value; $result = \setcookie($name, $value, time() + $ttl, $path, $domain, $secure, $http_only); if (isset($this->_deleted_cookies[$name])) { unset($this->_deleted_cookies[$name]); } return $result; }
php
public function set($name, $value, $ttl = 86400 /* 1 day */, $path = '/', $domain = '', $secure = false, $http_only = false) { $this->_cookies[$name] = $value; $result = \setcookie($name, $value, time() + $ttl, $path, $domain, $secure, $http_only); if (isset($this->_deleted_cookies[$name])) { unset($this->_deleted_cookies[$name]); } return $result; }
[ "public", "function", "set", "(", "$", "name", ",", "$", "value", ",", "$", "ttl", "=", "86400", "/* 1 day */", ",", "$", "path", "=", "'/'", ",", "$", "domain", "=", "''", ",", "$", "secure", "=", "false", ",", "$", "http_only", "=", "false", ")", "{", "$", "this", "->", "_cookies", "[", "$", "name", "]", "=", "$", "value", ";", "$", "result", "=", "\\", "setcookie", "(", "$", "name", ",", "$", "value", ",", "time", "(", ")", "+", "$", "ttl", ",", "$", "path", ",", "$", "domain", ",", "$", "secure", ",", "$", "http_only", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "_deleted_cookies", "[", "$", "name", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "_deleted_cookies", "[", "$", "name", "]", ")", ";", "}", "return", "$", "result", ";", "}" ]
sets a cookie @param string $name @param string $value @param mixed $ttl @param string $path @param string $domain @param bool $secure @param bool $http_only @return bool
[ "sets", "a", "cookie" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/Helper/Cookie.php#L36-L45
train
agentejo/cockpit
lib/Lime/Helper/Cookie.php
Cookie.get
public function get($name) { if (isset($this->_deleted_cookies[$name])) { return null; } if (\array_key_exists($name, $this->_cookies)) { return $this->_cookies[$name]; } $value = isset($_COOKIE[$name]) ? $_COOKIE[$name] : null; $this->_cookies[$name] = $value; return $value; }
php
public function get($name) { if (isset($this->_deleted_cookies[$name])) { return null; } if (\array_key_exists($name, $this->_cookies)) { return $this->_cookies[$name]; } $value = isset($_COOKIE[$name]) ? $_COOKIE[$name] : null; $this->_cookies[$name] = $value; return $value; }
[ "public", "function", "get", "(", "$", "name", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_deleted_cookies", "[", "$", "name", "]", ")", ")", "{", "return", "null", ";", "}", "if", "(", "\\", "array_key_exists", "(", "$", "name", ",", "$", "this", "->", "_cookies", ")", ")", "{", "return", "$", "this", "->", "_cookies", "[", "$", "name", "]", ";", "}", "$", "value", "=", "isset", "(", "$", "_COOKIE", "[", "$", "name", "]", ")", "?", "$", "_COOKIE", "[", "$", "name", "]", ":", "null", ";", "$", "this", "->", "_cookies", "[", "$", "name", "]", "=", "$", "value", ";", "return", "$", "value", ";", "}" ]
gets a cookie @param string $name @return mixed
[ "gets", "a", "cookie" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/Helper/Cookie.php#L53-L66
train
agentejo/cockpit
lib/Lime/Helper/Cookie.php
Cookie.delete
public function delete($name, $path = '/', $domain = '', $secure = false, $http_only = false) { $success = $this->set($name, null, -10, $path, $domain, $secure, $http_only); $this->_deleted_cookies[$name] = $name; if (isset($this->_cookies[$name])) { unset($this->_cookies[$name]); } return $success; }
php
public function delete($name, $path = '/', $domain = '', $secure = false, $http_only = false) { $success = $this->set($name, null, -10, $path, $domain, $secure, $http_only); $this->_deleted_cookies[$name] = $name; if (isset($this->_cookies[$name])) { unset($this->_cookies[$name]); } return $success; }
[ "public", "function", "delete", "(", "$", "name", ",", "$", "path", "=", "'/'", ",", "$", "domain", "=", "''", ",", "$", "secure", "=", "false", ",", "$", "http_only", "=", "false", ")", "{", "$", "success", "=", "$", "this", "->", "set", "(", "$", "name", ",", "null", ",", "-", "10", ",", "$", "path", ",", "$", "domain", ",", "$", "secure", ",", "$", "http_only", ")", ";", "$", "this", "->", "_deleted_cookies", "[", "$", "name", "]", "=", "$", "name", ";", "if", "(", "isset", "(", "$", "this", "->", "_cookies", "[", "$", "name", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "_cookies", "[", "$", "name", "]", ")", ";", "}", "return", "$", "success", ";", "}" ]
deletes a cookie @param string $name @return bool
[ "deletes", "a", "cookie" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/Helper/Cookie.php#L74-L83
train
agentejo/cockpit
lib/Lime/Helper/Cookie.php
Cookie.getAndDelete
public function getAndDelete($name, $path = '/', $domain = '', $secure = false, $http_only = false) { $value = $this->get($name); $this->delete($name, $path, $domain, $secure, $http_only); return $value; }
php
public function getAndDelete($name, $path = '/', $domain = '', $secure = false, $http_only = false) { $value = $this->get($name); $this->delete($name, $path, $domain, $secure, $http_only); return $value; }
[ "public", "function", "getAndDelete", "(", "$", "name", ",", "$", "path", "=", "'/'", ",", "$", "domain", "=", "''", ",", "$", "secure", "=", "false", ",", "$", "http_only", "=", "false", ")", "{", "$", "value", "=", "$", "this", "->", "get", "(", "$", "name", ")", ";", "$", "this", "->", "delete", "(", "$", "name", ",", "$", "path", ",", "$", "domain", ",", "$", "secure", ",", "$", "http_only", ")", ";", "return", "$", "value", ";", "}" ]
gets a cookie and eats it @param string $name @return mixed
[ "gets", "a", "cookie", "and", "eats", "it" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/Helper/Cookie.php#L91-L96
train
agentejo/cockpit
lib/MongoLite/Cursor.php
Cursor.getData
protected function getData() { $sql = ['SELECT document FROM '.$this->collection->name]; if ($this->criteria) { $sql[] = 'WHERE document_criteria("'.$this->criteria.'", document)'; } if ($this->sort) { $orders = []; foreach ($this->sort as $field => $direction) { $orders[] = 'document_key("'.$field.'", document) '.($direction==-1 ? 'DESC':'ASC'); } $sql[] = 'ORDER BY '.\implode(',', $orders); } if ($this->limit) { $sql[] = 'LIMIT '.$this->limit; if ($this->skip) { $sql[] = 'OFFSET '.$this->skip; } } $sql = implode(' ', $sql); $stmt = $this->collection->database->connection->query($sql); $result = $stmt->fetchAll( \PDO::FETCH_ASSOC); $documents = []; if (!$this->projection) { foreach ($result as &$doc) { $documents[] = \json_decode($doc['document'], true); } } else { $exclude = []; $include = []; foreach ($this->projection as $key => $value) { if ($value) { $include[$key] = 1; } else { $exclude[$key] = 1; } } foreach ($result as &$doc) { $item = \json_decode($doc['document'], true); $id = $item['_id']; if ($exclude) { $item = \array_diff_key($item, $exclude); } if ($include) { $item = array_key_intersect($item, $include); } if (!isset($exclude['_id'])) { $item['_id'] = $id; } $documents[] = $item; } } return $documents; }
php
protected function getData() { $sql = ['SELECT document FROM '.$this->collection->name]; if ($this->criteria) { $sql[] = 'WHERE document_criteria("'.$this->criteria.'", document)'; } if ($this->sort) { $orders = []; foreach ($this->sort as $field => $direction) { $orders[] = 'document_key("'.$field.'", document) '.($direction==-1 ? 'DESC':'ASC'); } $sql[] = 'ORDER BY '.\implode(',', $orders); } if ($this->limit) { $sql[] = 'LIMIT '.$this->limit; if ($this->skip) { $sql[] = 'OFFSET '.$this->skip; } } $sql = implode(' ', $sql); $stmt = $this->collection->database->connection->query($sql); $result = $stmt->fetchAll( \PDO::FETCH_ASSOC); $documents = []; if (!$this->projection) { foreach ($result as &$doc) { $documents[] = \json_decode($doc['document'], true); } } else { $exclude = []; $include = []; foreach ($this->projection as $key => $value) { if ($value) { $include[$key] = 1; } else { $exclude[$key] = 1; } } foreach ($result as &$doc) { $item = \json_decode($doc['document'], true); $id = $item['_id']; if ($exclude) { $item = \array_diff_key($item, $exclude); } if ($include) { $item = array_key_intersect($item, $include); } if (!isset($exclude['_id'])) { $item['_id'] = $id; } $documents[] = $item; } } return $documents; }
[ "protected", "function", "getData", "(", ")", "{", "$", "sql", "=", "[", "'SELECT document FROM '", ".", "$", "this", "->", "collection", "->", "name", "]", ";", "if", "(", "$", "this", "->", "criteria", ")", "{", "$", "sql", "[", "]", "=", "'WHERE document_criteria(\"'", ".", "$", "this", "->", "criteria", ".", "'\", document)'", ";", "}", "if", "(", "$", "this", "->", "sort", ")", "{", "$", "orders", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "sort", "as", "$", "field", "=>", "$", "direction", ")", "{", "$", "orders", "[", "]", "=", "'document_key(\"'", ".", "$", "field", ".", "'\", document) '", ".", "(", "$", "direction", "==", "-", "1", "?", "'DESC'", ":", "'ASC'", ")", ";", "}", "$", "sql", "[", "]", "=", "'ORDER BY '", ".", "\\", "implode", "(", "','", ",", "$", "orders", ")", ";", "}", "if", "(", "$", "this", "->", "limit", ")", "{", "$", "sql", "[", "]", "=", "'LIMIT '", ".", "$", "this", "->", "limit", ";", "if", "(", "$", "this", "->", "skip", ")", "{", "$", "sql", "[", "]", "=", "'OFFSET '", ".", "$", "this", "->", "skip", ";", "}", "}", "$", "sql", "=", "implode", "(", "' '", ",", "$", "sql", ")", ";", "$", "stmt", "=", "$", "this", "->", "collection", "->", "database", "->", "connection", "->", "query", "(", "$", "sql", ")", ";", "$", "result", "=", "$", "stmt", "->", "fetchAll", "(", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "$", "documents", "=", "[", "]", ";", "if", "(", "!", "$", "this", "->", "projection", ")", "{", "foreach", "(", "$", "result", "as", "&", "$", "doc", ")", "{", "$", "documents", "[", "]", "=", "\\", "json_decode", "(", "$", "doc", "[", "'document'", "]", ",", "true", ")", ";", "}", "}", "else", "{", "$", "exclude", "=", "[", "]", ";", "$", "include", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "projection", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "value", ")", "{", "$", "include", "[", "$", "key", "]", "=", "1", ";", "}", "else", "{", "$", "exclude", "[", "$", "key", "]", "=", "1", ";", "}", "}", "foreach", "(", "$", "result", "as", "&", "$", "doc", ")", "{", "$", "item", "=", "\\", "json_decode", "(", "$", "doc", "[", "'document'", "]", ",", "true", ")", ";", "$", "id", "=", "$", "item", "[", "'_id'", "]", ";", "if", "(", "$", "exclude", ")", "{", "$", "item", "=", "\\", "array_diff_key", "(", "$", "item", ",", "$", "exclude", ")", ";", "}", "if", "(", "$", "include", ")", "{", "$", "item", "=", "array_key_intersect", "(", "$", "item", ",", "$", "include", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "exclude", "[", "'_id'", "]", ")", ")", "{", "$", "item", "[", "'_id'", "]", "=", "$", "id", ";", "}", "$", "documents", "[", "]", "=", "$", "item", ";", "}", "}", "return", "$", "documents", ";", "}" ]
Get documents matching criteria @return array
[ "Get", "documents", "matching", "criteria" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/MongoLite/Cursor.php#L168-L242
train
agentejo/cockpit
lib/Lime/Helper/I18n.php
I18n.get
public function get($key, $alternative=null, $lang=null){ if (!$lang) { $lang = $this->locale; } if (!$alternative){ $alternative = $key; } return isset($this->_languages[$lang][$key]) ? $this->_languages[$lang][$key]:$alternative; }
php
public function get($key, $alternative=null, $lang=null){ if (!$lang) { $lang = $this->locale; } if (!$alternative){ $alternative = $key; } return isset($this->_languages[$lang][$key]) ? $this->_languages[$lang][$key]:$alternative; }
[ "public", "function", "get", "(", "$", "key", ",", "$", "alternative", "=", "null", ",", "$", "lang", "=", "null", ")", "{", "if", "(", "!", "$", "lang", ")", "{", "$", "lang", "=", "$", "this", "->", "locale", ";", "}", "if", "(", "!", "$", "alternative", ")", "{", "$", "alternative", "=", "$", "key", ";", "}", "return", "isset", "(", "$", "this", "->", "_languages", "[", "$", "lang", "]", "[", "$", "key", "]", ")", "?", "$", "this", "->", "_languages", "[", "$", "lang", "]", "[", "$", "key", "]", ":", "$", "alternative", ";", "}" ]
Get translated string by key @param string $key translation key @param array $alternative returns if $key doesn''t exist @return string
[ "Get", "translated", "string", "by", "key" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/Helper/I18n.php#L556-L567
train
agentejo/cockpit
lib/Lime/Helper/I18n.php
I18n.getstr
public function getstr($key, $params=[], $alternative=null, $lang=null){ if (!$lang) { $lang = $this->locale; } if (!$alternative){ $alternative = $key; } return \vsprintf(isset($this->_languages[$lang][$key]) ? $this->_languages[$lang][$key]:$alternative, $params); }
php
public function getstr($key, $params=[], $alternative=null, $lang=null){ if (!$lang) { $lang = $this->locale; } if (!$alternative){ $alternative = $key; } return \vsprintf(isset($this->_languages[$lang][$key]) ? $this->_languages[$lang][$key]:$alternative, $params); }
[ "public", "function", "getstr", "(", "$", "key", ",", "$", "params", "=", "[", "]", ",", "$", "alternative", "=", "null", ",", "$", "lang", "=", "null", ")", "{", "if", "(", "!", "$", "lang", ")", "{", "$", "lang", "=", "$", "this", "->", "locale", ";", "}", "if", "(", "!", "$", "alternative", ")", "{", "$", "alternative", "=", "$", "key", ";", "}", "return", "\\", "vsprintf", "(", "isset", "(", "$", "this", "->", "_languages", "[", "$", "lang", "]", "[", "$", "key", "]", ")", "?", "$", "this", "->", "_languages", "[", "$", "lang", "]", "[", "$", "key", "]", ":", "$", "alternative", ",", "$", "params", ")", ";", "}" ]
Get translated string by key and params @param string $key translation key @param array $params @param array $alternative returns if $key doesn''t exist @return string
[ "Get", "translated", "string", "by", "key", "and", "params" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/Helper/I18n.php#L577-L588
train
agentejo/cockpit
lib/Lime/Helper/I18n.php
I18n.load
public function load($langfile, $lang=null) { if (!$lang) { $lang = $this->locale; } if ($path = $this->app->path($langfile)){ if (!isset($this->_languages[$lang])){ $this->_languages[$lang] = []; } $langtable = include($path); $this->_languages[$lang] = \array_merge($this->_languages[$lang], (array)$langtable); return true; } return false; }
php
public function load($langfile, $lang=null) { if (!$lang) { $lang = $this->locale; } if ($path = $this->app->path($langfile)){ if (!isset($this->_languages[$lang])){ $this->_languages[$lang] = []; } $langtable = include($path); $this->_languages[$lang] = \array_merge($this->_languages[$lang], (array)$langtable); return true; } return false; }
[ "public", "function", "load", "(", "$", "langfile", ",", "$", "lang", "=", "null", ")", "{", "if", "(", "!", "$", "lang", ")", "{", "$", "lang", "=", "$", "this", "->", "locale", ";", "}", "if", "(", "$", "path", "=", "$", "this", "->", "app", "->", "path", "(", "$", "langfile", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_languages", "[", "$", "lang", "]", ")", ")", "{", "$", "this", "->", "_languages", "[", "$", "lang", "]", "=", "[", "]", ";", "}", "$", "langtable", "=", "include", "(", "$", "path", ")", ";", "$", "this", "->", "_languages", "[", "$", "lang", "]", "=", "\\", "array_merge", "(", "$", "this", "->", "_languages", "[", "$", "lang", "]", ",", "(", "array", ")", "$", "langtable", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Load language files @param string $langfile path to language file @param string $lang language to merge to @return boolean
[ "Load", "language", "files" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/Helper/I18n.php#L597-L617
train
agentejo/cockpit
lib/Lime/Helper/I18n.php
I18n.data
public function data($lang=null) { if ($lang) { return isset($this->_languages[$lang]) ? $this->_languages[$lang] : []; } return $this->_languages; }
php
public function data($lang=null) { if ($lang) { return isset($this->_languages[$lang]) ? $this->_languages[$lang] : []; } return $this->_languages; }
[ "public", "function", "data", "(", "$", "lang", "=", "null", ")", "{", "if", "(", "$", "lang", ")", "{", "return", "isset", "(", "$", "this", "->", "_languages", "[", "$", "lang", "]", ")", "?", "$", "this", "->", "_languages", "[", "$", "lang", "]", ":", "[", "]", ";", "}", "return", "$", "this", "->", "_languages", ";", "}" ]
Get language data @param string $lang language @return array
[ "Get", "language", "data" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/Lime/Helper/I18n.php#L624-L631
train
agentejo/cockpit
lib/MongoHybrid/Client.php
Client.hincrby
public function hincrby($collection, $key, $field, $by = 1) { $current = $this->hget($collection, $key, $field, 0); $newone = $current+$by; $this->hset($collection, $key, $field, $newone); return $newone; }
php
public function hincrby($collection, $key, $field, $by = 1) { $current = $this->hget($collection, $key, $field, 0); $newone = $current+$by; $this->hset($collection, $key, $field, $newone); return $newone; }
[ "public", "function", "hincrby", "(", "$", "collection", ",", "$", "key", ",", "$", "field", ",", "$", "by", "=", "1", ")", "{", "$", "current", "=", "$", "this", "->", "hget", "(", "$", "collection", ",", "$", "key", ",", "$", "field", ",", "0", ")", ";", "$", "newone", "=", "$", "current", "+", "$", "by", ";", "$", "this", "->", "hset", "(", "$", "collection", ",", "$", "key", ",", "$", "field", ",", "$", "newone", ")", ";", "return", "$", "newone", ";", "}" ]
Increment the integer value of a hash field by the given number @param string $key @param string $field @param integer $by @return integer
[ "Increment", "the", "integer", "value", "of", "a", "hash", "field", "by", "the", "given", "number" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/MongoHybrid/Client.php#L372-L380
train
agentejo/cockpit
lib/MongoHybrid/Client.php
Client.hmget
public function hmget($key) { $set = $this->getKey($collection, $key, []); $fields = func_get_args(); $values = []; for ($i=1; $i<count($fields); $i++){ $field = $fields[$i]; $values[] = isset($set[$field]) ? $set[$field]:null; } return $values; }
php
public function hmget($key) { $set = $this->getKey($collection, $key, []); $fields = func_get_args(); $values = []; for ($i=1; $i<count($fields); $i++){ $field = $fields[$i]; $values[] = isset($set[$field]) ? $set[$field]:null; } return $values; }
[ "public", "function", "hmget", "(", "$", "key", ")", "{", "$", "set", "=", "$", "this", "->", "getKey", "(", "$", "collection", ",", "$", "key", ",", "[", "]", ")", ";", "$", "fields", "=", "func_get_args", "(", ")", ";", "$", "values", "=", "[", "]", ";", "for", "(", "$", "i", "=", "1", ";", "$", "i", "<", "count", "(", "$", "fields", ")", ";", "$", "i", "++", ")", "{", "$", "field", "=", "$", "fields", "[", "$", "i", "]", ";", "$", "values", "[", "]", "=", "isset", "(", "$", "set", "[", "$", "field", "]", ")", "?", "$", "set", "[", "$", "field", "]", ":", "null", ";", "}", "return", "$", "values", ";", "}" ]
Get the values of all the given hash fields @param string $collection @param string $key @return array
[ "Get", "the", "values", "of", "all", "the", "given", "hash", "fields" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/MongoHybrid/Client.php#L389-L401
train
agentejo/cockpit
lib/ContainerArray.php
ContainerArray.offsetSet
public function offsetSet($key, $value) { if (strpos($key, '/')) { $keys = explode('/', $key); $mem = $this->props; foreach($keys as $keyname) { if (!isset($mem[$keyname])) { $mem[$keyname] = new ArrayObject([]); } $mem = &$mem[$keyname]; } $mem = $value; } else { $this->props[$key] = $value; } }
php
public function offsetSet($key, $value) { if (strpos($key, '/')) { $keys = explode('/', $key); $mem = $this->props; foreach($keys as $keyname) { if (!isset($mem[$keyname])) { $mem[$keyname] = new ArrayObject([]); } $mem = &$mem[$keyname]; } $mem = $value; } else { $this->props[$key] = $value; } }
[ "public", "function", "offsetSet", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "strpos", "(", "$", "key", ",", "'/'", ")", ")", "{", "$", "keys", "=", "explode", "(", "'/'", ",", "$", "key", ")", ";", "$", "mem", "=", "$", "this", "->", "props", ";", "foreach", "(", "$", "keys", "as", "$", "keyname", ")", "{", "if", "(", "!", "isset", "(", "$", "mem", "[", "$", "keyname", "]", ")", ")", "{", "$", "mem", "[", "$", "keyname", "]", "=", "new", "ArrayObject", "(", "[", "]", ")", ";", "}", "$", "mem", "=", "&", "$", "mem", "[", "$", "keyname", "]", ";", "}", "$", "mem", "=", "$", "value", ";", "}", "else", "{", "$", "this", "->", "props", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}" ]
Array Access implementation
[ "Array", "Access", "implementation" ]
de13f02242847c28b9eb116cb08f21290374ae89
https://github.com/agentejo/cockpit/blob/de13f02242847c28b9eb116cb08f21290374ae89/lib/ContainerArray.php#L92-L113
train
laravel/passport
src/TokenRepository.php
TokenRepository.findForUser
public function findForUser($id, $userId) { return Passport::token()->where('id', $id)->where('user_id', $userId)->first(); }
php
public function findForUser($id, $userId) { return Passport::token()->where('id', $id)->where('user_id', $userId)->first(); }
[ "public", "function", "findForUser", "(", "$", "id", ",", "$", "userId", ")", "{", "return", "Passport", "::", "token", "(", ")", "->", "where", "(", "'id'", ",", "$", "id", ")", "->", "where", "(", "'user_id'", ",", "$", "userId", ")", "->", "first", "(", ")", ";", "}" ]
Get a token by the given user ID and token ID. @param string $id @param int $userId @return \Laravel\Passport\Token|null
[ "Get", "a", "token", "by", "the", "given", "user", "ID", "and", "token", "ID", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/TokenRepository.php#L38-L41
train
laravel/passport
src/TokenRepository.php
TokenRepository.findValidToken
public function findValidToken($user, $client) { return $client->tokens() ->whereUserId($user->getKey()) ->where('revoked', 0) ->where('expires_at', '>', Carbon::now()) ->latest('expires_at') ->first(); }
php
public function findValidToken($user, $client) { return $client->tokens() ->whereUserId($user->getKey()) ->where('revoked', 0) ->where('expires_at', '>', Carbon::now()) ->latest('expires_at') ->first(); }
[ "public", "function", "findValidToken", "(", "$", "user", ",", "$", "client", ")", "{", "return", "$", "client", "->", "tokens", "(", ")", "->", "whereUserId", "(", "$", "user", "->", "getKey", "(", ")", ")", "->", "where", "(", "'revoked'", ",", "0", ")", "->", "where", "(", "'expires_at'", ",", "'>'", ",", "Carbon", "::", "now", "(", ")", ")", "->", "latest", "(", "'expires_at'", ")", "->", "first", "(", ")", ";", "}" ]
Find a valid token for the given user and client. @param \Illuminate\Database\Eloquent\Model $user @param \Laravel\Passport\Client $client @return \Laravel\Passport\Token|null
[ "Find", "a", "valid", "token", "for", "the", "given", "user", "and", "client", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/TokenRepository.php#L115-L123
train
laravel/passport
src/Console/ClientCommand.php
ClientCommand.createClientCredentialsClient
protected function createClientCredentialsClient(ClientRepository $clients) { $name = $this->option('name') ?: $this->ask( 'What should we name the client?', config('app.name').' ClientCredentials Grant Client' ); $client = $clients->create( null, $name, '' ); $this->info('New client created successfully.'); $this->outputClientDetails($client); }
php
protected function createClientCredentialsClient(ClientRepository $clients) { $name = $this->option('name') ?: $this->ask( 'What should we name the client?', config('app.name').' ClientCredentials Grant Client' ); $client = $clients->create( null, $name, '' ); $this->info('New client created successfully.'); $this->outputClientDetails($client); }
[ "protected", "function", "createClientCredentialsClient", "(", "ClientRepository", "$", "clients", ")", "{", "$", "name", "=", "$", "this", "->", "option", "(", "'name'", ")", "?", ":", "$", "this", "->", "ask", "(", "'What should we name the client?'", ",", "config", "(", "'app.name'", ")", ".", "' ClientCredentials Grant Client'", ")", ";", "$", "client", "=", "$", "clients", "->", "create", "(", "null", ",", "$", "name", ",", "''", ")", ";", "$", "this", "->", "info", "(", "'New client created successfully.'", ")", ";", "$", "this", "->", "outputClientDetails", "(", "$", "client", ")", ";", "}" ]
Create a client credentials grant client. @param \Laravel\Passport\ClientRepository $clients @return void
[ "Create", "a", "client", "credentials", "grant", "client", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Console/ClientCommand.php#L100-L114
train
laravel/passport
src/Console/ClientCommand.php
ClientCommand.outputClientDetails
protected function outputClientDetails(Client $client) { $this->line('<comment>Client ID:</comment> '.$client->id); $this->line('<comment>Client secret:</comment> '.$client->secret); }
php
protected function outputClientDetails(Client $client) { $this->line('<comment>Client ID:</comment> '.$client->id); $this->line('<comment>Client secret:</comment> '.$client->secret); }
[ "protected", "function", "outputClientDetails", "(", "Client", "$", "client", ")", "{", "$", "this", "->", "line", "(", "'<comment>Client ID:</comment> '", ".", "$", "client", "->", "id", ")", ";", "$", "this", "->", "line", "(", "'<comment>Client secret:</comment> '", ".", "$", "client", "->", "secret", ")", ";", "}" ]
Output the client's ID and secret key. @param \Laravel\Passport\Client $client @return void
[ "Output", "the", "client", "s", "ID", "and", "secret", "key", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Console/ClientCommand.php#L152-L156
train
laravel/passport
src/ApiTokenCookieFactory.php
ApiTokenCookieFactory.make
public function make($userId, $csrfToken) { $config = $this->config->get('session'); $expiration = Carbon::now()->addMinutes($config['lifetime']); return new Cookie( Passport::cookie(), $this->createToken($userId, $csrfToken, $expiration), $expiration, $config['path'], $config['domain'], $config['secure'], true, false, $config['same_site'] ?? null ); }
php
public function make($userId, $csrfToken) { $config = $this->config->get('session'); $expiration = Carbon::now()->addMinutes($config['lifetime']); return new Cookie( Passport::cookie(), $this->createToken($userId, $csrfToken, $expiration), $expiration, $config['path'], $config['domain'], $config['secure'], true, false, $config['same_site'] ?? null ); }
[ "public", "function", "make", "(", "$", "userId", ",", "$", "csrfToken", ")", "{", "$", "config", "=", "$", "this", "->", "config", "->", "get", "(", "'session'", ")", ";", "$", "expiration", "=", "Carbon", "::", "now", "(", ")", "->", "addMinutes", "(", "$", "config", "[", "'lifetime'", "]", ")", ";", "return", "new", "Cookie", "(", "Passport", "::", "cookie", "(", ")", ",", "$", "this", "->", "createToken", "(", "$", "userId", ",", "$", "csrfToken", ",", "$", "expiration", ")", ",", "$", "expiration", ",", "$", "config", "[", "'path'", "]", ",", "$", "config", "[", "'domain'", "]", ",", "$", "config", "[", "'secure'", "]", ",", "true", ",", "false", ",", "$", "config", "[", "'same_site'", "]", "??", "null", ")", ";", "}" ]
Create a new API token cookie. @param mixed $userId @param string $csrfToken @return \Symfony\Component\HttpFoundation\Cookie
[ "Create", "a", "new", "API", "token", "cookie", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/ApiTokenCookieFactory.php#L47-L64
train
laravel/passport
src/ApiTokenCookieFactory.php
ApiTokenCookieFactory.createToken
protected function createToken($userId, $csrfToken, Carbon $expiration) { return JWT::encode([ 'sub' => $userId, 'csrf' => $csrfToken, 'expiry' => $expiration->getTimestamp(), ], $this->encrypter->getKey()); }
php
protected function createToken($userId, $csrfToken, Carbon $expiration) { return JWT::encode([ 'sub' => $userId, 'csrf' => $csrfToken, 'expiry' => $expiration->getTimestamp(), ], $this->encrypter->getKey()); }
[ "protected", "function", "createToken", "(", "$", "userId", ",", "$", "csrfToken", ",", "Carbon", "$", "expiration", ")", "{", "return", "JWT", "::", "encode", "(", "[", "'sub'", "=>", "$", "userId", ",", "'csrf'", "=>", "$", "csrfToken", ",", "'expiry'", "=>", "$", "expiration", "->", "getTimestamp", "(", ")", ",", "]", ",", "$", "this", "->", "encrypter", "->", "getKey", "(", ")", ")", ";", "}" ]
Create a new JWT token for the given user ID and CSRF token. @param mixed $userId @param string $csrfToken @param \Carbon\Carbon $expiration @return string
[ "Create", "a", "new", "JWT", "token", "for", "the", "given", "user", "ID", "and", "CSRF", "token", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/ApiTokenCookieFactory.php#L74-L81
train
laravel/passport
src/PersonalAccessTokenFactory.php
PersonalAccessTokenFactory.make
public function make($userId, $name, array $scopes = []) { $response = $this->dispatchRequestToAuthorizationServer( $this->createRequest($this->clients->personalAccessClient(), $userId, $scopes) ); $token = tap($this->findAccessToken($response), function ($token) use ($userId, $name) { $this->tokens->save($token->forceFill([ 'user_id' => $userId, 'name' => $name, ])); }); return new PersonalAccessTokenResult( $response['access_token'], $token ); }
php
public function make($userId, $name, array $scopes = []) { $response = $this->dispatchRequestToAuthorizationServer( $this->createRequest($this->clients->personalAccessClient(), $userId, $scopes) ); $token = tap($this->findAccessToken($response), function ($token) use ($userId, $name) { $this->tokens->save($token->forceFill([ 'user_id' => $userId, 'name' => $name, ])); }); return new PersonalAccessTokenResult( $response['access_token'], $token ); }
[ "public", "function", "make", "(", "$", "userId", ",", "$", "name", ",", "array", "$", "scopes", "=", "[", "]", ")", "{", "$", "response", "=", "$", "this", "->", "dispatchRequestToAuthorizationServer", "(", "$", "this", "->", "createRequest", "(", "$", "this", "->", "clients", "->", "personalAccessClient", "(", ")", ",", "$", "userId", ",", "$", "scopes", ")", ")", ";", "$", "token", "=", "tap", "(", "$", "this", "->", "findAccessToken", "(", "$", "response", ")", ",", "function", "(", "$", "token", ")", "use", "(", "$", "userId", ",", "$", "name", ")", "{", "$", "this", "->", "tokens", "->", "save", "(", "$", "token", "->", "forceFill", "(", "[", "'user_id'", "=>", "$", "userId", ",", "'name'", "=>", "$", "name", ",", "]", ")", ")", ";", "}", ")", ";", "return", "new", "PersonalAccessTokenResult", "(", "$", "response", "[", "'access_token'", "]", ",", "$", "token", ")", ";", "}" ]
Create a new personal access token. @param mixed $userId @param string $name @param array $scopes @return \Laravel\Passport\PersonalAccessTokenResult
[ "Create", "a", "new", "personal", "access", "token", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/PersonalAccessTokenFactory.php#L68-L84
train
laravel/passport
src/PersonalAccessTokenFactory.php
PersonalAccessTokenFactory.dispatchRequestToAuthorizationServer
protected function dispatchRequestToAuthorizationServer(ServerRequest $request) { return json_decode($this->server->respondToAccessTokenRequest( $request, new Response )->getBody()->__toString(), true); }
php
protected function dispatchRequestToAuthorizationServer(ServerRequest $request) { return json_decode($this->server->respondToAccessTokenRequest( $request, new Response )->getBody()->__toString(), true); }
[ "protected", "function", "dispatchRequestToAuthorizationServer", "(", "ServerRequest", "$", "request", ")", "{", "return", "json_decode", "(", "$", "this", "->", "server", "->", "respondToAccessTokenRequest", "(", "$", "request", ",", "new", "Response", ")", "->", "getBody", "(", ")", "->", "__toString", "(", ")", ",", "true", ")", ";", "}" ]
Dispatch the given request to the authorization server. @param \Zend\Diactoros\ServerRequest $request @return array
[ "Dispatch", "the", "given", "request", "to", "the", "authorization", "server", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/PersonalAccessTokenFactory.php#L111-L116
train
laravel/passport
src/PersonalAccessTokenFactory.php
PersonalAccessTokenFactory.findAccessToken
protected function findAccessToken(array $response) { return $this->tokens->find( $this->jwt->parse($response['access_token'])->getClaim('jti') ); }
php
protected function findAccessToken(array $response) { return $this->tokens->find( $this->jwt->parse($response['access_token'])->getClaim('jti') ); }
[ "protected", "function", "findAccessToken", "(", "array", "$", "response", ")", "{", "return", "$", "this", "->", "tokens", "->", "find", "(", "$", "this", "->", "jwt", "->", "parse", "(", "$", "response", "[", "'access_token'", "]", ")", "->", "getClaim", "(", "'jti'", ")", ")", ";", "}" ]
Get the access token instance for the parsed response. @param array $response @return Token
[ "Get", "the", "access", "token", "instance", "for", "the", "parsed", "response", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/PersonalAccessTokenFactory.php#L124-L129
train
laravel/passport
src/Http/Controllers/TransientTokenController.php
TransientTokenController.refresh
public function refresh(Request $request) { return (new Response('Refreshed.'))->withCookie($this->cookieFactory->make( $request->user()->getKey(), $request->session()->token() )); }
php
public function refresh(Request $request) { return (new Response('Refreshed.'))->withCookie($this->cookieFactory->make( $request->user()->getKey(), $request->session()->token() )); }
[ "public", "function", "refresh", "(", "Request", "$", "request", ")", "{", "return", "(", "new", "Response", "(", "'Refreshed.'", ")", ")", "->", "withCookie", "(", "$", "this", "->", "cookieFactory", "->", "make", "(", "$", "request", "->", "user", "(", ")", "->", "getKey", "(", ")", ",", "$", "request", "->", "session", "(", ")", "->", "token", "(", ")", ")", ")", ";", "}" ]
Get a fresh transient token cookie for the authenticated user. @param \Illuminate\Http\Request $request @return \Illuminate\Http\Response
[ "Get", "a", "fresh", "transient", "token", "cookie", "for", "the", "authenticated", "user", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Http/Controllers/TransientTokenController.php#L35-L40
train
laravel/passport
src/Http/Controllers/RetrievesAuthRequestFromSession.php
RetrievesAuthRequestFromSession.getAuthRequestFromSession
protected function getAuthRequestFromSession(Request $request) { return tap($request->session()->get('authRequest'), function ($authRequest) use ($request) { if (! $authRequest) { throw new Exception('Authorization request was not present in the session.'); } $authRequest->setUser(new User($request->user()->getKey())); $authRequest->setAuthorizationApproved(true); }); }
php
protected function getAuthRequestFromSession(Request $request) { return tap($request->session()->get('authRequest'), function ($authRequest) use ($request) { if (! $authRequest) { throw new Exception('Authorization request was not present in the session.'); } $authRequest->setUser(new User($request->user()->getKey())); $authRequest->setAuthorizationApproved(true); }); }
[ "protected", "function", "getAuthRequestFromSession", "(", "Request", "$", "request", ")", "{", "return", "tap", "(", "$", "request", "->", "session", "(", ")", "->", "get", "(", "'authRequest'", ")", ",", "function", "(", "$", "authRequest", ")", "use", "(", "$", "request", ")", "{", "if", "(", "!", "$", "authRequest", ")", "{", "throw", "new", "Exception", "(", "'Authorization request was not present in the session.'", ")", ";", "}", "$", "authRequest", "->", "setUser", "(", "new", "User", "(", "$", "request", "->", "user", "(", ")", "->", "getKey", "(", ")", ")", ")", ";", "$", "authRequest", "->", "setAuthorizationApproved", "(", "true", ")", ";", "}", ")", ";", "}" ]
Get the authorization request from the session. @param \Illuminate\Http\Request $request @return \League\OAuth2\Server\RequestTypes\AuthorizationRequest @throws \Exception
[ "Get", "the", "authorization", "request", "from", "the", "session", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Http/Controllers/RetrievesAuthRequestFromSession.php#L18-L29
train
laravel/passport
src/PassportServiceProvider.php
PassportServiceProvider.registerAuthorizationServer
protected function registerAuthorizationServer() { $this->app->singleton(AuthorizationServer::class, function () { return tap($this->makeAuthorizationServer(), function ($server) { $server->setDefaultScope(Passport::$defaultScope); $server->enableGrantType( $this->makeAuthCodeGrant(), Passport::tokensExpireIn() ); $server->enableGrantType( $this->makeRefreshTokenGrant(), Passport::tokensExpireIn() ); $server->enableGrantType( $this->makePasswordGrant(), Passport::tokensExpireIn() ); $server->enableGrantType( new PersonalAccessGrant, Passport::personalAccessTokensExpireIn() ); $server->enableGrantType( new ClientCredentialsGrant, Passport::tokensExpireIn() ); if (Passport::$implicitGrantEnabled) { $server->enableGrantType( $this->makeImplicitGrant(), Passport::tokensExpireIn() ); } }); }); }
php
protected function registerAuthorizationServer() { $this->app->singleton(AuthorizationServer::class, function () { return tap($this->makeAuthorizationServer(), function ($server) { $server->setDefaultScope(Passport::$defaultScope); $server->enableGrantType( $this->makeAuthCodeGrant(), Passport::tokensExpireIn() ); $server->enableGrantType( $this->makeRefreshTokenGrant(), Passport::tokensExpireIn() ); $server->enableGrantType( $this->makePasswordGrant(), Passport::tokensExpireIn() ); $server->enableGrantType( new PersonalAccessGrant, Passport::personalAccessTokensExpireIn() ); $server->enableGrantType( new ClientCredentialsGrant, Passport::tokensExpireIn() ); if (Passport::$implicitGrantEnabled) { $server->enableGrantType( $this->makeImplicitGrant(), Passport::tokensExpireIn() ); } }); }); }
[ "protected", "function", "registerAuthorizationServer", "(", ")", "{", "$", "this", "->", "app", "->", "singleton", "(", "AuthorizationServer", "::", "class", ",", "function", "(", ")", "{", "return", "tap", "(", "$", "this", "->", "makeAuthorizationServer", "(", ")", ",", "function", "(", "$", "server", ")", "{", "$", "server", "->", "setDefaultScope", "(", "Passport", "::", "$", "defaultScope", ")", ";", "$", "server", "->", "enableGrantType", "(", "$", "this", "->", "makeAuthCodeGrant", "(", ")", ",", "Passport", "::", "tokensExpireIn", "(", ")", ")", ";", "$", "server", "->", "enableGrantType", "(", "$", "this", "->", "makeRefreshTokenGrant", "(", ")", ",", "Passport", "::", "tokensExpireIn", "(", ")", ")", ";", "$", "server", "->", "enableGrantType", "(", "$", "this", "->", "makePasswordGrant", "(", ")", ",", "Passport", "::", "tokensExpireIn", "(", ")", ")", ";", "$", "server", "->", "enableGrantType", "(", "new", "PersonalAccessGrant", ",", "Passport", "::", "personalAccessTokensExpireIn", "(", ")", ")", ";", "$", "server", "->", "enableGrantType", "(", "new", "ClientCredentialsGrant", ",", "Passport", "::", "tokensExpireIn", "(", ")", ")", ";", "if", "(", "Passport", "::", "$", "implicitGrantEnabled", ")", "{", "$", "server", "->", "enableGrantType", "(", "$", "this", "->", "makeImplicitGrant", "(", ")", ",", "Passport", "::", "tokensExpireIn", "(", ")", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Register the authorization server. @return void
[ "Register", "the", "authorization", "server", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/PassportServiceProvider.php#L95-L128
train
laravel/passport
src/PassportServiceProvider.php
PassportServiceProvider.buildAuthCodeGrant
protected function buildAuthCodeGrant() { return new AuthCodeGrant( $this->app->make(Bridge\AuthCodeRepository::class), $this->app->make(Bridge\RefreshTokenRepository::class), new DateInterval('PT10M') ); }
php
protected function buildAuthCodeGrant() { return new AuthCodeGrant( $this->app->make(Bridge\AuthCodeRepository::class), $this->app->make(Bridge\RefreshTokenRepository::class), new DateInterval('PT10M') ); }
[ "protected", "function", "buildAuthCodeGrant", "(", ")", "{", "return", "new", "AuthCodeGrant", "(", "$", "this", "->", "app", "->", "make", "(", "Bridge", "\\", "AuthCodeRepository", "::", "class", ")", ",", "$", "this", "->", "app", "->", "make", "(", "Bridge", "\\", "RefreshTokenRepository", "::", "class", ")", ",", "new", "DateInterval", "(", "'PT10M'", ")", ")", ";", "}" ]
Build the Auth Code grant instance. @return \League\OAuth2\Server\Grant\AuthCodeGrant
[ "Build", "the", "Auth", "Code", "grant", "instance", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/PassportServiceProvider.php#L147-L154
train
laravel/passport
src/PassportServiceProvider.php
PassportServiceProvider.makeRefreshTokenGrant
protected function makeRefreshTokenGrant() { $repository = $this->app->make(RefreshTokenRepository::class); return tap(new RefreshTokenGrant($repository), function ($grant) { $grant->setRefreshTokenTTL(Passport::refreshTokensExpireIn()); }); }
php
protected function makeRefreshTokenGrant() { $repository = $this->app->make(RefreshTokenRepository::class); return tap(new RefreshTokenGrant($repository), function ($grant) { $grant->setRefreshTokenTTL(Passport::refreshTokensExpireIn()); }); }
[ "protected", "function", "makeRefreshTokenGrant", "(", ")", "{", "$", "repository", "=", "$", "this", "->", "app", "->", "make", "(", "RefreshTokenRepository", "::", "class", ")", ";", "return", "tap", "(", "new", "RefreshTokenGrant", "(", "$", "repository", ")", ",", "function", "(", "$", "grant", ")", "{", "$", "grant", "->", "setRefreshTokenTTL", "(", "Passport", "::", "refreshTokensExpireIn", "(", ")", ")", ";", "}", ")", ";", "}" ]
Create and configure a Refresh Token grant instance. @return \League\OAuth2\Server\Grant\RefreshTokenGrant
[ "Create", "and", "configure", "a", "Refresh", "Token", "grant", "instance", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/PassportServiceProvider.php#L161-L168
train
laravel/passport
src/PassportServiceProvider.php
PassportServiceProvider.makeCryptKey
protected function makeCryptKey($type) { $key = str_replace('\\n', "\n", $this->app->make(Config::class)->get('passport.'.$type.'_key')); if (! $key) { $key = 'file://'.Passport::keyPath('oauth-'.$type.'.key'); } return new CryptKey($key, null, false); }
php
protected function makeCryptKey($type) { $key = str_replace('\\n', "\n", $this->app->make(Config::class)->get('passport.'.$type.'_key')); if (! $key) { $key = 'file://'.Passport::keyPath('oauth-'.$type.'.key'); } return new CryptKey($key, null, false); }
[ "protected", "function", "makeCryptKey", "(", "$", "type", ")", "{", "$", "key", "=", "str_replace", "(", "'\\\\n'", ",", "\"\\n\"", ",", "$", "this", "->", "app", "->", "make", "(", "Config", "::", "class", ")", "->", "get", "(", "'passport.'", ".", "$", "type", ".", "'_key'", ")", ")", ";", "if", "(", "!", "$", "key", ")", "{", "$", "key", "=", "'file://'", ".", "Passport", "::", "keyPath", "(", "'oauth-'", ".", "$", "type", ".", "'.key'", ")", ";", "}", "return", "new", "CryptKey", "(", "$", "key", ",", "null", ",", "false", ")", ";", "}" ]
Create a CryptKey instance without permissions check. @param string $key @return \League\OAuth2\Server\CryptKey
[ "Create", "a", "CryptKey", "instance", "without", "permissions", "check", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/PassportServiceProvider.php#L234-L243
train
laravel/passport
src/PassportServiceProvider.php
PassportServiceProvider.registerGuard
protected function registerGuard() { Auth::extend('passport', function ($app, $name, array $config) { return tap($this->makeGuard($config), function ($guard) { $this->app->refresh('request', $guard, 'setRequest'); }); }); }
php
protected function registerGuard() { Auth::extend('passport', function ($app, $name, array $config) { return tap($this->makeGuard($config), function ($guard) { $this->app->refresh('request', $guard, 'setRequest'); }); }); }
[ "protected", "function", "registerGuard", "(", ")", "{", "Auth", "::", "extend", "(", "'passport'", ",", "function", "(", "$", "app", ",", "$", "name", ",", "array", "$", "config", ")", "{", "return", "tap", "(", "$", "this", "->", "makeGuard", "(", "$", "config", ")", ",", "function", "(", "$", "guard", ")", "{", "$", "this", "->", "app", "->", "refresh", "(", "'request'", ",", "$", "guard", ",", "'setRequest'", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Register the token guard. @return void
[ "Register", "the", "token", "guard", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/PassportServiceProvider.php#L250-L257
train
laravel/passport
src/PassportServiceProvider.php
PassportServiceProvider.makeGuard
protected function makeGuard(array $config) { return new RequestGuard(function ($request) use ($config) { return (new TokenGuard( $this->app->make(ResourceServer::class), Auth::createUserProvider($config['provider']), $this->app->make(TokenRepository::class), $this->app->make(ClientRepository::class), $this->app->make('encrypter') ))->user($request); }, $this->app['request']); }
php
protected function makeGuard(array $config) { return new RequestGuard(function ($request) use ($config) { return (new TokenGuard( $this->app->make(ResourceServer::class), Auth::createUserProvider($config['provider']), $this->app->make(TokenRepository::class), $this->app->make(ClientRepository::class), $this->app->make('encrypter') ))->user($request); }, $this->app['request']); }
[ "protected", "function", "makeGuard", "(", "array", "$", "config", ")", "{", "return", "new", "RequestGuard", "(", "function", "(", "$", "request", ")", "use", "(", "$", "config", ")", "{", "return", "(", "new", "TokenGuard", "(", "$", "this", "->", "app", "->", "make", "(", "ResourceServer", "::", "class", ")", ",", "Auth", "::", "createUserProvider", "(", "$", "config", "[", "'provider'", "]", ")", ",", "$", "this", "->", "app", "->", "make", "(", "TokenRepository", "::", "class", ")", ",", "$", "this", "->", "app", "->", "make", "(", "ClientRepository", "::", "class", ")", ",", "$", "this", "->", "app", "->", "make", "(", "'encrypter'", ")", ")", ")", "->", "user", "(", "$", "request", ")", ";", "}", ",", "$", "this", "->", "app", "[", "'request'", "]", ")", ";", "}" ]
Make an instance of the token guard. @param array $config @return \Illuminate\Auth\RequestGuard
[ "Make", "an", "instance", "of", "the", "token", "guard", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/PassportServiceProvider.php#L265-L276
train
laravel/passport
src/PassportServiceProvider.php
PassportServiceProvider.deleteCookieOnLogout
protected function deleteCookieOnLogout() { Event::listen(Logout::class, function () { if (Request::hasCookie(Passport::cookie())) { Cookie::queue(Cookie::forget(Passport::cookie())); } }); }
php
protected function deleteCookieOnLogout() { Event::listen(Logout::class, function () { if (Request::hasCookie(Passport::cookie())) { Cookie::queue(Cookie::forget(Passport::cookie())); } }); }
[ "protected", "function", "deleteCookieOnLogout", "(", ")", "{", "Event", "::", "listen", "(", "Logout", "::", "class", ",", "function", "(", ")", "{", "if", "(", "Request", "::", "hasCookie", "(", "Passport", "::", "cookie", "(", ")", ")", ")", "{", "Cookie", "::", "queue", "(", "Cookie", "::", "forget", "(", "Passport", "::", "cookie", "(", ")", ")", ")", ";", "}", "}", ")", ";", "}" ]
Register the cookie deletion event handler. @return void
[ "Register", "the", "cookie", "deletion", "event", "handler", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/PassportServiceProvider.php#L283-L290
train
laravel/passport
src/Http/Controllers/AuthorizedAccessTokenController.php
AuthorizedAccessTokenController.forUser
public function forUser(Request $request) { $tokens = $this->tokenRepository->forUser($request->user()->getKey()); return $tokens->load('client')->filter(function ($token) { return ! $token->client->firstParty() && ! $token->revoked; })->values(); }
php
public function forUser(Request $request) { $tokens = $this->tokenRepository->forUser($request->user()->getKey()); return $tokens->load('client')->filter(function ($token) { return ! $token->client->firstParty() && ! $token->revoked; })->values(); }
[ "public", "function", "forUser", "(", "Request", "$", "request", ")", "{", "$", "tokens", "=", "$", "this", "->", "tokenRepository", "->", "forUser", "(", "$", "request", "->", "user", "(", ")", "->", "getKey", "(", ")", ")", ";", "return", "$", "tokens", "->", "load", "(", "'client'", ")", "->", "filter", "(", "function", "(", "$", "token", ")", "{", "return", "!", "$", "token", "->", "client", "->", "firstParty", "(", ")", "&&", "!", "$", "token", "->", "revoked", ";", "}", ")", "->", "values", "(", ")", ";", "}" ]
Get all of the authorized tokens for the authenticated user. @param \Illuminate\Http\Request $request @return \Illuminate\Database\Eloquent\Collection
[ "Get", "all", "of", "the", "authorized", "tokens", "for", "the", "authenticated", "user", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Http/Controllers/AuthorizedAccessTokenController.php#L35-L42
train
laravel/passport
src/Http/Controllers/AuthorizedAccessTokenController.php
AuthorizedAccessTokenController.destroy
public function destroy(Request $request, $tokenId) { $token = $this->tokenRepository->findForUser( $tokenId, $request->user()->getKey() ); if (is_null($token)) { return new Response('', 404); } $token->revoke(); return new Response('', Response::HTTP_NO_CONTENT); }
php
public function destroy(Request $request, $tokenId) { $token = $this->tokenRepository->findForUser( $tokenId, $request->user()->getKey() ); if (is_null($token)) { return new Response('', 404); } $token->revoke(); return new Response('', Response::HTTP_NO_CONTENT); }
[ "public", "function", "destroy", "(", "Request", "$", "request", ",", "$", "tokenId", ")", "{", "$", "token", "=", "$", "this", "->", "tokenRepository", "->", "findForUser", "(", "$", "tokenId", ",", "$", "request", "->", "user", "(", ")", "->", "getKey", "(", ")", ")", ";", "if", "(", "is_null", "(", "$", "token", ")", ")", "{", "return", "new", "Response", "(", "''", ",", "404", ")", ";", "}", "$", "token", "->", "revoke", "(", ")", ";", "return", "new", "Response", "(", "''", ",", "Response", "::", "HTTP_NO_CONTENT", ")", ";", "}" ]
Delete the given token. @param \Illuminate\Http\Request $request @param string $tokenId @return \Illuminate\Http\Response
[ "Delete", "the", "given", "token", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Http/Controllers/AuthorizedAccessTokenController.php#L51-L64
train
laravel/passport
src/Guards/TokenGuard.php
TokenGuard.user
public function user(Request $request) { if ($request->bearerToken()) { return $this->authenticateViaBearerToken($request); } elseif ($request->cookie(Passport::cookie())) { return $this->authenticateViaCookie($request); } }
php
public function user(Request $request) { if ($request->bearerToken()) { return $this->authenticateViaBearerToken($request); } elseif ($request->cookie(Passport::cookie())) { return $this->authenticateViaCookie($request); } }
[ "public", "function", "user", "(", "Request", "$", "request", ")", "{", "if", "(", "$", "request", "->", "bearerToken", "(", ")", ")", "{", "return", "$", "this", "->", "authenticateViaBearerToken", "(", "$", "request", ")", ";", "}", "elseif", "(", "$", "request", "->", "cookie", "(", "Passport", "::", "cookie", "(", ")", ")", ")", "{", "return", "$", "this", "->", "authenticateViaCookie", "(", "$", "request", ")", ";", "}", "}" ]
Get the user for the incoming request. @param \Illuminate\Http\Request $request @return mixed
[ "Get", "the", "user", "for", "the", "incoming", "request", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Guards/TokenGuard.php#L86-L93
train
laravel/passport
src/Guards/TokenGuard.php
TokenGuard.client
public function client(Request $request) { if ($request->bearerToken()) { if (! $psr = $this->getPsrRequestViaBearerToken($request)) { return; } return $this->clients->findActive( $psr->getAttribute('oauth_client_id') ); } elseif ($request->cookie(Passport::cookie())) { if ($token = $this->getTokenViaCookie($request)) { return $this->clients->findActive($token['aud']); } } }
php
public function client(Request $request) { if ($request->bearerToken()) { if (! $psr = $this->getPsrRequestViaBearerToken($request)) { return; } return $this->clients->findActive( $psr->getAttribute('oauth_client_id') ); } elseif ($request->cookie(Passport::cookie())) { if ($token = $this->getTokenViaCookie($request)) { return $this->clients->findActive($token['aud']); } } }
[ "public", "function", "client", "(", "Request", "$", "request", ")", "{", "if", "(", "$", "request", "->", "bearerToken", "(", ")", ")", "{", "if", "(", "!", "$", "psr", "=", "$", "this", "->", "getPsrRequestViaBearerToken", "(", "$", "request", ")", ")", "{", "return", ";", "}", "return", "$", "this", "->", "clients", "->", "findActive", "(", "$", "psr", "->", "getAttribute", "(", "'oauth_client_id'", ")", ")", ";", "}", "elseif", "(", "$", "request", "->", "cookie", "(", "Passport", "::", "cookie", "(", ")", ")", ")", "{", "if", "(", "$", "token", "=", "$", "this", "->", "getTokenViaCookie", "(", "$", "request", ")", ")", "{", "return", "$", "this", "->", "clients", "->", "findActive", "(", "$", "token", "[", "'aud'", "]", ")", ";", "}", "}", "}" ]
Get the client for the incoming request. @param \Illuminate\Http\Request $request @return mixed
[ "Get", "the", "client", "for", "the", "incoming", "request", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Guards/TokenGuard.php#L101-L116
train
laravel/passport
src/Guards/TokenGuard.php
TokenGuard.getPsrRequestViaBearerToken
protected function getPsrRequestViaBearerToken($request) { // First, we will convert the Symfony request to a PSR-7 implementation which will // be compatible with the base OAuth2 library. The Symfony bridge can perform a // conversion for us to a Zend Diactoros implementation of the PSR-7 request. $psr = (new DiactorosFactory)->createRequest($request); try { return $this->server->validateAuthenticatedRequest($psr); } catch (OAuthServerException $e) { $request->headers->set('Authorization', '', true); Container::getInstance()->make( ExceptionHandler::class )->report($e); } }
php
protected function getPsrRequestViaBearerToken($request) { // First, we will convert the Symfony request to a PSR-7 implementation which will // be compatible with the base OAuth2 library. The Symfony bridge can perform a // conversion for us to a Zend Diactoros implementation of the PSR-7 request. $psr = (new DiactorosFactory)->createRequest($request); try { return $this->server->validateAuthenticatedRequest($psr); } catch (OAuthServerException $e) { $request->headers->set('Authorization', '', true); Container::getInstance()->make( ExceptionHandler::class )->report($e); } }
[ "protected", "function", "getPsrRequestViaBearerToken", "(", "$", "request", ")", "{", "// First, we will convert the Symfony request to a PSR-7 implementation which will", "// be compatible with the base OAuth2 library. The Symfony bridge can perform a", "// conversion for us to a Zend Diactoros implementation of the PSR-7 request.", "$", "psr", "=", "(", "new", "DiactorosFactory", ")", "->", "createRequest", "(", "$", "request", ")", ";", "try", "{", "return", "$", "this", "->", "server", "->", "validateAuthenticatedRequest", "(", "$", "psr", ")", ";", "}", "catch", "(", "OAuthServerException", "$", "e", ")", "{", "$", "request", "->", "headers", "->", "set", "(", "'Authorization'", ",", "''", ",", "true", ")", ";", "Container", "::", "getInstance", "(", ")", "->", "make", "(", "ExceptionHandler", "::", "class", ")", "->", "report", "(", "$", "e", ")", ";", "}", "}" ]
Authenticate and get the incoming PSR-7 request via the Bearer token. @param \Illuminate\Http\Request $request @return \Psr\Http\Message\ServerRequestInterface
[ "Authenticate", "and", "get", "the", "incoming", "PSR", "-", "7", "request", "via", "the", "Bearer", "token", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Guards/TokenGuard.php#L166-L182
train
laravel/passport
src/Guards/TokenGuard.php
TokenGuard.getTokenViaCookie
protected function getTokenViaCookie($request) { // If we need to retrieve the token from the cookie, it'll be encrypted so we must // first decrypt the cookie and then attempt to find the token value within the // database. If we can't decrypt the value we'll bail out with a null return. try { $token = $this->decodeJwtTokenCookie($request); } catch (Exception $e) { return; } // We will compare the CSRF token in the decoded API token against the CSRF header // sent with the request. If they don't match then this request isn't sent from // a valid source and we won't authenticate the request for further handling. if (! Passport::$ignoreCsrfToken && (! $this->validCsrf($token, $request) || time() >= $token['expiry'])) { return; } return $token; }
php
protected function getTokenViaCookie($request) { // If we need to retrieve the token from the cookie, it'll be encrypted so we must // first decrypt the cookie and then attempt to find the token value within the // database. If we can't decrypt the value we'll bail out with a null return. try { $token = $this->decodeJwtTokenCookie($request); } catch (Exception $e) { return; } // We will compare the CSRF token in the decoded API token against the CSRF header // sent with the request. If they don't match then this request isn't sent from // a valid source and we won't authenticate the request for further handling. if (! Passport::$ignoreCsrfToken && (! $this->validCsrf($token, $request) || time() >= $token['expiry'])) { return; } return $token; }
[ "protected", "function", "getTokenViaCookie", "(", "$", "request", ")", "{", "// If we need to retrieve the token from the cookie, it'll be encrypted so we must", "// first decrypt the cookie and then attempt to find the token value within the", "// database. If we can't decrypt the value we'll bail out with a null return.", "try", "{", "$", "token", "=", "$", "this", "->", "decodeJwtTokenCookie", "(", "$", "request", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "return", ";", "}", "// We will compare the CSRF token in the decoded API token against the CSRF header", "// sent with the request. If they don't match then this request isn't sent from", "// a valid source and we won't authenticate the request for further handling.", "if", "(", "!", "Passport", "::", "$", "ignoreCsrfToken", "&&", "(", "!", "$", "this", "->", "validCsrf", "(", "$", "token", ",", "$", "request", ")", "||", "time", "(", ")", ">=", "$", "token", "[", "'expiry'", "]", ")", ")", "{", "return", ";", "}", "return", "$", "token", ";", "}" ]
Get the token cookie via the incoming request. @param \Illuminate\Http\Request $request @return mixed
[ "Get", "the", "token", "cookie", "via", "the", "incoming", "request", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Guards/TokenGuard.php#L210-L230
train
laravel/passport
src/ClientRepository.php
ClientRepository.find
public function find($id) { $client = Passport::client(); return $client->where($client->getKeyName(), $id)->first(); }
php
public function find($id) { $client = Passport::client(); return $client->where($client->getKeyName(), $id)->first(); }
[ "public", "function", "find", "(", "$", "id", ")", "{", "$", "client", "=", "Passport", "::", "client", "(", ")", ";", "return", "$", "client", "->", "where", "(", "$", "client", "->", "getKeyName", "(", ")", ",", "$", "id", ")", "->", "first", "(", ")", ";", "}" ]
Get a client by the given ID. @param int $id @return \Laravel\Passport\Client|null
[ "Get", "a", "client", "by", "the", "given", "ID", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/ClientRepository.php#L16-L21
train
laravel/passport
src/ClientRepository.php
ClientRepository.findActive
public function findActive($id) { $client = $this->find($id); return $client && ! $client->revoked ? $client : null; }
php
public function findActive($id) { $client = $this->find($id); return $client && ! $client->revoked ? $client : null; }
[ "public", "function", "findActive", "(", "$", "id", ")", "{", "$", "client", "=", "$", "this", "->", "find", "(", "$", "id", ")", ";", "return", "$", "client", "&&", "!", "$", "client", "->", "revoked", "?", "$", "client", ":", "null", ";", "}" ]
Get an active client by the given ID. @param int $id @return \Laravel\Passport\Client|null
[ "Get", "an", "active", "client", "by", "the", "given", "ID", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/ClientRepository.php#L29-L34
train
laravel/passport
src/ClientRepository.php
ClientRepository.findForUser
public function findForUser($clientId, $userId) { $client = Passport::client(); return $client ->where($client->getKeyName(), $clientId) ->where('user_id', $userId) ->first(); }
php
public function findForUser($clientId, $userId) { $client = Passport::client(); return $client ->where($client->getKeyName(), $clientId) ->where('user_id', $userId) ->first(); }
[ "public", "function", "findForUser", "(", "$", "clientId", ",", "$", "userId", ")", "{", "$", "client", "=", "Passport", "::", "client", "(", ")", ";", "return", "$", "client", "->", "where", "(", "$", "client", "->", "getKeyName", "(", ")", ",", "$", "clientId", ")", "->", "where", "(", "'user_id'", ",", "$", "userId", ")", "->", "first", "(", ")", ";", "}" ]
Get a client instance for the given ID and user ID. @param int $clientId @param mixed $userId @return \Laravel\Passport\Client|null
[ "Get", "a", "client", "instance", "for", "the", "given", "ID", "and", "user", "ID", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/ClientRepository.php#L43-L51
train
laravel/passport
src/ClientRepository.php
ClientRepository.activeForUser
public function activeForUser($userId) { return $this->forUser($userId)->reject(function ($client) { return $client->revoked; })->values(); }
php
public function activeForUser($userId) { return $this->forUser($userId)->reject(function ($client) { return $client->revoked; })->values(); }
[ "public", "function", "activeForUser", "(", "$", "userId", ")", "{", "return", "$", "this", "->", "forUser", "(", "$", "userId", ")", "->", "reject", "(", "function", "(", "$", "client", ")", "{", "return", "$", "client", "->", "revoked", ";", "}", ")", "->", "values", "(", ")", ";", "}" ]
Get the active client instances for the given user ID. @param mixed $userId @return \Illuminate\Database\Eloquent\Collection
[ "Get", "the", "active", "client", "instances", "for", "the", "given", "user", "ID", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/ClientRepository.php#L72-L77
train
laravel/passport
src/ClientRepository.php
ClientRepository.createPasswordGrantClient
public function createPasswordGrantClient($userId, $name, $redirect) { return $this->create($userId, $name, $redirect, false, true); }
php
public function createPasswordGrantClient($userId, $name, $redirect) { return $this->create($userId, $name, $redirect, false, true); }
[ "public", "function", "createPasswordGrantClient", "(", "$", "userId", ",", "$", "name", ",", "$", "redirect", ")", "{", "return", "$", "this", "->", "create", "(", "$", "userId", ",", "$", "name", ",", "$", "redirect", ",", "false", ",", "true", ")", ";", "}" ]
Store a new password grant client. @param int $userId @param string $name @param string $redirect @return \Laravel\Passport\Client
[ "Store", "a", "new", "password", "grant", "client", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/ClientRepository.php#L153-L156
train
laravel/passport
src/ClientRepository.php
ClientRepository.revoked
public function revoked($id) { $client = $this->find($id); return is_null($client) || $client->revoked; }
php
public function revoked($id) { $client = $this->find($id); return is_null($client) || $client->revoked; }
[ "public", "function", "revoked", "(", "$", "id", ")", "{", "$", "client", "=", "$", "this", "->", "find", "(", "$", "id", ")", ";", "return", "is_null", "(", "$", "client", ")", "||", "$", "client", "->", "revoked", ";", "}" ]
Determine if the given client is revoked. @param int $id @return bool
[ "Determine", "if", "the", "given", "client", "is", "revoked", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/ClientRepository.php#L196-L201
train
laravel/passport
src/Http/Controllers/ClientController.php
ClientController.forUser
public function forUser(Request $request) { $userId = $request->user()->getKey(); return $this->clients->activeForUser($userId)->makeVisible('secret'); }
php
public function forUser(Request $request) { $userId = $request->user()->getKey(); return $this->clients->activeForUser($userId)->makeVisible('secret'); }
[ "public", "function", "forUser", "(", "Request", "$", "request", ")", "{", "$", "userId", "=", "$", "request", "->", "user", "(", ")", "->", "getKey", "(", ")", ";", "return", "$", "this", "->", "clients", "->", "activeForUser", "(", "$", "userId", ")", "->", "makeVisible", "(", "'secret'", ")", ";", "}" ]
Get all of the clients for the authenticated user. @param \Illuminate\Http\Request $request @return \Illuminate\Database\Eloquent\Collection
[ "Get", "all", "of", "the", "clients", "for", "the", "authenticated", "user", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Http/Controllers/ClientController.php#L58-L63
train
laravel/passport
src/Token.php
Token.can
public function can($scope) { return in_array('*', $this->scopes) || array_key_exists($scope, array_flip($this->scopes)); }
php
public function can($scope) { return in_array('*', $this->scopes) || array_key_exists($scope, array_flip($this->scopes)); }
[ "public", "function", "can", "(", "$", "scope", ")", "{", "return", "in_array", "(", "'*'", ",", "$", "this", "->", "scopes", ")", "||", "array_key_exists", "(", "$", "scope", ",", "array_flip", "(", "$", "this", "->", "scopes", ")", ")", ";", "}" ]
Determine if the token has a given scope. @param string $scope @return bool
[ "Determine", "if", "the", "token", "has", "a", "given", "scope", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Token.php#L84-L88
train
laravel/passport
src/RouteRegistrar.php
RouteRegistrar.all
public function all() { $this->forAuthorization(); $this->forAccessTokens(); $this->forTransientTokens(); $this->forClients(); $this->forPersonalAccessTokens(); }
php
public function all() { $this->forAuthorization(); $this->forAccessTokens(); $this->forTransientTokens(); $this->forClients(); $this->forPersonalAccessTokens(); }
[ "public", "function", "all", "(", ")", "{", "$", "this", "->", "forAuthorization", "(", ")", ";", "$", "this", "->", "forAccessTokens", "(", ")", ";", "$", "this", "->", "forTransientTokens", "(", ")", ";", "$", "this", "->", "forClients", "(", ")", ";", "$", "this", "->", "forPersonalAccessTokens", "(", ")", ";", "}" ]
Register routes for transient tokens, clients, and personal access tokens. @return void
[ "Register", "routes", "for", "transient", "tokens", "clients", "and", "personal", "access", "tokens", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/RouteRegistrar.php#L32-L39
train
laravel/passport
src/Http/Controllers/AuthorizationController.php
AuthorizationController.parseScopes
protected function parseScopes($authRequest) { return Passport::scopesFor( collect($authRequest->getScopes())->map(function ($scope) { return $scope->getIdentifier(); })->unique()->all() ); }
php
protected function parseScopes($authRequest) { return Passport::scopesFor( collect($authRequest->getScopes())->map(function ($scope) { return $scope->getIdentifier(); })->unique()->all() ); }
[ "protected", "function", "parseScopes", "(", "$", "authRequest", ")", "{", "return", "Passport", "::", "scopesFor", "(", "collect", "(", "$", "authRequest", "->", "getScopes", "(", ")", ")", "->", "map", "(", "function", "(", "$", "scope", ")", "{", "return", "$", "scope", "->", "getIdentifier", "(", ")", ";", "}", ")", "->", "unique", "(", ")", "->", "all", "(", ")", ")", ";", "}" ]
Transform the authorization requests's scopes into Scope instances. @param \League\OAuth2\Server\RequestTypes\AuthorizationRequest $authRequest @return array
[ "Transform", "the", "authorization", "requests", "s", "scopes", "into", "Scope", "instances", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Http/Controllers/AuthorizationController.php#L91-L98
train
laravel/passport
src/Http/Middleware/CreateFreshApiToken.php
CreateFreshApiToken.alreadyContainsToken
protected function alreadyContainsToken($response) { foreach ($response->headers->getCookies() as $cookie) { if ($cookie->getName() === Passport::cookie()) { return true; } } return false; }
php
protected function alreadyContainsToken($response) { foreach ($response->headers->getCookies() as $cookie) { if ($cookie->getName() === Passport::cookie()) { return true; } } return false; }
[ "protected", "function", "alreadyContainsToken", "(", "$", "response", ")", "{", "foreach", "(", "$", "response", "->", "headers", "->", "getCookies", "(", ")", "as", "$", "cookie", ")", "{", "if", "(", "$", "cookie", "->", "getName", "(", ")", "===", "Passport", "::", "cookie", "(", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determine if the given response already contains an API token. This avoids us overwriting a just "refreshed" token. @param \Illuminate\Http\Response $response @return bool
[ "Determine", "if", "the", "given", "response", "already", "contains", "an", "API", "token", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Http/Middleware/CreateFreshApiToken.php#L106-L115
train
laravel/passport
src/Passport.php
Passport.scopes
public static function scopes() { return collect(static::$scopes)->map(function ($description, $id) { return new Scope($id, $description); })->values(); }
php
public static function scopes() { return collect(static::$scopes)->map(function ($description, $id) { return new Scope($id, $description); })->values(); }
[ "public", "static", "function", "scopes", "(", ")", "{", "return", "collect", "(", "static", "::", "$", "scopes", ")", "->", "map", "(", "function", "(", "$", "description", ",", "$", "id", ")", "{", "return", "new", "Scope", "(", "$", "id", ",", "$", "description", ")", ";", "}", ")", "->", "values", "(", ")", ";", "}" ]
Get all of the scopes defined for the application. @return \Illuminate\Support\Collection
[ "Get", "all", "of", "the", "scopes", "defined", "for", "the", "application", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Passport.php#L252-L257
train
laravel/passport
src/Passport.php
Passport.refreshTokensExpireIn
public static function refreshTokensExpireIn(DateTimeInterface $date = null) { if (is_null($date)) { return static::$refreshTokensExpireAt ? Carbon::now()->diff(static::$refreshTokensExpireAt) : new DateInterval('P1Y'); } static::$refreshTokensExpireAt = $date; return new static; }
php
public static function refreshTokensExpireIn(DateTimeInterface $date = null) { if (is_null($date)) { return static::$refreshTokensExpireAt ? Carbon::now()->diff(static::$refreshTokensExpireAt) : new DateInterval('P1Y'); } static::$refreshTokensExpireAt = $date; return new static; }
[ "public", "static", "function", "refreshTokensExpireIn", "(", "DateTimeInterface", "$", "date", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "date", ")", ")", "{", "return", "static", "::", "$", "refreshTokensExpireAt", "?", "Carbon", "::", "now", "(", ")", "->", "diff", "(", "static", "::", "$", "refreshTokensExpireAt", ")", ":", "new", "DateInterval", "(", "'P1Y'", ")", ";", "}", "static", "::", "$", "refreshTokensExpireAt", "=", "$", "date", ";", "return", "new", "static", ";", "}" ]
Get or set when refresh tokens expire. @param \DateTimeInterface|null $date @return \DateInterval|static
[ "Get", "or", "set", "when", "refresh", "tokens", "expire", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Passport.php#L310-L321
train
laravel/passport
src/Passport.php
Passport.personalAccessTokensExpireIn
public static function personalAccessTokensExpireIn(DateTimeInterface $date = null) { if (is_null($date)) { return static::$personalAccessTokensExpireAt ? Carbon::now()->diff(static::$personalAccessTokensExpireAt) : new DateInterval('P1Y'); } static::$personalAccessTokensExpireAt = $date; return new static; }
php
public static function personalAccessTokensExpireIn(DateTimeInterface $date = null) { if (is_null($date)) { return static::$personalAccessTokensExpireAt ? Carbon::now()->diff(static::$personalAccessTokensExpireAt) : new DateInterval('P1Y'); } static::$personalAccessTokensExpireAt = $date; return new static; }
[ "public", "static", "function", "personalAccessTokensExpireIn", "(", "DateTimeInterface", "$", "date", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "date", ")", ")", "{", "return", "static", "::", "$", "personalAccessTokensExpireAt", "?", "Carbon", "::", "now", "(", ")", "->", "diff", "(", "static", "::", "$", "personalAccessTokensExpireAt", ")", ":", "new", "DateInterval", "(", "'P1Y'", ")", ";", "}", "static", "::", "$", "personalAccessTokensExpireAt", "=", "$", "date", ";", "return", "new", "static", ";", "}" ]
Get or set when personal access tokens expire. @param \DateTimeInterface|null $date @return \DateInterval|static
[ "Get", "or", "set", "when", "personal", "access", "tokens", "expire", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Passport.php#L329-L340
train
laravel/passport
src/Passport.php
Passport.keyPath
public static function keyPath($file) { $file = ltrim($file, '/\\'); return static::$keyPath ? rtrim(static::$keyPath, '/\\').DIRECTORY_SEPARATOR.$file : storage_path($file); }
php
public static function keyPath($file) { $file = ltrim($file, '/\\'); return static::$keyPath ? rtrim(static::$keyPath, '/\\').DIRECTORY_SEPARATOR.$file : storage_path($file); }
[ "public", "static", "function", "keyPath", "(", "$", "file", ")", "{", "$", "file", "=", "ltrim", "(", "$", "file", ",", "'/\\\\'", ")", ";", "return", "static", "::", "$", "keyPath", "?", "rtrim", "(", "static", "::", "$", "keyPath", ",", "'/\\\\'", ")", ".", "DIRECTORY_SEPARATOR", ".", "$", "file", ":", "storage_path", "(", "$", "file", ")", ";", "}" ]
The location of the encryption keys. @param string $file @return string
[ "The", "location", "of", "the", "encryption", "keys", "." ]
c6e74bd188ad2ae168a45c0a9c4059f110e4f151
https://github.com/laravel/passport/blob/c6e74bd188ad2ae168a45c0a9c4059f110e4f151/src/Passport.php#L418-L425
train
stripe/stripe-php
lib/HttpClient/CurlClient.php
CurlClient.closeCurlHandle
private function closeCurlHandle() { if (!is_null($this->curlHandle)) { curl_close($this->curlHandle); $this->curlHandle = null; } }
php
private function closeCurlHandle() { if (!is_null($this->curlHandle)) { curl_close($this->curlHandle); $this->curlHandle = null; } }
[ "private", "function", "closeCurlHandle", "(", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "curlHandle", ")", ")", "{", "curl_close", "(", "$", "this", "->", "curlHandle", ")", ";", "$", "this", "->", "curlHandle", "=", "null", ";", "}", "}" ]
Closes the curl handle if initialized. Do nothing if already closed.
[ "Closes", "the", "curl", "handle", "if", "initialized", ".", "Do", "nothing", "if", "already", "closed", "." ]
8f74cbe130f962d96d4ba92e75a44396a40cf41a
https://github.com/stripe/stripe-php/blob/8f74cbe130f962d96d4ba92e75a44396a40cf41a/lib/HttpClient/CurlClient.php#L409-L415
train
stripe/stripe-php
lib/HttpClient/CurlClient.php
CurlClient.resetCurlHandle
private function resetCurlHandle() { if (!is_null($this->curlHandle) && $this->getEnablePersistentConnections()) { curl_reset($this->curlHandle); } else { $this->initCurlHandle(); } }
php
private function resetCurlHandle() { if (!is_null($this->curlHandle) && $this->getEnablePersistentConnections()) { curl_reset($this->curlHandle); } else { $this->initCurlHandle(); } }
[ "private", "function", "resetCurlHandle", "(", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "curlHandle", ")", "&&", "$", "this", "->", "getEnablePersistentConnections", "(", ")", ")", "{", "curl_reset", "(", "$", "this", "->", "curlHandle", ")", ";", "}", "else", "{", "$", "this", "->", "initCurlHandle", "(", ")", ";", "}", "}" ]
Resets the curl handle. If the handle is not already initialized, or if persistent connections are disabled, the handle is reinitialized instead.
[ "Resets", "the", "curl", "handle", ".", "If", "the", "handle", "is", "not", "already", "initialized", "or", "if", "persistent", "connections", "are", "disabled", "the", "handle", "is", "reinitialized", "instead", "." ]
8f74cbe130f962d96d4ba92e75a44396a40cf41a
https://github.com/stripe/stripe-php/blob/8f74cbe130f962d96d4ba92e75a44396a40cf41a/lib/HttpClient/CurlClient.php#L421-L428
train
stripe/stripe-php
lib/HttpClient/CurlClient.php
CurlClient.hasHeader
private function hasHeader($headers, $name) { foreach ($headers as $header) { if (strncasecmp($header, "{$name}: ", strlen($name) + 2) === 0) { return true; } } return false; }
php
private function hasHeader($headers, $name) { foreach ($headers as $header) { if (strncasecmp($header, "{$name}: ", strlen($name) + 2) === 0) { return true; } } return false; }
[ "private", "function", "hasHeader", "(", "$", "headers", ",", "$", "name", ")", "{", "foreach", "(", "$", "headers", "as", "$", "header", ")", "{", "if", "(", "strncasecmp", "(", "$", "header", ",", "\"{$name}: \"", ",", "strlen", "(", "$", "name", ")", "+", "2", ")", "===", "0", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks if a list of headers contains a specific header name. @param string[] $headers @param string $name @return boolean
[ "Checks", "if", "a", "list", "of", "headers", "contains", "a", "specific", "header", "name", "." ]
8f74cbe130f962d96d4ba92e75a44396a40cf41a
https://github.com/stripe/stripe-php/blob/8f74cbe130f962d96d4ba92e75a44396a40cf41a/lib/HttpClient/CurlClient.php#L450-L459
train
stripe/stripe-php
lib/Webhook.php
Webhook.constructEvent
public static function constructEvent($payload, $sigHeader, $secret, $tolerance = self::DEFAULT_TOLERANCE) { $data = json_decode($payload, true); $jsonError = json_last_error(); if ($data === null && $jsonError !== JSON_ERROR_NONE) { $msg = "Invalid payload: $payload " . "(json_last_error() was $jsonError)"; throw new \UnexpectedValueException($msg); } $event = Event::constructFrom($data); WebhookSignature::verifyHeader($payload, $sigHeader, $secret, $tolerance); return $event; }
php
public static function constructEvent($payload, $sigHeader, $secret, $tolerance = self::DEFAULT_TOLERANCE) { $data = json_decode($payload, true); $jsonError = json_last_error(); if ($data === null && $jsonError !== JSON_ERROR_NONE) { $msg = "Invalid payload: $payload " . "(json_last_error() was $jsonError)"; throw new \UnexpectedValueException($msg); } $event = Event::constructFrom($data); WebhookSignature::verifyHeader($payload, $sigHeader, $secret, $tolerance); return $event; }
[ "public", "static", "function", "constructEvent", "(", "$", "payload", ",", "$", "sigHeader", ",", "$", "secret", ",", "$", "tolerance", "=", "self", "::", "DEFAULT_TOLERANCE", ")", "{", "$", "data", "=", "json_decode", "(", "$", "payload", ",", "true", ")", ";", "$", "jsonError", "=", "json_last_error", "(", ")", ";", "if", "(", "$", "data", "===", "null", "&&", "$", "jsonError", "!==", "JSON_ERROR_NONE", ")", "{", "$", "msg", "=", "\"Invalid payload: $payload \"", ".", "\"(json_last_error() was $jsonError)\"", ";", "throw", "new", "\\", "UnexpectedValueException", "(", "$", "msg", ")", ";", "}", "$", "event", "=", "Event", "::", "constructFrom", "(", "$", "data", ")", ";", "WebhookSignature", "::", "verifyHeader", "(", "$", "payload", ",", "$", "sigHeader", ",", "$", "secret", ",", "$", "tolerance", ")", ";", "return", "$", "event", ";", "}" ]
Returns an Event instance using the provided JSON payload. Throws a \UnexpectedValueException if the payload is not valid JSON, and a \Stripe\SignatureVerificationException if the signature verification fails for any reason. @param string $payload the payload sent by Stripe. @param string $sigHeader the contents of the signature header sent by Stripe. @param string $secret secret used to generate the signature. @param int $tolerance maximum difference allowed between the header's timestamp and the current time @return \Stripe\Event the Event instance @throws \UnexpectedValueException if the payload is not valid JSON, @throws \Stripe\Error\SignatureVerification if the verification fails.
[ "Returns", "an", "Event", "instance", "using", "the", "provided", "JSON", "payload", ".", "Throws", "a", "\\", "UnexpectedValueException", "if", "the", "payload", "is", "not", "valid", "JSON", "and", "a", "\\", "Stripe", "\\", "SignatureVerificationException", "if", "the", "signature", "verification", "fails", "for", "any", "reason", "." ]
8f74cbe130f962d96d4ba92e75a44396a40cf41a
https://github.com/stripe/stripe-php/blob/8f74cbe130f962d96d4ba92e75a44396a40cf41a/lib/Webhook.php#L25-L39
train
stripe/stripe-php
lib/WebhookSignature.php
WebhookSignature.verifyHeader
public static function verifyHeader($payload, $header, $secret, $tolerance = null) { // Extract timestamp and signatures from header $timestamp = self::getTimestamp($header); $signatures = self::getSignatures($header, self::EXPECTED_SCHEME); if ($timestamp == -1) { throw new Error\SignatureVerification( "Unable to extract timestamp and signatures from header", $header, $payload ); } if (empty($signatures)) { throw new Error\SignatureVerification( "No signatures found with expected scheme", $header, $payload ); } // Check if expected signature is found in list of signatures from // header $signedPayload = "$timestamp.$payload"; $expectedSignature = self::computeSignature($signedPayload, $secret); $signatureFound = false; foreach ($signatures as $signature) { if (Util\Util::secureCompare($expectedSignature, $signature)) { $signatureFound = true; break; } } if (!$signatureFound) { throw new Error\SignatureVerification( "No signatures found matching the expected signature for payload", $header, $payload ); } // Check if timestamp is within tolerance if (($tolerance > 0) && ((time() - $timestamp) > $tolerance)) { throw new Error\SignatureVerification( "Timestamp outside the tolerance zone", $header, $payload ); } return true; }
php
public static function verifyHeader($payload, $header, $secret, $tolerance = null) { // Extract timestamp and signatures from header $timestamp = self::getTimestamp($header); $signatures = self::getSignatures($header, self::EXPECTED_SCHEME); if ($timestamp == -1) { throw new Error\SignatureVerification( "Unable to extract timestamp and signatures from header", $header, $payload ); } if (empty($signatures)) { throw new Error\SignatureVerification( "No signatures found with expected scheme", $header, $payload ); } // Check if expected signature is found in list of signatures from // header $signedPayload = "$timestamp.$payload"; $expectedSignature = self::computeSignature($signedPayload, $secret); $signatureFound = false; foreach ($signatures as $signature) { if (Util\Util::secureCompare($expectedSignature, $signature)) { $signatureFound = true; break; } } if (!$signatureFound) { throw new Error\SignatureVerification( "No signatures found matching the expected signature for payload", $header, $payload ); } // Check if timestamp is within tolerance if (($tolerance > 0) && ((time() - $timestamp) > $tolerance)) { throw new Error\SignatureVerification( "Timestamp outside the tolerance zone", $header, $payload ); } return true; }
[ "public", "static", "function", "verifyHeader", "(", "$", "payload", ",", "$", "header", ",", "$", "secret", ",", "$", "tolerance", "=", "null", ")", "{", "// Extract timestamp and signatures from header", "$", "timestamp", "=", "self", "::", "getTimestamp", "(", "$", "header", ")", ";", "$", "signatures", "=", "self", "::", "getSignatures", "(", "$", "header", ",", "self", "::", "EXPECTED_SCHEME", ")", ";", "if", "(", "$", "timestamp", "==", "-", "1", ")", "{", "throw", "new", "Error", "\\", "SignatureVerification", "(", "\"Unable to extract timestamp and signatures from header\"", ",", "$", "header", ",", "$", "payload", ")", ";", "}", "if", "(", "empty", "(", "$", "signatures", ")", ")", "{", "throw", "new", "Error", "\\", "SignatureVerification", "(", "\"No signatures found with expected scheme\"", ",", "$", "header", ",", "$", "payload", ")", ";", "}", "// Check if expected signature is found in list of signatures from", "// header", "$", "signedPayload", "=", "\"$timestamp.$payload\"", ";", "$", "expectedSignature", "=", "self", "::", "computeSignature", "(", "$", "signedPayload", ",", "$", "secret", ")", ";", "$", "signatureFound", "=", "false", ";", "foreach", "(", "$", "signatures", "as", "$", "signature", ")", "{", "if", "(", "Util", "\\", "Util", "::", "secureCompare", "(", "$", "expectedSignature", ",", "$", "signature", ")", ")", "{", "$", "signatureFound", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "$", "signatureFound", ")", "{", "throw", "new", "Error", "\\", "SignatureVerification", "(", "\"No signatures found matching the expected signature for payload\"", ",", "$", "header", ",", "$", "payload", ")", ";", "}", "// Check if timestamp is within tolerance", "if", "(", "(", "$", "tolerance", ">", "0", ")", "&&", "(", "(", "time", "(", ")", "-", "$", "timestamp", ")", ">", "$", "tolerance", ")", ")", "{", "throw", "new", "Error", "\\", "SignatureVerification", "(", "\"Timestamp outside the tolerance zone\"", ",", "$", "header", ",", "$", "payload", ")", ";", "}", "return", "true", ";", "}" ]
Verifies the signature header sent by Stripe. Throws a SignatureVerification exception if the verification fails for any reason. @param string $payload the payload sent by Stripe. @param string $header the contents of the signature header sent by Stripe. @param string $secret secret used to generate the signature. @param int $tolerance maximum difference allowed between the header's timestamp and the current time @throws \Stripe\Error\SignatureVerification if the verification fails. @return bool
[ "Verifies", "the", "signature", "header", "sent", "by", "Stripe", ".", "Throws", "a", "SignatureVerification", "exception", "if", "the", "verification", "fails", "for", "any", "reason", "." ]
8f74cbe130f962d96d4ba92e75a44396a40cf41a
https://github.com/stripe/stripe-php/blob/8f74cbe130f962d96d4ba92e75a44396a40cf41a/lib/WebhookSignature.php#L23-L72
train
stripe/stripe-php
lib/WebhookSignature.php
WebhookSignature.getTimestamp
private static function getTimestamp($header) { $items = explode(",", $header); foreach ($items as $item) { $itemParts = explode("=", $item, 2); if ($itemParts[0] == "t") { if (!is_numeric($itemParts[1])) { return -1; } return intval($itemParts[1]); } } return -1; }
php
private static function getTimestamp($header) { $items = explode(",", $header); foreach ($items as $item) { $itemParts = explode("=", $item, 2); if ($itemParts[0] == "t") { if (!is_numeric($itemParts[1])) { return -1; } return intval($itemParts[1]); } } return -1; }
[ "private", "static", "function", "getTimestamp", "(", "$", "header", ")", "{", "$", "items", "=", "explode", "(", "\",\"", ",", "$", "header", ")", ";", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "$", "itemParts", "=", "explode", "(", "\"=\"", ",", "$", "item", ",", "2", ")", ";", "if", "(", "$", "itemParts", "[", "0", "]", "==", "\"t\"", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "itemParts", "[", "1", "]", ")", ")", "{", "return", "-", "1", ";", "}", "return", "intval", "(", "$", "itemParts", "[", "1", "]", ")", ";", "}", "}", "return", "-", "1", ";", "}" ]
Extracts the timestamp in a signature header. @param string $header the signature header @return int the timestamp contained in the header, or -1 if no valid timestamp is found
[ "Extracts", "the", "timestamp", "in", "a", "signature", "header", "." ]
8f74cbe130f962d96d4ba92e75a44396a40cf41a
https://github.com/stripe/stripe-php/blob/8f74cbe130f962d96d4ba92e75a44396a40cf41a/lib/WebhookSignature.php#L81-L96
train
stripe/stripe-php
lib/WebhookSignature.php
WebhookSignature.getSignatures
private static function getSignatures($header, $scheme) { $signatures = []; $items = explode(",", $header); foreach ($items as $item) { $itemParts = explode("=", $item, 2); if ($itemParts[0] == $scheme) { array_push($signatures, $itemParts[1]); } } return $signatures; }
php
private static function getSignatures($header, $scheme) { $signatures = []; $items = explode(",", $header); foreach ($items as $item) { $itemParts = explode("=", $item, 2); if ($itemParts[0] == $scheme) { array_push($signatures, $itemParts[1]); } } return $signatures; }
[ "private", "static", "function", "getSignatures", "(", "$", "header", ",", "$", "scheme", ")", "{", "$", "signatures", "=", "[", "]", ";", "$", "items", "=", "explode", "(", "\",\"", ",", "$", "header", ")", ";", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "$", "itemParts", "=", "explode", "(", "\"=\"", ",", "$", "item", ",", "2", ")", ";", "if", "(", "$", "itemParts", "[", "0", "]", "==", "$", "scheme", ")", "{", "array_push", "(", "$", "signatures", ",", "$", "itemParts", "[", "1", "]", ")", ";", "}", "}", "return", "$", "signatures", ";", "}" ]
Extracts the signatures matching a given scheme in a signature header. @param string $header the signature header @param string $scheme the signature scheme to look for. @return array the list of signatures matching the provided scheme.
[ "Extracts", "the", "signatures", "matching", "a", "given", "scheme", "in", "a", "signature", "header", "." ]
8f74cbe130f962d96d4ba92e75a44396a40cf41a
https://github.com/stripe/stripe-php/blob/8f74cbe130f962d96d4ba92e75a44396a40cf41a/lib/WebhookSignature.php#L105-L118
train
stripe/stripe-php
lib/StripeObject.php
StripeObject.constructFrom
public static function constructFrom($values, $opts = null) { $obj = new static(isset($values['id']) ? $values['id'] : null); $obj->refreshFrom($values, $opts); return $obj; }
php
public static function constructFrom($values, $opts = null) { $obj = new static(isset($values['id']) ? $values['id'] : null); $obj->refreshFrom($values, $opts); return $obj; }
[ "public", "static", "function", "constructFrom", "(", "$", "values", ",", "$", "opts", "=", "null", ")", "{", "$", "obj", "=", "new", "static", "(", "isset", "(", "$", "values", "[", "'id'", "]", ")", "?", "$", "values", "[", "'id'", "]", ":", "null", ")", ";", "$", "obj", "->", "refreshFrom", "(", "$", "values", ",", "$", "opts", ")", ";", "return", "$", "obj", ";", "}" ]
This unfortunately needs to be public to be used in Util\Util @param array $values @param null|string|array|Util\RequestOptions $opts @return static The object constructed from the given values.
[ "This", "unfortunately", "needs", "to", "be", "public", "to", "be", "used", "in", "Util", "\\", "Util" ]
8f74cbe130f962d96d4ba92e75a44396a40cf41a
https://github.com/stripe/stripe-php/blob/8f74cbe130f962d96d4ba92e75a44396a40cf41a/lib/StripeObject.php#L225-L230
train
stripe/stripe-php
lib/StripeObject.php
StripeObject.updateAttributes
public function updateAttributes($values, $opts = null, $dirty = true) { foreach ($values as $k => $v) { // Special-case metadata to always be cast as a StripeObject // This is necessary in case metadata is empty, as PHP arrays do // not differentiate between lists and hashes, and we consider // empty arrays to be lists. if (($k === "metadata") && (is_array($v))) { $this->_values[$k] = StripeObject::constructFrom($v, $opts); } else { $this->_values[$k] = Util\Util::convertToStripeObject($v, $opts); } if ($dirty) { $this->dirtyValue($this->_values[$k]); } $this->_unsavedValues->add($k); } }
php
public function updateAttributes($values, $opts = null, $dirty = true) { foreach ($values as $k => $v) { // Special-case metadata to always be cast as a StripeObject // This is necessary in case metadata is empty, as PHP arrays do // not differentiate between lists and hashes, and we consider // empty arrays to be lists. if (($k === "metadata") && (is_array($v))) { $this->_values[$k] = StripeObject::constructFrom($v, $opts); } else { $this->_values[$k] = Util\Util::convertToStripeObject($v, $opts); } if ($dirty) { $this->dirtyValue($this->_values[$k]); } $this->_unsavedValues->add($k); } }
[ "public", "function", "updateAttributes", "(", "$", "values", ",", "$", "opts", "=", "null", ",", "$", "dirty", "=", "true", ")", "{", "foreach", "(", "$", "values", "as", "$", "k", "=>", "$", "v", ")", "{", "// Special-case metadata to always be cast as a StripeObject", "// This is necessary in case metadata is empty, as PHP arrays do", "// not differentiate between lists and hashes, and we consider", "// empty arrays to be lists.", "if", "(", "(", "$", "k", "===", "\"metadata\"", ")", "&&", "(", "is_array", "(", "$", "v", ")", ")", ")", "{", "$", "this", "->", "_values", "[", "$", "k", "]", "=", "StripeObject", "::", "constructFrom", "(", "$", "v", ",", "$", "opts", ")", ";", "}", "else", "{", "$", "this", "->", "_values", "[", "$", "k", "]", "=", "Util", "\\", "Util", "::", "convertToStripeObject", "(", "$", "v", ",", "$", "opts", ")", ";", "}", "if", "(", "$", "dirty", ")", "{", "$", "this", "->", "dirtyValue", "(", "$", "this", "->", "_values", "[", "$", "k", "]", ")", ";", "}", "$", "this", "->", "_unsavedValues", "->", "add", "(", "$", "k", ")", ";", "}", "}" ]
Mass assigns attributes on the model. @param array $values @param null|string|array|Util\RequestOptions $opts @param boolean $dirty Defaults to true.
[ "Mass", "assigns", "attributes", "on", "the", "model", "." ]
8f74cbe130f962d96d4ba92e75a44396a40cf41a
https://github.com/stripe/stripe-php/blob/8f74cbe130f962d96d4ba92e75a44396a40cf41a/lib/StripeObject.php#L276-L293
train
stripe/stripe-php
lib/StripeObject.php
StripeObject.dirty
public function dirty() { $this->_unsavedValues = new Util\Set(array_keys($this->_values)); foreach ($this->_values as $k => $v) { $this->dirtyValue($v); } }
php
public function dirty() { $this->_unsavedValues = new Util\Set(array_keys($this->_values)); foreach ($this->_values as $k => $v) { $this->dirtyValue($v); } }
[ "public", "function", "dirty", "(", ")", "{", "$", "this", "->", "_unsavedValues", "=", "new", "Util", "\\", "Set", "(", "array_keys", "(", "$", "this", "->", "_values", ")", ")", ";", "foreach", "(", "$", "this", "->", "_values", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "this", "->", "dirtyValue", "(", "$", "v", ")", ";", "}", "}" ]
Sets all keys within the StripeObject as unsaved so that they will be included with an update when `serializeParameters` is called. This method is also recursive, so any StripeObjects contained as values or which are values in a tenant array are also marked as dirty.
[ "Sets", "all", "keys", "within", "the", "StripeObject", "as", "unsaved", "so", "that", "they", "will", "be", "included", "with", "an", "update", "when", "serializeParameters", "is", "called", ".", "This", "method", "is", "also", "recursive", "so", "any", "StripeObjects", "contained", "as", "values", "or", "which", "are", "values", "in", "a", "tenant", "array", "are", "also", "marked", "as", "dirty", "." ]
8f74cbe130f962d96d4ba92e75a44396a40cf41a
https://github.com/stripe/stripe-php/blob/8f74cbe130f962d96d4ba92e75a44396a40cf41a/lib/StripeObject.php#L433-L439
train
stripe/stripe-php
lib/StripeObject.php
StripeObject.deepCopy
protected static function deepCopy($obj) { if (is_array($obj)) { $copy = []; foreach ($obj as $k => $v) { $copy[$k] = self::deepCopy($v); } return $copy; } elseif ($obj instanceof StripeObject) { return $obj::constructFrom( self::deepCopy($obj->_values), clone $obj->_opts ); } else { return $obj; } }
php
protected static function deepCopy($obj) { if (is_array($obj)) { $copy = []; foreach ($obj as $k => $v) { $copy[$k] = self::deepCopy($v); } return $copy; } elseif ($obj instanceof StripeObject) { return $obj::constructFrom( self::deepCopy($obj->_values), clone $obj->_opts ); } else { return $obj; } }
[ "protected", "static", "function", "deepCopy", "(", "$", "obj", ")", "{", "if", "(", "is_array", "(", "$", "obj", ")", ")", "{", "$", "copy", "=", "[", "]", ";", "foreach", "(", "$", "obj", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "copy", "[", "$", "k", "]", "=", "self", "::", "deepCopy", "(", "$", "v", ")", ";", "}", "return", "$", "copy", ";", "}", "elseif", "(", "$", "obj", "instanceof", "StripeObject", ")", "{", "return", "$", "obj", "::", "constructFrom", "(", "self", "::", "deepCopy", "(", "$", "obj", "->", "_values", ")", ",", "clone", "$", "obj", "->", "_opts", ")", ";", "}", "else", "{", "return", "$", "obj", ";", "}", "}" ]
Produces a deep copy of the given object including support for arrays and StripeObjects.
[ "Produces", "a", "deep", "copy", "of", "the", "given", "object", "including", "support", "for", "arrays", "and", "StripeObjects", "." ]
8f74cbe130f962d96d4ba92e75a44396a40cf41a
https://github.com/stripe/stripe-php/blob/8f74cbe130f962d96d4ba92e75a44396a40cf41a/lib/StripeObject.php#L456-L472
train
stripe/stripe-php
lib/StripeObject.php
StripeObject.emptyValues
public static function emptyValues($obj) { if (is_array($obj)) { $values = $obj; } elseif ($obj instanceof StripeObject) { $values = $obj->_values; } else { throw new \InvalidArgumentException( "empty_values got got unexpected object type: " . get_class($obj) ); } $update = array_fill_keys(array_keys($values), ""); return $update; }
php
public static function emptyValues($obj) { if (is_array($obj)) { $values = $obj; } elseif ($obj instanceof StripeObject) { $values = $obj->_values; } else { throw new \InvalidArgumentException( "empty_values got got unexpected object type: " . get_class($obj) ); } $update = array_fill_keys(array_keys($values), ""); return $update; }
[ "public", "static", "function", "emptyValues", "(", "$", "obj", ")", "{", "if", "(", "is_array", "(", "$", "obj", ")", ")", "{", "$", "values", "=", "$", "obj", ";", "}", "elseif", "(", "$", "obj", "instanceof", "StripeObject", ")", "{", "$", "values", "=", "$", "obj", "->", "_values", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"empty_values got got unexpected object type: \"", ".", "get_class", "(", "$", "obj", ")", ")", ";", "}", "$", "update", "=", "array_fill_keys", "(", "array_keys", "(", "$", "values", ")", ",", "\"\"", ")", ";", "return", "$", "update", ";", "}" ]
Returns a hash of empty values for all the values that are in the given StripeObject.
[ "Returns", "a", "hash", "of", "empty", "values", "for", "all", "the", "values", "that", "are", "in", "the", "given", "StripeObject", "." ]
8f74cbe130f962d96d4ba92e75a44396a40cf41a
https://github.com/stripe/stripe-php/blob/8f74cbe130f962d96d4ba92e75a44396a40cf41a/lib/StripeObject.php#L478-L491
train
stripe/stripe-php
lib/Util/Util.php
Util.convertStripeObjectToArray
public static function convertStripeObjectToArray($values) { $results = []; foreach ($values as $k => $v) { // FIXME: this is an encapsulation violation if ($k[0] == '_') { continue; } if ($v instanceof StripeObject) { $results[$k] = $v->__toArray(true); } elseif (is_array($v)) { $results[$k] = self::convertStripeObjectToArray($v); } else { $results[$k] = $v; } } return $results; }
php
public static function convertStripeObjectToArray($values) { $results = []; foreach ($values as $k => $v) { // FIXME: this is an encapsulation violation if ($k[0] == '_') { continue; } if ($v instanceof StripeObject) { $results[$k] = $v->__toArray(true); } elseif (is_array($v)) { $results[$k] = self::convertStripeObjectToArray($v); } else { $results[$k] = $v; } } return $results; }
[ "public", "static", "function", "convertStripeObjectToArray", "(", "$", "values", ")", "{", "$", "results", "=", "[", "]", ";", "foreach", "(", "$", "values", "as", "$", "k", "=>", "$", "v", ")", "{", "// FIXME: this is an encapsulation violation", "if", "(", "$", "k", "[", "0", "]", "==", "'_'", ")", "{", "continue", ";", "}", "if", "(", "$", "v", "instanceof", "StripeObject", ")", "{", "$", "results", "[", "$", "k", "]", "=", "$", "v", "->", "__toArray", "(", "true", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "v", ")", ")", "{", "$", "results", "[", "$", "k", "]", "=", "self", "::", "convertStripeObjectToArray", "(", "$", "v", ")", ";", "}", "else", "{", "$", "results", "[", "$", "k", "]", "=", "$", "v", ";", "}", "}", "return", "$", "results", ";", "}" ]
Recursively converts the PHP Stripe object to an array. @param array $values The PHP Stripe object to convert. @return array
[ "Recursively", "converts", "the", "PHP", "Stripe", "object", "to", "an", "array", "." ]
8f74cbe130f962d96d4ba92e75a44396a40cf41a
https://github.com/stripe/stripe-php/blob/8f74cbe130f962d96d4ba92e75a44396a40cf41a/lib/Util/Util.php#L40-L57
train