repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
dingo/api
src/Http/Response/Factory.php
Factory.item
public function item($item, $transformer, $parameters = [], Closure $after = null) { $class = get_class($item); if ($parameters instanceof \Closure) { $after = $parameters; $parameters = []; } $binding = $this->transformer->register($class, $transformer, $parameters, $after); return new Response($item, 200, [], $binding); }
php
public function item($item, $transformer, $parameters = [], Closure $after = null) { $class = get_class($item); if ($parameters instanceof \Closure) { $after = $parameters; $parameters = []; } $binding = $this->transformer->register($class, $transformer, $parameters, $after); return new Response($item, 200, [], $binding); }
[ "public", "function", "item", "(", "$", "item", ",", "$", "transformer", ",", "$", "parameters", "=", "[", "]", ",", "Closure", "$", "after", "=", "null", ")", "{", "$", "class", "=", "get_class", "(", "$", "item", ")", ";", "if", "(", "$", "parameters", "instanceof", "\\", "Closure", ")", "{", "$", "after", "=", "$", "parameters", ";", "$", "parameters", "=", "[", "]", ";", "}", "$", "binding", "=", "$", "this", "->", "transformer", "->", "register", "(", "$", "class", ",", "$", "transformer", ",", "$", "parameters", ",", "$", "after", ")", ";", "return", "new", "Response", "(", "$", "item", ",", "200", ",", "[", "]", ",", "$", "binding", ")", ";", "}" ]
Bind an item to a transformer and start building a response. @param object $item @param string|callable|object $transformer @param array $parameters @param \Closure $after @return \Dingo\Api\Http\Response
[ "Bind", "an", "item", "to", "a", "transformer", "and", "start", "building", "a", "response", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/Response/Factory.php#L124-L136
train
dingo/api
src/Transformer/Binding.php
Binding.resolveTransformer
public function resolveTransformer() { if (is_string($this->resolver)) { return $this->container->make($this->resolver); } elseif (is_callable($this->resolver)) { return call_user_func($this->resolver, $this->container); } elseif (is_object($this->resolver)) { return $this->resolver; } throw new RuntimeException('Unable to resolve transformer binding.'); }
php
public function resolveTransformer() { if (is_string($this->resolver)) { return $this->container->make($this->resolver); } elseif (is_callable($this->resolver)) { return call_user_func($this->resolver, $this->container); } elseif (is_object($this->resolver)) { return $this->resolver; } throw new RuntimeException('Unable to resolve transformer binding.'); }
[ "public", "function", "resolveTransformer", "(", ")", "{", "if", "(", "is_string", "(", "$", "this", "->", "resolver", ")", ")", "{", "return", "$", "this", "->", "container", "->", "make", "(", "$", "this", "->", "resolver", ")", ";", "}", "elseif", "(", "is_callable", "(", "$", "this", "->", "resolver", ")", ")", "{", "return", "call_user_func", "(", "$", "this", "->", "resolver", ",", "$", "this", "->", "container", ")", ";", "}", "elseif", "(", "is_object", "(", "$", "this", "->", "resolver", ")", ")", "{", "return", "$", "this", "->", "resolver", ";", "}", "throw", "new", "RuntimeException", "(", "'Unable to resolve transformer binding.'", ")", ";", "}" ]
Resolve a transformer binding instance. @throws \RuntimeException @return object
[ "Resolve", "a", "transformer", "binding", "instance", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Transformer/Binding.php#L71-L82
train
dingo/api
src/Routing/RouteCollection.php
RouteCollection.addLookups
protected function addLookups(Route $route) { $action = $route->getAction(); if (isset($action['as'])) { $this->names[$action['as']] = $route; } if (isset($action['controller'])) { $this->actions[$action['controller']] = $route; } }
php
protected function addLookups(Route $route) { $action = $route->getAction(); if (isset($action['as'])) { $this->names[$action['as']] = $route; } if (isset($action['controller'])) { $this->actions[$action['controller']] = $route; } }
[ "protected", "function", "addLookups", "(", "Route", "$", "route", ")", "{", "$", "action", "=", "$", "route", "->", "getAction", "(", ")", ";", "if", "(", "isset", "(", "$", "action", "[", "'as'", "]", ")", ")", "{", "$", "this", "->", "names", "[", "$", "action", "[", "'as'", "]", "]", "=", "$", "route", ";", "}", "if", "(", "isset", "(", "$", "action", "[", "'controller'", "]", ")", ")", "{", "$", "this", "->", "actions", "[", "$", "action", "[", "'controller'", "]", "]", "=", "$", "route", ";", "}", "}" ]
Add route lookups. @param \Dingo\Api\Routing\Route $route @return void
[ "Add", "route", "lookups", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/RouteCollection.php#L55-L66
train
dingo/api
src/Routing/RouteCollection.php
RouteCollection.getByName
public function getByName($name) { return isset($this->names[$name]) ? $this->names[$name] : null; }
php
public function getByName($name) { return isset($this->names[$name]) ? $this->names[$name] : null; }
[ "public", "function", "getByName", "(", "$", "name", ")", "{", "return", "isset", "(", "$", "this", "->", "names", "[", "$", "name", "]", ")", "?", "$", "this", "->", "names", "[", "$", "name", "]", ":", "null", ";", "}" ]
Get a route by name. @param string $name @return \Dingo\Api\Routing\Route|null
[ "Get", "a", "route", "by", "name", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/RouteCollection.php#L75-L78
train
dingo/api
src/Routing/RouteCollection.php
RouteCollection.getByAction
public function getByAction($action) { return isset($this->actions[$action]) ? $this->actions[$action] : null; }
php
public function getByAction($action) { return isset($this->actions[$action]) ? $this->actions[$action] : null; }
[ "public", "function", "getByAction", "(", "$", "action", ")", "{", "return", "isset", "(", "$", "this", "->", "actions", "[", "$", "action", "]", ")", "?", "$", "this", "->", "actions", "[", "$", "action", "]", ":", "null", ";", "}" ]
Get a route by action. @param string $action @return \Dingo\Api\Routing\Route|null
[ "Get", "a", "route", "by", "action", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/RouteCollection.php#L87-L90
train
dingo/api
src/Console/Command/Routes.php
Routes.routeRateLimit
protected function routeRateLimit($route) { list($limit, $expires) = [$route->getRateLimit(), $route->getRateLimitExpiration()]; if ($limit && $expires) { return sprintf('%s req/s', round($limit / ($expires * 60), 2)); } }
php
protected function routeRateLimit($route) { list($limit, $expires) = [$route->getRateLimit(), $route->getRateLimitExpiration()]; if ($limit && $expires) { return sprintf('%s req/s', round($limit / ($expires * 60), 2)); } }
[ "protected", "function", "routeRateLimit", "(", "$", "route", ")", "{", "list", "(", "$", "limit", ",", "$", "expires", ")", "=", "[", "$", "route", "->", "getRateLimit", "(", ")", ",", "$", "route", "->", "getRateLimitExpiration", "(", ")", "]", ";", "if", "(", "$", "limit", "&&", "$", "expires", ")", "{", "return", "sprintf", "(", "'%s req/s'", ",", "round", "(", "$", "limit", "/", "(", "$", "expires", "*", "60", ")", ",", "2", ")", ")", ";", "}", "}" ]
Display the routes rate limiting requests per second. This takes the limit and divides it by the expiration time in seconds to give you a rough idea of how many requests you'd be able to fire off per second on the route. @param \Dingo\Api\Routing\Route $route @return null|string
[ "Display", "the", "routes", "rate", "limiting", "requests", "per", "second", ".", "This", "takes", "the", "limit", "and", "divides", "it", "by", "the", "expiration", "time", "in", "seconds", "to", "give", "you", "a", "rough", "idea", "of", "how", "many", "requests", "you", "d", "be", "able", "to", "fire", "off", "per", "second", "on", "the", "route", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Console/Command/Routes.php#L145-L152
train
dingo/api
src/Console/Command/Routes.php
Routes.filterByVersions
protected function filterByVersions(array $route) { foreach ($this->option('versions') as $version) { if (Str::contains($route['versions'], $version)) { return true; } } return false; }
php
protected function filterByVersions(array $route) { foreach ($this->option('versions') as $version) { if (Str::contains($route['versions'], $version)) { return true; } } return false; }
[ "protected", "function", "filterByVersions", "(", "array", "$", "route", ")", "{", "foreach", "(", "$", "this", "->", "option", "(", "'versions'", ")", "as", "$", "version", ")", "{", "if", "(", "Str", "::", "contains", "(", "$", "route", "[", "'versions'", "]", ",", "$", "version", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Filter the route by its versions. @param array $route @return bool
[ "Filter", "the", "route", "by", "its", "versions", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Console/Command/Routes.php#L245-L254
train
dingo/api
src/Console/Command/Routes.php
Routes.filterByScopes
protected function filterByScopes(array $route) { foreach ($this->option('scopes') as $scope) { if (Str::contains($route['scopes'], $scope)) { return true; } } return false; }
php
protected function filterByScopes(array $route) { foreach ($this->option('scopes') as $scope) { if (Str::contains($route['scopes'], $scope)) { return true; } } return false; }
[ "protected", "function", "filterByScopes", "(", "array", "$", "route", ")", "{", "foreach", "(", "$", "this", "->", "option", "(", "'scopes'", ")", "as", "$", "scope", ")", "{", "if", "(", "Str", "::", "contains", "(", "$", "route", "[", "'scopes'", "]", ",", "$", "scope", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Filter the route by its scopes. @param array $route @return bool
[ "Filter", "the", "route", "by", "its", "scopes", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Console/Command/Routes.php#L275-L284
train
dingo/api
src/Transformer/Factory.php
Factory.register
public function register($class, $resolver, array $parameters = [], Closure $after = null) { return $this->bindings[$class] = $this->createBinding($resolver, $parameters, $after); }
php
public function register($class, $resolver, array $parameters = [], Closure $after = null) { return $this->bindings[$class] = $this->createBinding($resolver, $parameters, $after); }
[ "public", "function", "register", "(", "$", "class", ",", "$", "resolver", ",", "array", "$", "parameters", "=", "[", "]", ",", "Closure", "$", "after", "=", "null", ")", "{", "return", "$", "this", "->", "bindings", "[", "$", "class", "]", "=", "$", "this", "->", "createBinding", "(", "$", "resolver", ",", "$", "parameters", ",", "$", "after", ")", ";", "}" ]
Register a transformer binding resolver for a class. @param $class @param $resolver @param array $parameters @param \Closure|null $after @return \Dingo\Api\Transformer\Binding
[ "Register", "a", "transformer", "binding", "resolver", "for", "a", "class", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Transformer/Factory.php#L61-L64
train
dingo/api
src/Transformer/Factory.php
Factory.transform
public function transform($response) { $binding = $this->getBinding($response); return $this->adapter->transform($response, $binding->resolveTransformer(), $binding, $this->getRequest()); }
php
public function transform($response) { $binding = $this->getBinding($response); return $this->adapter->transform($response, $binding->resolveTransformer(), $binding, $this->getRequest()); }
[ "public", "function", "transform", "(", "$", "response", ")", "{", "$", "binding", "=", "$", "this", "->", "getBinding", "(", "$", "response", ")", ";", "return", "$", "this", "->", "adapter", "->", "transform", "(", "$", "response", ",", "$", "binding", "->", "resolveTransformer", "(", ")", ",", "$", "binding", ",", "$", "this", "->", "getRequest", "(", ")", ")", ";", "}" ]
Transform a response. @param string|object $response @return mixed
[ "Transform", "a", "response", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Transformer/Factory.php#L73-L78
train
dingo/api
src/Transformer/Factory.php
Factory.getBinding
protected function getBinding($class) { if ($this->isCollection($class) && ! $class->isEmpty()) { return $this->getBindingFromCollection($class); } $class = is_object($class) ? get_class($class) : $class; if (! $this->hasBinding($class)) { throw new RuntimeException('Unable to find bound transformer for "'.$class.'" class.'); } return $this->bindings[$class]; }
php
protected function getBinding($class) { if ($this->isCollection($class) && ! $class->isEmpty()) { return $this->getBindingFromCollection($class); } $class = is_object($class) ? get_class($class) : $class; if (! $this->hasBinding($class)) { throw new RuntimeException('Unable to find bound transformer for "'.$class.'" class.'); } return $this->bindings[$class]; }
[ "protected", "function", "getBinding", "(", "$", "class", ")", "{", "if", "(", "$", "this", "->", "isCollection", "(", "$", "class", ")", "&&", "!", "$", "class", "->", "isEmpty", "(", ")", ")", "{", "return", "$", "this", "->", "getBindingFromCollection", "(", "$", "class", ")", ";", "}", "$", "class", "=", "is_object", "(", "$", "class", ")", "?", "get_class", "(", "$", "class", ")", ":", "$", "class", ";", "if", "(", "!", "$", "this", "->", "hasBinding", "(", "$", "class", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'Unable to find bound transformer for \"'", ".", "$", "class", ".", "'\" class.'", ")", ";", "}", "return", "$", "this", "->", "bindings", "[", "$", "class", "]", ";", "}" ]
Get a registered transformer binding. @param string|object $class @throws \RuntimeException @return \Dingo\Api\Transformer\Binding
[ "Get", "a", "registered", "transformer", "binding", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Transformer/Factory.php#L113-L126
train
dingo/api
src/Transformer/Factory.php
Factory.createBinding
protected function createBinding($resolver, array $parameters = [], Closure $callback = null) { return new Binding($this->container, $resolver, $parameters, $callback); }
php
protected function createBinding($resolver, array $parameters = [], Closure $callback = null) { return new Binding($this->container, $resolver, $parameters, $callback); }
[ "protected", "function", "createBinding", "(", "$", "resolver", ",", "array", "$", "parameters", "=", "[", "]", ",", "Closure", "$", "callback", "=", "null", ")", "{", "return", "new", "Binding", "(", "$", "this", "->", "container", ",", "$", "resolver", ",", "$", "parameters", ",", "$", "callback", ")", ";", "}" ]
Create a new binding instance. @param string|callable|object $resolver @param array $parameters @param \Closure $callback @return \Dingo\Api\Transformer\Binding
[ "Create", "a", "new", "binding", "instance", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Transformer/Factory.php#L137-L140
train
dingo/api
src/Transformer/Factory.php
Factory.hasBinding
protected function hasBinding($class) { if ($this->isCollection($class) && ! $class->isEmpty()) { $class = $class->first(); } $class = is_object($class) ? get_class($class) : $class; return isset($this->bindings[$class]); }
php
protected function hasBinding($class) { if ($this->isCollection($class) && ! $class->isEmpty()) { $class = $class->first(); } $class = is_object($class) ? get_class($class) : $class; return isset($this->bindings[$class]); }
[ "protected", "function", "hasBinding", "(", "$", "class", ")", "{", "if", "(", "$", "this", "->", "isCollection", "(", "$", "class", ")", "&&", "!", "$", "class", "->", "isEmpty", "(", ")", ")", "{", "$", "class", "=", "$", "class", "->", "first", "(", ")", ";", "}", "$", "class", "=", "is_object", "(", "$", "class", ")", "?", "get_class", "(", "$", "class", ")", ":", "$", "class", ";", "return", "isset", "(", "$", "this", "->", "bindings", "[", "$", "class", "]", ")", ";", "}" ]
Determine if a class has a transformer binding. @param string|object $class @return bool
[ "Determine", "if", "a", "class", "has", "a", "transformer", "binding", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Transformer/Factory.php#L161-L170
train
dingo/api
src/Transformer/Factory.php
Factory.getRequest
public function getRequest() { $request = $this->container['request']; if ($request instanceof IlluminateRequest && ! $request instanceof Request) { $request = (new Request())->createFromIlluminate($request); } return $request; }
php
public function getRequest() { $request = $this->container['request']; if ($request instanceof IlluminateRequest && ! $request instanceof Request) { $request = (new Request())->createFromIlluminate($request); } return $request; }
[ "public", "function", "getRequest", "(", ")", "{", "$", "request", "=", "$", "this", "->", "container", "[", "'request'", "]", ";", "if", "(", "$", "request", "instanceof", "IlluminateRequest", "&&", "!", "$", "request", "instanceof", "Request", ")", "{", "$", "request", "=", "(", "new", "Request", "(", ")", ")", "->", "createFromIlluminate", "(", "$", "request", ")", ";", "}", "return", "$", "request", ";", "}" ]
Get the request from the container. @return \Dingo\Api\Http\Request
[ "Get", "the", "request", "from", "the", "container", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Transformer/Factory.php#L225-L234
train
dingo/api
src/Routing/Adapter/Lumen.php
Lumen.normalizeRequestUri
protected function normalizeRequestUri(Request $request) { $query = $request->server->get('QUERY_STRING'); $uri = '/'.trim(str_replace('?'.$query, '', $request->server->get('REQUEST_URI')), '/').($query ? '?'.$query : ''); $request->server->set('REQUEST_URI', $uri); }
php
protected function normalizeRequestUri(Request $request) { $query = $request->server->get('QUERY_STRING'); $uri = '/'.trim(str_replace('?'.$query, '', $request->server->get('REQUEST_URI')), '/').($query ? '?'.$query : ''); $request->server->set('REQUEST_URI', $uri); }
[ "protected", "function", "normalizeRequestUri", "(", "Request", "$", "request", ")", "{", "$", "query", "=", "$", "request", "->", "server", "->", "get", "(", "'QUERY_STRING'", ")", ";", "$", "uri", "=", "'/'", ".", "trim", "(", "str_replace", "(", "'?'", ".", "$", "query", ",", "''", ",", "$", "request", "->", "server", "->", "get", "(", "'REQUEST_URI'", ")", ")", ",", "'/'", ")", ".", "(", "$", "query", "?", "'?'", ".", "$", "query", ":", "''", ")", ";", "$", "request", "->", "server", "->", "set", "(", "'REQUEST_URI'", ",", "$", "uri", ")", ";", "}" ]
Normalize the request URI so that Lumen can properly dispatch it. @param \Illuminate\Http\Request $request @return void
[ "Normalize", "the", "request", "URI", "so", "that", "Lumen", "can", "properly", "dispatch", "it", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Adapter/Lumen.php#L148-L155
train
dingo/api
src/Routing/Adapter/Lumen.php
Lumen.breakUriSegments
protected function breakUriSegments($uri) { if (! Str::contains($uri, '?}')) { return (array) $uri; } $segments = preg_split( '/\/(\{.*?\})/', preg_replace('/\{(.*?)\?\}/', '{$1}', $uri), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY ); $uris = []; while ($segments) { $uris[] = implode('/', $segments); array_pop($segments); } return $uris; }
php
protected function breakUriSegments($uri) { if (! Str::contains($uri, '?}')) { return (array) $uri; } $segments = preg_split( '/\/(\{.*?\})/', preg_replace('/\{(.*?)\?\}/', '{$1}', $uri), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY ); $uris = []; while ($segments) { $uris[] = implode('/', $segments); array_pop($segments); } return $uris; }
[ "protected", "function", "breakUriSegments", "(", "$", "uri", ")", "{", "if", "(", "!", "Str", "::", "contains", "(", "$", "uri", ",", "'?}'", ")", ")", "{", "return", "(", "array", ")", "$", "uri", ";", "}", "$", "segments", "=", "preg_split", "(", "'/\\/(\\{.*?\\})/'", ",", "preg_replace", "(", "'/\\{(.*?)\\?\\}/'", ",", "'{$1}'", ",", "$", "uri", ")", ",", "-", "1", ",", "PREG_SPLIT_DELIM_CAPTURE", "|", "PREG_SPLIT_NO_EMPTY", ")", ";", "$", "uris", "=", "[", "]", ";", "while", "(", "$", "segments", ")", "{", "$", "uris", "[", "]", "=", "implode", "(", "'/'", ",", "$", "segments", ")", ";", "array_pop", "(", "$", "segments", ")", ";", "}", "return", "$", "uris", ";", "}" ]
Break a URI that has optional segments into individual URIs. @param string $uri @return array
[ "Break", "a", "URI", "that", "has", "optional", "segments", "into", "individual", "URIs", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Adapter/Lumen.php#L206-L228
train
dingo/api
src/Routing/Adapter/Lumen.php
Lumen.removeMiddlewareFromApp
protected function removeMiddlewareFromApp() { if ($this->middlewareRemoved) { return; } $this->middlewareRemoved = true; $reflection = new ReflectionClass($this->app); $property = $reflection->getProperty('middleware'); $property->setAccessible(true); $oldMiddlewares = $property->getValue($this->app); $newMiddlewares = []; foreach ($oldMiddlewares as $middle) { if ((new ReflectionClass($middle))->hasMethod('terminate') && $middle != 'Dingo\Api\Http\Middleware\Request') { $newMiddlewares = array_merge($newMiddlewares, [$middle]); } } $property->setValue($this->app, $newMiddlewares); $property->setAccessible(false); }
php
protected function removeMiddlewareFromApp() { if ($this->middlewareRemoved) { return; } $this->middlewareRemoved = true; $reflection = new ReflectionClass($this->app); $property = $reflection->getProperty('middleware'); $property->setAccessible(true); $oldMiddlewares = $property->getValue($this->app); $newMiddlewares = []; foreach ($oldMiddlewares as $middle) { if ((new ReflectionClass($middle))->hasMethod('terminate') && $middle != 'Dingo\Api\Http\Middleware\Request') { $newMiddlewares = array_merge($newMiddlewares, [$middle]); } } $property->setValue($this->app, $newMiddlewares); $property->setAccessible(false); }
[ "protected", "function", "removeMiddlewareFromApp", "(", ")", "{", "if", "(", "$", "this", "->", "middlewareRemoved", ")", "{", "return", ";", "}", "$", "this", "->", "middlewareRemoved", "=", "true", ";", "$", "reflection", "=", "new", "ReflectionClass", "(", "$", "this", "->", "app", ")", ";", "$", "property", "=", "$", "reflection", "->", "getProperty", "(", "'middleware'", ")", ";", "$", "property", "->", "setAccessible", "(", "true", ")", ";", "$", "oldMiddlewares", "=", "$", "property", "->", "getValue", "(", "$", "this", "->", "app", ")", ";", "$", "newMiddlewares", "=", "[", "]", ";", "foreach", "(", "$", "oldMiddlewares", "as", "$", "middle", ")", "{", "if", "(", "(", "new", "ReflectionClass", "(", "$", "middle", ")", ")", "->", "hasMethod", "(", "'terminate'", ")", "&&", "$", "middle", "!=", "'Dingo\\Api\\Http\\Middleware\\Request'", ")", "{", "$", "newMiddlewares", "=", "array_merge", "(", "$", "newMiddlewares", ",", "[", "$", "middle", "]", ")", ";", "}", "}", "$", "property", "->", "setValue", "(", "$", "this", "->", "app", ",", "$", "newMiddlewares", ")", ";", "$", "property", "->", "setAccessible", "(", "false", ")", ";", "}" ]
Remove the global application middleware as it's run from this packages Request middleware. Lumen runs middleware later in its life cycle which results in some middleware being executed twice. @return void
[ "Remove", "the", "global", "application", "middleware", "as", "it", "s", "run", "from", "this", "packages", "Request", "middleware", ".", "Lumen", "runs", "middleware", "later", "in", "its", "life", "cycle", "which", "results", "in", "some", "middleware", "being", "executed", "twice", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Adapter/Lumen.php#L253-L273
train
dingo/api
src/Routing/Adapter/Lumen.php
Lumen.getIterableRoutes
public function getIterableRoutes($version = null) { $iterable = []; foreach ($this->getRoutes($version) as $version => $collector) { $routeData = $collector->getData(); // The first element in the array are the static routes that do not have any parameters. foreach ($this->normalizeStaticRoutes($routeData[0]) as $method => $routes) { if ($method === 'HEAD') { continue; } foreach ($routes as $route) { $route['methods'] = $this->setRouteMethods($route, $method); $iterable[$version][] = $route; } } // The second element is the more complicated regex routes that have parameters. foreach ($routeData[1] as $method => $routes) { if ($method === 'HEAD') { continue; } foreach ($routes as $data) { foreach ($data['routeMap'] as list($route, $parameters)) { $route['methods'] = $this->setRouteMethods($route, $method); $iterable[$version][] = $route; } } } } return new ArrayIterator($iterable); }
php
public function getIterableRoutes($version = null) { $iterable = []; foreach ($this->getRoutes($version) as $version => $collector) { $routeData = $collector->getData(); // The first element in the array are the static routes that do not have any parameters. foreach ($this->normalizeStaticRoutes($routeData[0]) as $method => $routes) { if ($method === 'HEAD') { continue; } foreach ($routes as $route) { $route['methods'] = $this->setRouteMethods($route, $method); $iterable[$version][] = $route; } } // The second element is the more complicated regex routes that have parameters. foreach ($routeData[1] as $method => $routes) { if ($method === 'HEAD') { continue; } foreach ($routes as $data) { foreach ($data['routeMap'] as list($route, $parameters)) { $route['methods'] = $this->setRouteMethods($route, $method); $iterable[$version][] = $route; } } } } return new ArrayIterator($iterable); }
[ "public", "function", "getIterableRoutes", "(", "$", "version", "=", "null", ")", "{", "$", "iterable", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getRoutes", "(", "$", "version", ")", "as", "$", "version", "=>", "$", "collector", ")", "{", "$", "routeData", "=", "$", "collector", "->", "getData", "(", ")", ";", "// The first element in the array are the static routes that do not have any parameters.", "foreach", "(", "$", "this", "->", "normalizeStaticRoutes", "(", "$", "routeData", "[", "0", "]", ")", "as", "$", "method", "=>", "$", "routes", ")", "{", "if", "(", "$", "method", "===", "'HEAD'", ")", "{", "continue", ";", "}", "foreach", "(", "$", "routes", "as", "$", "route", ")", "{", "$", "route", "[", "'methods'", "]", "=", "$", "this", "->", "setRouteMethods", "(", "$", "route", ",", "$", "method", ")", ";", "$", "iterable", "[", "$", "version", "]", "[", "]", "=", "$", "route", ";", "}", "}", "// The second element is the more complicated regex routes that have parameters.", "foreach", "(", "$", "routeData", "[", "1", "]", "as", "$", "method", "=>", "$", "routes", ")", "{", "if", "(", "$", "method", "===", "'HEAD'", ")", "{", "continue", ";", "}", "foreach", "(", "$", "routes", "as", "$", "data", ")", "{", "foreach", "(", "$", "data", "[", "'routeMap'", "]", "as", "list", "(", "$", "route", ",", "$", "parameters", ")", ")", "{", "$", "route", "[", "'methods'", "]", "=", "$", "this", "->", "setRouteMethods", "(", "$", "route", ",", "$", "method", ")", ";", "$", "iterable", "[", "$", "version", "]", "[", "]", "=", "$", "route", ";", "}", "}", "}", "}", "return", "new", "ArrayIterator", "(", "$", "iterable", ")", ";", "}" ]
Get routes in an iterable form. @param string $version @return \ArrayIterator
[ "Get", "routes", "in", "an", "iterable", "form", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Adapter/Lumen.php#L298-L335
train
dingo/api
src/Http/Middleware/Request.php
Request.terminate
public function terminate($request, $response) { if (! ($request = $this->app['request']) instanceof HttpRequest) { return; } // Laravel's route middlewares can be terminated just like application // middleware, so we'll gather all the route middleware here. // On Lumen this will simply be an empty array as it does // not implement terminable route middleware. $middlewares = $this->gatherRouteMiddlewares($request); // Because of how middleware is executed on Lumen we'll need to merge in the // application middlewares now so that we can terminate them. Laravel does // not need this as it handles things a little more gracefully so it // can terminate the application ones itself. if (class_exists(Application::class, false)) { $middlewares = array_merge($middlewares, $this->middleware); } foreach ($middlewares as $middleware) { if ($middleware instanceof Closure) { continue; } list($name, $parameters) = $this->parseMiddleware($middleware); $instance = $this->app->make($name); if (method_exists($instance, 'terminate')) { $instance->terminate($request, $response); } } }
php
public function terminate($request, $response) { if (! ($request = $this->app['request']) instanceof HttpRequest) { return; } // Laravel's route middlewares can be terminated just like application // middleware, so we'll gather all the route middleware here. // On Lumen this will simply be an empty array as it does // not implement terminable route middleware. $middlewares = $this->gatherRouteMiddlewares($request); // Because of how middleware is executed on Lumen we'll need to merge in the // application middlewares now so that we can terminate them. Laravel does // not need this as it handles things a little more gracefully so it // can terminate the application ones itself. if (class_exists(Application::class, false)) { $middlewares = array_merge($middlewares, $this->middleware); } foreach ($middlewares as $middleware) { if ($middleware instanceof Closure) { continue; } list($name, $parameters) = $this->parseMiddleware($middleware); $instance = $this->app->make($name); if (method_exists($instance, 'terminate')) { $instance->terminate($request, $response); } } }
[ "public", "function", "terminate", "(", "$", "request", ",", "$", "response", ")", "{", "if", "(", "!", "(", "$", "request", "=", "$", "this", "->", "app", "[", "'request'", "]", ")", "instanceof", "HttpRequest", ")", "{", "return", ";", "}", "// Laravel's route middlewares can be terminated just like application", "// middleware, so we'll gather all the route middleware here.", "// On Lumen this will simply be an empty array as it does", "// not implement terminable route middleware.", "$", "middlewares", "=", "$", "this", "->", "gatherRouteMiddlewares", "(", "$", "request", ")", ";", "// Because of how middleware is executed on Lumen we'll need to merge in the", "// application middlewares now so that we can terminate them. Laravel does", "// not need this as it handles things a little more gracefully so it", "// can terminate the application ones itself.", "if", "(", "class_exists", "(", "Application", "::", "class", ",", "false", ")", ")", "{", "$", "middlewares", "=", "array_merge", "(", "$", "middlewares", ",", "$", "this", "->", "middleware", ")", ";", "}", "foreach", "(", "$", "middlewares", "as", "$", "middleware", ")", "{", "if", "(", "$", "middleware", "instanceof", "Closure", ")", "{", "continue", ";", "}", "list", "(", "$", "name", ",", "$", "parameters", ")", "=", "$", "this", "->", "parseMiddleware", "(", "$", "middleware", ")", ";", "$", "instance", "=", "$", "this", "->", "app", "->", "make", "(", "$", "name", ")", ";", "if", "(", "method_exists", "(", "$", "instance", ",", "'terminate'", ")", ")", "{", "$", "instance", "->", "terminate", "(", "$", "request", ",", "$", "response", ")", ";", "}", "}", "}" ]
Call the terminate method on middlewares. @return void
[ "Call", "the", "terminate", "method", "on", "middlewares", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/Middleware/Request.php#L135-L168
train
dingo/api
src/Routing/Route.php
Route.setupRouteProperties
protected function setupRouteProperties(Request $request, $route) { list($this->uri, $this->methods, $this->action) = $this->adapter->getRouteProperties($route, $request); $this->versions = Arr::pull($this->action, 'version'); $this->conditionalRequest = Arr::pull($this->action, 'conditionalRequest', true); $this->middleware = (array) Arr::pull($this->action, 'middleware', []); $this->throttle = Arr::pull($this->action, 'throttle'); $this->scopes = Arr::pull($this->action, 'scopes', []); $this->authenticationProviders = Arr::pull($this->action, 'providers', []); $this->rateLimit = Arr::pull($this->action, 'limit', 0); $this->rateExpiration = Arr::pull($this->action, 'expires', 0); // Now that the default route properties have been set we'll go ahead and merge // any controller properties to fully configure the route. $this->mergeControllerProperties(); // If we have a string based throttle then we'll new up an instance of the // throttle through the container. if (is_string($this->throttle)) { $this->throttle = $this->container->make($this->throttle); } }
php
protected function setupRouteProperties(Request $request, $route) { list($this->uri, $this->methods, $this->action) = $this->adapter->getRouteProperties($route, $request); $this->versions = Arr::pull($this->action, 'version'); $this->conditionalRequest = Arr::pull($this->action, 'conditionalRequest', true); $this->middleware = (array) Arr::pull($this->action, 'middleware', []); $this->throttle = Arr::pull($this->action, 'throttle'); $this->scopes = Arr::pull($this->action, 'scopes', []); $this->authenticationProviders = Arr::pull($this->action, 'providers', []); $this->rateLimit = Arr::pull($this->action, 'limit', 0); $this->rateExpiration = Arr::pull($this->action, 'expires', 0); // Now that the default route properties have been set we'll go ahead and merge // any controller properties to fully configure the route. $this->mergeControllerProperties(); // If we have a string based throttle then we'll new up an instance of the // throttle through the container. if (is_string($this->throttle)) { $this->throttle = $this->container->make($this->throttle); } }
[ "protected", "function", "setupRouteProperties", "(", "Request", "$", "request", ",", "$", "route", ")", "{", "list", "(", "$", "this", "->", "uri", ",", "$", "this", "->", "methods", ",", "$", "this", "->", "action", ")", "=", "$", "this", "->", "adapter", "->", "getRouteProperties", "(", "$", "route", ",", "$", "request", ")", ";", "$", "this", "->", "versions", "=", "Arr", "::", "pull", "(", "$", "this", "->", "action", ",", "'version'", ")", ";", "$", "this", "->", "conditionalRequest", "=", "Arr", "::", "pull", "(", "$", "this", "->", "action", ",", "'conditionalRequest'", ",", "true", ")", ";", "$", "this", "->", "middleware", "=", "(", "array", ")", "Arr", "::", "pull", "(", "$", "this", "->", "action", ",", "'middleware'", ",", "[", "]", ")", ";", "$", "this", "->", "throttle", "=", "Arr", "::", "pull", "(", "$", "this", "->", "action", ",", "'throttle'", ")", ";", "$", "this", "->", "scopes", "=", "Arr", "::", "pull", "(", "$", "this", "->", "action", ",", "'scopes'", ",", "[", "]", ")", ";", "$", "this", "->", "authenticationProviders", "=", "Arr", "::", "pull", "(", "$", "this", "->", "action", ",", "'providers'", ",", "[", "]", ")", ";", "$", "this", "->", "rateLimit", "=", "Arr", "::", "pull", "(", "$", "this", "->", "action", ",", "'limit'", ",", "0", ")", ";", "$", "this", "->", "rateExpiration", "=", "Arr", "::", "pull", "(", "$", "this", "->", "action", ",", "'expires'", ",", "0", ")", ";", "// Now that the default route properties have been set we'll go ahead and merge", "// any controller properties to fully configure the route.", "$", "this", "->", "mergeControllerProperties", "(", ")", ";", "// If we have a string based throttle then we'll new up an instance of the", "// throttle through the container.", "if", "(", "is_string", "(", "$", "this", "->", "throttle", ")", ")", "{", "$", "this", "->", "throttle", "=", "$", "this", "->", "container", "->", "make", "(", "$", "this", "->", "throttle", ")", ";", "}", "}" ]
Setup the route properties. @param Request $request @param $route @return void
[ "Setup", "the", "route", "properties", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Route.php#L111-L133
train
dingo/api
src/Routing/Route.php
Route.mergeControllerProperties
protected function mergeControllerProperties() { if (isset($this->action['uses']) && is_string($this->action['uses']) && Str::contains($this->action['uses'], '@')) { $this->action['controller'] = $this->action['uses']; $this->makeControllerInstance(); } if (! $this->controllerUsesHelpersTrait()) { return; } $controller = $this->getControllerInstance(); $controllerMiddleware = []; if (method_exists($controller, 'getMiddleware')) { $controllerMiddleware = $controller->getMiddleware(); } elseif (method_exists($controller, 'getMiddlewareForMethod')) { $controllerMiddleware = $controller->getMiddlewareForMethod($this->controllerMethod); } $this->middleware = array_merge($this->middleware, $controllerMiddleware); if ($property = $this->findControllerPropertyOptions('throttles')) { $this->throttle = $property['class']; } if ($property = $this->findControllerPropertyOptions('scopes')) { $this->scopes = array_merge($this->scopes, $property['scopes']); } if ($property = $this->findControllerPropertyOptions('authenticationProviders')) { $this->authenticationProviders = array_merge($this->authenticationProviders, $property['providers']); } if ($property = $this->findControllerPropertyOptions('rateLimit')) { $this->rateLimit = $property['limit']; $this->rateExpiration = $property['expires']; } }
php
protected function mergeControllerProperties() { if (isset($this->action['uses']) && is_string($this->action['uses']) && Str::contains($this->action['uses'], '@')) { $this->action['controller'] = $this->action['uses']; $this->makeControllerInstance(); } if (! $this->controllerUsesHelpersTrait()) { return; } $controller = $this->getControllerInstance(); $controllerMiddleware = []; if (method_exists($controller, 'getMiddleware')) { $controllerMiddleware = $controller->getMiddleware(); } elseif (method_exists($controller, 'getMiddlewareForMethod')) { $controllerMiddleware = $controller->getMiddlewareForMethod($this->controllerMethod); } $this->middleware = array_merge($this->middleware, $controllerMiddleware); if ($property = $this->findControllerPropertyOptions('throttles')) { $this->throttle = $property['class']; } if ($property = $this->findControllerPropertyOptions('scopes')) { $this->scopes = array_merge($this->scopes, $property['scopes']); } if ($property = $this->findControllerPropertyOptions('authenticationProviders')) { $this->authenticationProviders = array_merge($this->authenticationProviders, $property['providers']); } if ($property = $this->findControllerPropertyOptions('rateLimit')) { $this->rateLimit = $property['limit']; $this->rateExpiration = $property['expires']; } }
[ "protected", "function", "mergeControllerProperties", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "action", "[", "'uses'", "]", ")", "&&", "is_string", "(", "$", "this", "->", "action", "[", "'uses'", "]", ")", "&&", "Str", "::", "contains", "(", "$", "this", "->", "action", "[", "'uses'", "]", ",", "'@'", ")", ")", "{", "$", "this", "->", "action", "[", "'controller'", "]", "=", "$", "this", "->", "action", "[", "'uses'", "]", ";", "$", "this", "->", "makeControllerInstance", "(", ")", ";", "}", "if", "(", "!", "$", "this", "->", "controllerUsesHelpersTrait", "(", ")", ")", "{", "return", ";", "}", "$", "controller", "=", "$", "this", "->", "getControllerInstance", "(", ")", ";", "$", "controllerMiddleware", "=", "[", "]", ";", "if", "(", "method_exists", "(", "$", "controller", ",", "'getMiddleware'", ")", ")", "{", "$", "controllerMiddleware", "=", "$", "controller", "->", "getMiddleware", "(", ")", ";", "}", "elseif", "(", "method_exists", "(", "$", "controller", ",", "'getMiddlewareForMethod'", ")", ")", "{", "$", "controllerMiddleware", "=", "$", "controller", "->", "getMiddlewareForMethod", "(", "$", "this", "->", "controllerMethod", ")", ";", "}", "$", "this", "->", "middleware", "=", "array_merge", "(", "$", "this", "->", "middleware", ",", "$", "controllerMiddleware", ")", ";", "if", "(", "$", "property", "=", "$", "this", "->", "findControllerPropertyOptions", "(", "'throttles'", ")", ")", "{", "$", "this", "->", "throttle", "=", "$", "property", "[", "'class'", "]", ";", "}", "if", "(", "$", "property", "=", "$", "this", "->", "findControllerPropertyOptions", "(", "'scopes'", ")", ")", "{", "$", "this", "->", "scopes", "=", "array_merge", "(", "$", "this", "->", "scopes", ",", "$", "property", "[", "'scopes'", "]", ")", ";", "}", "if", "(", "$", "property", "=", "$", "this", "->", "findControllerPropertyOptions", "(", "'authenticationProviders'", ")", ")", "{", "$", "this", "->", "authenticationProviders", "=", "array_merge", "(", "$", "this", "->", "authenticationProviders", ",", "$", "property", "[", "'providers'", "]", ")", ";", "}", "if", "(", "$", "property", "=", "$", "this", "->", "findControllerPropertyOptions", "(", "'rateLimit'", ")", ")", "{", "$", "this", "->", "rateLimit", "=", "$", "property", "[", "'limit'", "]", ";", "$", "this", "->", "rateExpiration", "=", "$", "property", "[", "'expires'", "]", ";", "}", "}" ]
Merge the controller properties onto the route properties.
[ "Merge", "the", "controller", "properties", "onto", "the", "route", "properties", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Route.php#L138-L179
train
dingo/api
src/Routing/Route.php
Route.findControllerPropertyOptions
protected function findControllerPropertyOptions($name) { $properties = []; foreach ($this->getControllerInstance()->{'get'.ucfirst($name)}() as $property) { if (isset($property['options']) && ! $this->optionsApplyToControllerMethod($property['options'])) { continue; } unset($property['options']); $properties = array_merge_recursive($properties, $property); } return $properties; }
php
protected function findControllerPropertyOptions($name) { $properties = []; foreach ($this->getControllerInstance()->{'get'.ucfirst($name)}() as $property) { if (isset($property['options']) && ! $this->optionsApplyToControllerMethod($property['options'])) { continue; } unset($property['options']); $properties = array_merge_recursive($properties, $property); } return $properties; }
[ "protected", "function", "findControllerPropertyOptions", "(", "$", "name", ")", "{", "$", "properties", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getControllerInstance", "(", ")", "->", "{", "'get'", ".", "ucfirst", "(", "$", "name", ")", "}", "(", ")", "as", "$", "property", ")", "{", "if", "(", "isset", "(", "$", "property", "[", "'options'", "]", ")", "&&", "!", "$", "this", "->", "optionsApplyToControllerMethod", "(", "$", "property", "[", "'options'", "]", ")", ")", "{", "continue", ";", "}", "unset", "(", "$", "property", "[", "'options'", "]", ")", ";", "$", "properties", "=", "array_merge_recursive", "(", "$", "properties", ",", "$", "property", ")", ";", "}", "return", "$", "properties", ";", "}" ]
Find the controller options and whether or not it will apply to this routes controller method. @param string $name @return array
[ "Find", "the", "controller", "options", "and", "whether", "or", "not", "it", "will", "apply", "to", "this", "routes", "controller", "method", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Route.php#L188-L203
train
dingo/api
src/Routing/Route.php
Route.optionsApplyToControllerMethod
protected function optionsApplyToControllerMethod(array $options) { if (empty($options)) { return true; } elseif (isset($options['only']) && in_array($this->controllerMethod, $this->explodeOnPipes($options['only']))) { return true; } elseif (isset($options['except'])) { return ! in_array($this->controllerMethod, $this->explodeOnPipes($options['except'])); } elseif (in_array($this->controllerMethod, $this->explodeOnPipes($options))) { return true; } return false; }
php
protected function optionsApplyToControllerMethod(array $options) { if (empty($options)) { return true; } elseif (isset($options['only']) && in_array($this->controllerMethod, $this->explodeOnPipes($options['only']))) { return true; } elseif (isset($options['except'])) { return ! in_array($this->controllerMethod, $this->explodeOnPipes($options['except'])); } elseif (in_array($this->controllerMethod, $this->explodeOnPipes($options))) { return true; } return false; }
[ "protected", "function", "optionsApplyToControllerMethod", "(", "array", "$", "options", ")", "{", "if", "(", "empty", "(", "$", "options", ")", ")", "{", "return", "true", ";", "}", "elseif", "(", "isset", "(", "$", "options", "[", "'only'", "]", ")", "&&", "in_array", "(", "$", "this", "->", "controllerMethod", ",", "$", "this", "->", "explodeOnPipes", "(", "$", "options", "[", "'only'", "]", ")", ")", ")", "{", "return", "true", ";", "}", "elseif", "(", "isset", "(", "$", "options", "[", "'except'", "]", ")", ")", "{", "return", "!", "in_array", "(", "$", "this", "->", "controllerMethod", ",", "$", "this", "->", "explodeOnPipes", "(", "$", "options", "[", "'except'", "]", ")", ")", ";", "}", "elseif", "(", "in_array", "(", "$", "this", "->", "controllerMethod", ",", "$", "this", "->", "explodeOnPipes", "(", "$", "options", ")", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Determine if a controller method is in an array of options. @param array $options @return bool
[ "Determine", "if", "a", "controller", "method", "is", "in", "an", "array", "of", "options", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Route.php#L212-L226
train
dingo/api
src/Routing/Route.php
Route.controllerUsesHelpersTrait
protected function controllerUsesHelpersTrait() { if (! $controller = $this->getControllerInstance()) { return false; } $traits = []; do { $traits = array_merge(class_uses($controller, false), $traits); } while ($controller = get_parent_class($controller)); foreach ($traits as $trait => $same) { $traits = array_merge(class_uses($trait, false), $traits); } return isset($traits[Helpers::class]); }
php
protected function controllerUsesHelpersTrait() { if (! $controller = $this->getControllerInstance()) { return false; } $traits = []; do { $traits = array_merge(class_uses($controller, false), $traits); } while ($controller = get_parent_class($controller)); foreach ($traits as $trait => $same) { $traits = array_merge(class_uses($trait, false), $traits); } return isset($traits[Helpers::class]); }
[ "protected", "function", "controllerUsesHelpersTrait", "(", ")", "{", "if", "(", "!", "$", "controller", "=", "$", "this", "->", "getControllerInstance", "(", ")", ")", "{", "return", "false", ";", "}", "$", "traits", "=", "[", "]", ";", "do", "{", "$", "traits", "=", "array_merge", "(", "class_uses", "(", "$", "controller", ",", "false", ")", ",", "$", "traits", ")", ";", "}", "while", "(", "$", "controller", "=", "get_parent_class", "(", "$", "controller", ")", ")", ";", "foreach", "(", "$", "traits", "as", "$", "trait", "=>", "$", "same", ")", "{", "$", "traits", "=", "array_merge", "(", "class_uses", "(", "$", "trait", ",", "false", ")", ",", "$", "traits", ")", ";", "}", "return", "isset", "(", "$", "traits", "[", "Helpers", "::", "class", "]", ")", ";", "}" ]
Determine if the controller instance uses the helpers trait. @return bool
[ "Determine", "if", "the", "controller", "instance", "uses", "the", "helpers", "trait", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Route.php#L245-L262
train
dingo/api
src/Routing/Route.php
Route.makeControllerInstance
protected function makeControllerInstance() { list($this->controllerClass, $this->controllerMethod) = explode('@', $this->action['uses']); $this->container->instance($this->controllerClass, $this->controller = $this->container->make($this->controllerClass)); return $this->controller; }
php
protected function makeControllerInstance() { list($this->controllerClass, $this->controllerMethod) = explode('@', $this->action['uses']); $this->container->instance($this->controllerClass, $this->controller = $this->container->make($this->controllerClass)); return $this->controller; }
[ "protected", "function", "makeControllerInstance", "(", ")", "{", "list", "(", "$", "this", "->", "controllerClass", ",", "$", "this", "->", "controllerMethod", ")", "=", "explode", "(", "'@'", ",", "$", "this", "->", "action", "[", "'uses'", "]", ")", ";", "$", "this", "->", "container", "->", "instance", "(", "$", "this", "->", "controllerClass", ",", "$", "this", "->", "controller", "=", "$", "this", "->", "container", "->", "make", "(", "$", "this", "->", "controllerClass", ")", ")", ";", "return", "$", "this", "->", "controller", ";", "}" ]
Make a new controller instance through the container. @return \Illuminate\Routing\Controller|\Laravel\Lumen\Routing\Controller
[ "Make", "a", "new", "controller", "instance", "through", "the", "container", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Route.php#L279-L287
train
dingo/api
src/Routing/Route.php
Route.isProtected
public function isProtected() { if (isset($this->middleware['api.auth']) || in_array('api.auth', $this->middleware)) { if ($this->controller && isset($this->middleware['api.auth'])) { return $this->optionsApplyToControllerMethod($this->middleware['api.auth']); } return true; } return false; }
php
public function isProtected() { if (isset($this->middleware['api.auth']) || in_array('api.auth', $this->middleware)) { if ($this->controller && isset($this->middleware['api.auth'])) { return $this->optionsApplyToControllerMethod($this->middleware['api.auth']); } return true; } return false; }
[ "public", "function", "isProtected", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "middleware", "[", "'api.auth'", "]", ")", "||", "in_array", "(", "'api.auth'", ",", "$", "this", "->", "middleware", ")", ")", "{", "if", "(", "$", "this", "->", "controller", "&&", "isset", "(", "$", "this", "->", "middleware", "[", "'api.auth'", "]", ")", ")", "{", "return", "$", "this", "->", "optionsApplyToControllerMethod", "(", "$", "this", "->", "middleware", "[", "'api.auth'", "]", ")", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Determine if the route is protected. @return bool
[ "Determine", "if", "the", "route", "is", "protected", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Route.php#L294-L305
train
dingo/api
src/Auth/Provider/JWT.php
JWT.getToken
protected function getToken(Request $request) { try { $this->validateAuthorizationHeader($request); $token = $this->parseAuthorizationHeader($request); } catch (Exception $exception) { if (! $token = $request->query('token', false)) { throw $exception; } } return $token; }
php
protected function getToken(Request $request) { try { $this->validateAuthorizationHeader($request); $token = $this->parseAuthorizationHeader($request); } catch (Exception $exception) { if (! $token = $request->query('token', false)) { throw $exception; } } return $token; }
[ "protected", "function", "getToken", "(", "Request", "$", "request", ")", "{", "try", "{", "$", "this", "->", "validateAuthorizationHeader", "(", "$", "request", ")", ";", "$", "token", "=", "$", "this", "->", "parseAuthorizationHeader", "(", "$", "request", ")", ";", "}", "catch", "(", "Exception", "$", "exception", ")", "{", "if", "(", "!", "$", "token", "=", "$", "request", "->", "query", "(", "'token'", ",", "false", ")", ")", "{", "throw", "$", "exception", ";", "}", "}", "return", "$", "token", ";", "}" ]
Get the JWT from the request. @param \Illuminate\Http\Request $request @throws \Exception @return string
[ "Get", "the", "JWT", "from", "the", "request", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Auth/Provider/JWT.php#L65-L78
train
dingo/api
src/Http/Response/Format/JsonOptionalFormatting.php
JsonOptionalFormatting.isCustomIndentStyleRequired
protected function isCustomIndentStyleRequired() { return $this->isJsonPrettyPrintEnabled() && isset($this->options['indent_style']) && in_array($this->options['indent_style'], $this->indentStyles); }
php
protected function isCustomIndentStyleRequired() { return $this->isJsonPrettyPrintEnabled() && isset($this->options['indent_style']) && in_array($this->options['indent_style'], $this->indentStyles); }
[ "protected", "function", "isCustomIndentStyleRequired", "(", ")", "{", "return", "$", "this", "->", "isJsonPrettyPrintEnabled", "(", ")", "&&", "isset", "(", "$", "this", "->", "options", "[", "'indent_style'", "]", ")", "&&", "in_array", "(", "$", "this", "->", "options", "[", "'indent_style'", "]", ",", "$", "this", "->", "indentStyles", ")", ";", "}" ]
Determine if JSON custom indent style is set. @return bool
[ "Determine", "if", "JSON", "custom", "indent", "style", "is", "set", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/Response/Format/JsonOptionalFormatting.php#L63-L68
train
dingo/api
src/Http/Response/Format/JsonOptionalFormatting.php
JsonOptionalFormatting.performJsonEncoding
protected function performJsonEncoding($content, array $jsonEncodeOptions = []) { $jsonEncodeOptions = $this->filterJsonEncodeOptions($jsonEncodeOptions); $optionsBitmask = $this->calucateJsonEncodeOptionsBitmask($jsonEncodeOptions); if (($encodedString = json_encode($content, $optionsBitmask)) === false) { throw new \ErrorException('Error encoding data in JSON format: '.json_last_error()); } return $encodedString; }
php
protected function performJsonEncoding($content, array $jsonEncodeOptions = []) { $jsonEncodeOptions = $this->filterJsonEncodeOptions($jsonEncodeOptions); $optionsBitmask = $this->calucateJsonEncodeOptionsBitmask($jsonEncodeOptions); if (($encodedString = json_encode($content, $optionsBitmask)) === false) { throw new \ErrorException('Error encoding data in JSON format: '.json_last_error()); } return $encodedString; }
[ "protected", "function", "performJsonEncoding", "(", "$", "content", ",", "array", "$", "jsonEncodeOptions", "=", "[", "]", ")", "{", "$", "jsonEncodeOptions", "=", "$", "this", "->", "filterJsonEncodeOptions", "(", "$", "jsonEncodeOptions", ")", ";", "$", "optionsBitmask", "=", "$", "this", "->", "calucateJsonEncodeOptionsBitmask", "(", "$", "jsonEncodeOptions", ")", ";", "if", "(", "(", "$", "encodedString", "=", "json_encode", "(", "$", "content", ",", "$", "optionsBitmask", ")", ")", "===", "false", ")", "{", "throw", "new", "\\", "ErrorException", "(", "'Error encoding data in JSON format: '", ".", "json_last_error", "(", ")", ")", ";", "}", "return", "$", "encodedString", ";", "}" ]
Perform JSON encode. @param string $content @param array $jsonEncodeOptions @return string
[ "Perform", "JSON", "encode", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/Response/Format/JsonOptionalFormatting.php#L78-L89
train
dingo/api
src/Http/Response/Format/JsonOptionalFormatting.php
JsonOptionalFormatting.indentPrettyPrintedJson
protected function indentPrettyPrintedJson($jsonString, $indentStyle, $defaultIndentSize = 2) { $indentChar = $this->getIndentCharForIndentStyle($indentStyle); $indentSize = $this->getPrettyPrintIndentSize() ?: $defaultIndentSize; // If the given indentation style is allowed to have various indent size // (number of chars, that are used to indent one level in each line), // indent the JSON string with given (or default) indent size. if ($this->hasVariousIndentSize($indentStyle)) { return $this->peformIndentation($jsonString, $indentChar, $indentSize); } // Otherwise following the convention, that indent styles, that does not // allowed to have various indent size (e.g. tab) are indented using // one tabulation character per one indent level in each line. return $this->peformIndentation($jsonString, $indentChar); }
php
protected function indentPrettyPrintedJson($jsonString, $indentStyle, $defaultIndentSize = 2) { $indentChar = $this->getIndentCharForIndentStyle($indentStyle); $indentSize = $this->getPrettyPrintIndentSize() ?: $defaultIndentSize; // If the given indentation style is allowed to have various indent size // (number of chars, that are used to indent one level in each line), // indent the JSON string with given (or default) indent size. if ($this->hasVariousIndentSize($indentStyle)) { return $this->peformIndentation($jsonString, $indentChar, $indentSize); } // Otherwise following the convention, that indent styles, that does not // allowed to have various indent size (e.g. tab) are indented using // one tabulation character per one indent level in each line. return $this->peformIndentation($jsonString, $indentChar); }
[ "protected", "function", "indentPrettyPrintedJson", "(", "$", "jsonString", ",", "$", "indentStyle", ",", "$", "defaultIndentSize", "=", "2", ")", "{", "$", "indentChar", "=", "$", "this", "->", "getIndentCharForIndentStyle", "(", "$", "indentStyle", ")", ";", "$", "indentSize", "=", "$", "this", "->", "getPrettyPrintIndentSize", "(", ")", "?", ":", "$", "defaultIndentSize", ";", "// If the given indentation style is allowed to have various indent size", "// (number of chars, that are used to indent one level in each line),", "// indent the JSON string with given (or default) indent size.", "if", "(", "$", "this", "->", "hasVariousIndentSize", "(", "$", "indentStyle", ")", ")", "{", "return", "$", "this", "->", "peformIndentation", "(", "$", "jsonString", ",", "$", "indentChar", ",", "$", "indentSize", ")", ";", "}", "// Otherwise following the convention, that indent styles, that does not", "// allowed to have various indent size (e.g. tab) are indented using", "// one tabulation character per one indent level in each line.", "return", "$", "this", "->", "peformIndentation", "(", "$", "jsonString", ",", "$", "indentChar", ")", ";", "}" ]
Indent pretty printed JSON string, using given indent style. @param string $jsonString @param string $indentStyle @param int $defaultIndentSize @return string
[ "Indent", "pretty", "printed", "JSON", "string", "using", "given", "indent", "style", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/Response/Format/JsonOptionalFormatting.php#L124-L140
train
dingo/api
src/Http/Response/Format/JsonOptionalFormatting.php
JsonOptionalFormatting.peformIndentation
protected function peformIndentation($jsonString, $indentChar = "\t", $indentSize = 1, $defaultSpaces = 4) { $pattern = '/(^|\G) {'.$defaultSpaces.'}/m'; $replacement = str_repeat($indentChar, $indentSize).'$1'; return preg_replace($pattern, $replacement, $jsonString); }
php
protected function peformIndentation($jsonString, $indentChar = "\t", $indentSize = 1, $defaultSpaces = 4) { $pattern = '/(^|\G) {'.$defaultSpaces.'}/m'; $replacement = str_repeat($indentChar, $indentSize).'$1'; return preg_replace($pattern, $replacement, $jsonString); }
[ "protected", "function", "peformIndentation", "(", "$", "jsonString", ",", "$", "indentChar", "=", "\"\\t\"", ",", "$", "indentSize", "=", "1", ",", "$", "defaultSpaces", "=", "4", ")", "{", "$", "pattern", "=", "'/(^|\\G) {'", ".", "$", "defaultSpaces", ".", "'}/m'", ";", "$", "replacement", "=", "str_repeat", "(", "$", "indentChar", ",", "$", "indentSize", ")", ".", "'$1'", ";", "return", "preg_replace", "(", "$", "pattern", ",", "$", "replacement", ",", "$", "jsonString", ")", ";", "}" ]
Perform indentation for pretty printed JSON string with a given indent char, repeated N times, as determined by indent size. @param string $jsonString JSON string, which must be indented @param string $indentChar Char, used for indent (default is tab) @param int $indentSize Number of times to repeat indent char per one indent level @param int $defaultSpaces Default number of indent spaces after json_encode() @return string
[ "Perform", "indentation", "for", "pretty", "printed", "JSON", "string", "with", "a", "given", "indent", "char", "repeated", "N", "times", "as", "determined", "by", "indent", "size", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/Response/Format/JsonOptionalFormatting.php#L189-L195
train
dingo/api
src/Provider/ServiceProvider.php
ServiceProvider.config
protected function config($item, $instantiate = true) { $value = $this->app['config']->get('api.'.$item); if (is_array($value)) { return $instantiate ? $this->instantiateConfigValues($item, $value) : $value; } return $instantiate ? $this->instantiateConfigValue($item, $value) : $value; }
php
protected function config($item, $instantiate = true) { $value = $this->app['config']->get('api.'.$item); if (is_array($value)) { return $instantiate ? $this->instantiateConfigValues($item, $value) : $value; } return $instantiate ? $this->instantiateConfigValue($item, $value) : $value; }
[ "protected", "function", "config", "(", "$", "item", ",", "$", "instantiate", "=", "true", ")", "{", "$", "value", "=", "$", "this", "->", "app", "[", "'config'", "]", "->", "get", "(", "'api.'", ".", "$", "item", ")", ";", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "return", "$", "instantiate", "?", "$", "this", "->", "instantiateConfigValues", "(", "$", "item", ",", "$", "value", ")", ":", "$", "value", ";", "}", "return", "$", "instantiate", "?", "$", "this", "->", "instantiateConfigValue", "(", "$", "item", ",", "$", "value", ")", ":", "$", "value", ";", "}" ]
Retrieve and instantiate a config value if it exists and is a class. @param string $item @param bool $instantiate @return mixed
[ "Retrieve", "and", "instantiate", "a", "config", "value", "if", "it", "exists", "and", "is", "a", "class", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Provider/ServiceProvider.php#L26-L35
train
dingo/api
src/Provider/ServiceProvider.php
ServiceProvider.instantiateConfigValues
protected function instantiateConfigValues($item, array $values) { foreach ($values as $key => $value) { $values[$key] = $this->instantiateConfigValue($item, $value); } return $values; }
php
protected function instantiateConfigValues($item, array $values) { foreach ($values as $key => $value) { $values[$key] = $this->instantiateConfigValue($item, $value); } return $values; }
[ "protected", "function", "instantiateConfigValues", "(", "$", "item", ",", "array", "$", "values", ")", "{", "foreach", "(", "$", "values", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "values", "[", "$", "key", "]", "=", "$", "this", "->", "instantiateConfigValue", "(", "$", "item", ",", "$", "value", ")", ";", "}", "return", "$", "values", ";", "}" ]
Instantiate an array of instantiable configuration values. @param string $item @param array $values @return array
[ "Instantiate", "an", "array", "of", "instantiable", "configuration", "values", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Provider/ServiceProvider.php#L45-L52
train
dingo/api
src/Http/Validation/Accept.php
Accept.validate
public function validate(Request $request) { try { $this->accept->parse($request, $this->strict); } catch (BadRequestHttpException $exception) { if ($request->getMethod() === 'OPTIONS') { return true; } throw $exception; } }
php
public function validate(Request $request) { try { $this->accept->parse($request, $this->strict); } catch (BadRequestHttpException $exception) { if ($request->getMethod() === 'OPTIONS') { return true; } throw $exception; } }
[ "public", "function", "validate", "(", "Request", "$", "request", ")", "{", "try", "{", "$", "this", "->", "accept", "->", "parse", "(", "$", "request", ",", "$", "this", "->", "strict", ")", ";", "}", "catch", "(", "BadRequestHttpException", "$", "exception", ")", "{", "if", "(", "$", "request", "->", "getMethod", "(", ")", "===", "'OPTIONS'", ")", "{", "return", "true", ";", "}", "throw", "$", "exception", ";", "}", "}" ]
Validate the accept header on the request. If this fails it will throw an HTTP exception that will be caught by the middleware. This validator should always be run last and must not return a success boolean. @param \Illuminate\Http\Request $request @throws \Exception|\Symfony\Component\HttpKernel\Exception\BadRequestHttpException @return bool
[ "Validate", "the", "accept", "header", "on", "the", "request", ".", "If", "this", "fails", "it", "will", "throw", "an", "HTTP", "exception", "that", "will", "be", "caught", "by", "the", "middleware", ".", "This", "validator", "should", "always", "be", "run", "last", "and", "must", "not", "return", "a", "success", "boolean", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/Validation/Accept.php#L52-L63
train
dingo/api
src/Provider/LaravelServiceProvider.php
LaravelServiceProvider.updateRouterBindings
protected function updateRouterBindings() { foreach ($this->getRouterBindings() as $key => $binding) { $this->app['api.router.adapter']->getRouter()->bind($key, $binding); } }
php
protected function updateRouterBindings() { foreach ($this->getRouterBindings() as $key => $binding) { $this->app['api.router.adapter']->getRouter()->bind($key, $binding); } }
[ "protected", "function", "updateRouterBindings", "(", ")", "{", "foreach", "(", "$", "this", "->", "getRouterBindings", "(", ")", "as", "$", "key", "=>", "$", "binding", ")", "{", "$", "this", "->", "app", "[", "'api.router.adapter'", "]", "->", "getRouter", "(", ")", "->", "bind", "(", "$", "key", ",", "$", "binding", ")", ";", "}", "}" ]
Grab the bindings from the Laravel router and set them on the adapters router. @return void
[ "Grab", "the", "bindings", "from", "the", "Laravel", "router", "and", "set", "them", "on", "the", "adapters", "router", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Provider/LaravelServiceProvider.php#L75-L80
train
dingo/api
src/Routing/Router.php
Router.version
public function version($version, $second, $third = null) { if (func_num_args() == 2) { list($version, $callback, $attributes) = array_merge(func_get_args(), [[]]); } else { list($version, $attributes, $callback) = func_get_args(); } $attributes = array_merge($attributes, ['version' => $version]); $this->group($attributes, $callback); }
php
public function version($version, $second, $third = null) { if (func_num_args() == 2) { list($version, $callback, $attributes) = array_merge(func_get_args(), [[]]); } else { list($version, $attributes, $callback) = func_get_args(); } $attributes = array_merge($attributes, ['version' => $version]); $this->group($attributes, $callback); }
[ "public", "function", "version", "(", "$", "version", ",", "$", "second", ",", "$", "third", "=", "null", ")", "{", "if", "(", "func_num_args", "(", ")", "==", "2", ")", "{", "list", "(", "$", "version", ",", "$", "callback", ",", "$", "attributes", ")", "=", "array_merge", "(", "func_get_args", "(", ")", ",", "[", "[", "]", "]", ")", ";", "}", "else", "{", "list", "(", "$", "version", ",", "$", "attributes", ",", "$", "callback", ")", "=", "func_get_args", "(", ")", ";", "}", "$", "attributes", "=", "array_merge", "(", "$", "attributes", ",", "[", "'version'", "=>", "$", "version", "]", ")", ";", "$", "this", "->", "group", "(", "$", "attributes", ",", "$", "callback", ")", ";", "}" ]
An alias for calling the group method, allows a more fluent API for registering a new API version group with optional attributes and a required callback. This method can be called without the third parameter, however, the callback should always be the last parameter. @param array|string $version @param array|callable $second @param callable $third @return void
[ "An", "alias", "for", "calling", "the", "group", "method", "allows", "a", "more", "fluent", "API", "for", "registering", "a", "new", "API", "version", "group", "with", "optional", "attributes", "and", "a", "required", "callback", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Router.php#L128-L139
train
dingo/api
src/Routing/Router.php
Router.resource
public function resource($name, $controller, array $options = []) { if ($this->container->bound(ResourceRegistrar::class)) { $registrar = $this->container->make(ResourceRegistrar::class); } else { $registrar = new ResourceRegistrar($this); } $registrar->register($name, $controller, $options); }
php
public function resource($name, $controller, array $options = []) { if ($this->container->bound(ResourceRegistrar::class)) { $registrar = $this->container->make(ResourceRegistrar::class); } else { $registrar = new ResourceRegistrar($this); } $registrar->register($name, $controller, $options); }
[ "public", "function", "resource", "(", "$", "name", ",", "$", "controller", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "$", "this", "->", "container", "->", "bound", "(", "ResourceRegistrar", "::", "class", ")", ")", "{", "$", "registrar", "=", "$", "this", "->", "container", "->", "make", "(", "ResourceRegistrar", "::", "class", ")", ";", "}", "else", "{", "$", "registrar", "=", "new", "ResourceRegistrar", "(", "$", "this", ")", ";", "}", "$", "registrar", "->", "register", "(", "$", "name", ",", "$", "controller", ",", "$", "options", ")", ";", "}" ]
Register a resource controller. @param string $name @param string $controller @param array $options @return void
[ "Register", "a", "resource", "controller", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Router.php#L314-L323
train
dingo/api
src/Routing/Router.php
Router.mergeLastGroupAttributes
protected function mergeLastGroupAttributes(array $attributes) { if (empty($this->groupStack)) { return $this->mergeGroup($attributes, []); } return $this->mergeGroup($attributes, end($this->groupStack)); }
php
protected function mergeLastGroupAttributes(array $attributes) { if (empty($this->groupStack)) { return $this->mergeGroup($attributes, []); } return $this->mergeGroup($attributes, end($this->groupStack)); }
[ "protected", "function", "mergeLastGroupAttributes", "(", "array", "$", "attributes", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "groupStack", ")", ")", "{", "return", "$", "this", "->", "mergeGroup", "(", "$", "attributes", ",", "[", "]", ")", ";", "}", "return", "$", "this", "->", "mergeGroup", "(", "$", "attributes", ",", "end", "(", "$", "this", "->", "groupStack", ")", ")", ";", "}" ]
Merge the last groups attributes. @param array $attributes @return array
[ "Merge", "the", "last", "groups", "attributes", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Router.php#L380-L387
train
dingo/api
src/Routing/Router.php
Router.dispatch
public function dispatch(Request $request) { $this->currentRoute = null; $this->container->instance(Request::class, $request); $this->routesDispatched++; try { $response = $this->adapter->dispatch($request, $request->version()); } catch (Exception $exception) { if ($request instanceof InternalRequest) { throw $exception; } $this->exception->report($exception); $response = $this->exception->handle($exception); } return $this->prepareResponse($response, $request, $request->format()); }
php
public function dispatch(Request $request) { $this->currentRoute = null; $this->container->instance(Request::class, $request); $this->routesDispatched++; try { $response = $this->adapter->dispatch($request, $request->version()); } catch (Exception $exception) { if ($request instanceof InternalRequest) { throw $exception; } $this->exception->report($exception); $response = $this->exception->handle($exception); } return $this->prepareResponse($response, $request, $request->format()); }
[ "public", "function", "dispatch", "(", "Request", "$", "request", ")", "{", "$", "this", "->", "currentRoute", "=", "null", ";", "$", "this", "->", "container", "->", "instance", "(", "Request", "::", "class", ",", "$", "request", ")", ";", "$", "this", "->", "routesDispatched", "++", ";", "try", "{", "$", "response", "=", "$", "this", "->", "adapter", "->", "dispatch", "(", "$", "request", ",", "$", "request", "->", "version", "(", ")", ")", ";", "}", "catch", "(", "Exception", "$", "exception", ")", "{", "if", "(", "$", "request", "instanceof", "InternalRequest", ")", "{", "throw", "$", "exception", ";", "}", "$", "this", "->", "exception", "->", "report", "(", "$", "exception", ")", ";", "$", "response", "=", "$", "this", "->", "exception", "->", "handle", "(", "$", "exception", ")", ";", "}", "return", "$", "this", "->", "prepareResponse", "(", "$", "response", ",", "$", "request", ",", "$", "request", "->", "format", "(", ")", ")", ";", "}" ]
Dispatch a request via the adapter. @param \Dingo\Api\Http\Request $request @throws \Exception @return \Dingo\Api\Http\Response
[ "Dispatch", "a", "request", "via", "the", "adapter", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Router.php#L505-L526
train
dingo/api
src/Routing/Router.php
Router.createRoute
public function createRoute($route) { return new Route($this->adapter, $this->container, $this->container['request'], $route); }
php
public function createRoute($route) { return new Route($this->adapter, $this->container, $this->container['request'], $route); }
[ "public", "function", "createRoute", "(", "$", "route", ")", "{", "return", "new", "Route", "(", "$", "this", "->", "adapter", ",", "$", "this", "->", "container", ",", "$", "this", "->", "container", "[", "'request'", "]", ",", "$", "route", ")", ";", "}" ]
Create a new route instance from an adapter route. @param array|\Illuminate\Routing\Route $route @return \Dingo\Api\Routing\Route
[ "Create", "a", "new", "route", "instance", "from", "an", "adapter", "route", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Router.php#L658-L661
train
dingo/api
src/Routing/Router.php
Router.getRoutes
public function getRoutes($version = null) { $routes = $this->adapter->getIterableRoutes($version); if (! is_null($version)) { $routes = [$version => $routes]; } $collections = []; foreach ($routes as $key => $value) { $collections[$key] = new RouteCollection($this->container['request']); foreach ($value as $route) { $route = $this->createRoute($route); $collections[$key]->add($route); } } return is_null($version) ? $collections : $collections[$version]; }
php
public function getRoutes($version = null) { $routes = $this->adapter->getIterableRoutes($version); if (! is_null($version)) { $routes = [$version => $routes]; } $collections = []; foreach ($routes as $key => $value) { $collections[$key] = new RouteCollection($this->container['request']); foreach ($value as $route) { $route = $this->createRoute($route); $collections[$key]->add($route); } } return is_null($version) ? $collections : $collections[$version]; }
[ "public", "function", "getRoutes", "(", "$", "version", "=", "null", ")", "{", "$", "routes", "=", "$", "this", "->", "adapter", "->", "getIterableRoutes", "(", "$", "version", ")", ";", "if", "(", "!", "is_null", "(", "$", "version", ")", ")", "{", "$", "routes", "=", "[", "$", "version", "=>", "$", "routes", "]", ";", "}", "$", "collections", "=", "[", "]", ";", "foreach", "(", "$", "routes", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "collections", "[", "$", "key", "]", "=", "new", "RouteCollection", "(", "$", "this", "->", "container", "[", "'request'", "]", ")", ";", "foreach", "(", "$", "value", "as", "$", "route", ")", "{", "$", "route", "=", "$", "this", "->", "createRoute", "(", "$", "route", ")", ";", "$", "collections", "[", "$", "key", "]", "->", "add", "(", "$", "route", ")", ";", "}", "}", "return", "is_null", "(", "$", "version", ")", "?", "$", "collections", ":", "$", "collections", "[", "$", "version", "]", ";", "}" ]
Get all routes registered on the adapter. @param string $version @return mixed
[ "Get", "all", "routes", "registered", "on", "the", "adapter", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Router.php#L708-L729
train
dingo/api
src/Routing/Router.php
Router.setAdapterRoutes
public function setAdapterRoutes(array $routes) { $this->adapter->setRoutes($routes); $this->container->instance('api.routes', $this->getRoutes()); }
php
public function setAdapterRoutes(array $routes) { $this->adapter->setRoutes($routes); $this->container->instance('api.routes', $this->getRoutes()); }
[ "public", "function", "setAdapterRoutes", "(", "array", "$", "routes", ")", "{", "$", "this", "->", "adapter", "->", "setRoutes", "(", "$", "routes", ")", ";", "$", "this", "->", "container", "->", "instance", "(", "'api.routes'", ",", "$", "this", "->", "getRoutes", "(", ")", ")", ";", "}" ]
Set the raw adapter routes. @param array $routes @return void
[ "Set", "the", "raw", "adapter", "routes", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Routing/Router.php#L748-L753
train
dingo/api
src/Auth/Auth.php
Auth.filterProviders
protected function filterProviders(array $providers) { if (empty($providers)) { return $this->providers; } return array_intersect_key($this->providers, array_flip($providers)); }
php
protected function filterProviders(array $providers) { if (empty($providers)) { return $this->providers; } return array_intersect_key($this->providers, array_flip($providers)); }
[ "protected", "function", "filterProviders", "(", "array", "$", "providers", ")", "{", "if", "(", "empty", "(", "$", "providers", ")", ")", "{", "return", "$", "this", "->", "providers", ";", "}", "return", "array_intersect_key", "(", "$", "this", "->", "providers", ",", "array_flip", "(", "$", "providers", ")", ")", ";", "}" ]
Filter the requested providers from the available providers. @param array $providers @return array
[ "Filter", "the", "requested", "providers", "from", "the", "available", "providers", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Auth/Auth.php#L126-L133
train
dingo/api
src/Auth/Auth.php
Auth.extend
public function extend($key, $provider) { if (is_callable($provider)) { $provider = call_user_func($provider, $this->container); } $this->providers[$key] = $provider; }
php
public function extend($key, $provider) { if (is_callable($provider)) { $provider = call_user_func($provider, $this->container); } $this->providers[$key] = $provider; }
[ "public", "function", "extend", "(", "$", "key", ",", "$", "provider", ")", "{", "if", "(", "is_callable", "(", "$", "provider", ")", ")", "{", "$", "provider", "=", "call_user_func", "(", "$", "provider", ",", "$", "this", "->", "container", ")", ";", "}", "$", "this", "->", "providers", "[", "$", "key", "]", "=", "$", "provider", ";", "}" ]
Extend the authentication layer with a custom provider. @param string $key @param object|callable $provider @return void
[ "Extend", "the", "authentication", "layer", "with", "a", "custom", "provider", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Auth/Auth.php#L213-L220
train
dingo/api
src/Http/Middleware/RateLimit.php
RateLimit.handle
public function handle($request, Closure $next) { if ($request instanceof InternalRequest) { return $next($request); } $route = $this->router->getCurrentRoute(); if ($route->hasThrottle()) { $this->handler->setThrottle($route->getThrottle()); } $this->handler->rateLimitRequest($request, $route->getRateLimit(), $route->getRateLimitExpiration()); if ($this->handler->exceededRateLimit()) { throw new RateLimitExceededException('You have exceeded your rate limit.', null, $this->getHeaders()); } $response = $next($request); if ($this->handler->requestWasRateLimited()) { return $this->responseWithHeaders($response); } return $response; }
php
public function handle($request, Closure $next) { if ($request instanceof InternalRequest) { return $next($request); } $route = $this->router->getCurrentRoute(); if ($route->hasThrottle()) { $this->handler->setThrottle($route->getThrottle()); } $this->handler->rateLimitRequest($request, $route->getRateLimit(), $route->getRateLimitExpiration()); if ($this->handler->exceededRateLimit()) { throw new RateLimitExceededException('You have exceeded your rate limit.', null, $this->getHeaders()); } $response = $next($request); if ($this->handler->requestWasRateLimited()) { return $this->responseWithHeaders($response); } return $response; }
[ "public", "function", "handle", "(", "$", "request", ",", "Closure", "$", "next", ")", "{", "if", "(", "$", "request", "instanceof", "InternalRequest", ")", "{", "return", "$", "next", "(", "$", "request", ")", ";", "}", "$", "route", "=", "$", "this", "->", "router", "->", "getCurrentRoute", "(", ")", ";", "if", "(", "$", "route", "->", "hasThrottle", "(", ")", ")", "{", "$", "this", "->", "handler", "->", "setThrottle", "(", "$", "route", "->", "getThrottle", "(", ")", ")", ";", "}", "$", "this", "->", "handler", "->", "rateLimitRequest", "(", "$", "request", ",", "$", "route", "->", "getRateLimit", "(", ")", ",", "$", "route", "->", "getRateLimitExpiration", "(", ")", ")", ";", "if", "(", "$", "this", "->", "handler", "->", "exceededRateLimit", "(", ")", ")", "{", "throw", "new", "RateLimitExceededException", "(", "'You have exceeded your rate limit.'", ",", "null", ",", "$", "this", "->", "getHeaders", "(", ")", ")", ";", "}", "$", "response", "=", "$", "next", "(", "$", "request", ")", ";", "if", "(", "$", "this", "->", "handler", "->", "requestWasRateLimited", "(", ")", ")", "{", "return", "$", "this", "->", "responseWithHeaders", "(", "$", "response", ")", ";", "}", "return", "$", "response", ";", "}" ]
Perform rate limiting before a request is executed. @param \Dingo\Api\Http\Request $request @param \Closure $next @throws \Symfony\Component\HttpKernel\Exception\HttpException @return mixed
[ "Perform", "rate", "limiting", "before", "a", "request", "is", "executed", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/Middleware/RateLimit.php#L52-L77
train
dingo/api
src/Http/Middleware/RateLimit.php
RateLimit.responseWithHeaders
protected function responseWithHeaders($response) { foreach ($this->getHeaders() as $key => $value) { $response->headers->set($key, $value); } return $response; }
php
protected function responseWithHeaders($response) { foreach ($this->getHeaders() as $key => $value) { $response->headers->set($key, $value); } return $response; }
[ "protected", "function", "responseWithHeaders", "(", "$", "response", ")", "{", "foreach", "(", "$", "this", "->", "getHeaders", "(", ")", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "response", "->", "headers", "->", "set", "(", "$", "key", ",", "$", "value", ")", ";", "}", "return", "$", "response", ";", "}" ]
Send the response with the rate limit headers. @param \Dingo\Api\Http\Response $response @return \Dingo\Api\Http\Response
[ "Send", "the", "response", "with", "the", "rate", "limit", "headers", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/Middleware/RateLimit.php#L86-L93
train
dingo/api
src/Http/Middleware/RateLimit.php
RateLimit.getHeaders
protected function getHeaders() { return [ 'X-RateLimit-Limit' => $this->handler->getThrottleLimit(), 'X-RateLimit-Remaining' => $this->handler->getRemainingLimit(), 'X-RateLimit-Reset' => $this->handler->getRateLimitReset(), ]; }
php
protected function getHeaders() { return [ 'X-RateLimit-Limit' => $this->handler->getThrottleLimit(), 'X-RateLimit-Remaining' => $this->handler->getRemainingLimit(), 'X-RateLimit-Reset' => $this->handler->getRateLimitReset(), ]; }
[ "protected", "function", "getHeaders", "(", ")", "{", "return", "[", "'X-RateLimit-Limit'", "=>", "$", "this", "->", "handler", "->", "getThrottleLimit", "(", ")", ",", "'X-RateLimit-Remaining'", "=>", "$", "this", "->", "handler", "->", "getRemainingLimit", "(", ")", ",", "'X-RateLimit-Reset'", "=>", "$", "this", "->", "handler", "->", "getRateLimitReset", "(", ")", ",", "]", ";", "}" ]
Get the headers for the response. @return array
[ "Get", "the", "headers", "for", "the", "response", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/Middleware/RateLimit.php#L100-L107
train
dingo/api
src/Console/Command/Docs.php
Docs.getDocName
protected function getDocName() { $name = $this->option('name') ?: $this->name; if (! $name) { $this->comment('A name for the documentation was not supplied. Use the --name option or set a default in the configuration.'); exit; } return $name; }
php
protected function getDocName() { $name = $this->option('name') ?: $this->name; if (! $name) { $this->comment('A name for the documentation was not supplied. Use the --name option or set a default in the configuration.'); exit; } return $name; }
[ "protected", "function", "getDocName", "(", ")", "{", "$", "name", "=", "$", "this", "->", "option", "(", "'name'", ")", "?", ":", "$", "this", "->", "name", ";", "if", "(", "!", "$", "name", ")", "{", "$", "this", "->", "comment", "(", "'A name for the documentation was not supplied. Use the --name option or set a default in the configuration.'", ")", ";", "exit", ";", "}", "return", "$", "name", ";", "}" ]
Get the documentation name. @return string
[ "Get", "the", "documentation", "name", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Console/Command/Docs.php#L120-L131
train
dingo/api
src/Console/Command/Docs.php
Docs.getVersion
protected function getVersion() { $version = $this->option('use-version') ?: $this->version; if (! $version) { $this->comment('A version for the documentation was not supplied. Use the --use-version option or set a default in the configuration.'); exit; } return $version; }
php
protected function getVersion() { $version = $this->option('use-version') ?: $this->version; if (! $version) { $this->comment('A version for the documentation was not supplied. Use the --use-version option or set a default in the configuration.'); exit; } return $version; }
[ "protected", "function", "getVersion", "(", ")", "{", "$", "version", "=", "$", "this", "->", "option", "(", "'use-version'", ")", "?", ":", "$", "this", "->", "version", ";", "if", "(", "!", "$", "version", ")", "{", "$", "this", "->", "comment", "(", "'A version for the documentation was not supplied. Use the --use-version option or set a default in the configuration.'", ")", ";", "exit", ";", "}", "return", "$", "version", ";", "}" ]
Get the documentation version. @return string
[ "Get", "the", "documentation", "version", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Console/Command/Docs.php#L148-L159
train
dingo/api
src/Console/Command/Docs.php
Docs.getControllers
protected function getControllers() { $controllers = new Collection; if ($controller = $this->option('use-controller')) { $this->addControllerIfNotExists($controllers, app($controller)); return $controllers; } foreach ($this->router->getRoutes() as $collections) { foreach ($collections as $route) { if ($controller = $route->getControllerInstance()) { $this->addControllerIfNotExists($controllers, $controller); } } } return $controllers; }
php
protected function getControllers() { $controllers = new Collection; if ($controller = $this->option('use-controller')) { $this->addControllerIfNotExists($controllers, app($controller)); return $controllers; } foreach ($this->router->getRoutes() as $collections) { foreach ($collections as $route) { if ($controller = $route->getControllerInstance()) { $this->addControllerIfNotExists($controllers, $controller); } } } return $controllers; }
[ "protected", "function", "getControllers", "(", ")", "{", "$", "controllers", "=", "new", "Collection", ";", "if", "(", "$", "controller", "=", "$", "this", "->", "option", "(", "'use-controller'", ")", ")", "{", "$", "this", "->", "addControllerIfNotExists", "(", "$", "controllers", ",", "app", "(", "$", "controller", ")", ")", ";", "return", "$", "controllers", ";", "}", "foreach", "(", "$", "this", "->", "router", "->", "getRoutes", "(", ")", "as", "$", "collections", ")", "{", "foreach", "(", "$", "collections", "as", "$", "route", ")", "{", "if", "(", "$", "controller", "=", "$", "route", "->", "getControllerInstance", "(", ")", ")", "{", "$", "this", "->", "addControllerIfNotExists", "(", "$", "controllers", ",", "$", "controller", ")", ";", "}", "}", "}", "return", "$", "controllers", ";", "}" ]
Get all the controller instances. @return array
[ "Get", "all", "the", "controller", "instances", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Console/Command/Docs.php#L166-L185
train
dingo/api
src/Console/Command/Docs.php
Docs.addControllerIfNotExists
protected function addControllerIfNotExists(Collection $controllers, $controller) { $class = get_class($controller); if ($controllers->has($class)) { return; } $reflection = new ReflectionClass($controller); $interface = Arr::first($reflection->getInterfaces(), function ($key, $value) { return ends_with($key, 'Docs'); }); if ($interface) { $controller = $interface; } $controllers->put($class, $controller); }
php
protected function addControllerIfNotExists(Collection $controllers, $controller) { $class = get_class($controller); if ($controllers->has($class)) { return; } $reflection = new ReflectionClass($controller); $interface = Arr::first($reflection->getInterfaces(), function ($key, $value) { return ends_with($key, 'Docs'); }); if ($interface) { $controller = $interface; } $controllers->put($class, $controller); }
[ "protected", "function", "addControllerIfNotExists", "(", "Collection", "$", "controllers", ",", "$", "controller", ")", "{", "$", "class", "=", "get_class", "(", "$", "controller", ")", ";", "if", "(", "$", "controllers", "->", "has", "(", "$", "class", ")", ")", "{", "return", ";", "}", "$", "reflection", "=", "new", "ReflectionClass", "(", "$", "controller", ")", ";", "$", "interface", "=", "Arr", "::", "first", "(", "$", "reflection", "->", "getInterfaces", "(", ")", ",", "function", "(", "$", "key", ",", "$", "value", ")", "{", "return", "ends_with", "(", "$", "key", ",", "'Docs'", ")", ";", "}", ")", ";", "if", "(", "$", "interface", ")", "{", "$", "controller", "=", "$", "interface", ";", "}", "$", "controllers", "->", "put", "(", "$", "class", ",", "$", "controller", ")", ";", "}" ]
Add a controller to the collection if it does not exist. If the controller implements an interface suffixed with "Docs" it will be used instead of the controller. @param \Illuminate\Support\Collection $controllers @param object $controller @return void
[ "Add", "a", "controller", "to", "the", "collection", "if", "it", "does", "not", "exist", ".", "If", "the", "controller", "implements", "an", "interface", "suffixed", "with", "Docs", "it", "will", "be", "used", "instead", "of", "the", "controller", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Console/Command/Docs.php#L197-L216
train
dingo/api
src/Dispatcher.php
Dispatcher.attach
public function attach(array $files) { foreach ($files as $key => $file) { if (is_array($file)) { $file = new UploadedFile($file['path'], basename($file['path']), $file['mime'], $file['size']); } elseif (is_string($file)) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $file = new UploadedFile($file, basename($file), finfo_file($finfo, $file), $this->files->size($file)); } elseif (! $file instanceof UploadedFile) { continue; } $this->uploads[$key] = $file; } return $this; }
php
public function attach(array $files) { foreach ($files as $key => $file) { if (is_array($file)) { $file = new UploadedFile($file['path'], basename($file['path']), $file['mime'], $file['size']); } elseif (is_string($file)) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $file = new UploadedFile($file, basename($file), finfo_file($finfo, $file), $this->files->size($file)); } elseif (! $file instanceof UploadedFile) { continue; } $this->uploads[$key] = $file; } return $this; }
[ "public", "function", "attach", "(", "array", "$", "files", ")", "{", "foreach", "(", "$", "files", "as", "$", "key", "=>", "$", "file", ")", "{", "if", "(", "is_array", "(", "$", "file", ")", ")", "{", "$", "file", "=", "new", "UploadedFile", "(", "$", "file", "[", "'path'", "]", ",", "basename", "(", "$", "file", "[", "'path'", "]", ")", ",", "$", "file", "[", "'mime'", "]", ",", "$", "file", "[", "'size'", "]", ")", ";", "}", "elseif", "(", "is_string", "(", "$", "file", ")", ")", "{", "$", "finfo", "=", "finfo_open", "(", "FILEINFO_MIME_TYPE", ")", ";", "$", "file", "=", "new", "UploadedFile", "(", "$", "file", ",", "basename", "(", "$", "file", ")", ",", "finfo_file", "(", "$", "finfo", ",", "$", "file", ")", ",", "$", "this", "->", "files", "->", "size", "(", "$", "file", ")", ")", ";", "}", "elseif", "(", "!", "$", "file", "instanceof", "UploadedFile", ")", "{", "continue", ";", "}", "$", "this", "->", "uploads", "[", "$", "key", "]", "=", "$", "file", ";", "}", "return", "$", "this", ";", "}" ]
Attach files to be uploaded. @param array $files @return \Dingo\Api\Dispatcher
[ "Attach", "files", "to", "be", "uploaded", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Dispatcher.php#L202-L219
train
dingo/api
src/Dispatcher.php
Dispatcher.json
public function json($content) { if (is_array($content)) { $content = json_encode($content); } $this->content = $content; return $this->header('Content-Type', 'application/json'); }
php
public function json($content) { if (is_array($content)) { $content = json_encode($content); } $this->content = $content; return $this->header('Content-Type', 'application/json'); }
[ "public", "function", "json", "(", "$", "content", ")", "{", "if", "(", "is_array", "(", "$", "content", ")", ")", "{", "$", "content", "=", "json_encode", "(", "$", "content", ")", ";", "}", "$", "this", "->", "content", "=", "$", "content", ";", "return", "$", "this", "->", "header", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "}" ]
Send a JSON payload in the request body. @param string|array $content @return \Dingo\Api\Dispatcher
[ "Send", "a", "JSON", "payload", "in", "the", "request", "body", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Dispatcher.php#L242-L251
train
dingo/api
src/Dispatcher.php
Dispatcher.with
public function with($parameters) { $this->parameters = array_merge($this->parameters, is_array($parameters) ? $parameters : func_get_args()); return $this; }
php
public function with($parameters) { $this->parameters = array_merge($this->parameters, is_array($parameters) ? $parameters : func_get_args()); return $this; }
[ "public", "function", "with", "(", "$", "parameters", ")", "{", "$", "this", "->", "parameters", "=", "array_merge", "(", "$", "this", "->", "parameters", ",", "is_array", "(", "$", "parameters", ")", "?", "$", "parameters", ":", "func_get_args", "(", ")", ")", ";", "return", "$", "this", ";", "}" ]
Set the parameters to be sent on the next API request. @param string|array $parameters @return \Dingo\Api\Dispatcher
[ "Set", "the", "parameters", "to", "be", "sent", "on", "the", "next", "API", "request", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Dispatcher.php#L312-L317
train
dingo/api
src/Dispatcher.php
Dispatcher.queueRequest
protected function queueRequest($verb, $uri, $parameters, $content = '') { if (! empty($content)) { $this->content = $content; } // Sometimes after setting the initial request another request might be made prior to // internally dispatching an API request. We need to capture this request as well // and add it to the request stack as it has become the new parent request to // this internal request. This will generally occur during tests when // using the crawler to navigate pages that also make internal // requests. if (end($this->requestStack) != $this->container['request']) { $this->requestStack[] = $this->container['request']; } $this->requestStack[] = $request = $this->createRequest($verb, $uri, $parameters); return $this->dispatch($request); }
php
protected function queueRequest($verb, $uri, $parameters, $content = '') { if (! empty($content)) { $this->content = $content; } // Sometimes after setting the initial request another request might be made prior to // internally dispatching an API request. We need to capture this request as well // and add it to the request stack as it has become the new parent request to // this internal request. This will generally occur during tests when // using the crawler to navigate pages that also make internal // requests. if (end($this->requestStack) != $this->container['request']) { $this->requestStack[] = $this->container['request']; } $this->requestStack[] = $request = $this->createRequest($verb, $uri, $parameters); return $this->dispatch($request); }
[ "protected", "function", "queueRequest", "(", "$", "verb", ",", "$", "uri", ",", "$", "parameters", ",", "$", "content", "=", "''", ")", "{", "if", "(", "!", "empty", "(", "$", "content", ")", ")", "{", "$", "this", "->", "content", "=", "$", "content", ";", "}", "// Sometimes after setting the initial request another request might be made prior to", "// internally dispatching an API request. We need to capture this request as well", "// and add it to the request stack as it has become the new parent request to", "// this internal request. This will generally occur during tests when", "// using the crawler to navigate pages that also make internal", "// requests.", "if", "(", "end", "(", "$", "this", "->", "requestStack", ")", "!=", "$", "this", "->", "container", "[", "'request'", "]", ")", "{", "$", "this", "->", "requestStack", "[", "]", "=", "$", "this", "->", "container", "[", "'request'", "]", ";", "}", "$", "this", "->", "requestStack", "[", "]", "=", "$", "request", "=", "$", "this", "->", "createRequest", "(", "$", "verb", ",", "$", "uri", ",", "$", "parameters", ")", ";", "return", "$", "this", "->", "dispatch", "(", "$", "request", ")", ";", "}" ]
Queue up and dispatch a new request. @param string $verb @param string $uri @param string|array $parameters @param string $content @return mixed
[ "Queue", "up", "and", "dispatch", "a", "new", "request", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Dispatcher.php#L427-L446
train
dingo/api
src/Dispatcher.php
Dispatcher.dispatch
protected function dispatch(InternalRequest $request) { $this->routeStack[] = $this->router->getCurrentRoute(); $this->clearCachedFacadeInstance(); try { $this->container->instance('request', $request); $response = $this->router->dispatch($request); if (! $response->isSuccessful() && ! $response->isRedirection()) { throw new InternalHttpException($response); } if (! $this->raw) { $response = $response->getOriginalContent(); } } catch (HttpExceptionInterface $exception) { $this->refreshRequestStack(); throw $exception; } $this->refreshRequestStack(); return $response; }
php
protected function dispatch(InternalRequest $request) { $this->routeStack[] = $this->router->getCurrentRoute(); $this->clearCachedFacadeInstance(); try { $this->container->instance('request', $request); $response = $this->router->dispatch($request); if (! $response->isSuccessful() && ! $response->isRedirection()) { throw new InternalHttpException($response); } if (! $this->raw) { $response = $response->getOriginalContent(); } } catch (HttpExceptionInterface $exception) { $this->refreshRequestStack(); throw $exception; } $this->refreshRequestStack(); return $response; }
[ "protected", "function", "dispatch", "(", "InternalRequest", "$", "request", ")", "{", "$", "this", "->", "routeStack", "[", "]", "=", "$", "this", "->", "router", "->", "getCurrentRoute", "(", ")", ";", "$", "this", "->", "clearCachedFacadeInstance", "(", ")", ";", "try", "{", "$", "this", "->", "container", "->", "instance", "(", "'request'", ",", "$", "request", ")", ";", "$", "response", "=", "$", "this", "->", "router", "->", "dispatch", "(", "$", "request", ")", ";", "if", "(", "!", "$", "response", "->", "isSuccessful", "(", ")", "&&", "!", "$", "response", "->", "isRedirection", "(", ")", ")", "{", "throw", "new", "InternalHttpException", "(", "$", "response", ")", ";", "}", "if", "(", "!", "$", "this", "->", "raw", ")", "{", "$", "response", "=", "$", "response", "->", "getOriginalContent", "(", ")", ";", "}", "}", "catch", "(", "HttpExceptionInterface", "$", "exception", ")", "{", "$", "this", "->", "refreshRequestStack", "(", ")", ";", "throw", "$", "exception", ";", "}", "$", "this", "->", "refreshRequestStack", "(", ")", ";", "return", "$", "response", ";", "}" ]
Attempt to dispatch an internal request. @param \Dingo\Api\Http\InternalRequest $request @throws \Exception|\Symfony\Component\HttpKernel\Exception\HttpExceptionInterface @return mixed
[ "Attempt", "to", "dispatch", "an", "internal", "request", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Dispatcher.php#L532-L559
train
dingo/api
src/Http/Response/Format/Json.php
Json.formatEloquentModel
public function formatEloquentModel($model) { $key = Str::singular($model->getTable()); if (! $model::$snakeAttributes) { $key = Str::camel($key); } return $this->encode([$key => $model->toArray()]); }
php
public function formatEloquentModel($model) { $key = Str::singular($model->getTable()); if (! $model::$snakeAttributes) { $key = Str::camel($key); } return $this->encode([$key => $model->toArray()]); }
[ "public", "function", "formatEloquentModel", "(", "$", "model", ")", "{", "$", "key", "=", "Str", "::", "singular", "(", "$", "model", "->", "getTable", "(", ")", ")", ";", "if", "(", "!", "$", "model", "::", "$", "snakeAttributes", ")", "{", "$", "key", "=", "Str", "::", "camel", "(", "$", "key", ")", ";", "}", "return", "$", "this", "->", "encode", "(", "[", "$", "key", "=>", "$", "model", "->", "toArray", "(", ")", "]", ")", ";", "}" ]
Format an Eloquent model. @param \Illuminate\Database\Eloquent\Model $model @return string
[ "Format", "an", "Eloquent", "model", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/Response/Format/Json.php#L24-L33
train
dingo/api
src/Http/Response/Format/Json.php
Json.formatEloquentCollection
public function formatEloquentCollection($collection) { if ($collection->isEmpty()) { return $this->encode([]); } $model = $collection->first(); $key = Str::plural($model->getTable()); if (! $model::$snakeAttributes) { $key = Str::camel($key); } return $this->encode([$key => $collection->toArray()]); }
php
public function formatEloquentCollection($collection) { if ($collection->isEmpty()) { return $this->encode([]); } $model = $collection->first(); $key = Str::plural($model->getTable()); if (! $model::$snakeAttributes) { $key = Str::camel($key); } return $this->encode([$key => $collection->toArray()]); }
[ "public", "function", "formatEloquentCollection", "(", "$", "collection", ")", "{", "if", "(", "$", "collection", "->", "isEmpty", "(", ")", ")", "{", "return", "$", "this", "->", "encode", "(", "[", "]", ")", ";", "}", "$", "model", "=", "$", "collection", "->", "first", "(", ")", ";", "$", "key", "=", "Str", "::", "plural", "(", "$", "model", "->", "getTable", "(", ")", ")", ";", "if", "(", "!", "$", "model", "::", "$", "snakeAttributes", ")", "{", "$", "key", "=", "Str", "::", "camel", "(", "$", "key", ")", ";", "}", "return", "$", "this", "->", "encode", "(", "[", "$", "key", "=>", "$", "collection", "->", "toArray", "(", ")", "]", ")", ";", "}" ]
Format an Eloquent collection. @param \Illuminate\Database\Eloquent\Collection $collection @return string
[ "Format", "an", "Eloquent", "collection", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/Response/Format/Json.php#L42-L56
train
dingo/api
src/Http/Response/Format/Json.php
Json.encode
protected function encode($content) { $jsonEncodeOptions = []; // Here is a place, where any available JSON encoding options, that // deal with users' requirements to JSON response formatting and // structure, can be conveniently applied to tweak the output. if ($this->isJsonPrettyPrintEnabled()) { $jsonEncodeOptions[] = JSON_PRETTY_PRINT; } $encodedString = $this->performJsonEncoding($content, $jsonEncodeOptions); if ($this->isCustomIndentStyleRequired()) { $encodedString = $this->indentPrettyPrintedJson( $encodedString, $this->options['indent_style'] ); } return $encodedString; }
php
protected function encode($content) { $jsonEncodeOptions = []; // Here is a place, where any available JSON encoding options, that // deal with users' requirements to JSON response formatting and // structure, can be conveniently applied to tweak the output. if ($this->isJsonPrettyPrintEnabled()) { $jsonEncodeOptions[] = JSON_PRETTY_PRINT; } $encodedString = $this->performJsonEncoding($content, $jsonEncodeOptions); if ($this->isCustomIndentStyleRequired()) { $encodedString = $this->indentPrettyPrintedJson( $encodedString, $this->options['indent_style'] ); } return $encodedString; }
[ "protected", "function", "encode", "(", "$", "content", ")", "{", "$", "jsonEncodeOptions", "=", "[", "]", ";", "// Here is a place, where any available JSON encoding options, that", "// deal with users' requirements to JSON response formatting and", "// structure, can be conveniently applied to tweak the output.", "if", "(", "$", "this", "->", "isJsonPrettyPrintEnabled", "(", ")", ")", "{", "$", "jsonEncodeOptions", "[", "]", "=", "JSON_PRETTY_PRINT", ";", "}", "$", "encodedString", "=", "$", "this", "->", "performJsonEncoding", "(", "$", "content", ",", "$", "jsonEncodeOptions", ")", ";", "if", "(", "$", "this", "->", "isCustomIndentStyleRequired", "(", ")", ")", "{", "$", "encodedString", "=", "$", "this", "->", "indentPrettyPrintedJson", "(", "$", "encodedString", ",", "$", "this", "->", "options", "[", "'indent_style'", "]", ")", ";", "}", "return", "$", "encodedString", ";", "}" ]
Encode the content to its JSON representation. @param mixed $content @return string
[ "Encode", "the", "content", "to", "its", "JSON", "representation", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/Response/Format/Json.php#L105-L127
train
dingo/api
src/Http/RateLimit/Handler.php
Handler.rateLimitRequest
public function rateLimitRequest(Request $request, $limit = 0, $expires = 0) { $this->request = $request; // If the throttle instance is already set then we'll just carry on as // per usual. if ($this->throttle instanceof Throttle) { // If the developer specified a certain amount of requests or expiration // time on a specific route then we'll always use the route specific // throttle with the given values. } elseif ($limit > 0 || $expires > 0) { $this->throttle = new Route(['limit' => $limit, 'expires' => $expires]); $this->keyPrefix = sha1($request->path()); // Otherwise we'll use the throttle that gives the consumer the largest // amount of requests. If no matching throttle is found then rate // limiting will not be imposed for the request. } else { $this->throttle = $this->getMatchingThrottles()->sort(function ($a, $b) { return $a->getLimit() < $b->getLimit(); })->first(); } if (is_null($this->throttle)) { return; } if ($this->throttle instanceof HasRateLimiter) { $this->setRateLimiter([$this->throttle, 'getRateLimiter']); } $this->prepareCacheStore(); $this->cache('requests', 0, $this->throttle->getExpires()); $this->cache('expires', $this->throttle->getExpires(), $this->throttle->getExpires()); $this->cache('reset', time() + ($this->throttle->getExpires() * 60), $this->throttle->getExpires()); $this->increment('requests'); }
php
public function rateLimitRequest(Request $request, $limit = 0, $expires = 0) { $this->request = $request; // If the throttle instance is already set then we'll just carry on as // per usual. if ($this->throttle instanceof Throttle) { // If the developer specified a certain amount of requests or expiration // time on a specific route then we'll always use the route specific // throttle with the given values. } elseif ($limit > 0 || $expires > 0) { $this->throttle = new Route(['limit' => $limit, 'expires' => $expires]); $this->keyPrefix = sha1($request->path()); // Otherwise we'll use the throttle that gives the consumer the largest // amount of requests. If no matching throttle is found then rate // limiting will not be imposed for the request. } else { $this->throttle = $this->getMatchingThrottles()->sort(function ($a, $b) { return $a->getLimit() < $b->getLimit(); })->first(); } if (is_null($this->throttle)) { return; } if ($this->throttle instanceof HasRateLimiter) { $this->setRateLimiter([$this->throttle, 'getRateLimiter']); } $this->prepareCacheStore(); $this->cache('requests', 0, $this->throttle->getExpires()); $this->cache('expires', $this->throttle->getExpires(), $this->throttle->getExpires()); $this->cache('reset', time() + ($this->throttle->getExpires() * 60), $this->throttle->getExpires()); $this->increment('requests'); }
[ "public", "function", "rateLimitRequest", "(", "Request", "$", "request", ",", "$", "limit", "=", "0", ",", "$", "expires", "=", "0", ")", "{", "$", "this", "->", "request", "=", "$", "request", ";", "// If the throttle instance is already set then we'll just carry on as", "// per usual.", "if", "(", "$", "this", "->", "throttle", "instanceof", "Throttle", ")", "{", "// If the developer specified a certain amount of requests or expiration", "// time on a specific route then we'll always use the route specific", "// throttle with the given values.", "}", "elseif", "(", "$", "limit", ">", "0", "||", "$", "expires", ">", "0", ")", "{", "$", "this", "->", "throttle", "=", "new", "Route", "(", "[", "'limit'", "=>", "$", "limit", ",", "'expires'", "=>", "$", "expires", "]", ")", ";", "$", "this", "->", "keyPrefix", "=", "sha1", "(", "$", "request", "->", "path", "(", ")", ")", ";", "// Otherwise we'll use the throttle that gives the consumer the largest", "// amount of requests. If no matching throttle is found then rate", "// limiting will not be imposed for the request.", "}", "else", "{", "$", "this", "->", "throttle", "=", "$", "this", "->", "getMatchingThrottles", "(", ")", "->", "sort", "(", "function", "(", "$", "a", ",", "$", "b", ")", "{", "return", "$", "a", "->", "getLimit", "(", ")", "<", "$", "b", "->", "getLimit", "(", ")", ";", "}", ")", "->", "first", "(", ")", ";", "}", "if", "(", "is_null", "(", "$", "this", "->", "throttle", ")", ")", "{", "return", ";", "}", "if", "(", "$", "this", "->", "throttle", "instanceof", "HasRateLimiter", ")", "{", "$", "this", "->", "setRateLimiter", "(", "[", "$", "this", "->", "throttle", ",", "'getRateLimiter'", "]", ")", ";", "}", "$", "this", "->", "prepareCacheStore", "(", ")", ";", "$", "this", "->", "cache", "(", "'requests'", ",", "0", ",", "$", "this", "->", "throttle", "->", "getExpires", "(", ")", ")", ";", "$", "this", "->", "cache", "(", "'expires'", ",", "$", "this", "->", "throttle", "->", "getExpires", "(", ")", ",", "$", "this", "->", "throttle", "->", "getExpires", "(", ")", ")", ";", "$", "this", "->", "cache", "(", "'reset'", ",", "time", "(", ")", "+", "(", "$", "this", "->", "throttle", "->", "getExpires", "(", ")", "*", "60", ")", ",", "$", "this", "->", "throttle", "->", "getExpires", "(", ")", ")", ";", "$", "this", "->", "increment", "(", "'requests'", ")", ";", "}" ]
Execute the rate limiting for the given request. @param \Dingo\Api\Http\Request $request @param int $limit @param int $expires @return void
[ "Execute", "the", "rate", "limiting", "for", "the", "given", "request", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/RateLimit/Handler.php#L90-L128
train
dingo/api
src/Http/RateLimit/Handler.php
Handler.prepareCacheStore
protected function prepareCacheStore() { if ($this->retrieve('expires') != $this->throttle->getExpires()) { $this->forget('requests'); $this->forget('expires'); $this->forget('reset'); } }
php
protected function prepareCacheStore() { if ($this->retrieve('expires') != $this->throttle->getExpires()) { $this->forget('requests'); $this->forget('expires'); $this->forget('reset'); } }
[ "protected", "function", "prepareCacheStore", "(", ")", "{", "if", "(", "$", "this", "->", "retrieve", "(", "'expires'", ")", "!=", "$", "this", "->", "throttle", "->", "getExpires", "(", ")", ")", "{", "$", "this", "->", "forget", "(", "'requests'", ")", ";", "$", "this", "->", "forget", "(", "'expires'", ")", ";", "$", "this", "->", "forget", "(", "'reset'", ")", ";", "}", "}" ]
Prepare the cache store. @return void
[ "Prepare", "the", "cache", "store", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/RateLimit/Handler.php#L135-L142
train
dingo/api
src/Http/RateLimit/Handler.php
Handler.cache
protected function cache($key, $value, $minutes) { $this->cache->add($this->key($key), $value, Carbon::now()->addMinutes($minutes)); }
php
protected function cache($key, $value, $minutes) { $this->cache->add($this->key($key), $value, Carbon::now()->addMinutes($minutes)); }
[ "protected", "function", "cache", "(", "$", "key", ",", "$", "value", ",", "$", "minutes", ")", "{", "$", "this", "->", "cache", "->", "add", "(", "$", "this", "->", "key", "(", "$", "key", ")", ",", "$", "value", ",", "Carbon", "::", "now", "(", ")", "->", "addMinutes", "(", "$", "minutes", ")", ")", ";", "}" ]
Cache a value under a given key for a certain amount of minutes. @param string $key @param mixed $value @param int $minutes @return void
[ "Cache", "a", "value", "under", "a", "given", "key", "for", "a", "certain", "amount", "of", "minutes", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/RateLimit/Handler.php#L187-L190
train
dingo/api
src/Http/RateLimit/Handler.php
Handler.extend
public function extend($throttle) { if (is_callable($throttle)) { $throttle = call_user_func($throttle, $this->container); } $this->throttles->push($throttle); }
php
public function extend($throttle) { if (is_callable($throttle)) { $throttle = call_user_func($throttle, $this->container); } $this->throttles->push($throttle); }
[ "public", "function", "extend", "(", "$", "throttle", ")", "{", "if", "(", "is_callable", "(", "$", "throttle", ")", ")", "{", "$", "throttle", "=", "call_user_func", "(", "$", "throttle", ",", "$", "this", "->", "container", ")", ";", "}", "$", "this", "->", "throttles", "->", "push", "(", "$", "throttle", ")", ";", "}" ]
Extend the rate limiter by adding a new throttle. @param callable|\Dingo\Api\Http\RateLimit\Throttle $throttle @return void
[ "Extend", "the", "rate", "limiter", "by", "adding", "a", "new", "throttle", "." ]
8f97fadae800202e618e0c3f678b4aab78e1dc05
https://github.com/dingo/api/blob/8f97fadae800202e618e0c3f678b4aab78e1dc05/src/Http/RateLimit/Handler.php#L327-L334
train
roots/bedrock
web/app/mu-plugins/bedrock-autoloader.php
Autoloader.loadPlugins
public function loadPlugins() { $this->checkCache(); $this->validatePlugins(); $this->countPlugins(); array_map(static function () { include_once WPMU_PLUGIN_DIR . '/' . func_get_args()[0]; }, array_keys(self::$cache['plugins'])); $this->pluginHooks(); }
php
public function loadPlugins() { $this->checkCache(); $this->validatePlugins(); $this->countPlugins(); array_map(static function () { include_once WPMU_PLUGIN_DIR . '/' . func_get_args()[0]; }, array_keys(self::$cache['plugins'])); $this->pluginHooks(); }
[ "public", "function", "loadPlugins", "(", ")", "{", "$", "this", "->", "checkCache", "(", ")", ";", "$", "this", "->", "validatePlugins", "(", ")", ";", "$", "this", "->", "countPlugins", "(", ")", ";", "array_map", "(", "static", "function", "(", ")", "{", "include_once", "WPMU_PLUGIN_DIR", ".", "'/'", ".", "func_get_args", "(", ")", "[", "0", "]", ";", "}", ",", "array_keys", "(", "self", "::", "$", "cache", "[", "'plugins'", "]", ")", ")", ";", "$", "this", "->", "pluginHooks", "(", ")", ";", "}" ]
Run some checks then autoload our plugins.
[ "Run", "some", "checks", "then", "autoload", "our", "plugins", "." ]
96b7e793848cdb33eebac979c42b40b6053e43fb
https://github.com/roots/bedrock/blob/96b7e793848cdb33eebac979c42b40b6053e43fb/web/app/mu-plugins/bedrock-autoloader.php#L69-L80
train
roots/bedrock
web/app/mu-plugins/bedrock-autoloader.php
Autoloader.checkCache
private function checkCache() { $cache = get_site_option('bedrock_autoloader'); if ($cache === false || (isset($cache['plugins'], $cache['count']) && count($cache['plugins']) !== $cache['count'])) { $this->updateCache(); return; } self::$cache = $cache; }
php
private function checkCache() { $cache = get_site_option('bedrock_autoloader'); if ($cache === false || (isset($cache['plugins'], $cache['count']) && count($cache['plugins']) !== $cache['count'])) { $this->updateCache(); return; } self::$cache = $cache; }
[ "private", "function", "checkCache", "(", ")", "{", "$", "cache", "=", "get_site_option", "(", "'bedrock_autoloader'", ")", ";", "if", "(", "$", "cache", "===", "false", "||", "(", "isset", "(", "$", "cache", "[", "'plugins'", "]", ",", "$", "cache", "[", "'count'", "]", ")", "&&", "count", "(", "$", "cache", "[", "'plugins'", "]", ")", "!==", "$", "cache", "[", "'count'", "]", ")", ")", "{", "$", "this", "->", "updateCache", "(", ")", ";", "return", ";", "}", "self", "::", "$", "cache", "=", "$", "cache", ";", "}" ]
This sets the cache or calls for an update
[ "This", "sets", "the", "cache", "or", "calls", "for", "an", "update" ]
96b7e793848cdb33eebac979c42b40b6053e43fb
https://github.com/roots/bedrock/blob/96b7e793848cdb33eebac979c42b40b6053e43fb/web/app/mu-plugins/bedrock-autoloader.php#L113-L123
train
roots/bedrock
web/app/mu-plugins/bedrock-autoloader.php
Autoloader.validatePlugins
private function validatePlugins() { foreach (self::$cache['plugins'] as $plugin_file => $plugin_info) { if (!file_exists(WPMU_PLUGIN_DIR . '/' . $plugin_file)) { $this->updateCache(); break; } } }
php
private function validatePlugins() { foreach (self::$cache['plugins'] as $plugin_file => $plugin_info) { if (!file_exists(WPMU_PLUGIN_DIR . '/' . $plugin_file)) { $this->updateCache(); break; } } }
[ "private", "function", "validatePlugins", "(", ")", "{", "foreach", "(", "self", "::", "$", "cache", "[", "'plugins'", "]", "as", "$", "plugin_file", "=>", "$", "plugin_info", ")", "{", "if", "(", "!", "file_exists", "(", "WPMU_PLUGIN_DIR", ".", "'/'", ".", "$", "plugin_file", ")", ")", "{", "$", "this", "->", "updateCache", "(", ")", ";", "break", ";", "}", "}", "}" ]
Check that the plugin file exists, if it doesn't update the cache.
[ "Check", "that", "the", "plugin", "file", "exists", "if", "it", "doesn", "t", "update", "the", "cache", "." ]
96b7e793848cdb33eebac979c42b40b6053e43fb
https://github.com/roots/bedrock/blob/96b7e793848cdb33eebac979c42b40b6053e43fb/web/app/mu-plugins/bedrock-autoloader.php#L163-L171
train
roots/bedrock
web/app/mu-plugins/bedrock-autoloader.php
Autoloader.countPlugins
private function countPlugins() { if (isset(self::$count)) { return self::$count; } $count = count(glob(WPMU_PLUGIN_DIR . '/*/', GLOB_ONLYDIR | GLOB_NOSORT)); if (!isset(self::$cache['count']) || $count !== self::$cache['count']) { self::$count = $count; $this->updateCache(); } return self::$count; }
php
private function countPlugins() { if (isset(self::$count)) { return self::$count; } $count = count(glob(WPMU_PLUGIN_DIR . '/*/', GLOB_ONLYDIR | GLOB_NOSORT)); if (!isset(self::$cache['count']) || $count !== self::$cache['count']) { self::$count = $count; $this->updateCache(); } return self::$count; }
[ "private", "function", "countPlugins", "(", ")", "{", "if", "(", "isset", "(", "self", "::", "$", "count", ")", ")", "{", "return", "self", "::", "$", "count", ";", "}", "$", "count", "=", "count", "(", "glob", "(", "WPMU_PLUGIN_DIR", ".", "'/*/'", ",", "GLOB_ONLYDIR", "|", "GLOB_NOSORT", ")", ")", ";", "if", "(", "!", "isset", "(", "self", "::", "$", "cache", "[", "'count'", "]", ")", "||", "$", "count", "!==", "self", "::", "$", "cache", "[", "'count'", "]", ")", "{", "self", "::", "$", "count", "=", "$", "count", ";", "$", "this", "->", "updateCache", "(", ")", ";", "}", "return", "self", "::", "$", "count", ";", "}" ]
Count the number of autoloaded plugins. Count our plugins (but only once) by counting the top level folders in the mu-plugins dir. If it's more or less than last time, update the cache. @return int Number of autoloaded plugins.
[ "Count", "the", "number", "of", "autoloaded", "plugins", "." ]
96b7e793848cdb33eebac979c42b40b6053e43fb
https://github.com/roots/bedrock/blob/96b7e793848cdb33eebac979c42b40b6053e43fb/web/app/mu-plugins/bedrock-autoloader.php#L181-L195
train
danog/MadelineProto
src/danog/MadelineProto/Serialization.php
Serialization.serialize
public static function serialize($filename, $instance, $force = false) { if ($filename == '') { throw new \danog\MadelineProto\Exception('Empty filename'); } if ($instance->API->asyncInitPromise) { return $instance->call(static function () use ($filename, $instance, $force) { yield $instance->API->asyncInitPromise; $instance->API->asyncInitPromise = null; return self::serialize($filename, $instance, $force); }); } if (isset($instance->API->setdem) && $instance->API->setdem) { $instance->API->setdem = false; $instance->API->__construct($instance->API->settings); } if ($instance->API === null && !$instance->getting_api_id) { return false; } $instance->serialized = time(); $realpaths = self::realpaths($filename); if (!file_exists($realpaths['lockfile'])) { touch($realpaths['lockfile']); clearstatcache(); } $realpaths['lockfile'] = fopen($realpaths['lockfile'], 'w'); \danog\MadelineProto\Logger::log('Waiting for exclusive lock of serialization lockfile...'); flock($realpaths['lockfile'], LOCK_EX); \danog\MadelineProto\Logger::log('Lock acquired, serializing'); try { if (!$instance->getting_api_id) { $update_closure = $instance->API->settings['updates']['callback']; if ($instance->API->settings['updates']['callback'] instanceof \Closure) { $instance->API->settings['updates']['callback'] = [$instance->API, 'noop']; } $logger_closure = $instance->API->settings['logger']['logger_param']; if ($instance->API->settings['logger']['logger_param'] instanceof \Closure) { $instance->API->settings['logger']['logger_param'] = [$instance->API, 'noop']; } } $wrote = file_put_contents($realpaths['tempfile'], serialize($instance)); rename($realpaths['tempfile'], $realpaths['file']); } finally { if (!$instance->getting_api_id) { $instance->API->settings['updates']['callback'] = $update_closure; $instance->API->settings['logger']['logger_param'] = $logger_closure; } flock($realpaths['lockfile'], LOCK_UN); fclose($realpaths['lockfile']); } return $wrote; }
php
public static function serialize($filename, $instance, $force = false) { if ($filename == '') { throw new \danog\MadelineProto\Exception('Empty filename'); } if ($instance->API->asyncInitPromise) { return $instance->call(static function () use ($filename, $instance, $force) { yield $instance->API->asyncInitPromise; $instance->API->asyncInitPromise = null; return self::serialize($filename, $instance, $force); }); } if (isset($instance->API->setdem) && $instance->API->setdem) { $instance->API->setdem = false; $instance->API->__construct($instance->API->settings); } if ($instance->API === null && !$instance->getting_api_id) { return false; } $instance->serialized = time(); $realpaths = self::realpaths($filename); if (!file_exists($realpaths['lockfile'])) { touch($realpaths['lockfile']); clearstatcache(); } $realpaths['lockfile'] = fopen($realpaths['lockfile'], 'w'); \danog\MadelineProto\Logger::log('Waiting for exclusive lock of serialization lockfile...'); flock($realpaths['lockfile'], LOCK_EX); \danog\MadelineProto\Logger::log('Lock acquired, serializing'); try { if (!$instance->getting_api_id) { $update_closure = $instance->API->settings['updates']['callback']; if ($instance->API->settings['updates']['callback'] instanceof \Closure) { $instance->API->settings['updates']['callback'] = [$instance->API, 'noop']; } $logger_closure = $instance->API->settings['logger']['logger_param']; if ($instance->API->settings['logger']['logger_param'] instanceof \Closure) { $instance->API->settings['logger']['logger_param'] = [$instance->API, 'noop']; } } $wrote = file_put_contents($realpaths['tempfile'], serialize($instance)); rename($realpaths['tempfile'], $realpaths['file']); } finally { if (!$instance->getting_api_id) { $instance->API->settings['updates']['callback'] = $update_closure; $instance->API->settings['logger']['logger_param'] = $logger_closure; } flock($realpaths['lockfile'], LOCK_UN); fclose($realpaths['lockfile']); } return $wrote; }
[ "public", "static", "function", "serialize", "(", "$", "filename", ",", "$", "instance", ",", "$", "force", "=", "false", ")", "{", "if", "(", "$", "filename", "==", "''", ")", "{", "throw", "new", "\\", "danog", "\\", "MadelineProto", "\\", "Exception", "(", "'Empty filename'", ")", ";", "}", "if", "(", "$", "instance", "->", "API", "->", "asyncInitPromise", ")", "{", "return", "$", "instance", "->", "call", "(", "static", "function", "(", ")", "use", "(", "$", "filename", ",", "$", "instance", ",", "$", "force", ")", "{", "yield", "$", "instance", "->", "API", "->", "asyncInitPromise", ";", "$", "instance", "->", "API", "->", "asyncInitPromise", "=", "null", ";", "return", "self", "::", "serialize", "(", "$", "filename", ",", "$", "instance", ",", "$", "force", ")", ";", "}", ")", ";", "}", "if", "(", "isset", "(", "$", "instance", "->", "API", "->", "setdem", ")", "&&", "$", "instance", "->", "API", "->", "setdem", ")", "{", "$", "instance", "->", "API", "->", "setdem", "=", "false", ";", "$", "instance", "->", "API", "->", "__construct", "(", "$", "instance", "->", "API", "->", "settings", ")", ";", "}", "if", "(", "$", "instance", "->", "API", "===", "null", "&&", "!", "$", "instance", "->", "getting_api_id", ")", "{", "return", "false", ";", "}", "$", "instance", "->", "serialized", "=", "time", "(", ")", ";", "$", "realpaths", "=", "self", "::", "realpaths", "(", "$", "filename", ")", ";", "if", "(", "!", "file_exists", "(", "$", "realpaths", "[", "'lockfile'", "]", ")", ")", "{", "touch", "(", "$", "realpaths", "[", "'lockfile'", "]", ")", ";", "clearstatcache", "(", ")", ";", "}", "$", "realpaths", "[", "'lockfile'", "]", "=", "fopen", "(", "$", "realpaths", "[", "'lockfile'", "]", ",", "'w'", ")", ";", "\\", "danog", "\\", "MadelineProto", "\\", "Logger", "::", "log", "(", "'Waiting for exclusive lock of serialization lockfile...'", ")", ";", "flock", "(", "$", "realpaths", "[", "'lockfile'", "]", ",", "LOCK_EX", ")", ";", "\\", "danog", "\\", "MadelineProto", "\\", "Logger", "::", "log", "(", "'Lock acquired, serializing'", ")", ";", "try", "{", "if", "(", "!", "$", "instance", "->", "getting_api_id", ")", "{", "$", "update_closure", "=", "$", "instance", "->", "API", "->", "settings", "[", "'updates'", "]", "[", "'callback'", "]", ";", "if", "(", "$", "instance", "->", "API", "->", "settings", "[", "'updates'", "]", "[", "'callback'", "]", "instanceof", "\\", "Closure", ")", "{", "$", "instance", "->", "API", "->", "settings", "[", "'updates'", "]", "[", "'callback'", "]", "=", "[", "$", "instance", "->", "API", ",", "'noop'", "]", ";", "}", "$", "logger_closure", "=", "$", "instance", "->", "API", "->", "settings", "[", "'logger'", "]", "[", "'logger_param'", "]", ";", "if", "(", "$", "instance", "->", "API", "->", "settings", "[", "'logger'", "]", "[", "'logger_param'", "]", "instanceof", "\\", "Closure", ")", "{", "$", "instance", "->", "API", "->", "settings", "[", "'logger'", "]", "[", "'logger_param'", "]", "=", "[", "$", "instance", "->", "API", ",", "'noop'", "]", ";", "}", "}", "$", "wrote", "=", "file_put_contents", "(", "$", "realpaths", "[", "'tempfile'", "]", ",", "serialize", "(", "$", "instance", ")", ")", ";", "rename", "(", "$", "realpaths", "[", "'tempfile'", "]", ",", "$", "realpaths", "[", "'file'", "]", ")", ";", "}", "finally", "{", "if", "(", "!", "$", "instance", "->", "getting_api_id", ")", "{", "$", "instance", "->", "API", "->", "settings", "[", "'updates'", "]", "[", "'callback'", "]", "=", "$", "update_closure", ";", "$", "instance", "->", "API", "->", "settings", "[", "'logger'", "]", "[", "'logger_param'", "]", "=", "$", "logger_closure", ";", "}", "flock", "(", "$", "realpaths", "[", "'lockfile'", "]", ",", "LOCK_UN", ")", ";", "fclose", "(", "$", "realpaths", "[", "'lockfile'", "]", ")", ";", "}", "return", "$", "wrote", ";", "}" ]
Serialize API class. @param string $filename the dump file @param API $instance @param bool $force @return number
[ "Serialize", "API", "class", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Serialization.php#L55-L108
train
danog/MadelineProto
src/danog/MadelineProto/Stream/MTProtoTransport/ObfuscatedStream.php
ObfuscatedStream.bufferReadAsync
public function bufferReadAsync(int $length): \Generator { return @$this->decrypt->encrypt(yield $this->read_buffer->bufferRead($length)); }
php
public function bufferReadAsync(int $length): \Generator { return @$this->decrypt->encrypt(yield $this->read_buffer->bufferRead($length)); }
[ "public", "function", "bufferReadAsync", "(", "int", "$", "length", ")", ":", "\\", "Generator", "{", "return", "@", "$", "this", "->", "decrypt", "->", "encrypt", "(", "yield", "$", "this", "->", "read_buffer", "->", "bufferRead", "(", "$", "length", ")", ")", ";", "}" ]
Decrypts read data asynchronously. @param Promise $promise Promise that resolves with a string when new data is available or `null` if the stream has closed. @throws PendingReadError Thrown if another read operation is still pending. @return Generator That resolves with a string when the provided promise is resolved and the data is decrypted
[ "Decrypts", "read", "data", "asynchronously", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Stream/MTProtoTransport/ObfuscatedStream.php#L150-L153
train
danog/MadelineProto
src/danog/MadelineProto/Stream/MTProtoTransport/ObfuscatedStream.php
ObfuscatedStream.setExtra
public function setExtra($extra) { if (isset($extra['secret']) && strlen($extra['secret']) > 17) { $extra['secret'] = hex2bin($extra['secret']); } if (isset($extra['secret']) && strlen($extra['secret']) == 17) { $extra['secret'] = substr($extra['secret'], 0, 16); } $this->extra = $extra; }
php
public function setExtra($extra) { if (isset($extra['secret']) && strlen($extra['secret']) > 17) { $extra['secret'] = hex2bin($extra['secret']); } if (isset($extra['secret']) && strlen($extra['secret']) == 17) { $extra['secret'] = substr($extra['secret'], 0, 16); } $this->extra = $extra; }
[ "public", "function", "setExtra", "(", "$", "extra", ")", "{", "if", "(", "isset", "(", "$", "extra", "[", "'secret'", "]", ")", "&&", "strlen", "(", "$", "extra", "[", "'secret'", "]", ")", ">", "17", ")", "{", "$", "extra", "[", "'secret'", "]", "=", "hex2bin", "(", "$", "extra", "[", "'secret'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "extra", "[", "'secret'", "]", ")", "&&", "strlen", "(", "$", "extra", "[", "'secret'", "]", ")", "==", "17", ")", "{", "$", "extra", "[", "'secret'", "]", "=", "substr", "(", "$", "extra", "[", "'secret'", "]", ",", "0", ",", "16", ")", ";", "}", "$", "this", "->", "extra", "=", "$", "extra", ";", "}" ]
Does nothing. @param void $data Nothing @return void
[ "Does", "nothing", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Stream/MTProtoTransport/ObfuscatedStream.php#L189-L198
train
danog/MadelineProto
src/danog/MadelineProto/Stream/Transport/DefaultStream.php
DefaultStream.read
public function read(): Promise { return $this->stream ? $this->stream->read() : new \Amp\Success(null); }
php
public function read(): Promise { return $this->stream ? $this->stream->read() : new \Amp\Success(null); }
[ "public", "function", "read", "(", ")", ":", "Promise", "{", "return", "$", "this", "->", "stream", "?", "$", "this", "->", "stream", "->", "read", "(", ")", ":", "new", "\\", "Amp", "\\", "Success", "(", "null", ")", ";", "}" ]
Async chunked read. @return Promise
[ "Async", "chunked", "read", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Stream/Transport/DefaultStream.php#L69-L72
train
danog/MadelineProto
src/danog/MadelineProto/Stream/MTProtoTransport/HttpStream.php
HttpStream.setExtra
public function setExtra($extra) { if (isset($extra['user']) && isset($extra['password'])) { $this->header = \base64_encode($extra['user'].':'.$extra['password'])."\r\n"; } }
php
public function setExtra($extra) { if (isset($extra['user']) && isset($extra['password'])) { $this->header = \base64_encode($extra['user'].':'.$extra['password'])."\r\n"; } }
[ "public", "function", "setExtra", "(", "$", "extra", ")", "{", "if", "(", "isset", "(", "$", "extra", "[", "'user'", "]", ")", "&&", "isset", "(", "$", "extra", "[", "'password'", "]", ")", ")", "{", "$", "this", "->", "header", "=", "\\", "base64_encode", "(", "$", "extra", "[", "'user'", "]", ".", "':'", ".", "$", "extra", "[", "'password'", "]", ")", ".", "\"\\r\\n\"", ";", "}", "}" ]
Set proxy data. @param array $extra Proxy parameters @return void
[ "Set", "proxy", "data", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Stream/MTProtoTransport/HttpStream.php#L70-L75
train
danog/MadelineProto
src/danog/MadelineProto/MyTelegramOrgWrapper.php
MyTelegramOrgWrapper.get_headers
private function get_headers($httpType, $cookies) { // Common header flags. $headers = []; $headers[] = 'Dnt: 1'; $headers[] = 'Connection: keep-alive'; $headers[] = 'Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4'; $headers[] = 'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'; // Add additional headers based on the type of request. switch ($httpType) { case 'origin': $headers[] = 'Origin: '.self::MY_TELEGRAM_URL; $headers[] = 'Accept-Encoding: gzip, deflate, br'; $headers[] = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8'; $headers[] = 'Accept: application/json, text/javascript, */*; q=0.01'; $headers[] = 'Referer: '.self::MY_TELEGRAM_URL.'/auth'; $headers[] = 'X-Requested-With: XMLHttpRequest'; break; case 'refer': $headers[] = 'Accept-Encoding: gzip, deflate, sdch, br'; $headers[] = 'Upgrade-Insecure-Requests: 1'; $headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'; $headers[] = 'Referer: '.self::MY_TELEGRAM_URL; $headers[] = 'Cache-Control: max-age=0'; break; case 'app': $headers[] = 'Origin: '.self::MY_TELEGRAM_URL; $headers[] = 'Accept-Encoding: gzip, deflate, br'; $headers[] = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8'; $headers[] = 'Accept: */*'; $headers[] = 'Referer: '.self::MY_TELEGRAM_URL.'/apps'; $headers[] = 'X-Requested-With: XMLHttpRequest'; break; } // Add every cookie to the header. foreach ($cookies as $cookie) { $headers[] = 'Cookie: '.$cookie; } return $headers; }
php
private function get_headers($httpType, $cookies) { // Common header flags. $headers = []; $headers[] = 'Dnt: 1'; $headers[] = 'Connection: keep-alive'; $headers[] = 'Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4'; $headers[] = 'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'; // Add additional headers based on the type of request. switch ($httpType) { case 'origin': $headers[] = 'Origin: '.self::MY_TELEGRAM_URL; $headers[] = 'Accept-Encoding: gzip, deflate, br'; $headers[] = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8'; $headers[] = 'Accept: application/json, text/javascript, */*; q=0.01'; $headers[] = 'Referer: '.self::MY_TELEGRAM_URL.'/auth'; $headers[] = 'X-Requested-With: XMLHttpRequest'; break; case 'refer': $headers[] = 'Accept-Encoding: gzip, deflate, sdch, br'; $headers[] = 'Upgrade-Insecure-Requests: 1'; $headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'; $headers[] = 'Referer: '.self::MY_TELEGRAM_URL; $headers[] = 'Cache-Control: max-age=0'; break; case 'app': $headers[] = 'Origin: '.self::MY_TELEGRAM_URL; $headers[] = 'Accept-Encoding: gzip, deflate, br'; $headers[] = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8'; $headers[] = 'Accept: */*'; $headers[] = 'Referer: '.self::MY_TELEGRAM_URL.'/apps'; $headers[] = 'X-Requested-With: XMLHttpRequest'; break; } // Add every cookie to the header. foreach ($cookies as $cookie) { $headers[] = 'Cookie: '.$cookie; } return $headers; }
[ "private", "function", "get_headers", "(", "$", "httpType", ",", "$", "cookies", ")", "{", "// Common header flags.", "$", "headers", "=", "[", "]", ";", "$", "headers", "[", "]", "=", "'Dnt: 1'", ";", "$", "headers", "[", "]", "=", "'Connection: keep-alive'", ";", "$", "headers", "[", "]", "=", "'Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4'", ";", "$", "headers", "[", "]", "=", "'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'", ";", "// Add additional headers based on the type of request.", "switch", "(", "$", "httpType", ")", "{", "case", "'origin'", ":", "$", "headers", "[", "]", "=", "'Origin: '", ".", "self", "::", "MY_TELEGRAM_URL", ";", "$", "headers", "[", "]", "=", "'Accept-Encoding: gzip, deflate, br'", ";", "$", "headers", "[", "]", "=", "'Content-Type: application/x-www-form-urlencoded; charset=UTF-8'", ";", "$", "headers", "[", "]", "=", "'Accept: application/json, text/javascript, */*; q=0.01'", ";", "$", "headers", "[", "]", "=", "'Referer: '", ".", "self", "::", "MY_TELEGRAM_URL", ".", "'/auth'", ";", "$", "headers", "[", "]", "=", "'X-Requested-With: XMLHttpRequest'", ";", "break", ";", "case", "'refer'", ":", "$", "headers", "[", "]", "=", "'Accept-Encoding: gzip, deflate, sdch, br'", ";", "$", "headers", "[", "]", "=", "'Upgrade-Insecure-Requests: 1'", ";", "$", "headers", "[", "]", "=", "'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'", ";", "$", "headers", "[", "]", "=", "'Referer: '", ".", "self", "::", "MY_TELEGRAM_URL", ";", "$", "headers", "[", "]", "=", "'Cache-Control: max-age=0'", ";", "break", ";", "case", "'app'", ":", "$", "headers", "[", "]", "=", "'Origin: '", ".", "self", "::", "MY_TELEGRAM_URL", ";", "$", "headers", "[", "]", "=", "'Accept-Encoding: gzip, deflate, br'", ";", "$", "headers", "[", "]", "=", "'Content-Type: application/x-www-form-urlencoded; charset=UTF-8'", ";", "$", "headers", "[", "]", "=", "'Accept: */*'", ";", "$", "headers", "[", "]", "=", "'Referer: '", ".", "self", "::", "MY_TELEGRAM_URL", ".", "'/apps'", ";", "$", "headers", "[", "]", "=", "'X-Requested-With: XMLHttpRequest'", ";", "break", ";", "}", "// Add every cookie to the header.", "foreach", "(", "$", "cookies", "as", "$", "cookie", ")", "{", "$", "headers", "[", "]", "=", "'Cookie: '", ".", "$", "cookie", ";", "}", "return", "$", "headers", ";", "}" ]
Function for generating curl request headers.
[ "Function", "for", "generating", "curl", "request", "headers", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/MyTelegramOrgWrapper.php#L62-L104
train
danog/MadelineProto
src/danog/MadelineProto/Stream/ConnectionContext.php
ConnectionContext.setUri
public function setUri($uri): self { $this->uri = $uri instanceof Uri ? $uri : new Uri($uri); return $this; }
php
public function setUri($uri): self { $this->uri = $uri instanceof Uri ? $uri : new Uri($uri); return $this; }
[ "public", "function", "setUri", "(", "$", "uri", ")", ":", "self", "{", "$", "this", "->", "uri", "=", "$", "uri", "instanceof", "Uri", "?", "$", "uri", ":", "new", "Uri", "(", "$", "uri", ")", ";", "return", "$", "this", ";", "}" ]
Set the connection URI. @param string|\Amp\Uri\Uri $uri @return self
[ "Set", "the", "connection", "URI", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Stream/ConnectionContext.php#L123-L128
train
danog/MadelineProto
src/danog/MadelineProto/Stream/ConnectionContext.php
ConnectionContext.getIntDc
public function getIntDc() { $dc = intval($this->dc); if ($this->test) { $dc += 10000; } if (strpos($this->dc, '_media')) { $dc = -$dc; } return $dc; }
php
public function getIntDc() { $dc = intval($this->dc); if ($this->test) { $dc += 10000; } if (strpos($this->dc, '_media')) { $dc = -$dc; } return $dc; }
[ "public", "function", "getIntDc", "(", ")", "{", "$", "dc", "=", "intval", "(", "$", "this", "->", "dc", ")", ";", "if", "(", "$", "this", "->", "test", ")", "{", "$", "dc", "+=", "10000", ";", "}", "if", "(", "strpos", "(", "$", "this", "->", "dc", ",", "'_media'", ")", ")", "{", "$", "dc", "=", "-", "$", "dc", ";", "}", "return", "$", "dc", ";", "}" ]
Get the int DC ID. @return string|int
[ "Get", "the", "int", "DC", "ID", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Stream/ConnectionContext.php#L251-L262
train
danog/MadelineProto
src/danog/MadelineProto/Stream/ConnectionContext.php
ConnectionContext.addStream
public function addStream(string $streamName, $extra = null): self { $this->nextStreams[] = [$streamName, $extra]; $this->key = count($this->nextStreams) - 1; return $this; }
php
public function addStream(string $streamName, $extra = null): self { $this->nextStreams[] = [$streamName, $extra]; $this->key = count($this->nextStreams) - 1; return $this; }
[ "public", "function", "addStream", "(", "string", "$", "streamName", ",", "$", "extra", "=", "null", ")", ":", "self", "{", "$", "this", "->", "nextStreams", "[", "]", "=", "[", "$", "streamName", ",", "$", "extra", "]", ";", "$", "this", "->", "key", "=", "count", "(", "$", "this", "->", "nextStreams", ")", "-", "1", ";", "return", "$", "this", ";", "}" ]
Add a stream to the stream chain. @param string $streamName @param any $extra @return self
[ "Add", "a", "stream", "to", "the", "stream", "chain", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Stream/ConnectionContext.php#L306-L312
train
danog/MadelineProto
src/danog/MadelineProto/Stream/ConnectionContext.php
ConnectionContext.getStreamAsync
public function getStreamAsync(string $buffer = ''): \Generator { list($clazz, $extra) = $this->nextStreams[$this->key--]; $obj = new $clazz(); if ($obj instanceof ProxyStreamInterface) { $obj->setExtra($extra); } yield $obj->connect($this, $buffer); return $obj; }
php
public function getStreamAsync(string $buffer = ''): \Generator { list($clazz, $extra) = $this->nextStreams[$this->key--]; $obj = new $clazz(); if ($obj instanceof ProxyStreamInterface) { $obj->setExtra($extra); } yield $obj->connect($this, $buffer); return $obj; }
[ "public", "function", "getStreamAsync", "(", "string", "$", "buffer", "=", "''", ")", ":", "\\", "Generator", "{", "list", "(", "$", "clazz", ",", "$", "extra", ")", "=", "$", "this", "->", "nextStreams", "[", "$", "this", "->", "key", "--", "]", ";", "$", "obj", "=", "new", "$", "clazz", "(", ")", ";", "if", "(", "$", "obj", "instanceof", "ProxyStreamInterface", ")", "{", "$", "obj", "->", "setExtra", "(", "$", "extra", ")", ";", "}", "yield", "$", "obj", "->", "connect", "(", "$", "this", ",", "$", "buffer", ")", ";", "return", "$", "obj", ";", "}" ]
Get a stream from the stream chain. @internal Generator func @return \Generator
[ "Get", "a", "stream", "from", "the", "stream", "chain", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Stream/ConnectionContext.php#L341-L351
train
danog/MadelineProto
src/danog/MadelineProto/Stream/ConnectionContext.php
ConnectionContext.getName
public function getName(): string { $string = $this->getStringUri(); if ($this->isSecure()) { $string .= ' (TLS)'; } $string .= ' DC '; $string .= $this->getDc(); $string .= ', via '; $string .= $this->getIpv6() ? 'ipv6' : 'ipv4'; $string .= ' using '; foreach (array_reverse($this->nextStreams) as $k => $stream) { if ($k) { $string .= ' => '; } $string .= preg_replace('/.*\\\\/', '', $stream[0]); if ($stream[1]) { $string .= ' ('.json_encode($stream[1]).')'; } } return $string; }
php
public function getName(): string { $string = $this->getStringUri(); if ($this->isSecure()) { $string .= ' (TLS)'; } $string .= ' DC '; $string .= $this->getDc(); $string .= ', via '; $string .= $this->getIpv6() ? 'ipv6' : 'ipv4'; $string .= ' using '; foreach (array_reverse($this->nextStreams) as $k => $stream) { if ($k) { $string .= ' => '; } $string .= preg_replace('/.*\\\\/', '', $stream[0]); if ($stream[1]) { $string .= ' ('.json_encode($stream[1]).')'; } } return $string; }
[ "public", "function", "getName", "(", ")", ":", "string", "{", "$", "string", "=", "$", "this", "->", "getStringUri", "(", ")", ";", "if", "(", "$", "this", "->", "isSecure", "(", ")", ")", "{", "$", "string", ".=", "' (TLS)'", ";", "}", "$", "string", ".=", "' DC '", ";", "$", "string", ".=", "$", "this", "->", "getDc", "(", ")", ";", "$", "string", ".=", "', via '", ";", "$", "string", ".=", "$", "this", "->", "getIpv6", "(", ")", "?", "'ipv6'", ":", "'ipv4'", ";", "$", "string", ".=", "' using '", ";", "foreach", "(", "array_reverse", "(", "$", "this", "->", "nextStreams", ")", "as", "$", "k", "=>", "$", "stream", ")", "{", "if", "(", "$", "k", ")", "{", "$", "string", ".=", "' => '", ";", "}", "$", "string", ".=", "preg_replace", "(", "'/.*\\\\\\\\/'", ",", "''", ",", "$", "stream", "[", "0", "]", ")", ";", "if", "(", "$", "stream", "[", "1", "]", ")", "{", "$", "string", ".=", "' ('", ".", "json_encode", "(", "$", "stream", "[", "1", "]", ")", ".", "')'", ";", "}", "}", "return", "$", "string", ";", "}" ]
Get a description "name" of the context. @return string
[ "Get", "a", "description", "name", "of", "the", "context", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Stream/ConnectionContext.php#L358-L380
train
danog/MadelineProto
src/danog/MadelineProto/AnnotationsBuilder.php
AnnotationsBuilder.setProperties
private function setProperties() { \danog\MadelineProto\Logger::log('Generating properties...', \danog\MadelineProto\Logger::NOTICE); $fixture = DocBlockFactory::createInstance(); $class = new \ReflectionClass(APIFactory::class); $content = file_get_contents($filename = $class->getFileName()); foreach ($class->getProperties() as $property) { if ($raw_docblock = $property->getDocComment()) { $docblock = $fixture->create($raw_docblock); if ($docblock->hasTag('internal')) { $content = str_replace("\n ".$raw_docblock."\n public \$".$property->getName().';', '', $content); } } } foreach ($this->get_method_namespaces() as $namespace) { $content = preg_replace('/(class( \\w+[,]?){0,}\\n{\\n)/', '${1}'." /**\n"." * @internal this is a internal property generated by build_docs.php, don't change manually\n"." *\n"." * @var {$namespace}\n"." */\n"." public \${$namespace};\n", $content); } file_put_contents($filename, $content); }
php
private function setProperties() { \danog\MadelineProto\Logger::log('Generating properties...', \danog\MadelineProto\Logger::NOTICE); $fixture = DocBlockFactory::createInstance(); $class = new \ReflectionClass(APIFactory::class); $content = file_get_contents($filename = $class->getFileName()); foreach ($class->getProperties() as $property) { if ($raw_docblock = $property->getDocComment()) { $docblock = $fixture->create($raw_docblock); if ($docblock->hasTag('internal')) { $content = str_replace("\n ".$raw_docblock."\n public \$".$property->getName().';', '', $content); } } } foreach ($this->get_method_namespaces() as $namespace) { $content = preg_replace('/(class( \\w+[,]?){0,}\\n{\\n)/', '${1}'." /**\n"." * @internal this is a internal property generated by build_docs.php, don't change manually\n"." *\n"." * @var {$namespace}\n"." */\n"." public \${$namespace};\n", $content); } file_put_contents($filename, $content); }
[ "private", "function", "setProperties", "(", ")", "{", "\\", "danog", "\\", "MadelineProto", "\\", "Logger", "::", "log", "(", "'Generating properties...'", ",", "\\", "danog", "\\", "MadelineProto", "\\", "Logger", "::", "NOTICE", ")", ";", "$", "fixture", "=", "DocBlockFactory", "::", "createInstance", "(", ")", ";", "$", "class", "=", "new", "\\", "ReflectionClass", "(", "APIFactory", "::", "class", ")", ";", "$", "content", "=", "file_get_contents", "(", "$", "filename", "=", "$", "class", "->", "getFileName", "(", ")", ")", ";", "foreach", "(", "$", "class", "->", "getProperties", "(", ")", "as", "$", "property", ")", "{", "if", "(", "$", "raw_docblock", "=", "$", "property", "->", "getDocComment", "(", ")", ")", "{", "$", "docblock", "=", "$", "fixture", "->", "create", "(", "$", "raw_docblock", ")", ";", "if", "(", "$", "docblock", "->", "hasTag", "(", "'internal'", ")", ")", "{", "$", "content", "=", "str_replace", "(", "\"\\n \"", ".", "$", "raw_docblock", ".", "\"\\n public \\$\"", ".", "$", "property", "->", "getName", "(", ")", ".", "';'", ",", "''", ",", "$", "content", ")", ";", "}", "}", "}", "foreach", "(", "$", "this", "->", "get_method_namespaces", "(", ")", "as", "$", "namespace", ")", "{", "$", "content", "=", "preg_replace", "(", "'/(class( \\\\w+[,]?){0,}\\\\n{\\\\n)/'", ",", "'${1}'", ".", "\" /**\\n\"", ".", "\" * @internal this is a internal property generated by build_docs.php, don't change manually\\n\"", ".", "\" *\\n\"", ".", "\" * @var {$namespace}\\n\"", ".", "\" */\\n\"", ".", "\" public \\${$namespace};\\n\"", ",", "$", "content", ")", ";", "}", "file_put_contents", "(", "$", "filename", ",", "$", "content", ")", ";", "}" ]
Open file of class APIFactory Insert properties save the file with new content.
[ "Open", "file", "of", "class", "APIFactory", "Insert", "properties", "save", "the", "file", "with", "new", "content", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/AnnotationsBuilder.php#L48-L66
train
danog/MadelineProto
src/danog/MadelineProto/Stream/Common/HashedBufferedStream.php
HashedBufferedStream.getReadHash
public function getReadHash(): string { $hash = hash_final($this->read_hash, true); if ($this->rev) { $hash = strrev($hash); } $this->read_hash = null; $this->read_check_after = 0; $this->read_check_pos = 0; return $hash; }
php
public function getReadHash(): string { $hash = hash_final($this->read_hash, true); if ($this->rev) { $hash = strrev($hash); } $this->read_hash = null; $this->read_check_after = 0; $this->read_check_pos = 0; return $hash; }
[ "public", "function", "getReadHash", "(", ")", ":", "string", "{", "$", "hash", "=", "hash_final", "(", "$", "this", "->", "read_hash", ",", "true", ")", ";", "if", "(", "$", "this", "->", "rev", ")", "{", "$", "hash", "=", "strrev", "(", "$", "hash", ")", ";", "}", "$", "this", "->", "read_hash", "=", "null", ";", "$", "this", "->", "read_check_after", "=", "0", ";", "$", "this", "->", "read_check_pos", "=", "0", ";", "return", "$", "hash", ";", "}" ]
Stop read hashing and get final hash. @return string
[ "Stop", "read", "hashing", "and", "get", "final", "hash", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Stream/Common/HashedBufferedStream.php#L76-L87
train
danog/MadelineProto
src/danog/MadelineProto/Stream/Common/HashedBufferedStream.php
HashedBufferedStream.getWriteHash
public function getWriteHash(): string { $hash = hash_final($this->write_hash, true); if ($this->rev) { $hash = strrev($hash); } $this->write_hash = null; $this->write_check_after = 0; $this->write_check_pos = 0; return $hash; }
php
public function getWriteHash(): string { $hash = hash_final($this->write_hash, true); if ($this->rev) { $hash = strrev($hash); } $this->write_hash = null; $this->write_check_after = 0; $this->write_check_pos = 0; return $hash; }
[ "public", "function", "getWriteHash", "(", ")", ":", "string", "{", "$", "hash", "=", "hash_final", "(", "$", "this", "->", "write_hash", ",", "true", ")", ";", "if", "(", "$", "this", "->", "rev", ")", "{", "$", "hash", "=", "strrev", "(", "$", "hash", ")", ";", "}", "$", "this", "->", "write_hash", "=", "null", ";", "$", "this", "->", "write_check_after", "=", "0", ";", "$", "this", "->", "write_check_pos", "=", "0", ";", "return", "$", "hash", ";", "}" ]
Stop write hashing and get final hash. @return string
[ "Stop", "write", "hashing", "and", "get", "final", "hash", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Stream/Common/HashedBufferedStream.php#L126-L137
train
danog/MadelineProto
src/danog/MadelineProto/Stream/Common/HashedBufferedStream.php
HashedBufferedStream.bufferReadAsync
public function bufferReadAsync(int $length): \Generator { if ($this->read_check_after && $length + $this->read_check_pos >= $this->read_check_after) { if ($length + $this->read_check_pos > $this->read_check_after) { throw new \danog\MadelineProto\Exception('Tried to read too much out of frame data'); } $data = yield $this->read_buffer->bufferRead($length); hash_update($this->read_hash, $data); $hash = $this->getReadHash(); if ($hash !== yield $this->read_buffer->bufferRead(strlen($hash))) { throw new \danog\MadelineProto\Exception('Hash mismatch'); } return $data; } $data = yield $this->read_buffer->bufferRead($length); hash_update($this->read_hash, $data); if ($this->read_check_after) { $this->read_check_pos += $length; } return $data; }
php
public function bufferReadAsync(int $length): \Generator { if ($this->read_check_after && $length + $this->read_check_pos >= $this->read_check_after) { if ($length + $this->read_check_pos > $this->read_check_after) { throw new \danog\MadelineProto\Exception('Tried to read too much out of frame data'); } $data = yield $this->read_buffer->bufferRead($length); hash_update($this->read_hash, $data); $hash = $this->getReadHash(); if ($hash !== yield $this->read_buffer->bufferRead(strlen($hash))) { throw new \danog\MadelineProto\Exception('Hash mismatch'); } return $data; } $data = yield $this->read_buffer->bufferRead($length); hash_update($this->read_hash, $data); if ($this->read_check_after) { $this->read_check_pos += $length; } return $data; }
[ "public", "function", "bufferReadAsync", "(", "int", "$", "length", ")", ":", "\\", "Generator", "{", "if", "(", "$", "this", "->", "read_check_after", "&&", "$", "length", "+", "$", "this", "->", "read_check_pos", ">=", "$", "this", "->", "read_check_after", ")", "{", "if", "(", "$", "length", "+", "$", "this", "->", "read_check_pos", ">", "$", "this", "->", "read_check_after", ")", "{", "throw", "new", "\\", "danog", "\\", "MadelineProto", "\\", "Exception", "(", "'Tried to read too much out of frame data'", ")", ";", "}", "$", "data", "=", "yield", "$", "this", "->", "read_buffer", "->", "bufferRead", "(", "$", "length", ")", ";", "hash_update", "(", "$", "this", "->", "read_hash", ",", "$", "data", ")", ";", "$", "hash", "=", "$", "this", "->", "getReadHash", "(", ")", ";", "if", "(", "$", "hash", "!==", "yield", "$", "this", "->", "read_buffer", "->", "bufferRead", "(", "strlen", "(", "$", "hash", ")", ")", ")", "{", "throw", "new", "\\", "danog", "\\", "MadelineProto", "\\", "Exception", "(", "'Hash mismatch'", ")", ";", "}", "return", "$", "data", ";", "}", "$", "data", "=", "yield", "$", "this", "->", "read_buffer", "->", "bufferRead", "(", "$", "length", ")", ";", "hash_update", "(", "$", "this", "->", "read_hash", ",", "$", "data", ")", ";", "if", "(", "$", "this", "->", "read_check_after", ")", "{", "$", "this", "->", "read_check_pos", "+=", "$", "length", ";", "}", "return", "$", "data", ";", "}" ]
Hashes read data asynchronously. @param int $length Read and hash $length bytes @throws PendingReadError Thrown if another read operation is still pending. @return Generator That resolves with a string when the provided promise is resolved and the data is added to the hashing context
[ "Hashes", "read", "data", "asynchronously", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Stream/Common/HashedBufferedStream.php#L158-L180
train
danog/MadelineProto
src/danog/MadelineProto/Stream/Common/HashedBufferedStream.php
HashedBufferedStream.setExtra
public function setExtra($hash) { $rev = strpos($hash, '_rev'); $this->rev = false; if ($rev !== false) { $hash = substr($hash, 0, $rev); $this->rev = true; } $this->hash_name = $hash; }
php
public function setExtra($hash) { $rev = strpos($hash, '_rev'); $this->rev = false; if ($rev !== false) { $hash = substr($hash, 0, $rev); $this->rev = true; } $this->hash_name = $hash; }
[ "public", "function", "setExtra", "(", "$", "hash", ")", "{", "$", "rev", "=", "strpos", "(", "$", "hash", ",", "'_rev'", ")", ";", "$", "this", "->", "rev", "=", "false", ";", "if", "(", "$", "rev", "!==", "false", ")", "{", "$", "hash", "=", "substr", "(", "$", "hash", ",", "0", ",", "$", "rev", ")", ";", "$", "this", "->", "rev", "=", "true", ";", "}", "$", "this", "->", "hash_name", "=", "$", "hash", ";", "}" ]
Set the hash algorithm. @param string $hash Algorithm name @return void
[ "Set", "the", "hash", "algorithm", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Stream/Common/HashedBufferedStream.php#L189-L198
train
danog/MadelineProto
src/danog/MadelineProto/Stream/MTProtoTransport/FullStream.php
FullStream.connect
public function connect(ConnectionContext $ctx, string $header = ''): Promise { $this->in_seq_no = -1; $this->out_seq_no = -1; $this->stream = new HashedBufferedStream(); $this->stream->setExtra('crc32b_rev'); return $this->stream->connect($ctx, $header); }
php
public function connect(ConnectionContext $ctx, string $header = ''): Promise { $this->in_seq_no = -1; $this->out_seq_no = -1; $this->stream = new HashedBufferedStream(); $this->stream->setExtra('crc32b_rev'); return $this->stream->connect($ctx, $header); }
[ "public", "function", "connect", "(", "ConnectionContext", "$", "ctx", ",", "string", "$", "header", "=", "''", ")", ":", "Promise", "{", "$", "this", "->", "in_seq_no", "=", "-", "1", ";", "$", "this", "->", "out_seq_no", "=", "-", "1", ";", "$", "this", "->", "stream", "=", "new", "HashedBufferedStream", "(", ")", ";", "$", "this", "->", "stream", "->", "setExtra", "(", "'crc32b_rev'", ")", ";", "return", "$", "this", "->", "stream", "->", "connect", "(", "$", "ctx", ",", "$", "header", ")", ";", "}" ]
Stream to use as data source. @param ConnectionContext $ctx @return Promise
[ "Stream", "to", "use", "as", "data", "source", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Stream/MTProtoTransport/FullStream.php#L49-L57
train
danog/MadelineProto
src/danog/MadelineProto/Stream/Common/BufferedRawStream.php
BufferedRawStream.bufferWrite
public function bufferWrite(string $data): Promise { if ($this->append_after) { $this->append_after -= strlen($data); if ($this->append_after === 0) { $data .= $this->append; $this->append = ''; } elseif ($this->append_after < 0) { $this->append_after = 0; $this->append = ''; throw new Exception('Tried to send too much out of frame data, cannot append'); } } return $this->write($data); }
php
public function bufferWrite(string $data): Promise { if ($this->append_after) { $this->append_after -= strlen($data); if ($this->append_after === 0) { $data .= $this->append; $this->append = ''; } elseif ($this->append_after < 0) { $this->append_after = 0; $this->append = ''; throw new Exception('Tried to send too much out of frame data, cannot append'); } } return $this->write($data); }
[ "public", "function", "bufferWrite", "(", "string", "$", "data", ")", ":", "Promise", "{", "if", "(", "$", "this", "->", "append_after", ")", "{", "$", "this", "->", "append_after", "-=", "strlen", "(", "$", "data", ")", ";", "if", "(", "$", "this", "->", "append_after", "===", "0", ")", "{", "$", "data", ".=", "$", "this", "->", "append", ";", "$", "this", "->", "append", "=", "''", ";", "}", "elseif", "(", "$", "this", "->", "append_after", "<", "0", ")", "{", "$", "this", "->", "append_after", "=", "0", ";", "$", "this", "->", "append", "=", "''", ";", "throw", "new", "Exception", "(", "'Tried to send too much out of frame data, cannot append'", ")", ";", "}", "}", "return", "$", "this", "->", "write", "(", "$", "data", ")", ";", "}" ]
Async write. @param string $data Data to write @return Promise
[ "Async", "write", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Stream/Common/BufferedRawStream.php#L198-L214
train
danog/MadelineProto
src/danog/MadelineProto/Connection.php
Connection.connectAsync
public function connectAsync(ConnectionContext $ctx): \Generator { $this->API->logger->logger("Trying connection via $ctx", \danog\MadelineProto\Logger::WARNING); $this->ctx = $ctx->getCtx(); $this->datacenter = $ctx->getDc(); $this->stream = yield $ctx->getStream(); if (isset($this->old)) { unset($this->old); } if (!isset($this->writer)) { $this->writer = new WriteLoop($this->API, $this->datacenter); } if (!isset($this->reader)) { $this->reader = new ReadLoop($this->API, $this->datacenter); } if (!isset($this->checker)) { $this->checker = new CheckLoop($this->API, $this->datacenter); } if (!isset($this->waiter)) { $this->waiter = new HttpWaitLoop($this->API, $this->datacenter); } if (!isset($this->updater)) { $this->updater = new UpdateLoop($this->API, $this->datacenter); } foreach ($this->new_outgoing as $message_id) { if ($this->outgoing_messages[$message_id]['unencrypted']) { $promise = $this->outgoing_messages[$message_id]['promise']; \Amp\Loop::defer(function () use ($promise) { $promise->fail(new Exception('Restart')); }); unset($this->new_outgoing[$message_id]); unset($this->outgoing_messages[$message_id]); } } $this->http_req_count = 0; $this->http_res_count = 0; $this->writer->start(); $this->reader->start(); if (!$this->checker->start()) { $this->checker->resume(); } $this->waiter->start(); if ($this->datacenter === $this->API->settings['connection_settings']['default_dc']) { $this->updater->start(); } }
php
public function connectAsync(ConnectionContext $ctx): \Generator { $this->API->logger->logger("Trying connection via $ctx", \danog\MadelineProto\Logger::WARNING); $this->ctx = $ctx->getCtx(); $this->datacenter = $ctx->getDc(); $this->stream = yield $ctx->getStream(); if (isset($this->old)) { unset($this->old); } if (!isset($this->writer)) { $this->writer = new WriteLoop($this->API, $this->datacenter); } if (!isset($this->reader)) { $this->reader = new ReadLoop($this->API, $this->datacenter); } if (!isset($this->checker)) { $this->checker = new CheckLoop($this->API, $this->datacenter); } if (!isset($this->waiter)) { $this->waiter = new HttpWaitLoop($this->API, $this->datacenter); } if (!isset($this->updater)) { $this->updater = new UpdateLoop($this->API, $this->datacenter); } foreach ($this->new_outgoing as $message_id) { if ($this->outgoing_messages[$message_id]['unencrypted']) { $promise = $this->outgoing_messages[$message_id]['promise']; \Amp\Loop::defer(function () use ($promise) { $promise->fail(new Exception('Restart')); }); unset($this->new_outgoing[$message_id]); unset($this->outgoing_messages[$message_id]); } } $this->http_req_count = 0; $this->http_res_count = 0; $this->writer->start(); $this->reader->start(); if (!$this->checker->start()) { $this->checker->resume(); } $this->waiter->start(); if ($this->datacenter === $this->API->settings['connection_settings']['default_dc']) { $this->updater->start(); } }
[ "public", "function", "connectAsync", "(", "ConnectionContext", "$", "ctx", ")", ":", "\\", "Generator", "{", "$", "this", "->", "API", "->", "logger", "->", "logger", "(", "\"Trying connection via $ctx\"", ",", "\\", "danog", "\\", "MadelineProto", "\\", "Logger", "::", "WARNING", ")", ";", "$", "this", "->", "ctx", "=", "$", "ctx", "->", "getCtx", "(", ")", ";", "$", "this", "->", "datacenter", "=", "$", "ctx", "->", "getDc", "(", ")", ";", "$", "this", "->", "stream", "=", "yield", "$", "ctx", "->", "getStream", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "old", ")", ")", "{", "unset", "(", "$", "this", "->", "old", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "writer", ")", ")", "{", "$", "this", "->", "writer", "=", "new", "WriteLoop", "(", "$", "this", "->", "API", ",", "$", "this", "->", "datacenter", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "reader", ")", ")", "{", "$", "this", "->", "reader", "=", "new", "ReadLoop", "(", "$", "this", "->", "API", ",", "$", "this", "->", "datacenter", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "checker", ")", ")", "{", "$", "this", "->", "checker", "=", "new", "CheckLoop", "(", "$", "this", "->", "API", ",", "$", "this", "->", "datacenter", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "waiter", ")", ")", "{", "$", "this", "->", "waiter", "=", "new", "HttpWaitLoop", "(", "$", "this", "->", "API", ",", "$", "this", "->", "datacenter", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "updater", ")", ")", "{", "$", "this", "->", "updater", "=", "new", "UpdateLoop", "(", "$", "this", "->", "API", ",", "$", "this", "->", "datacenter", ")", ";", "}", "foreach", "(", "$", "this", "->", "new_outgoing", "as", "$", "message_id", ")", "{", "if", "(", "$", "this", "->", "outgoing_messages", "[", "$", "message_id", "]", "[", "'unencrypted'", "]", ")", "{", "$", "promise", "=", "$", "this", "->", "outgoing_messages", "[", "$", "message_id", "]", "[", "'promise'", "]", ";", "\\", "Amp", "\\", "Loop", "::", "defer", "(", "function", "(", ")", "use", "(", "$", "promise", ")", "{", "$", "promise", "->", "fail", "(", "new", "Exception", "(", "'Restart'", ")", ")", ";", "}", ")", ";", "unset", "(", "$", "this", "->", "new_outgoing", "[", "$", "message_id", "]", ")", ";", "unset", "(", "$", "this", "->", "outgoing_messages", "[", "$", "message_id", "]", ")", ";", "}", "}", "$", "this", "->", "http_req_count", "=", "0", ";", "$", "this", "->", "http_res_count", "=", "0", ";", "$", "this", "->", "writer", "->", "start", "(", ")", ";", "$", "this", "->", "reader", "->", "start", "(", ")", ";", "if", "(", "!", "$", "this", "->", "checker", "->", "start", "(", ")", ")", "{", "$", "this", "->", "checker", "->", "resume", "(", ")", ";", "}", "$", "this", "->", "waiter", "->", "start", "(", ")", ";", "if", "(", "$", "this", "->", "datacenter", "===", "$", "this", "->", "API", "->", "settings", "[", "'connection_settings'", "]", "[", "'default_dc'", "]", ")", "{", "$", "this", "->", "updater", "->", "start", "(", ")", ";", "}", "}" ]
Connect function. Connects to a telegram DC using the specified protocol, proxy and connection parameters @param string $proxy Proxy class name @internal @return \Amp\Promise
[ "Connect", "function", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Connection.php#L122-L171
train
danog/MadelineProto
src/danog/MadelineProto/Async/Parameters.php
Parameters.fetchParametersAsync
public function fetchParametersAsync(): \Generator { $refetchable = $this->isRefetchable(); if ($this->fetched && !$refetchable) { return $this->params; } $params = yield call([$this, 'getParameters']); if (!$refetchable) { $this->params = $params; } return $params; }
php
public function fetchParametersAsync(): \Generator { $refetchable = $this->isRefetchable(); if ($this->fetched && !$refetchable) { return $this->params; } $params = yield call([$this, 'getParameters']); if (!$refetchable) { $this->params = $params; } return $params; }
[ "public", "function", "fetchParametersAsync", "(", ")", ":", "\\", "Generator", "{", "$", "refetchable", "=", "$", "this", "->", "isRefetchable", "(", ")", ";", "if", "(", "$", "this", "->", "fetched", "&&", "!", "$", "refetchable", ")", "{", "return", "$", "this", "->", "params", ";", "}", "$", "params", "=", "yield", "call", "(", "[", "$", "this", ",", "'getParameters'", "]", ")", ";", "if", "(", "!", "$", "refetchable", ")", "{", "$", "this", "->", "params", "=", "$", "params", ";", "}", "return", "$", "params", ";", "}" ]
Fetch parameters asynchronously. @return \Generator
[ "Fetch", "parameters", "asynchronously", "." ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/Async/Parameters.php#L51-L64
train
danog/MadelineProto
src/danog/MadelineProto/MTProto.php
MTProto.connect_to_all_dcs_async
public function connect_to_all_dcs_async(): \Generator { $this->datacenter->__construct($this, $this->settings['connection'], $this->settings['connection_settings']); $dcs = []; foreach ($this->datacenter->get_dcs() as $new_dc) { $dcs[] = $this->datacenter->dc_connect_async($new_dc); } yield $dcs; yield $this->init_authorization_async(); $dcs = []; foreach ($this->datacenter->get_dcs(false) as $new_dc) { $dcs[] = $this->datacenter->dc_connect_async($new_dc); } yield $dcs; yield $this->init_authorization_async(); if (!$this->phoneConfigWatcherId) { $this->phoneConfigWatcherId = Loop::repeat(24 * 3600 * 1000, [$this, 'get_phone_config_async']); } yield $this->get_phone_config_async(); $this->logger->logger("Started phone config fetcher"); }
php
public function connect_to_all_dcs_async(): \Generator { $this->datacenter->__construct($this, $this->settings['connection'], $this->settings['connection_settings']); $dcs = []; foreach ($this->datacenter->get_dcs() as $new_dc) { $dcs[] = $this->datacenter->dc_connect_async($new_dc); } yield $dcs; yield $this->init_authorization_async(); $dcs = []; foreach ($this->datacenter->get_dcs(false) as $new_dc) { $dcs[] = $this->datacenter->dc_connect_async($new_dc); } yield $dcs; yield $this->init_authorization_async(); if (!$this->phoneConfigWatcherId) { $this->phoneConfigWatcherId = Loop::repeat(24 * 3600 * 1000, [$this, 'get_phone_config_async']); } yield $this->get_phone_config_async(); $this->logger->logger("Started phone config fetcher"); }
[ "public", "function", "connect_to_all_dcs_async", "(", ")", ":", "\\", "Generator", "{", "$", "this", "->", "datacenter", "->", "__construct", "(", "$", "this", ",", "$", "this", "->", "settings", "[", "'connection'", "]", ",", "$", "this", "->", "settings", "[", "'connection_settings'", "]", ")", ";", "$", "dcs", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "datacenter", "->", "get_dcs", "(", ")", "as", "$", "new_dc", ")", "{", "$", "dcs", "[", "]", "=", "$", "this", "->", "datacenter", "->", "dc_connect_async", "(", "$", "new_dc", ")", ";", "}", "yield", "$", "dcs", ";", "yield", "$", "this", "->", "init_authorization_async", "(", ")", ";", "$", "dcs", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "datacenter", "->", "get_dcs", "(", "false", ")", "as", "$", "new_dc", ")", "{", "$", "dcs", "[", "]", "=", "$", "this", "->", "datacenter", "->", "dc_connect_async", "(", "$", "new_dc", ")", ";", "}", "yield", "$", "dcs", ";", "yield", "$", "this", "->", "init_authorization_async", "(", ")", ";", "if", "(", "!", "$", "this", "->", "phoneConfigWatcherId", ")", "{", "$", "this", "->", "phoneConfigWatcherId", "=", "Loop", "::", "repeat", "(", "24", "*", "3600", "*", "1000", ",", "[", "$", "this", ",", "'get_phone_config_async'", "]", ")", ";", "}", "yield", "$", "this", "->", "get_phone_config_async", "(", ")", ";", "$", "this", "->", "logger", "->", "logger", "(", "\"Started phone config fetcher\"", ")", ";", "}" ]
Connects to all datacenters and if necessary creates authorization keys, binds them and writes client info
[ "Connects", "to", "all", "datacenters", "and", "if", "necessary", "creates", "authorization", "keys", "binds", "them", "and", "writes", "client", "info" ]
52fffa7a6817ccdedc8b3129e054554c6e141485
https://github.com/danog/MadelineProto/blob/52fffa7a6817ccdedc8b3129e054554c6e141485/src/danog/MadelineProto/MTProto.php#L828-L849
train
botman/botman
src/Messages/Conversations/Conversation.php
Conversation.repeat
public function repeat($question = '') { $conversation = $this->bot->getStoredConversation(); if (! $question instanceof Question && ! $question) { $question = unserialize($conversation['question']); } $next = $conversation['next']; $additionalParameters = unserialize($conversation['additionalParameters']); if (is_string($next)) { $next = unserialize($next)->getClosure(); } elseif (is_array($next)) { $next = Collection::make($next)->map(function ($callback) { if ($this->bot->getDriver()->serializesCallbacks() && ! $this->bot->runsOnSocket()) { $callback['callback'] = unserialize($callback['callback'])->getClosure(); } return $callback; })->toArray(); } $this->ask($question, $next, $additionalParameters); }
php
public function repeat($question = '') { $conversation = $this->bot->getStoredConversation(); if (! $question instanceof Question && ! $question) { $question = unserialize($conversation['question']); } $next = $conversation['next']; $additionalParameters = unserialize($conversation['additionalParameters']); if (is_string($next)) { $next = unserialize($next)->getClosure(); } elseif (is_array($next)) { $next = Collection::make($next)->map(function ($callback) { if ($this->bot->getDriver()->serializesCallbacks() && ! $this->bot->runsOnSocket()) { $callback['callback'] = unserialize($callback['callback'])->getClosure(); } return $callback; })->toArray(); } $this->ask($question, $next, $additionalParameters); }
[ "public", "function", "repeat", "(", "$", "question", "=", "''", ")", "{", "$", "conversation", "=", "$", "this", "->", "bot", "->", "getStoredConversation", "(", ")", ";", "if", "(", "!", "$", "question", "instanceof", "Question", "&&", "!", "$", "question", ")", "{", "$", "question", "=", "unserialize", "(", "$", "conversation", "[", "'question'", "]", ")", ";", "}", "$", "next", "=", "$", "conversation", "[", "'next'", "]", ";", "$", "additionalParameters", "=", "unserialize", "(", "$", "conversation", "[", "'additionalParameters'", "]", ")", ";", "if", "(", "is_string", "(", "$", "next", ")", ")", "{", "$", "next", "=", "unserialize", "(", "$", "next", ")", "->", "getClosure", "(", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "next", ")", ")", "{", "$", "next", "=", "Collection", "::", "make", "(", "$", "next", ")", "->", "map", "(", "function", "(", "$", "callback", ")", "{", "if", "(", "$", "this", "->", "bot", "->", "getDriver", "(", ")", "->", "serializesCallbacks", "(", ")", "&&", "!", "$", "this", "->", "bot", "->", "runsOnSocket", "(", ")", ")", "{", "$", "callback", "[", "'callback'", "]", "=", "unserialize", "(", "$", "callback", "[", "'callback'", "]", ")", "->", "getClosure", "(", ")", ";", "}", "return", "$", "callback", ";", "}", ")", "->", "toArray", "(", ")", ";", "}", "$", "this", "->", "ask", "(", "$", "question", ",", "$", "next", ",", "$", "additionalParameters", ")", ";", "}" ]
Repeat the previously asked question. @param string|Question $question
[ "Repeat", "the", "previously", "asked", "question", "." ]
ac9ecf78d25f8e5703125efb2be8b5898f67cd54
https://github.com/botman/botman/blob/ac9ecf78d25f8e5703125efb2be8b5898f67cd54/src/Messages/Conversations/Conversation.php#L156-L179
train
botman/botman
src/Drivers/DriverManager.php
DriverManager.loadFromName
public static function loadFromName($name, array $config, Request $request = null) { /* * Use the driver class basename without "Driver" if we're dealing with a * DriverInterface object. */ if (class_exists($name) && is_subclass_of($name, DriverInterface::class)) { $name = preg_replace('#(Driver$)#', '', basename(str_replace('\\', '/', $name))); } /* * Use the driver name constant if we try to load a driver by it's * fully qualified class name. */ if (class_exists($name) && is_subclass_of($name, HttpDriver::class)) { $name = $name::DRIVER_NAME; } if (is_null($request)) { $request = Request::createFromGlobals(); } foreach (self::getAvailableDrivers() as $driver) { /** @var HttpDriver $driver */ $driver = new $driver($request, $config, new Curl()); if ($driver->getName() === $name) { return $driver; } } return new NullDriver($request, [], new Curl()); }
php
public static function loadFromName($name, array $config, Request $request = null) { /* * Use the driver class basename without "Driver" if we're dealing with a * DriverInterface object. */ if (class_exists($name) && is_subclass_of($name, DriverInterface::class)) { $name = preg_replace('#(Driver$)#', '', basename(str_replace('\\', '/', $name))); } /* * Use the driver name constant if we try to load a driver by it's * fully qualified class name. */ if (class_exists($name) && is_subclass_of($name, HttpDriver::class)) { $name = $name::DRIVER_NAME; } if (is_null($request)) { $request = Request::createFromGlobals(); } foreach (self::getAvailableDrivers() as $driver) { /** @var HttpDriver $driver */ $driver = new $driver($request, $config, new Curl()); if ($driver->getName() === $name) { return $driver; } } return new NullDriver($request, [], new Curl()); }
[ "public", "static", "function", "loadFromName", "(", "$", "name", ",", "array", "$", "config", ",", "Request", "$", "request", "=", "null", ")", "{", "/*\n * Use the driver class basename without \"Driver\" if we're dealing with a\n * DriverInterface object.\n */", "if", "(", "class_exists", "(", "$", "name", ")", "&&", "is_subclass_of", "(", "$", "name", ",", "DriverInterface", "::", "class", ")", ")", "{", "$", "name", "=", "preg_replace", "(", "'#(Driver$)#'", ",", "''", ",", "basename", "(", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "$", "name", ")", ")", ")", ";", "}", "/*\n * Use the driver name constant if we try to load a driver by it's\n * fully qualified class name.\n */", "if", "(", "class_exists", "(", "$", "name", ")", "&&", "is_subclass_of", "(", "$", "name", ",", "HttpDriver", "::", "class", ")", ")", "{", "$", "name", "=", "$", "name", "::", "DRIVER_NAME", ";", "}", "if", "(", "is_null", "(", "$", "request", ")", ")", "{", "$", "request", "=", "Request", "::", "createFromGlobals", "(", ")", ";", "}", "foreach", "(", "self", "::", "getAvailableDrivers", "(", ")", "as", "$", "driver", ")", "{", "/** @var HttpDriver $driver */", "$", "driver", "=", "new", "$", "driver", "(", "$", "request", ",", "$", "config", ",", "new", "Curl", "(", ")", ")", ";", "if", "(", "$", "driver", "->", "getName", "(", ")", "===", "$", "name", ")", "{", "return", "$", "driver", ";", "}", "}", "return", "new", "NullDriver", "(", "$", "request", ",", "[", "]", ",", "new", "Curl", "(", ")", ")", ";", "}" ]
Load a driver by using its name. @param string $name @param array $config @param Request|null $request @return mixed|HttpDriver|NullDriver
[ "Load", "a", "driver", "by", "using", "its", "name", "." ]
ac9ecf78d25f8e5703125efb2be8b5898f67cd54
https://github.com/botman/botman/blob/ac9ecf78d25f8e5703125efb2be8b5898f67cd54/src/Drivers/DriverManager.php#L62-L90
train
botman/botman
src/Drivers/DriverManager.php
DriverManager.loadDriver
public static function loadDriver($driver, $explicit = false) { array_unshift(self::$drivers, $driver); if (method_exists($driver, 'loadExtension')) { call_user_func([$driver, 'loadExtension']); } if (method_exists($driver, 'additionalDrivers') && $explicit === false) { $additionalDrivers = (array) call_user_func([$driver, 'additionalDrivers']); foreach ($additionalDrivers as $additionalDriver) { self::loadDriver($additionalDriver); } } self::$drivers = array_unique(self::$drivers); }
php
public static function loadDriver($driver, $explicit = false) { array_unshift(self::$drivers, $driver); if (method_exists($driver, 'loadExtension')) { call_user_func([$driver, 'loadExtension']); } if (method_exists($driver, 'additionalDrivers') && $explicit === false) { $additionalDrivers = (array) call_user_func([$driver, 'additionalDrivers']); foreach ($additionalDrivers as $additionalDriver) { self::loadDriver($additionalDriver); } } self::$drivers = array_unique(self::$drivers); }
[ "public", "static", "function", "loadDriver", "(", "$", "driver", ",", "$", "explicit", "=", "false", ")", "{", "array_unshift", "(", "self", "::", "$", "drivers", ",", "$", "driver", ")", ";", "if", "(", "method_exists", "(", "$", "driver", ",", "'loadExtension'", ")", ")", "{", "call_user_func", "(", "[", "$", "driver", ",", "'loadExtension'", "]", ")", ";", "}", "if", "(", "method_exists", "(", "$", "driver", ",", "'additionalDrivers'", ")", "&&", "$", "explicit", "===", "false", ")", "{", "$", "additionalDrivers", "=", "(", "array", ")", "call_user_func", "(", "[", "$", "driver", ",", "'additionalDrivers'", "]", ")", ";", "foreach", "(", "$", "additionalDrivers", "as", "$", "additionalDriver", ")", "{", "self", "::", "loadDriver", "(", "$", "additionalDriver", ")", ";", "}", "}", "self", "::", "$", "drivers", "=", "array_unique", "(", "self", "::", "$", "drivers", ")", ";", "}" ]
Append a driver to the list of loadable drivers. @param string $driver Driver class name @param bool $explicit Only load this one driver and not any additional (sub)-drivers
[ "Append", "a", "driver", "to", "the", "list", "of", "loadable", "drivers", "." ]
ac9ecf78d25f8e5703125efb2be8b5898f67cd54
https://github.com/botman/botman/blob/ac9ecf78d25f8e5703125efb2be8b5898f67cd54/src/Drivers/DriverManager.php#L116-L131
train
botman/botman
src/Drivers/DriverManager.php
DriverManager.unloadDriver
public static function unloadDriver($driver) { foreach (array_keys(self::$drivers, $driver) as $key) { unset(self::$drivers[$key]); } }
php
public static function unloadDriver($driver) { foreach (array_keys(self::$drivers, $driver) as $key) { unset(self::$drivers[$key]); } }
[ "public", "static", "function", "unloadDriver", "(", "$", "driver", ")", "{", "foreach", "(", "array_keys", "(", "self", "::", "$", "drivers", ",", "$", "driver", ")", "as", "$", "key", ")", "{", "unset", "(", "self", "::", "$", "drivers", "[", "$", "key", "]", ")", ";", "}", "}" ]
Remove a driver from the list of loadable drivers. @param string $driver Driver class name
[ "Remove", "a", "driver", "from", "the", "list", "of", "loadable", "drivers", "." ]
ac9ecf78d25f8e5703125efb2be8b5898f67cd54
https://github.com/botman/botman/blob/ac9ecf78d25f8e5703125efb2be8b5898f67cd54/src/Drivers/DriverManager.php#L138-L143
train
botman/botman
src/Drivers/DriverManager.php
DriverManager.verifyServices
public static function verifyServices(array $config, Request $request = null) { $request = (isset($request)) ? $request : Request::createFromGlobals(); foreach (self::getAvailableHttpDrivers() as $driver) { $driver = new $driver($request, $config, new Curl()); if ($driver instanceof VerifiesService && ! is_null($driver->verifyRequest($request))) { return true; } } return false; }
php
public static function verifyServices(array $config, Request $request = null) { $request = (isset($request)) ? $request : Request::createFromGlobals(); foreach (self::getAvailableHttpDrivers() as $driver) { $driver = new $driver($request, $config, new Curl()); if ($driver instanceof VerifiesService && ! is_null($driver->verifyRequest($request))) { return true; } } return false; }
[ "public", "static", "function", "verifyServices", "(", "array", "$", "config", ",", "Request", "$", "request", "=", "null", ")", "{", "$", "request", "=", "(", "isset", "(", "$", "request", ")", ")", "?", "$", "request", ":", "Request", "::", "createFromGlobals", "(", ")", ";", "foreach", "(", "self", "::", "getAvailableHttpDrivers", "(", ")", "as", "$", "driver", ")", "{", "$", "driver", "=", "new", "$", "driver", "(", "$", "request", ",", "$", "config", ",", "new", "Curl", "(", ")", ")", ";", "if", "(", "$", "driver", "instanceof", "VerifiesService", "&&", "!", "is_null", "(", "$", "driver", "->", "verifyRequest", "(", "$", "request", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Verify service webhook URLs. @param array $config @param Request|null $request @return bool
[ "Verify", "service", "webhook", "URLs", "." ]
ac9ecf78d25f8e5703125efb2be8b5898f67cd54
https://github.com/botman/botman/blob/ac9ecf78d25f8e5703125efb2be8b5898f67cd54/src/Drivers/DriverManager.php#L152-L163
train
botman/botman
src/Middleware/ApiAi.php
ApiAi.getResponse
protected function getResponse(IncomingMessage $message) { $response = $this->http->post($this->apiUrl, [], [ 'query' => [$message->getText()], 'sessionId' => md5($message->getConversationIdentifier()), 'lang' => $this->lang, ], [ 'Authorization: Bearer '.$this->token, 'Content-Type: application/json; charset=utf-8', ], true); $this->response = json_decode($response->getContent()); return $this->response; }
php
protected function getResponse(IncomingMessage $message) { $response = $this->http->post($this->apiUrl, [], [ 'query' => [$message->getText()], 'sessionId' => md5($message->getConversationIdentifier()), 'lang' => $this->lang, ], [ 'Authorization: Bearer '.$this->token, 'Content-Type: application/json; charset=utf-8', ], true); $this->response = json_decode($response->getContent()); return $this->response; }
[ "protected", "function", "getResponse", "(", "IncomingMessage", "$", "message", ")", "{", "$", "response", "=", "$", "this", "->", "http", "->", "post", "(", "$", "this", "->", "apiUrl", ",", "[", "]", ",", "[", "'query'", "=>", "[", "$", "message", "->", "getText", "(", ")", "]", ",", "'sessionId'", "=>", "md5", "(", "$", "message", "->", "getConversationIdentifier", "(", ")", ")", ",", "'lang'", "=>", "$", "this", "->", "lang", ",", "]", ",", "[", "'Authorization: Bearer '", ".", "$", "this", "->", "token", ",", "'Content-Type: application/json; charset=utf-8'", ",", "]", ",", "true", ")", ";", "$", "this", "->", "response", "=", "json_decode", "(", "$", "response", "->", "getContent", "(", ")", ")", ";", "return", "$", "this", "->", "response", ";", "}" ]
Perform the API.ai API call and cache it for the message. @param \BotMan\BotMan\Messages\Incoming\IncomingMessage $message @return \stdClass
[ "Perform", "the", "API", ".", "ai", "API", "call", "and", "cache", "it", "for", "the", "message", "." ]
ac9ecf78d25f8e5703125efb2be8b5898f67cd54
https://github.com/botman/botman/blob/ac9ecf78d25f8e5703125efb2be8b5898f67cd54/src/Middleware/ApiAi.php#L75-L89
train
botman/botman
src/BotManFactory.php
BotManFactory.createForSocket
public static function createForSocket( array $config, LoopInterface $loop, CacheInterface $cache = null, StorageInterface $storageDriver = null ) { $port = isset($config['port']) ? $config['port'] : 8080; $socket = new Server($loop); if (empty($cache)) { $cache = new ArrayCache(); } if (empty($storageDriver)) { $storageDriver = new FileStorage(__DIR__); } $driverManager = new DriverManager($config, new Curl()); $botman = new BotMan($cache, DriverManager::loadFromName('Null', $config), $config, $storageDriver); $botman->runsOnSocket(true); $socket->on('connection', function ($conn) use ($botman, $driverManager) { $conn->on('data', function ($data) use ($botman, $driverManager) { $requestData = json_decode($data, true); $request = new Request($requestData['query'], $requestData['request'], $requestData['attributes'], [], [], [], $requestData['content']); $driver = $driverManager->getMatchingDriver($request); $botman->setDriver($driver); $botman->listen(); }); }); $socket->listen($port); return $botman; }
php
public static function createForSocket( array $config, LoopInterface $loop, CacheInterface $cache = null, StorageInterface $storageDriver = null ) { $port = isset($config['port']) ? $config['port'] : 8080; $socket = new Server($loop); if (empty($cache)) { $cache = new ArrayCache(); } if (empty($storageDriver)) { $storageDriver = new FileStorage(__DIR__); } $driverManager = new DriverManager($config, new Curl()); $botman = new BotMan($cache, DriverManager::loadFromName('Null', $config), $config, $storageDriver); $botman->runsOnSocket(true); $socket->on('connection', function ($conn) use ($botman, $driverManager) { $conn->on('data', function ($data) use ($botman, $driverManager) { $requestData = json_decode($data, true); $request = new Request($requestData['query'], $requestData['request'], $requestData['attributes'], [], [], [], $requestData['content']); $driver = $driverManager->getMatchingDriver($request); $botman->setDriver($driver); $botman->listen(); }); }); $socket->listen($port); return $botman; }
[ "public", "static", "function", "createForSocket", "(", "array", "$", "config", ",", "LoopInterface", "$", "loop", ",", "CacheInterface", "$", "cache", "=", "null", ",", "StorageInterface", "$", "storageDriver", "=", "null", ")", "{", "$", "port", "=", "isset", "(", "$", "config", "[", "'port'", "]", ")", "?", "$", "config", "[", "'port'", "]", ":", "8080", ";", "$", "socket", "=", "new", "Server", "(", "$", "loop", ")", ";", "if", "(", "empty", "(", "$", "cache", ")", ")", "{", "$", "cache", "=", "new", "ArrayCache", "(", ")", ";", "}", "if", "(", "empty", "(", "$", "storageDriver", ")", ")", "{", "$", "storageDriver", "=", "new", "FileStorage", "(", "__DIR__", ")", ";", "}", "$", "driverManager", "=", "new", "DriverManager", "(", "$", "config", ",", "new", "Curl", "(", ")", ")", ";", "$", "botman", "=", "new", "BotMan", "(", "$", "cache", ",", "DriverManager", "::", "loadFromName", "(", "'Null'", ",", "$", "config", ")", ",", "$", "config", ",", "$", "storageDriver", ")", ";", "$", "botman", "->", "runsOnSocket", "(", "true", ")", ";", "$", "socket", "->", "on", "(", "'connection'", ",", "function", "(", "$", "conn", ")", "use", "(", "$", "botman", ",", "$", "driverManager", ")", "{", "$", "conn", "->", "on", "(", "'data'", ",", "function", "(", "$", "data", ")", "use", "(", "$", "botman", ",", "$", "driverManager", ")", "{", "$", "requestData", "=", "json_decode", "(", "$", "data", ",", "true", ")", ";", "$", "request", "=", "new", "Request", "(", "$", "requestData", "[", "'query'", "]", ",", "$", "requestData", "[", "'request'", "]", ",", "$", "requestData", "[", "'attributes'", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", ",", "$", "requestData", "[", "'content'", "]", ")", ";", "$", "driver", "=", "$", "driverManager", "->", "getMatchingDriver", "(", "$", "request", ")", ";", "$", "botman", "->", "setDriver", "(", "$", "driver", ")", ";", "$", "botman", "->", "listen", "(", ")", ";", "}", ")", ";", "}", ")", ";", "$", "socket", "->", "listen", "(", "$", "port", ")", ";", "return", "$", "botman", ";", "}" ]
Create a new BotMan instance that listens on a socket. @param array $config @param LoopInterface $loop @param CacheInterface $cache @param StorageInterface $storageDriver @return \BotMan\BotMan\BotMan
[ "Create", "a", "new", "BotMan", "instance", "that", "listens", "on", "a", "socket", "." ]
ac9ecf78d25f8e5703125efb2be8b5898f67cd54
https://github.com/botman/botman/blob/ac9ecf78d25f8e5703125efb2be8b5898f67cd54/src/BotManFactory.php#L82-L117
train
botman/botman
src/BotManFactory.php
BotManFactory.passRequestToSocket
public static function passRequestToSocket($port = 8080, Request $request = null) { if (empty($request)) { $request = Request::createFromGlobals(); } $client = stream_socket_client('tcp://127.0.0.1:'.$port); fwrite($client, json_encode([ 'attributes' => $request->attributes->all(), 'query' => $request->query->all(), 'request' => $request->request->all(), 'content' => $request->getContent(), ])); fclose($client); }
php
public static function passRequestToSocket($port = 8080, Request $request = null) { if (empty($request)) { $request = Request::createFromGlobals(); } $client = stream_socket_client('tcp://127.0.0.1:'.$port); fwrite($client, json_encode([ 'attributes' => $request->attributes->all(), 'query' => $request->query->all(), 'request' => $request->request->all(), 'content' => $request->getContent(), ])); fclose($client); }
[ "public", "static", "function", "passRequestToSocket", "(", "$", "port", "=", "8080", ",", "Request", "$", "request", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "request", ")", ")", "{", "$", "request", "=", "Request", "::", "createFromGlobals", "(", ")", ";", "}", "$", "client", "=", "stream_socket_client", "(", "'tcp://127.0.0.1:'", ".", "$", "port", ")", ";", "fwrite", "(", "$", "client", ",", "json_encode", "(", "[", "'attributes'", "=>", "$", "request", "->", "attributes", "->", "all", "(", ")", ",", "'query'", "=>", "$", "request", "->", "query", "->", "all", "(", ")", ",", "'request'", "=>", "$", "request", "->", "request", "->", "all", "(", ")", ",", "'content'", "=>", "$", "request", "->", "getContent", "(", ")", ",", "]", ")", ")", ";", "fclose", "(", "$", "client", ")", ";", "}" ]
Pass an incoming HTTP request to the socket. @param int $port The port to use. Default is 8080 @param Request|null $request @return void
[ "Pass", "an", "incoming", "HTTP", "request", "to", "the", "socket", "." ]
ac9ecf78d25f8e5703125efb2be8b5898f67cd54
https://github.com/botman/botman/blob/ac9ecf78d25f8e5703125efb2be8b5898f67cd54/src/BotManFactory.php#L126-L140
train
botman/botman
src/BotMan.php
BotMan.getBotMessages
public function getBotMessages() { return Collection::make($this->getDriver()->getMessages())->filter(function (IncomingMessage $message) { return $message->isFromBot(); })->toArray(); }
php
public function getBotMessages() { return Collection::make($this->getDriver()->getMessages())->filter(function (IncomingMessage $message) { return $message->isFromBot(); })->toArray(); }
[ "public", "function", "getBotMessages", "(", ")", "{", "return", "Collection", "::", "make", "(", "$", "this", "->", "getDriver", "(", ")", "->", "getMessages", "(", ")", ")", "->", "filter", "(", "function", "(", "IncomingMessage", "$", "message", ")", "{", "return", "$", "message", "->", "isFromBot", "(", ")", ";", "}", ")", "->", "toArray", "(", ")", ";", "}" ]
Retrieve the chat message that are sent from bots. @return array
[ "Retrieve", "the", "chat", "message", "that", "are", "sent", "from", "bots", "." ]
ac9ecf78d25f8e5703125efb2be8b5898f67cd54
https://github.com/botman/botman/blob/ac9ecf78d25f8e5703125efb2be8b5898f67cd54/src/BotMan.php#L200-L205
train
botman/botman
src/BotMan.php
BotMan.on
public function on($names, $callback) { if (! is_array($names)) { $names = [$names]; } $callable = $this->getCallable($callback); foreach ($names as $name) { $this->events[] = [ 'name' => $name, 'callback' => $callable, ]; } }
php
public function on($names, $callback) { if (! is_array($names)) { $names = [$names]; } $callable = $this->getCallable($callback); foreach ($names as $name) { $this->events[] = [ 'name' => $name, 'callback' => $callable, ]; } }
[ "public", "function", "on", "(", "$", "names", ",", "$", "callback", ")", "{", "if", "(", "!", "is_array", "(", "$", "names", ")", ")", "{", "$", "names", "=", "[", "$", "names", "]", ";", "}", "$", "callable", "=", "$", "this", "->", "getCallable", "(", "$", "callback", ")", ";", "foreach", "(", "$", "names", "as", "$", "name", ")", "{", "$", "this", "->", "events", "[", "]", "=", "[", "'name'", "=>", "$", "name", ",", "'callback'", "=>", "$", "callable", ",", "]", ";", "}", "}" ]
Listen for messaging service events. @param array|string $names @param Closure|string $callback
[ "Listen", "for", "messaging", "service", "events", "." ]
ac9ecf78d25f8e5703125efb2be8b5898f67cd54
https://github.com/botman/botman/blob/ac9ecf78d25f8e5703125efb2be8b5898f67cd54/src/BotMan.php#L281-L295
train
botman/botman
src/BotMan.php
BotMan.group
public function group(array $attributes, Closure $callback) { $previousGroupAttributes = $this->groupAttributes; $this->groupAttributes = array_merge_recursive($previousGroupAttributes, $attributes); \call_user_func($callback, $this); $this->groupAttributes = $previousGroupAttributes; }
php
public function group(array $attributes, Closure $callback) { $previousGroupAttributes = $this->groupAttributes; $this->groupAttributes = array_merge_recursive($previousGroupAttributes, $attributes); \call_user_func($callback, $this); $this->groupAttributes = $previousGroupAttributes; }
[ "public", "function", "group", "(", "array", "$", "attributes", ",", "Closure", "$", "callback", ")", "{", "$", "previousGroupAttributes", "=", "$", "this", "->", "groupAttributes", ";", "$", "this", "->", "groupAttributes", "=", "array_merge_recursive", "(", "$", "previousGroupAttributes", ",", "$", "attributes", ")", ";", "\\", "call_user_func", "(", "$", "callback", ",", "$", "this", ")", ";", "$", "this", "->", "groupAttributes", "=", "$", "previousGroupAttributes", ";", "}" ]
Create a command group with shared attributes. @param array $attributes @param \Closure $callback
[ "Create", "a", "command", "group", "with", "shared", "attributes", "." ]
ac9ecf78d25f8e5703125efb2be8b5898f67cd54
https://github.com/botman/botman/blob/ac9ecf78d25f8e5703125efb2be8b5898f67cd54/src/BotMan.php#L370-L378
train
botman/botman
src/BotMan.php
BotMan.fireDriverEvents
protected function fireDriverEvents() { $driverEvent = $this->getDriver()->hasMatchingEvent(); if ($driverEvent instanceof DriverEventInterface) { $this->firedDriverEvents = true; Collection::make($this->events)->filter(function ($event) use ($driverEvent) { return $driverEvent->getName() === $event['name']; })->each(function ($event) use ($driverEvent) { /** * Load the message, so driver events can reply. */ $messages = $this->getDriver()->getMessages(); if (isset($messages[0])) { $this->message = $messages[0]; } \call_user_func_array($event['callback'], [$driverEvent->getPayload(), $this]); }); } }
php
protected function fireDriverEvents() { $driverEvent = $this->getDriver()->hasMatchingEvent(); if ($driverEvent instanceof DriverEventInterface) { $this->firedDriverEvents = true; Collection::make($this->events)->filter(function ($event) use ($driverEvent) { return $driverEvent->getName() === $event['name']; })->each(function ($event) use ($driverEvent) { /** * Load the message, so driver events can reply. */ $messages = $this->getDriver()->getMessages(); if (isset($messages[0])) { $this->message = $messages[0]; } \call_user_func_array($event['callback'], [$driverEvent->getPayload(), $this]); }); } }
[ "protected", "function", "fireDriverEvents", "(", ")", "{", "$", "driverEvent", "=", "$", "this", "->", "getDriver", "(", ")", "->", "hasMatchingEvent", "(", ")", ";", "if", "(", "$", "driverEvent", "instanceof", "DriverEventInterface", ")", "{", "$", "this", "->", "firedDriverEvents", "=", "true", ";", "Collection", "::", "make", "(", "$", "this", "->", "events", ")", "->", "filter", "(", "function", "(", "$", "event", ")", "use", "(", "$", "driverEvent", ")", "{", "return", "$", "driverEvent", "->", "getName", "(", ")", "===", "$", "event", "[", "'name'", "]", ";", "}", ")", "->", "each", "(", "function", "(", "$", "event", ")", "use", "(", "$", "driverEvent", ")", "{", "/**\n * Load the message, so driver events can reply.\n */", "$", "messages", "=", "$", "this", "->", "getDriver", "(", ")", "->", "getMessages", "(", ")", ";", "if", "(", "isset", "(", "$", "messages", "[", "0", "]", ")", ")", "{", "$", "this", "->", "message", "=", "$", "messages", "[", "0", "]", ";", "}", "\\", "call_user_func_array", "(", "$", "event", "[", "'callback'", "]", ",", "[", "$", "driverEvent", "->", "getPayload", "(", ")", ",", "$", "this", "]", ")", ";", "}", ")", ";", "}", "}" ]
Fire potential driver event callbacks.
[ "Fire", "potential", "driver", "event", "callbacks", "." ]
ac9ecf78d25f8e5703125efb2be8b5898f67cd54
https://github.com/botman/botman/blob/ac9ecf78d25f8e5703125efb2be8b5898f67cd54/src/BotMan.php#L383-L403
train