repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
nezamy/route
system/Route.php
Route.matched
protected function matched($patt, $call = true) { if (preg_match($patt, $this->req->path, $m)) { if ($call) { $this->matched = true; } array_shift($m); $this->matchedArgs = array_map([$this, 'trimSlash'], $m); return true; } return false; }
php
protected function matched($patt, $call = true) { if (preg_match($patt, $this->req->path, $m)) { if ($call) { $this->matched = true; } array_shift($m); $this->matchedArgs = array_map([$this, 'trimSlash'], $m); return true; } return false; }
[ "protected", "function", "matched", "(", "$", "patt", ",", "$", "call", "=", "true", ")", "{", "if", "(", "preg_match", "(", "$", "patt", ",", "$", "this", "->", "req", "->", "path", ",", "$", "m", ")", ")", "{", "if", "(", "$", "call", ")", ...
Checks whether the current route matches the specified pattern. @param string $patt @param bool $call @return bool
[ "Checks", "whether", "the", "current", "route", "matches", "the", "specified", "pattern", "." ]
train
https://github.com/nezamy/route/blob/de0d5133530117b6999e6e0955138dc3bd3c66b5/system/Route.php#L373-L384
nezamy/route
system/Route.php
Route._as
public function _as($name) { if (empty($name)) return $this; $name = rtrim($this->getGroupAs() . str_replace('/', '.', strtolower($name)), '.'); // if (array_key_exists($name, $this->routes)) { // throw new \Exception("Route name ($name) already registered."); // } $patt = $this->patt; $pram = $this->prams; // Merge group parameters with route parameters. if ($this->isGroup) { $patt = array_merge($this->pattGroup, $patt); if (count($patt) > count($pram)) { $pram = array_merge($this->pramsGroup, $pram); } } // :param if (count($pram)) { foreach ($pram as $k => $v) { $pram[$k] = '/:' . $v; } } // Replace pattern to named parameters. $replaced = $this->group . $this->currentUri; foreach ($patt as $k => $v) { $pos = strpos($replaced, $v); if ($pos !== false) { $replaced = substr_replace($replaced, $pram[$k], $pos, strlen($v)); } } $this->routes[$name] = ltrim($this->removeDuplSlash(strtolower($replaced)), '/'); return $this; }
php
public function _as($name) { if (empty($name)) return $this; $name = rtrim($this->getGroupAs() . str_replace('/', '.', strtolower($name)), '.'); // if (array_key_exists($name, $this->routes)) { // throw new \Exception("Route name ($name) already registered."); // } $patt = $this->patt; $pram = $this->prams; // Merge group parameters with route parameters. if ($this->isGroup) { $patt = array_merge($this->pattGroup, $patt); if (count($patt) > count($pram)) { $pram = array_merge($this->pramsGroup, $pram); } } // :param if (count($pram)) { foreach ($pram as $k => $v) { $pram[$k] = '/:' . $v; } } // Replace pattern to named parameters. $replaced = $this->group . $this->currentUri; foreach ($patt as $k => $v) { $pos = strpos($replaced, $v); if ($pos !== false) { $replaced = substr_replace($replaced, $pram[$k], $pos, strlen($v)); } } $this->routes[$name] = ltrim($this->removeDuplSlash(strtolower($replaced)), '/'); return $this; }
[ "public", "function", "_as", "(", "$", "name", ")", "{", "if", "(", "empty", "(", "$", "name", ")", ")", "return", "$", "this", ";", "$", "name", "=", "rtrim", "(", "$", "this", "->", "getGroupAs", "(", ")", ".", "str_replace", "(", "'/'", ",", ...
Set a route name. @param string $name @return $this @throws \Exception
[ "Set", "a", "route", "name", "." ]
train
https://github.com/nezamy/route/blob/de0d5133530117b6999e6e0955138dc3bd3c66b5/system/Route.php#L427-L464
nezamy/route
system/Route.php
Route.getRoute
public function getRoute($name, array $args = []) { $name = strtolower($name); if (isset($this->routes[$name])) { $route = $this->routes[$name]; foreach ($args as $k => $v) { $route = str_replace(':' . $k, $v, $route); } return $route; } return null; }
php
public function getRoute($name, array $args = []) { $name = strtolower($name); if (isset($this->routes[$name])) { $route = $this->routes[$name]; foreach ($args as $k => $v) { $route = str_replace(':' . $k, $v, $route); } return $route; } return null; }
[ "public", "function", "getRoute", "(", "$", "name", ",", "array", "$", "args", "=", "[", "]", ")", "{", "$", "name", "=", "strtolower", "(", "$", "name", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "routes", "[", "$", "name", "]", ")"...
Register a new listener into the specified event. @param string $name @param array $args @return string|null
[ "Register", "a", "new", "listener", "into", "the", "specified", "event", "." ]
train
https://github.com/nezamy/route/blob/de0d5133530117b6999e6e0955138dc3bd3c66b5/system/Route.php#L511-L524
nezamy/route
system/Route.php
Route.end
public function end() { ob_start(); if ($this->matched && count($this->routeCallback)) { count($this->before) && $this->emit($this->before); foreach ($this->routeCallback as $call) { $this->callback($call, $this->req->args); } count($this->after) && $this->emit($this->after); } else if($this->req->method != 'OPTIONS'){ http_response_code(404); print('<h1>404 Not Found</h1>'); } if (ob_get_length()) { ob_end_flush(); } exit; }
php
public function end() { ob_start(); if ($this->matched && count($this->routeCallback)) { count($this->before) && $this->emit($this->before); foreach ($this->routeCallback as $call) { $this->callback($call, $this->req->args); } count($this->after) && $this->emit($this->after); } else if($this->req->method != 'OPTIONS'){ http_response_code(404); print('<h1>404 Not Found</h1>'); } if (ob_get_length()) { ob_end_flush(); } exit; }
[ "public", "function", "end", "(", ")", "{", "ob_start", "(", ")", ";", "if", "(", "$", "this", "->", "matched", "&&", "count", "(", "$", "this", "->", "routeCallback", ")", ")", "{", "count", "(", "$", "this", "->", "before", ")", "&&", "$", "thi...
Run and get a response.
[ "Run", "and", "get", "a", "response", "." ]
train
https://github.com/nezamy/route/blob/de0d5133530117b6999e6e0955138dc3bd3c66b5/system/Route.php#L594-L612
nezamy/route
system/Route.php
Route.callback
protected function callback($callback, array $args = []) { if (isset($callback)) { if (is_callable($callback) && $callback instanceof \Closure) { // Set new object and append the callback with some data. $o = new \ArrayObject($args); $o->app = App::instance(); $callback = $callback->bindTo($o); } elseif (is_string($callback) && strpos($callback, '@') !== false) { $fixcallback = explode('@', $callback, 2); $this->Controller = $fixcallback[0]; if (is_callable( $callback = [$fixcallback[0], (isset($fixcallback[1]) ? $fixcallback[1] : 'index')] )) { $this->Method = $callback[1]; } else { throw new \Exception("Callable error on {$callback[0]} -> {$callback[1]} !"); } } if (is_array($callback) && !is_object($callback[0])) { $callback[0] = new $callback[0]; } if (isset($args[0]) && $args[0] == $this->fullArg) { array_shift($args); } // Finally, call the method. return call_user_func_array($callback, $args); } return false; }
php
protected function callback($callback, array $args = []) { if (isset($callback)) { if (is_callable($callback) && $callback instanceof \Closure) { // Set new object and append the callback with some data. $o = new \ArrayObject($args); $o->app = App::instance(); $callback = $callback->bindTo($o); } elseif (is_string($callback) && strpos($callback, '@') !== false) { $fixcallback = explode('@', $callback, 2); $this->Controller = $fixcallback[0]; if (is_callable( $callback = [$fixcallback[0], (isset($fixcallback[1]) ? $fixcallback[1] : 'index')] )) { $this->Method = $callback[1]; } else { throw new \Exception("Callable error on {$callback[0]} -> {$callback[1]} !"); } } if (is_array($callback) && !is_object($callback[0])) { $callback[0] = new $callback[0]; } if (isset($args[0]) && $args[0] == $this->fullArg) { array_shift($args); } // Finally, call the method. return call_user_func_array($callback, $args); } return false; }
[ "protected", "function", "callback", "(", "$", "callback", ",", "array", "$", "args", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "$", "callback", ")", ")", "{", "if", "(", "is_callable", "(", "$", "callback", ")", "&&", "$", "callback", "ins...
Call a route that has been matched. @param mixed $callback @param array $args @return string @throws \Exception
[ "Call", "a", "route", "that", "has", "been", "matched", "." ]
train
https://github.com/nezamy/route/blob/de0d5133530117b6999e6e0955138dc3bd3c66b5/system/Route.php#L622-L655
unsplash/unsplash-php
src/Collection.php
Collection.all
public static function all($page = 1, $per_page = 10) { $collections = self::get( "/collections", ['query' => ['page' => $page, 'per_page' => $per_page]] ); $collectionsArray = self::getArray($collections->getBody(), get_called_class()); return new ArrayObject($collectionsArray, $collections->getHeaders()); }
php
public static function all($page = 1, $per_page = 10) { $collections = self::get( "/collections", ['query' => ['page' => $page, 'per_page' => $per_page]] ); $collectionsArray = self::getArray($collections->getBody(), get_called_class()); return new ArrayObject($collectionsArray, $collections->getHeaders()); }
[ "public", "static", "function", "all", "(", "$", "page", "=", "1", ",", "$", "per_page", "=", "10", ")", "{", "$", "collections", "=", "self", "::", "get", "(", "\"/collections\"", ",", "[", "'query'", "=>", "[", "'page'", "=>", "$", "page", ",", "...
Retrieve all collections for a given page @param integer $page Page from which the collections need to be retrieved @param integer $per_page Number of elements on a page @return ArrayObject of Collections
[ "Retrieve", "all", "collections", "for", "a", "given", "page" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Collection.php#L21-L31
unsplash/unsplash-php
src/Collection.php
Collection.find
public static function find($id) { $collection = json_decode(self::get("/collections/{$id}")->getBody(), true); return new self($collection); }
php
public static function find($id) { $collection = json_decode(self::get("/collections/{$id}")->getBody(), true); return new self($collection); }
[ "public", "static", "function", "find", "(", "$", "id", ")", "{", "$", "collection", "=", "json_decode", "(", "self", "::", "get", "(", "\"/collections/{$id}\"", ")", "->", "getBody", "(", ")", ",", "true", ")", ";", "return", "new", "self", "(", "$", ...
Retrieve a specific collection @param int $id Id of the collection @return Collection
[ "Retrieve", "a", "specific", "collection" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Collection.php#L39-L44
unsplash/unsplash-php
src/Collection.php
Collection.add
public function add($photo_id) { $photo_and_collection = json_decode( self::post( "/collections/{$this->id}/add", ['query' => ['photo_id' => $photo_id]] )->getBody(), true ); # Reset $this->photos = []; }
php
public function add($photo_id) { $photo_and_collection = json_decode( self::post( "/collections/{$this->id}/add", ['query' => ['photo_id' => $photo_id]] )->getBody(), true ); # Reset $this->photos = []; }
[ "public", "function", "add", "(", "$", "photo_id", ")", "{", "$", "photo_and_collection", "=", "json_decode", "(", "self", "::", "post", "(", "\"/collections/{$this->id}/add\"", ",", "[", "'query'", "=>", "[", "'photo_id'", "=>", "$", "photo_id", "]", "]", "...
Add a photo in user's collection @param int $photo_id photo id from photo to add @return array [photo, collection]
[ "Add", "a", "photo", "in", "user", "s", "collection" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Collection.php#L87-L99
unsplash/unsplash-php
src/Collection.php
Collection.create
public static function create($title, $description = '', $private = false) { $collection = json_decode( self::post( "/collections", [ 'query' => [ 'title' => $title, 'description' => $description, 'private' => $private ] ] )->getBody(), true ); return new self($collection); }
php
public static function create($title, $description = '', $private = false) { $collection = json_decode( self::post( "/collections", [ 'query' => [ 'title' => $title, 'description' => $description, 'private' => $private ] ] )->getBody(), true ); return new self($collection); }
[ "public", "static", "function", "create", "(", "$", "title", ",", "$", "description", "=", "''", ",", "$", "private", "=", "false", ")", "{", "$", "collection", "=", "json_decode", "(", "self", "::", "post", "(", "\"/collections\"", ",", "[", "'query'", ...
Create a new collection. The user needs to connect their account and authorize the write_collections permission scope. @param string $title Collection's title @param string $description Collection's description @param boolean $private Whether to make this collection private @return Photo
[ "Create", "a", "new", "collection", ".", "The", "user", "needs", "to", "connect", "their", "account", "and", "authorize", "the", "write_collections", "permission", "scope", "." ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Collection.php#L126-L142
unsplash/unsplash-php
src/Collection.php
Collection.related
public function related() { $collections = self::get("/collections/{$this->id}/related"); $collectionsArray = self::getArray($collections->getBody(), get_called_class()); return new ArrayObject($collectionsArray, $collections->getHeaders()); }
php
public function related() { $collections = self::get("/collections/{$this->id}/related"); $collectionsArray = self::getArray($collections->getBody(), get_called_class()); return new ArrayObject($collectionsArray, $collections->getHeaders()); }
[ "public", "function", "related", "(", ")", "{", "$", "collections", "=", "self", "::", "get", "(", "\"/collections/{$this->id}/related\"", ")", ";", "$", "collectionsArray", "=", "self", "::", "getArray", "(", "$", "collections", "->", "getBody", "(", ")", "...
Get related collections to current collection @return ArrayObject
[ "Get", "related", "collections", "to", "current", "collection" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Collection.php#L180-L185
unsplash/unsplash-php
src/Category.php
Category.find
public static function find($id) { $category = json_decode(self::get("/categories/{$id}")->getBody(), true); return new self($category); }
php
public static function find($id) { $category = json_decode(self::get("/categories/{$id}")->getBody(), true); return new self($category); }
[ "public", "static", "function", "find", "(", "$", "id", ")", "{", "$", "category", "=", "json_decode", "(", "self", "::", "get", "(", "\"/categories/{$id}\"", ")", "->", "getBody", "(", ")", ",", "true", ")", ";", "return", "new", "self", "(", "$", "...
Retrieve the a Category object from the id specified @param integer $id Id of the category to find @return Category @deprecated @see Collection::find()
[ "Retrieve", "the", "a", "Category", "object", "from", "the", "id", "specified" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Category.php#L24-L29
unsplash/unsplash-php
src/Category.php
Category.all
public static function all($page = 1, $per_page = 10) { $categories = self::get( "/categories", ['query' => ['page' => $page, 'per_page' => $per_page]] ); $categoriesArray = self::getArray($categories->getBody(), get_called_class()); return new ArrayObject($categoriesArray, $categories->getHeaders()); }
php
public static function all($page = 1, $per_page = 10) { $categories = self::get( "/categories", ['query' => ['page' => $page, 'per_page' => $per_page]] ); $categoriesArray = self::getArray($categories->getBody(), get_called_class()); return new ArrayObject($categoriesArray, $categories->getHeaders()); }
[ "public", "static", "function", "all", "(", "$", "page", "=", "1", ",", "$", "per_page", "=", "10", ")", "{", "$", "categories", "=", "self", "::", "get", "(", "\"/categories\"", ",", "[", "'query'", "=>", "[", "'page'", "=>", "$", "page", ",", "'p...
Retrieve all the categories on a specific page. Returns an ArrayObject that contains Category objects. @param integer $page Page from which the categories need to be retrieved @param integer $per_page Number of elements on a page @return ArrayObject of Category objects. @deprecated @see Collection::all()
[ "Retrieve", "all", "the", "categories", "on", "a", "specific", "page", ".", "Returns", "an", "ArrayObject", "that", "contains", "Category", "objects", "." ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Category.php#L41-L51
unsplash/unsplash-php
src/Category.php
Category.photos
public function photos($page = 1, $per_page = 10) { if (! isset($this->photos["{$page}-{$per_page}"])) { $photos = self::get( "/categories/{$this->id}/photos", ['query' => ['page' => $page, 'per_page' => $per_page]] ); $this->photos["{$page}-{$per_page}"] = [ 'body' => self::getArray($photos->getBody(), __NAMESPACE__.'\\Photo'), 'headers' => $photos->getHeaders() ]; } return new ArrayObject( $this->photos["{$page}-{$per_page}"]['body'], $this->photos["{$page}-{$per_page}"]['headers'] ); }
php
public function photos($page = 1, $per_page = 10) { if (! isset($this->photos["{$page}-{$per_page}"])) { $photos = self::get( "/categories/{$this->id}/photos", ['query' => ['page' => $page, 'per_page' => $per_page]] ); $this->photos["{$page}-{$per_page}"] = [ 'body' => self::getArray($photos->getBody(), __NAMESPACE__.'\\Photo'), 'headers' => $photos->getHeaders() ]; } return new ArrayObject( $this->photos["{$page}-{$per_page}"]['body'], $this->photos["{$page}-{$per_page}"]['headers'] ); }
[ "public", "function", "photos", "(", "$", "page", "=", "1", ",", "$", "per_page", "=", "10", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "photos", "[", "\"{$page}-{$per_page}\"", "]", ")", ")", "{", "$", "photos", "=", "self", "::", ...
Retrieve all the photos for a specific category on a specific page. Returns an ArrayObject that contains Photo objects. @param integer $page Page from which the photos need to be retrieve @param integer $per_page Number of element in a page @return ArrayObject of Photo objects. @deprecated @see Collection::photos()
[ "Retrieve", "all", "the", "photos", "for", "a", "specific", "category", "on", "a", "specific", "page", ".", "Returns", "an", "ArrayObject", "that", "contains", "Photo", "objects", "." ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Category.php#L63-L81
unsplash/unsplash-php
src/HttpClient.php
HttpClient.init
public static function init($credentials = [], $accessToken = []) { $token = null; if (! empty($accessToken)) { $token = self::initAccessToken($accessToken); } if (!isset($credentials['utmSource']) || empty($credentials['utmSource'])) { $terms = "https://community.unsplash.com/developersblog/unsplash-api-terms-explained#block-yui_3_17_2_1_1490972762425_202608"; trigger_error("utmSource is required as part of API Terms: {$terms}"); } else { self::$utmSource = $credentials['utmSource']; } self::$connection = new Connection(self::initProvider($credentials), $token); }
php
public static function init($credentials = [], $accessToken = []) { $token = null; if (! empty($accessToken)) { $token = self::initAccessToken($accessToken); } if (!isset($credentials['utmSource']) || empty($credentials['utmSource'])) { $terms = "https://community.unsplash.com/developersblog/unsplash-api-terms-explained#block-yui_3_17_2_1_1490972762425_202608"; trigger_error("utmSource is required as part of API Terms: {$terms}"); } else { self::$utmSource = $credentials['utmSource']; } self::$connection = new Connection(self::initProvider($credentials), $token); }
[ "public", "static", "function", "init", "(", "$", "credentials", "=", "[", "]", ",", "$", "accessToken", "=", "[", "]", ")", "{", "$", "token", "=", "null", ";", "if", "(", "!", "empty", "(", "$", "accessToken", ")", ")", "{", "$", "token", "=", ...
Initialize the $connection object that is used for all requests to the API $credentials array Credentials needed for the API request ['applicationId'] string Application id. This value is needed across all requests ['secret'] string Application secret. Application secret is needed for OAuth authentication ['callbackUrl'] string Callback url. After OAuth authentication, the user will be redirected to this url. ['utmSource'] string Name of your application. This is required, a notice will be raised if missing $accessToken array Access Token information ['access_token'] string Access Token identifier ['refresh_token'] string Refresh Token necessary when the access token is expired ['expires_in'] int Define in when the access token will expire @param array $credentials see above @param array| \League\OAuth2\Client\Token\accessToken $accessToken see above @return void
[ "Initialize", "the", "$connection", "object", "that", "is", "used", "for", "all", "requests", "to", "the", "API" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/HttpClient.php#L78-L93
unsplash/unsplash-php
src/HttpClient.php
HttpClient.initProvider
private static function initProvider($credentials = []) { return new Unsplash([ 'clientId' => isset($credentials['applicationId']) ? $credentials['applicationId'] : null, 'clientSecret' => isset($credentials['secret']) ? $credentials['secret'] : null, 'redirectUri' => isset($credentials['callbackUrl']) ? $credentials['callbackUrl'] : null ]); }
php
private static function initProvider($credentials = []) { return new Unsplash([ 'clientId' => isset($credentials['applicationId']) ? $credentials['applicationId'] : null, 'clientSecret' => isset($credentials['secret']) ? $credentials['secret'] : null, 'redirectUri' => isset($credentials['callbackUrl']) ? $credentials['callbackUrl'] : null ]); }
[ "private", "static", "function", "initProvider", "(", "$", "credentials", "=", "[", "]", ")", "{", "return", "new", "Unsplash", "(", "[", "'clientId'", "=>", "isset", "(", "$", "credentials", "[", "'applicationId'", "]", ")", "?", "$", "credentials", "[", ...
Create an unsplash provider from the credentials provided by the user. If only the `applicationId` is set, non-public scoped permissions won't work since access tokens can't be created without the secret and callback url @param array $credentials @return Unsplash Provider object used for the authentication @see HttpClient::init documentation
[ "Create", "an", "unsplash", "provider", "from", "the", "credentials", "provided", "by", "the", "user", ".", "If", "only", "the", "applicationId", "is", "set", "non", "-", "public", "scoped", "permissions", "won", "t", "work", "since", "access", "tokens", "ca...
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/HttpClient.php#L104-L111
unsplash/unsplash-php
src/HttpClient.php
HttpClient.initAccessToken
private static function initAccessToken($accessToken) { if (is_array($accessToken)) { return new AccessToken($accessToken); } elseif (is_a($accessToken, '\League\OAuth2\Client\Token\AccessToken')) { return $accessToken; } else { return null; } }
php
private static function initAccessToken($accessToken) { if (is_array($accessToken)) { return new AccessToken($accessToken); } elseif (is_a($accessToken, '\League\OAuth2\Client\Token\AccessToken')) { return $accessToken; } else { return null; } }
[ "private", "static", "function", "initAccessToken", "(", "$", "accessToken", ")", "{", "if", "(", "is_array", "(", "$", "accessToken", ")", ")", "{", "return", "new", "AccessToken", "(", "$", "accessToken", ")", ";", "}", "elseif", "(", "is_a", "(", "$",...
Create an Access Token the provider can use for authentication @param mixed $accessToken see HttpClient::init documentation @return \League\OAuth2\Client\Token\AccessToken | null
[ "Create", "an", "Access", "Token", "the", "provider", "can", "use", "for", "authentication" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/HttpClient.php#L119-L128
unsplash/unsplash-php
src/HttpClient.php
HttpClient.send
public function send($method, $arguments) { $uri = $arguments[0]; $params = isset($arguments[1]) ? $arguments[1] : []; if (substr($uri, 0, 1) !== '/') { $uri = '/' . $uri; } $response = $this->httpClient->send( new Request($method, new Uri($uri)), $params ); return $response; }
php
public function send($method, $arguments) { $uri = $arguments[0]; $params = isset($arguments[1]) ? $arguments[1] : []; if (substr($uri, 0, 1) !== '/') { $uri = '/' . $uri; } $response = $this->httpClient->send( new Request($method, new Uri($uri)), $params ); return $response; }
[ "public", "function", "send", "(", "$", "method", ",", "$", "arguments", ")", "{", "$", "uri", "=", "$", "arguments", "[", "0", "]", ";", "$", "params", "=", "isset", "(", "$", "arguments", "[", "1", "]", ")", "?", "$", "arguments", "[", "1", "...
Send an http request through the http client. @param string $method http method sent @param array $arguments Array containing the URI to send the request and the parameters of the request @return \GuzzleHttp\Psr7\Response
[ "Send", "an", "http", "request", "through", "the", "http", "client", "." ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/HttpClient.php#L137-L151
unsplash/unsplash-php
src/HttpClient.php
HttpClient.setHandler
private function setHandler($authorization) { $stack = new HandlerStack(); $stack->setHandler(new CurlHandler()); // Set authorization headers $this->authorization = $authorization; $stack->push(Middleware::mapRequest(function (Request $request) { return $request->withHeader('Authorization', $this->authorization); }), 'set_authorization_header'); // Set the request ui $stack->push(Middleware::mapRequest(function (Request $request) { $uri = $request->getUri()->withHost($this->host)->withScheme($this->scheme); return $request->withUri($uri); }), 'set_host'); return $stack; }
php
private function setHandler($authorization) { $stack = new HandlerStack(); $stack->setHandler(new CurlHandler()); // Set authorization headers $this->authorization = $authorization; $stack->push(Middleware::mapRequest(function (Request $request) { return $request->withHeader('Authorization', $this->authorization); }), 'set_authorization_header'); // Set the request ui $stack->push(Middleware::mapRequest(function (Request $request) { $uri = $request->getUri()->withHost($this->host)->withScheme($this->scheme); return $request->withUri($uri); }), 'set_host'); return $stack; }
[ "private", "function", "setHandler", "(", "$", "authorization", ")", "{", "$", "stack", "=", "new", "HandlerStack", "(", ")", ";", "$", "stack", "->", "setHandler", "(", "new", "CurlHandler", "(", ")", ")", ";", "// Set authorization headers", "$", "this", ...
Generate a new handler that will manage the HTTP requests. Some middleware are also configured to manage the authorization header and request URI @param string $authorization Authorization code to pass in the header @return \GuzzleHttp\HandlerStack
[ "Generate", "a", "new", "handler", "that", "will", "manage", "the", "HTTP", "requests", "." ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/HttpClient.php#L161-L181
unsplash/unsplash-php
src/Photo.php
Photo.find
public static function find($id) { $photo = json_decode(self::get("/photos/{$id}")->getBody(), true); return new self($photo); }
php
public static function find($id) { $photo = json_decode(self::get("/photos/{$id}")->getBody(), true); return new self($photo); }
[ "public", "static", "function", "find", "(", "$", "id", ")", "{", "$", "photo", "=", "json_decode", "(", "self", "::", "get", "(", "\"/photos/{$id}\"", ")", "->", "getBody", "(", ")", ",", "true", ")", ";", "return", "new", "self", "(", "$", "photo",...
Retrieve the a photo object from the ID specified @param string $id ID of the photo @return Photo
[ "Retrieve", "the", "a", "photo", "object", "from", "the", "ID", "specified" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Photo.php#L21-L26
unsplash/unsplash-php
src/Photo.php
Photo.all
public static function all($page = 1, $per_page = 10, $order_by = 'latest') { $photos = self::get("/photos", [ 'query' => ['page' => $page, 'per_page' => $per_page, 'order_by' => $order_by] ]); $photosArray = self::getArray($photos->getBody(), get_called_class()); return new ArrayObject($photosArray, $photos->getHeaders()); }
php
public static function all($page = 1, $per_page = 10, $order_by = 'latest') { $photos = self::get("/photos", [ 'query' => ['page' => $page, 'per_page' => $per_page, 'order_by' => $order_by] ]); $photosArray = self::getArray($photos->getBody(), get_called_class()); return new ArrayObject($photosArray, $photos->getHeaders()); }
[ "public", "static", "function", "all", "(", "$", "page", "=", "1", ",", "$", "per_page", "=", "10", ",", "$", "order_by", "=", "'latest'", ")", "{", "$", "photos", "=", "self", "::", "get", "(", "\"/photos\"", ",", "[", "'query'", "=>", "[", "'page...
Retrieve all the photos on a specific page. Returns an ArrayObject that contains Photo objects. @param integer $page Page from which the photos need to be retrieve @param integer $per_page Number of element in a page @param string $order_by Order in which to retrieve photos @return ArrayObject of Photos
[ "Retrieve", "all", "the", "photos", "on", "a", "specific", "page", ".", "Returns", "an", "ArrayObject", "that", "contains", "Photo", "objects", "." ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Photo.php#L37-L46
unsplash/unsplash-php
src/Photo.php
Photo.search
public static function search($search, $category = null, $page = 1, $per_page = 10, $orientation = null) { $photos = self::get( "/photos/search", ['query' => [ 'query' => $search, 'category' => $category, 'orientation' => $orientation, 'page' => $page, 'per_page' => $per_page ] ] ); $photosArray = self::getArray($photos->getBody(), get_called_class()); return new ArrayObject($photosArray, $photos->getHeaders()); }
php
public static function search($search, $category = null, $page = 1, $per_page = 10, $orientation = null) { $photos = self::get( "/photos/search", ['query' => [ 'query' => $search, 'category' => $category, 'orientation' => $orientation, 'page' => $page, 'per_page' => $per_page ] ] ); $photosArray = self::getArray($photos->getBody(), get_called_class()); return new ArrayObject($photosArray, $photos->getHeaders()); }
[ "public", "static", "function", "search", "(", "$", "search", ",", "$", "category", "=", "null", ",", "$", "page", "=", "1", ",", "$", "per_page", "=", "10", ",", "$", "orientation", "=", "null", ")", "{", "$", "photos", "=", "self", "::", "get", ...
Retrieve all the photos on a specific page depending on search results Returns ArrayObject that contain Photo object. @param string $search Retrieve photos matching the search term. @param integer $category Retrieve photos matching the category ID @param integer $page Page from which the photos need to be retrieved @param integer $per_page Number of elements on a page @param string|null $orientation Orientation to search for @deprecated @see Search::photos() @return ArrayObject of Photos
[ "Retrieve", "all", "the", "photos", "on", "a", "specific", "page", "depending", "on", "search", "results", "Returns", "ArrayObject", "that", "contain", "Photo", "object", "." ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Photo.php#L82-L99
unsplash/unsplash-php
src/Photo.php
Photo.create
public static function create($filePath) { if (!file_exists($filePath)) { throw new Exception(["{$filePath} has not been found"]); } $file = fopen($filePath, 'r'); $photo = json_decode( self::post( "photos", [ 'multipart' => [['name' => 'photo', 'contents' => $file]], 'headers' => ['Content-Length' => filesize($filePath)] ] )->getBody(), true ); return new self($photo); }
php
public static function create($filePath) { if (!file_exists($filePath)) { throw new Exception(["{$filePath} has not been found"]); } $file = fopen($filePath, 'r'); $photo = json_decode( self::post( "photos", [ 'multipart' => [['name' => 'photo', 'contents' => $file]], 'headers' => ['Content-Length' => filesize($filePath)] ] )->getBody(), true ); return new self($photo); }
[ "public", "static", "function", "create", "(", "$", "filePath", ")", "{", "if", "(", "!", "file_exists", "(", "$", "filePath", ")", ")", "{", "throw", "new", "Exception", "(", "[", "\"{$filePath} has not been found\"", "]", ")", ";", "}", "$", "file", "=...
Create a new photo. The user needs to connect their account and authorize the write_photo permission scope. @param string $filePath Path of the file to upload @throws Exception - if filePath does not exist @return Photo
[ "Create", "a", "new", "photo", ".", "The", "user", "needs", "to", "connect", "their", "account", "and", "authorize", "the", "write_photo", "permission", "scope", "." ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Photo.php#L108-L128
unsplash/unsplash-php
src/Photo.php
Photo.photographer
public function photographer() { if (! isset($this->photographer)) { $this->photographer = User::find($this->user['username']); } return $this->photographer; }
php
public function photographer() { if (! isset($this->photographer)) { $this->photographer = User::find($this->user['username']); } return $this->photographer; }
[ "public", "function", "photographer", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "photographer", ")", ")", "{", "$", "this", "->", "photographer", "=", "User", "::", "find", "(", "$", "this", "->", "user", "[", "'username'", "]",...
Retrieve the user that uploaded the photo @return User
[ "Retrieve", "the", "user", "that", "uploaded", "the", "photo" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Photo.php#L135-L142
unsplash/unsplash-php
src/Photo.php
Photo.random
public static function random($filters = []) { if (isset($filters['category']) && is_array($filters['category'])) { $filters['category'] = implode(',', $filters['category']); } $filters['featured'] = (isset($filters['featured']) && $filters['featured']) ? 'true' : null; $photo = json_decode(self::get("photos/random", ['query' => $filters])->getBody(), true); return new self($photo); }
php
public static function random($filters = []) { if (isset($filters['category']) && is_array($filters['category'])) { $filters['category'] = implode(',', $filters['category']); } $filters['featured'] = (isset($filters['featured']) && $filters['featured']) ? 'true' : null; $photo = json_decode(self::get("photos/random", ['query' => $filters])->getBody(), true); return new self($photo); }
[ "public", "static", "function", "random", "(", "$", "filters", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "$", "filters", "[", "'category'", "]", ")", "&&", "is_array", "(", "$", "filters", "[", "'category'", "]", ")", ")", "{", "$", "filter...
Retrieve a single random photo, given optional filters. @param $filters array Apply optional filters. @return Photo
[ "Retrieve", "a", "single", "random", "photo", "given", "optional", "filters", "." ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Photo.php#L150-L161
unsplash/unsplash-php
src/Photo.php
Photo.statistics
public function statistics($resolution = 'days', $quantity = 30) { $statistics = self::get("photos/{$this->id}/statistics", ['query' => ['resolution' => $resolution, 'quantity' => $quantity]]); $statisticsArray = self::getArray($statistics->getBody(), Stat::class); return new ArrayObject($statisticsArray, $statistics->getHeaders()); }
php
public function statistics($resolution = 'days', $quantity = 30) { $statistics = self::get("photos/{$this->id}/statistics", ['query' => ['resolution' => $resolution, 'quantity' => $quantity]]); $statisticsArray = self::getArray($statistics->getBody(), Stat::class); return new ArrayObject($statisticsArray, $statistics->getHeaders()); }
[ "public", "function", "statistics", "(", "$", "resolution", "=", "'days'", ",", "$", "quantity", "=", "30", ")", "{", "$", "statistics", "=", "self", "::", "get", "(", "\"photos/{$this->id}/statistics\"", ",", "[", "'query'", "=>", "[", "'resolution'", "=>",...
Retrieve statistics for a photo @param string $resolution @param int $quantity @return ArrayObject
[ "Retrieve", "statistics", "for", "a", "photo" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Photo.php#L192-L197
unsplash/unsplash-php
src/Photo.php
Photo.download
public function download() { $download_path = parse_url($this->links['download_location'], PHP_URL_PATH); $download_query = parse_url($this->links['download_location'], PHP_URL_QUERY); $link = self::get($download_path . "?" . $download_query); $linkClass = \GuzzleHttp\json_decode($link->getBody()); return $linkClass->url; }
php
public function download() { $download_path = parse_url($this->links['download_location'], PHP_URL_PATH); $download_query = parse_url($this->links['download_location'], PHP_URL_QUERY); $link = self::get($download_path . "?" . $download_query); $linkClass = \GuzzleHttp\json_decode($link->getBody()); return $linkClass->url; }
[ "public", "function", "download", "(", ")", "{", "$", "download_path", "=", "parse_url", "(", "$", "this", "->", "links", "[", "'download_location'", "]", ",", "PHP_URL_PATH", ")", ";", "$", "download_query", "=", "parse_url", "(", "$", "this", "->", "link...
Triggers a download for a photo Required under API Guidelines @return string - full-res photo URL for downloading
[ "Triggers", "a", "download", "for", "a", "photo", "Required", "under", "API", "Guidelines" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Photo.php#L204-L211
unsplash/unsplash-php
src/Photo.php
Photo.update
public function update(array $parameters = []) { json_decode(self::put("/photos/{$this->id}", ['query' => $parameters])->getBody(), true); parent::update($parameters); }
php
public function update(array $parameters = []) { json_decode(self::put("/photos/{$this->id}", ['query' => $parameters])->getBody(), true); parent::update($parameters); }
[ "public", "function", "update", "(", "array", "$", "parameters", "=", "[", "]", ")", "{", "json_decode", "(", "self", "::", "put", "(", "\"/photos/{$this->id}\"", ",", "[", "'query'", "=>", "$", "parameters", "]", ")", "->", "getBody", "(", ")", ",", "...
Update an existing photo @param array $parameters @return Photo
[ "Update", "an", "existing", "photo" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Photo.php#L218-L222
unsplash/unsplash-php
src/Search.php
Search.photos
public static function photos($search, $page = 1, $per_page = 10, $orientation = null, $collections = null) { $query = [ 'query' => $search, 'page' => $page, 'per_page' => $per_page ]; if ( ! empty($orientation)) { $query['orientation'] = $orientation; } if ( ! empty($collections)) { $query['collections'] = $collections; } $photos = self::get( "/search/photos", [ 'query' => $query ] ); return self::getPageResult($photos->getBody(), $photos->getHeaders(), Photo::class); }
php
public static function photos($search, $page = 1, $per_page = 10, $orientation = null, $collections = null) { $query = [ 'query' => $search, 'page' => $page, 'per_page' => $per_page ]; if ( ! empty($orientation)) { $query['orientation'] = $orientation; } if ( ! empty($collections)) { $query['collections'] = $collections; } $photos = self::get( "/search/photos", [ 'query' => $query ] ); return self::getPageResult($photos->getBody(), $photos->getHeaders(), Photo::class); }
[ "public", "static", "function", "photos", "(", "$", "search", ",", "$", "page", "=", "1", ",", "$", "per_page", "=", "10", ",", "$", "orientation", "=", "null", ",", "$", "collections", "=", "null", ")", "{", "$", "query", "=", "[", "'query'", "=>"...
Retrieve a single page of photo results depending on search results Returns ArrayObject that contain PageResult object. @param string $search Search terms. @param integer $page Page number to retrieve. (Optional; default: 1) @param integer $per_page Number of items per page. (Optional; default: 10) @param string $orientation Filter search results by photo orientation. Valid values are landscape, portrait, and squarish. (Optional) @param string $collections Collection ID(‘s) to narrow search. If multiple, comma-separated. (Optional) @return PageResult
[ "Retrieve", "a", "single", "page", "of", "photo", "results", "depending", "on", "search", "results", "Returns", "ArrayObject", "that", "contain", "PageResult", "object", "." ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Search.php#L23-L45
unsplash/unsplash-php
src/Search.php
Search.collections
public static function collections($search, $page = 1, $per_page = 10) { $collections = self::get( "/search/collections", ['query' => [ 'query' => $search, 'page' => $page, 'per_page' => $per_page ] ] ); return self::getPageResult($collections->getBody(), $collections->getHeaders(), Collection::class); }
php
public static function collections($search, $page = 1, $per_page = 10) { $collections = self::get( "/search/collections", ['query' => [ 'query' => $search, 'page' => $page, 'per_page' => $per_page ] ] ); return self::getPageResult($collections->getBody(), $collections->getHeaders(), Collection::class); }
[ "public", "static", "function", "collections", "(", "$", "search", ",", "$", "page", "=", "1", ",", "$", "per_page", "=", "10", ")", "{", "$", "collections", "=", "self", "::", "get", "(", "\"/search/collections\"", ",", "[", "'query'", "=>", "[", "'qu...
Retrieve a single page of collection results depending on search results Returns ArrayObject that contain PageResult object. @param string $search Search terms. @param integer $page Page from which the photos need to be retrieve @param integer $per_page Number of element in a page @return PageResult
[ "Retrieve", "a", "single", "page", "of", "collection", "results", "depending", "on", "search", "results", "Returns", "ArrayObject", "that", "contain", "PageResult", "object", "." ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Search.php#L56-L69
unsplash/unsplash-php
src/Search.php
Search.users
public static function users($search, $page = 1, $per_page = 10) { $users = self::get( "/search/users", ['query' => [ 'query' => $search, 'page' => $page, 'per_page' => $per_page ] ] ); return self::getPageResult($users->getBody(), $users->getHeaders(), User::class); }
php
public static function users($search, $page = 1, $per_page = 10) { $users = self::get( "/search/users", ['query' => [ 'query' => $search, 'page' => $page, 'per_page' => $per_page ] ] ); return self::getPageResult($users->getBody(), $users->getHeaders(), User::class); }
[ "public", "static", "function", "users", "(", "$", "search", ",", "$", "page", "=", "1", ",", "$", "per_page", "=", "10", ")", "{", "$", "users", "=", "self", "::", "get", "(", "\"/search/users\"", ",", "[", "'query'", "=>", "[", "'query'", "=>", "...
Retrieve a single page of user results depending on search results Returns ArrayObject that contain PageResult object. @param string $search Search terms. @param integer $page Page from which the photos need to be retrieve @param integer $per_page Number of element in a page @return PageResult
[ "Retrieve", "a", "single", "page", "of", "user", "results", "depending", "on", "search", "results", "Returns", "ArrayObject", "that", "contain", "PageResult", "object", "." ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Search.php#L80-L93
unsplash/unsplash-php
src/Connection.php
Connection.getConnectionUrl
public function getConnectionUrl($scopes = []) { $connectionUrl = $this->provider->getAuthorizationUrl(['scope' => $scopes]); $_SESSION[self::STATE] = $this->provider->getState(); return $connectionUrl; }
php
public function getConnectionUrl($scopes = []) { $connectionUrl = $this->provider->getAuthorizationUrl(['scope' => $scopes]); $_SESSION[self::STATE] = $this->provider->getState(); return $connectionUrl; }
[ "public", "function", "getConnectionUrl", "(", "$", "scopes", "=", "[", "]", ")", "{", "$", "connectionUrl", "=", "$", "this", "->", "provider", "->", "getAuthorizationUrl", "(", "[", "'scope'", "=>", "$", "scopes", "]", ")", ";", "$", "_SESSION", "[", ...
Retrieve the URL that generates the authorization code @param array $scopes Scopes to include in the authorization URL @return string
[ "Retrieve", "the", "URL", "that", "generates", "the", "authorization", "code" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Connection.php#L43-L49
unsplash/unsplash-php
src/Connection.php
Connection.generateToken
public function generateToken($code) { $this->token = $this->provider->getAccessToken('authorization_code', [ 'code' => $code ]); return $this->token; }
php
public function generateToken($code) { $this->token = $this->provider->getAccessToken('authorization_code', [ 'code' => $code ]); return $this->token; }
[ "public", "function", "generateToken", "(", "$", "code", ")", "{", "$", "this", "->", "token", "=", "$", "this", "->", "provider", "->", "getAccessToken", "(", "'authorization_code'", ",", "[", "'code'", "=>", "$", "code", "]", ")", ";", "return", "$", ...
Generate a new access token object from an authorization code @param string $code Authorization code provided by the Unsplash OAuth2 service @return \League\OAuth2\Client\Token\AccessToken
[ "Generate", "a", "new", "access", "token", "object", "from", "an", "authorization", "code" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Connection.php#L68-L75
unsplash/unsplash-php
src/Connection.php
Connection.refreshToken
public function refreshToken() { if (is_null($this->token) || is_null($this->token->getRefreshToken())) { return null; } $grant = new RefreshToken(); $refreshToken = $this->provider->getAccessToken($grant, [ 'refresh_token' => $this->token->getRefreshToken() ]); $this->token = $refreshToken; return $this->token; }
php
public function refreshToken() { if (is_null($this->token) || is_null($this->token->getRefreshToken())) { return null; } $grant = new RefreshToken(); $refreshToken = $this->provider->getAccessToken($grant, [ 'refresh_token' => $this->token->getRefreshToken() ]); $this->token = $refreshToken; return $this->token; }
[ "public", "function", "refreshToken", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "token", ")", "||", "is_null", "(", "$", "this", "->", "token", "->", "getRefreshToken", "(", ")", ")", ")", "{", "return", "null", ";", "}", "$", "g...
Refresh an expired token and generate a new AccessToken object. @return \League\OAuth2\Client\Token\AccessToken|null
[ "Refresh", "an", "expired", "token", "and", "generate", "a", "new", "AccessToken", "object", "." ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Connection.php#L92-L107
unsplash/unsplash-php
src/Connection.php
Connection.getAuthorizationToken
public function getAuthorizationToken() { $authorizationToken = "Client-ID {$this->provider->getClientId()}"; if (! is_null($this->token)) { // Validate if the token object link to this class is expire // refresh it if it's the case if ($this->token->hasExpired()) { $this->refreshToken(); } $authorizationToken = "Bearer {$this->token->getToken()}"; } return $authorizationToken; }
php
public function getAuthorizationToken() { $authorizationToken = "Client-ID {$this->provider->getClientId()}"; if (! is_null($this->token)) { // Validate if the token object link to this class is expire // refresh it if it's the case if ($this->token->hasExpired()) { $this->refreshToken(); } $authorizationToken = "Bearer {$this->token->getToken()}"; } return $authorizationToken; }
[ "public", "function", "getAuthorizationToken", "(", ")", "{", "$", "authorizationToken", "=", "\"Client-ID {$this->provider->getClientId()}\"", ";", "if", "(", "!", "is_null", "(", "$", "this", "->", "token", ")", ")", "{", "// Validate if the token object link to this ...
Generate the authorization string to pass in via the http header. Check if a token is linked to the connection object and use the client ID if there is not. The method will also refresh the access token if it has expired. @return string
[ "Generate", "the", "authorization", "string", "to", "pass", "in", "via", "the", "http", "header", ".", "Check", "if", "a", "token", "is", "linked", "to", "the", "connection", "object", "and", "use", "the", "client", "ID", "if", "there", "is", "not", ".",...
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Connection.php#L116-L131
unsplash/unsplash-php
src/Endpoint.php
Endpoint.getPageResult
protected static function getPageResult($responseBody, array $headers, $className) { $data = json_decode($responseBody, true); $result = new PageResult($data['results'], $data['total'], $data['total_pages'], $headers, $className); return $result; }
php
protected static function getPageResult($responseBody, array $headers, $className) { $data = json_decode($responseBody, true); $result = new PageResult($data['results'], $data['total'], $data['total_pages'], $headers, $className); return $result; }
[ "protected", "static", "function", "getPageResult", "(", "$", "responseBody", ",", "array", "$", "headers", ",", "$", "className", ")", "{", "$", "data", "=", "json_decode", "(", "$", "responseBody", ",", "true", ")", ";", "$", "result", "=", "new", "Pag...
@param string $responseBody @param array $headers @param string $className @return PageResult
[ "@param", "string", "$responseBody", "@param", "array", "$headers", "@param", "string", "$className" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Endpoint.php#L111-L117
unsplash/unsplash-php
src/Endpoint.php
Endpoint.getErrorMessage
private static function getErrorMessage($response) { $body = $response->getBody(); $message = json_decode($body, true); $errors = []; if (is_array($message) && isset($message['errors'])) { $errors = $message['errors']; } if ($body == self::RATE_LIMIT_ERROR_MESSAGE) { $errors = [self::RATE_LIMIT_ERROR_MESSAGE]; } return $errors; }
php
private static function getErrorMessage($response) { $body = $response->getBody(); $message = json_decode($body, true); $errors = []; if (is_array($message) && isset($message['errors'])) { $errors = $message['errors']; } if ($body == self::RATE_LIMIT_ERROR_MESSAGE) { $errors = [self::RATE_LIMIT_ERROR_MESSAGE]; } return $errors; }
[ "private", "static", "function", "getErrorMessage", "(", "$", "response", ")", "{", "$", "body", "=", "$", "response", "->", "getBody", "(", ")", ";", "$", "message", "=", "json_decode", "(", "$", "body", ",", "true", ")", ";", "$", "errors", "=", "[...
Retrieve the error messages in the body @param \GuzzleHttp\Psr7\Response $response of the HTTP request @return array Array of error messages
[ "Retrieve", "the", "error", "messages", "in", "the", "body" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Endpoint.php#L148-L164
unsplash/unsplash-php
src/Endpoint.php
Endpoint.addUtmSource
private function addUtmSource(array $parameters) { if (empty($parameters['links'])) { return $parameters; } $queryString = http_build_query([ 'utm_source' => HttpClient::$utmSource, 'utm_medium' => 'referral', 'utm_campaign' => 'api-credit' ]); array_walk_recursive($parameters, function (&$link) use ($queryString) { $parsedUrl = parse_url($link); if (!filter_var($link, FILTER_VALIDATE_URL) || $parsedUrl['host'] !== 'unsplash.com') { return; } $queryPrefix = '?'; if (isset($parsedUrl['query'])) { $queryPrefix = '&'; } $link = $link . $queryPrefix . $queryString; return $link; }); return $parameters; }
php
private function addUtmSource(array $parameters) { if (empty($parameters['links'])) { return $parameters; } $queryString = http_build_query([ 'utm_source' => HttpClient::$utmSource, 'utm_medium' => 'referral', 'utm_campaign' => 'api-credit' ]); array_walk_recursive($parameters, function (&$link) use ($queryString) { $parsedUrl = parse_url($link); if (!filter_var($link, FILTER_VALIDATE_URL) || $parsedUrl['host'] !== 'unsplash.com') { return; } $queryPrefix = '?'; if (isset($parsedUrl['query'])) { $queryPrefix = '&'; } $link = $link . $queryPrefix . $queryString; return $link; }); return $parameters; }
[ "private", "function", "addUtmSource", "(", "array", "$", "parameters", ")", "{", "if", "(", "empty", "(", "$", "parameters", "[", "'links'", "]", ")", ")", "{", "return", "$", "parameters", ";", "}", "$", "queryString", "=", "http_build_query", "(", "["...
Append utm_* values @param array $parameters @return array
[ "Append", "utm_", "*", "values" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/Endpoint.php#L171-L201
unsplash/unsplash-php
src/ArrayObject.php
ArrayObject.totalPages
public function totalPages() { $total = $this->totalObjects(); $perPage = $this->objectsPerPage(); return (int) ceil($total / $perPage); }
php
public function totalPages() { $total = $this->totalObjects(); $perPage = $this->objectsPerPage(); return (int) ceil($total / $perPage); }
[ "public", "function", "totalPages", "(", ")", "{", "$", "total", "=", "$", "this", "->", "totalObjects", "(", ")", ";", "$", "perPage", "=", "$", "this", "->", "objectsPerPage", "(", ")", ";", "return", "(", "int", ")", "ceil", "(", "$", "total", "...
Total number of pages for this call @return int Total page
[ "Total", "number", "of", "pages", "for", "this", "call" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/ArrayObject.php#L63-L69
unsplash/unsplash-php
src/ArrayObject.php
ArrayObject.totalObjects
public function totalObjects() { $total = 0; if (!empty($this->headers[self::TOTAL]) && is_array($this->headers[self::TOTAL])) { $total = (int) $this->headers[self::TOTAL][0]; } return $total; }
php
public function totalObjects() { $total = 0; if (!empty($this->headers[self::TOTAL]) && is_array($this->headers[self::TOTAL])) { $total = (int) $this->headers[self::TOTAL][0]; } return $total; }
[ "public", "function", "totalObjects", "(", ")", "{", "$", "total", "=", "0", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "headers", "[", "self", "::", "TOTAL", "]", ")", "&&", "is_array", "(", "$", "this", "->", "headers", "[", "self", ...
Total of object in the collections Value come from X-Total header's value @return int Number of Objects
[ "Total", "of", "object", "in", "the", "collections", "Value", "come", "from", "X", "-", "Total", "header", "s", "value" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/ArrayObject.php#L76-L84
unsplash/unsplash-php
src/ArrayObject.php
ArrayObject.objectsPerPage
public function objectsPerPage() { $perPage = 10; if (!empty($this->headers[self::PER_PAGE]) && is_array($this->headers[self::PER_PAGE])) { $perPage = (int) $this->headers[self::PER_PAGE][0]; } return $perPage; }
php
public function objectsPerPage() { $perPage = 10; if (!empty($this->headers[self::PER_PAGE]) && is_array($this->headers[self::PER_PAGE])) { $perPage = (int) $this->headers[self::PER_PAGE][0]; } return $perPage; }
[ "public", "function", "objectsPerPage", "(", ")", "{", "$", "perPage", "=", "10", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "headers", "[", "self", "::", "PER_PAGE", "]", ")", "&&", "is_array", "(", "$", "this", "->", "headers", "[", "s...
Number of element per page @return int element per page
[ "Number", "of", "element", "per", "page" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/ArrayObject.php#L90-L98
unsplash/unsplash-php
src/ArrayObject.php
ArrayObject.currentPage
public function currentPage() { if (isset($this->pages[self::NEXT])) { $page = $this->pages[self::NEXT] - 1; } else { $page = $this->pages[self::PREV] + 1; } return $page; }
php
public function currentPage() { if (isset($this->pages[self::NEXT])) { $page = $this->pages[self::NEXT] - 1; } else { $page = $this->pages[self::PREV] + 1; } return $page; }
[ "public", "function", "currentPage", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "pages", "[", "self", "::", "NEXT", "]", ")", ")", "{", "$", "page", "=", "$", "this", "->", "pages", "[", "self", "::", "NEXT", "]", "-", "1", ";",...
Current page number based on the Link header @return int Current page number
[ "Current", "page", "number", "based", "on", "the", "Link", "header" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/ArrayObject.php#L104-L113
unsplash/unsplash-php
src/ArrayObject.php
ArrayObject.generatePages
private function generatePages() { $links = explode(',', $this->headers[self::LINK][0]); foreach ($links as $link) { // Run two preg_match to retrieve specific element in the string // snce the page attributes is not always at the same position, // we can't retireve both information in the same regex preg_match('/page=([^&>]*)/', $link, $page); preg_match('/rel="([a-z]+)"/', $link, $rel); if ($page[1] !== null && $rel[1] !== null) { $this->pages[$rel[1]] = $page[1]; } } $this->pagesProcessed = true; return $this->pages; }
php
private function generatePages() { $links = explode(',', $this->headers[self::LINK][0]); foreach ($links as $link) { // Run two preg_match to retrieve specific element in the string // snce the page attributes is not always at the same position, // we can't retireve both information in the same regex preg_match('/page=([^&>]*)/', $link, $page); preg_match('/rel="([a-z]+)"/', $link, $rel); if ($page[1] !== null && $rel[1] !== null) { $this->pages[$rel[1]] = $page[1]; } } $this->pagesProcessed = true; return $this->pages; }
[ "private", "function", "generatePages", "(", ")", "{", "$", "links", "=", "explode", "(", "','", ",", "$", "this", "->", "headers", "[", "self", "::", "LINK", "]", "[", "0", "]", ")", ";", "foreach", "(", "$", "links", "as", "$", "link", ")", "{"...
Return an array containing the page number for all positions: last, previous, next, first If the page number for a specific position doesn't exist (i.e it is the current page), the position will return null @return array
[ "Return", "an", "array", "containing", "the", "page", "number", "for", "all", "positions", ":", "last", "previous", "next", "first", "If", "the", "page", "number", "for", "a", "specific", "position", "doesn", "t", "exist", "(", "i", ".", "e", "it", "is",...
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/ArrayObject.php#L131-L150
unsplash/unsplash-php
src/User.php
User.find
public static function find($username) { $user = json_decode(self::get("/users/{$username}")->getBody(), true); return new self($user); }
php
public static function find($username) { $user = json_decode(self::get("/users/{$username}")->getBody(), true); return new self($user); }
[ "public", "static", "function", "find", "(", "$", "username", ")", "{", "$", "user", "=", "json_decode", "(", "self", "::", "get", "(", "\"/users/{$username}\"", ")", "->", "getBody", "(", ")", ",", "true", ")", ";", "return", "new", "self", "(", "$", ...
Retrieve a User object from the username specified @param string $username Username of the user @return User
[ "Retrieve", "a", "User", "object", "from", "the", "username", "specified" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/User.php#L24-L29
unsplash/unsplash-php
src/User.php
User.collections
public function collections($page = 1, $per_page = 10) { if (! isset($this->collections["{$page}-{$per_page}"])) { $collections = self::get( "/users/{$this->username}/collections", ['query' => ['page' => $page, 'per_page' => $per_page]] ); $this->collections["{$page}-{$per_page}"] = [ 'body' => self::getArray($collections->getBody(), __NAMESPACE__.'\\Collection'), 'headers' => $collections->getHeaders() ]; } return new ArrayObject( $this->collections["{$page}-{$per_page}"]['body'], $this->collections["{$page}-{$per_page}"]['headers'] ); }
php
public function collections($page = 1, $per_page = 10) { if (! isset($this->collections["{$page}-{$per_page}"])) { $collections = self::get( "/users/{$this->username}/collections", ['query' => ['page' => $page, 'per_page' => $per_page]] ); $this->collections["{$page}-{$per_page}"] = [ 'body' => self::getArray($collections->getBody(), __NAMESPACE__.'\\Collection'), 'headers' => $collections->getHeaders() ]; } return new ArrayObject( $this->collections["{$page}-{$per_page}"]['body'], $this->collections["{$page}-{$per_page}"]['headers'] ); }
[ "public", "function", "collections", "(", "$", "page", "=", "1", ",", "$", "per_page", "=", "10", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "collections", "[", "\"{$page}-{$per_page}\"", "]", ")", ")", "{", "$", "collections", "=", "...
Retrieve all the collections for a specific user on a given page. Returns an ArrayObject that contains Collection objects. Include private collection if it's the user bearer token @param integer $page Page from which the collections are to be retrieved @param integer $per_page Number of elements on a page @return ArrayObject of Collections
[ "Retrieve", "all", "the", "collections", "for", "a", "specific", "user", "on", "a", "given", "page", ".", "Returns", "an", "ArrayObject", "that", "contains", "Collection", "objects", "." ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/User.php#L69-L87
unsplash/unsplash-php
src/User.php
User.likes
public function likes($page = 1, $per_page = 10, $order_by = 'latest') { if (! isset($this->likes["{$page}-{$per_page}-{$order_by}"])) { $likes = self::get("/users/{$this->username}/likes", [ 'query' => ['page' => $page, 'per_page' => $per_page, 'order_by' => $order_by] ]); $this->likes["{$page}-{$per_page}-{$order_by}"] = [ 'body' => self::getArray($likes->getBody(), __NAMESPACE__.'\\Photo'), 'headers' => $likes->getHeaders() ]; } return new ArrayObject( $this->likes["{$page}-{$per_page}-{$order_by}"]['body'], $this->likes["{$page}-{$per_page}-{$order_by}"]['headers'] ); }
php
public function likes($page = 1, $per_page = 10, $order_by = 'latest') { if (! isset($this->likes["{$page}-{$per_page}-{$order_by}"])) { $likes = self::get("/users/{$this->username}/likes", [ 'query' => ['page' => $page, 'per_page' => $per_page, 'order_by' => $order_by] ]); $this->likes["{$page}-{$per_page}-{$order_by}"] = [ 'body' => self::getArray($likes->getBody(), __NAMESPACE__.'\\Photo'), 'headers' => $likes->getHeaders() ]; } return new ArrayObject( $this->likes["{$page}-{$per_page}-{$order_by}"]['body'], $this->likes["{$page}-{$per_page}-{$order_by}"]['headers'] ); }
[ "public", "function", "likes", "(", "$", "page", "=", "1", ",", "$", "per_page", "=", "10", ",", "$", "order_by", "=", "'latest'", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "likes", "[", "\"{$page}-{$per_page}-{$order_by}\"", "]", ")",...
Retrieve all the photos liked by a specific user on a given page. Returns an ArrayObject that contains Photo object @param integer $page Page from which the photos are to be retrieved @param integer $per_page Number of elements on a page @param string $order_by Order in which to retrieve photos @return ArrayObject of Photos
[ "Retrieve", "all", "the", "photos", "liked", "by", "a", "specific", "user", "on", "a", "given", "page", ".", "Returns", "an", "ArrayObject", "that", "contains", "Photo", "object" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/User.php#L98-L115
unsplash/unsplash-php
src/CuratedCollection.php
CuratedCollection.find
public static function find($id) { $curatedBatch = json_decode(self::get("/collections/curated/{$id}")->getBody(), true); return new self($curatedBatch); }
php
public static function find($id) { $curatedBatch = json_decode(self::get("/collections/curated/{$id}")->getBody(), true); return new self($curatedBatch); }
[ "public", "static", "function", "find", "(", "$", "id", ")", "{", "$", "curatedBatch", "=", "json_decode", "(", "self", "::", "get", "(", "\"/collections/curated/{$id}\"", ")", "->", "getBody", "(", ")", ",", "true", ")", ";", "return", "new", "self", "(...
Retrieve a specific curated batch @param int $id Id of the curated batch @return CuratedCollection
[ "Retrieve", "a", "specific", "curated", "batch" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/CuratedCollection.php#L20-L25
unsplash/unsplash-php
src/CuratedCollection.php
CuratedCollection.all
public static function all($page = 1, $per_page = 10) { $curatedBatches = self::get( "/collections/curated", ['query' => ['page' => $page, 'per_page' => $per_page]] ); $curatedBatchesArray = self::getArray($curatedBatches->getBody(), get_called_class()); return new ArrayObject($curatedBatchesArray, $curatedBatches->getHeaders()); }
php
public static function all($page = 1, $per_page = 10) { $curatedBatches = self::get( "/collections/curated", ['query' => ['page' => $page, 'per_page' => $per_page]] ); $curatedBatchesArray = self::getArray($curatedBatches->getBody(), get_called_class()); return new ArrayObject($curatedBatchesArray, $curatedBatches->getHeaders()); }
[ "public", "static", "function", "all", "(", "$", "page", "=", "1", ",", "$", "per_page", "=", "10", ")", "{", "$", "curatedBatches", "=", "self", "::", "get", "(", "\"/collections/curated\"", ",", "[", "'query'", "=>", "[", "'page'", "=>", "$", "page",...
Retrieve all curated batches for a given page @param integer $page Page from which the curated batches need to be retrieved @param integer $per_page Number of elements on a page @return ArrayObject of CuratedBatch
[ "Retrieve", "all", "curated", "batches", "for", "a", "given", "page" ]
train
https://github.com/unsplash/unsplash-php/blob/af907f6192bfd4be9e9814a1242942442604c4de/src/CuratedCollection.php#L34-L44
localheinz/phpstan-rules
src/Methods/NoParameterWithNullableTypeDeclarationRule.php
NoParameterWithNullableTypeDeclarationRule.processNode
public function processNode(Node $node, Scope $scope): array { if (0 === \count($node->params)) { return []; } $params = \array_filter($node->params, static function (Node\Param $node): bool { return $node->type instanceof Node\NullableType; }); if (0 === \count($params)) { return []; } $methodName = $node->name->toString(); /** @var Reflection\ClassReflection $classReflection */ $classReflection = $scope->getClassReflection(); if ($classReflection->isAnonymous()) { return \array_map(static function (Node\Param $node) use ($methodName): string { /** @var Node\Expr\Variable $variable */ $variable = $node->var; /** @var string $parameterName */ $parameterName = $variable->name; return \sprintf( 'Method %s() in anonymous class has parameter $%s with a nullable type declaration.', $methodName, $parameterName ); }, $params); } $className = $classReflection->getName(); return \array_map(static function (Node\Param $node) use ($className, $methodName): string { /** @var Node\Expr\Variable $variable */ $variable = $node->var; /** @var string $parameterName */ $parameterName = $variable->name; return \sprintf( 'Method %s::%s() has parameter $%s with a nullable type declaration.', $className, $methodName, $parameterName ); }, $params); }
php
public function processNode(Node $node, Scope $scope): array { if (0 === \count($node->params)) { return []; } $params = \array_filter($node->params, static function (Node\Param $node): bool { return $node->type instanceof Node\NullableType; }); if (0 === \count($params)) { return []; } $methodName = $node->name->toString(); /** @var Reflection\ClassReflection $classReflection */ $classReflection = $scope->getClassReflection(); if ($classReflection->isAnonymous()) { return \array_map(static function (Node\Param $node) use ($methodName): string { /** @var Node\Expr\Variable $variable */ $variable = $node->var; /** @var string $parameterName */ $parameterName = $variable->name; return \sprintf( 'Method %s() in anonymous class has parameter $%s with a nullable type declaration.', $methodName, $parameterName ); }, $params); } $className = $classReflection->getName(); return \array_map(static function (Node\Param $node) use ($className, $methodName): string { /** @var Node\Expr\Variable $variable */ $variable = $node->var; /** @var string $parameterName */ $parameterName = $variable->name; return \sprintf( 'Method %s::%s() has parameter $%s with a nullable type declaration.', $className, $methodName, $parameterName ); }, $params); }
[ "public", "function", "processNode", "(", "Node", "$", "node", ",", "Scope", "$", "scope", ")", ":", "array", "{", "if", "(", "0", "===", "\\", "count", "(", "$", "node", "->", "params", ")", ")", "{", "return", "[", "]", ";", "}", "$", "params",...
@param Node\Stmt\ClassMethod $node @param Scope $scope @return array
[ "@param", "Node", "\\", "Stmt", "\\", "ClassMethod", "$node", "@param", "Scope", "$scope" ]
train
https://github.com/localheinz/phpstan-rules/blob/f5a704c4df465338025783b5d74a94648320b31b/src/Methods/NoParameterWithNullableTypeDeclarationRule.php#L34-L85
localheinz/phpstan-rules
src/Classes/FinalRule.php
FinalRule.processNode
public function processNode(Node $node, Scope $scope): array { if (!isset($node->namespacedName) || \in_array($node->namespacedName->toString(), $this->classesNotRequiredToBeAbstractOrFinal, true) ) { return []; } if (true === $this->allowAbstractClasses && $node->isAbstract()) { return []; } if ($node->isFinal()) { return []; } return [ \sprintf( $this->errorMessageTemplate, $node->namespacedName ), ]; }
php
public function processNode(Node $node, Scope $scope): array { if (!isset($node->namespacedName) || \in_array($node->namespacedName->toString(), $this->classesNotRequiredToBeAbstractOrFinal, true) ) { return []; } if (true === $this->allowAbstractClasses && $node->isAbstract()) { return []; } if ($node->isFinal()) { return []; } return [ \sprintf( $this->errorMessageTemplate, $node->namespacedName ), ]; }
[ "public", "function", "processNode", "(", "Node", "$", "node", ",", "Scope", "$", "scope", ")", ":", "array", "{", "if", "(", "!", "isset", "(", "$", "node", "->", "namespacedName", ")", "||", "\\", "in_array", "(", "$", "node", "->", "namespacedName",...
@param Node\Stmt\Class_ $node @param Scope $scope @return array
[ "@param", "Node", "\\", "Stmt", "\\", "Class_", "$node", "@param", "Scope", "$scope" ]
train
https://github.com/localheinz/phpstan-rules/blob/f5a704c4df465338025783b5d74a94648320b31b/src/Classes/FinalRule.php#L64-L86
localheinz/phpstan-rules
src/Functions/NoNullableReturnTypeDeclarationRule.php
NoNullableReturnTypeDeclarationRule.processNode
public function processNode(Node $node, Scope $scope): array { if (!isset($node->namespacedName) || !$node->getReturnType() instanceof Node\NullableType) { return []; } return [ \sprintf( 'Function %s() has a nullable return type declaration.', $node->namespacedName ), ]; }
php
public function processNode(Node $node, Scope $scope): array { if (!isset($node->namespacedName) || !$node->getReturnType() instanceof Node\NullableType) { return []; } return [ \sprintf( 'Function %s() has a nullable return type declaration.', $node->namespacedName ), ]; }
[ "public", "function", "processNode", "(", "Node", "$", "node", ",", "Scope", "$", "scope", ")", ":", "array", "{", "if", "(", "!", "isset", "(", "$", "node", "->", "namespacedName", ")", "||", "!", "$", "node", "->", "getReturnType", "(", ")", "insta...
@param Node\Stmt\Function_ $node @param Scope $scope @return array
[ "@param", "Node", "\\", "Stmt", "\\", "Function_", "$node", "@param", "Scope", "$scope" ]
train
https://github.com/localheinz/phpstan-rules/blob/f5a704c4df465338025783b5d74a94648320b31b/src/Functions/NoNullableReturnTypeDeclarationRule.php#L33-L45
localheinz/phpstan-rules
src/Methods/NoParameterWithNullDefaultValueRule.php
NoParameterWithNullDefaultValueRule.processNode
public function processNode(Node $node, Scope $scope): array { if (0 === \count($node->params)) { return []; } $params = \array_filter($node->params, static function (Node\Param $node): bool { if (!$node->default instanceof Node\Expr\ConstFetch) { return false; } return 'null' === $node->default->name->toLowerString(); }); if (0 === \count($params)) { return []; } $methodName = $node->name->toString(); /** @var Reflection\ClassReflection $classReflection */ $classReflection = $scope->getClassReflection(); if ($classReflection->isAnonymous()) { return \array_map(static function (Node\Param $node) use ($methodName): string { /** @var Node\Expr\Variable $variable */ $variable = $node->var; /** @var string $parameterName */ $parameterName = $variable->name; return \sprintf( 'Method %s() in anonymous class has parameter $%s with null as default value.', $methodName, $parameterName ); }, $params); } $className = $classReflection->getName(); return \array_map(static function (Node\Param $node) use ($className, $methodName): string { /** @var Node\Expr\Variable $variable */ $variable = $node->var; /** @var string $parameterName */ $parameterName = $variable->name; return \sprintf( 'Method %s::%s() has parameter $%s with null as default value.', $className, $methodName, $parameterName ); }, $params); }
php
public function processNode(Node $node, Scope $scope): array { if (0 === \count($node->params)) { return []; } $params = \array_filter($node->params, static function (Node\Param $node): bool { if (!$node->default instanceof Node\Expr\ConstFetch) { return false; } return 'null' === $node->default->name->toLowerString(); }); if (0 === \count($params)) { return []; } $methodName = $node->name->toString(); /** @var Reflection\ClassReflection $classReflection */ $classReflection = $scope->getClassReflection(); if ($classReflection->isAnonymous()) { return \array_map(static function (Node\Param $node) use ($methodName): string { /** @var Node\Expr\Variable $variable */ $variable = $node->var; /** @var string $parameterName */ $parameterName = $variable->name; return \sprintf( 'Method %s() in anonymous class has parameter $%s with null as default value.', $methodName, $parameterName ); }, $params); } $className = $classReflection->getName(); return \array_map(static function (Node\Param $node) use ($className, $methodName): string { /** @var Node\Expr\Variable $variable */ $variable = $node->var; /** @var string $parameterName */ $parameterName = $variable->name; return \sprintf( 'Method %s::%s() has parameter $%s with null as default value.', $className, $methodName, $parameterName ); }, $params); }
[ "public", "function", "processNode", "(", "Node", "$", "node", ",", "Scope", "$", "scope", ")", ":", "array", "{", "if", "(", "0", "===", "\\", "count", "(", "$", "node", "->", "params", ")", ")", "{", "return", "[", "]", ";", "}", "$", "params",...
@param Node\Stmt\ClassMethod $node @param Scope $scope @return array
[ "@param", "Node", "\\", "Stmt", "\\", "ClassMethod", "$node", "@param", "Scope", "$scope" ]
train
https://github.com/localheinz/phpstan-rules/blob/f5a704c4df465338025783b5d74a94648320b31b/src/Methods/NoParameterWithNullDefaultValueRule.php#L34-L89
localheinz/phpstan-rules
src/Methods/NoNullableReturnTypeDeclarationRule.php
NoNullableReturnTypeDeclarationRule.processNode
public function processNode(Node $node, Scope $scope): array { $returnType = $node->getReturnType(); if (!$returnType instanceof Node\NullableType) { return []; } /** @var Reflection\ClassReflection $classReflection */ $classReflection = $scope->getClassReflection(); if ($classReflection->isAnonymous()) { return [ \sprintf( 'Method %s() in anonymous class has a nullable return type declaration.', $node->name->name ), ]; } return [ \sprintf( 'Method %s::%s() has a nullable return type declaration.', $classReflection->getName(), $node->name->name ), ]; }
php
public function processNode(Node $node, Scope $scope): array { $returnType = $node->getReturnType(); if (!$returnType instanceof Node\NullableType) { return []; } /** @var Reflection\ClassReflection $classReflection */ $classReflection = $scope->getClassReflection(); if ($classReflection->isAnonymous()) { return [ \sprintf( 'Method %s() in anonymous class has a nullable return type declaration.', $node->name->name ), ]; } return [ \sprintf( 'Method %s::%s() has a nullable return type declaration.', $classReflection->getName(), $node->name->name ), ]; }
[ "public", "function", "processNode", "(", "Node", "$", "node", ",", "Scope", "$", "scope", ")", ":", "array", "{", "$", "returnType", "=", "$", "node", "->", "getReturnType", "(", ")", ";", "if", "(", "!", "$", "returnType", "instanceof", "Node", "\\",...
@param Node\Stmt\ClassMethod $node @param Scope $scope @return array
[ "@param", "Node", "\\", "Stmt", "\\", "ClassMethod", "$node", "@param", "Scope", "$scope" ]
train
https://github.com/localheinz/phpstan-rules/blob/f5a704c4df465338025783b5d74a94648320b31b/src/Methods/NoNullableReturnTypeDeclarationRule.php#L34-L61
localheinz/phpstan-rules
src/Methods/NoConstructorParameterWithDefaultValueRule.php
NoConstructorParameterWithDefaultValueRule.processNode
public function processNode(Node $node, Scope $scope): array { if ('__construct' !== $node->name->toLowerString()) { return []; } if (0 === \count($node->params)) { return []; } $params = \array_filter($node->params, static function (Node\Param $node): bool { return null !== $node->default; }); if (0 === \count($params)) { return []; } /** @var Reflection\ClassReflection $classReflection */ $classReflection = $scope->getClassReflection(); if ($classReflection->isAnonymous()) { return \array_map(static function (Node\Param $node): string { /** @var Node\Expr\Variable $variable */ $variable = $node->var; /** @var string $parameterName */ $parameterName = $variable->name; return \sprintf( 'Constructor in anonymous class has parameter $%s with default value.', $parameterName ); }, $params); } $className = $classReflection->getName(); return \array_map(static function (Node\Param $node) use ($className): string { /** @var Node\Expr\Variable $variable */ $variable = $node->var; /** @var string $parameterName */ $parameterName = $variable->name; return \sprintf( 'Constructor in %s has parameter $%s with default value.', $className, $parameterName ); }, $params); }
php
public function processNode(Node $node, Scope $scope): array { if ('__construct' !== $node->name->toLowerString()) { return []; } if (0 === \count($node->params)) { return []; } $params = \array_filter($node->params, static function (Node\Param $node): bool { return null !== $node->default; }); if (0 === \count($params)) { return []; } /** @var Reflection\ClassReflection $classReflection */ $classReflection = $scope->getClassReflection(); if ($classReflection->isAnonymous()) { return \array_map(static function (Node\Param $node): string { /** @var Node\Expr\Variable $variable */ $variable = $node->var; /** @var string $parameterName */ $parameterName = $variable->name; return \sprintf( 'Constructor in anonymous class has parameter $%s with default value.', $parameterName ); }, $params); } $className = $classReflection->getName(); return \array_map(static function (Node\Param $node) use ($className): string { /** @var Node\Expr\Variable $variable */ $variable = $node->var; /** @var string $parameterName */ $parameterName = $variable->name; return \sprintf( 'Constructor in %s has parameter $%s with default value.', $className, $parameterName ); }, $params); }
[ "public", "function", "processNode", "(", "Node", "$", "node", ",", "Scope", "$", "scope", ")", ":", "array", "{", "if", "(", "'__construct'", "!==", "$", "node", "->", "name", "->", "toLowerString", "(", ")", ")", "{", "return", "[", "]", ";", "}", ...
@param Node\Stmt\ClassMethod $node @param Scope $scope @return array
[ "@param", "Node", "\\", "Stmt", "\\", "ClassMethod", "$node", "@param", "Scope", "$scope" ]
train
https://github.com/localheinz/phpstan-rules/blob/f5a704c4df465338025783b5d74a94648320b31b/src/Methods/NoConstructorParameterWithDefaultValueRule.php#L34-L85
localheinz/phpstan-rules
src/Functions/NoParameterWithNullableTypeDeclarationRule.php
NoParameterWithNullableTypeDeclarationRule.processNode
public function processNode(Node $node, Scope $scope): array { if (0 === \count($node->params)) { return []; } $params = \array_filter($node->params, static function (Node\Param $node): bool { return $node->type instanceof Node\NullableType; }); if (0 === \count($params)) { return []; } $functionName = $node->namespacedName; return \array_map(static function (Node\Param $node) use ($functionName): string { /** @var Node\Expr\Variable $variable */ $variable = $node->var; /** @var string $parameterName */ $parameterName = $variable->name; return \sprintf( 'Function %s() has parameter $%s with a nullable type declaration.', $functionName, $parameterName ); }, $params); }
php
public function processNode(Node $node, Scope $scope): array { if (0 === \count($node->params)) { return []; } $params = \array_filter($node->params, static function (Node\Param $node): bool { return $node->type instanceof Node\NullableType; }); if (0 === \count($params)) { return []; } $functionName = $node->namespacedName; return \array_map(static function (Node\Param $node) use ($functionName): string { /** @var Node\Expr\Variable $variable */ $variable = $node->var; /** @var string $parameterName */ $parameterName = $variable->name; return \sprintf( 'Function %s() has parameter $%s with a nullable type declaration.', $functionName, $parameterName ); }, $params); }
[ "public", "function", "processNode", "(", "Node", "$", "node", ",", "Scope", "$", "scope", ")", ":", "array", "{", "if", "(", "0", "===", "\\", "count", "(", "$", "node", "->", "params", ")", ")", "{", "return", "[", "]", ";", "}", "$", "params",...
@param Node\Stmt\Function_ $node @param Scope $scope @return array
[ "@param", "Node", "\\", "Stmt", "\\", "Function_", "$node", "@param", "Scope", "$scope" ]
train
https://github.com/localheinz/phpstan-rules/blob/f5a704c4df465338025783b5d74a94648320b31b/src/Functions/NoParameterWithNullableTypeDeclarationRule.php#L33-L62
localheinz/phpstan-rules
src/Classes/NoExtendsRule.php
NoExtendsRule.processNode
public function processNode(Node $node, Scope $scope): array { if (!$node->extends instanceof Node\Name) { return []; } $extendedClassName = $node->extends->toString(); if (\in_array($extendedClassName, $this->classesAllowedToBeExtended, true)) { return []; } if (!isset($node->namespacedName)) { return [ \sprintf( 'Anonymous class is not allowed to extend "%s".', $extendedClassName ), ]; } return [ \sprintf( 'Class "%s" is not allowed to extend "%s".', $node->namespacedName, $extendedClassName ), ]; }
php
public function processNode(Node $node, Scope $scope): array { if (!$node->extends instanceof Node\Name) { return []; } $extendedClassName = $node->extends->toString(); if (\in_array($extendedClassName, $this->classesAllowedToBeExtended, true)) { return []; } if (!isset($node->namespacedName)) { return [ \sprintf( 'Anonymous class is not allowed to extend "%s".', $extendedClassName ), ]; } return [ \sprintf( 'Class "%s" is not allowed to extend "%s".', $node->namespacedName, $extendedClassName ), ]; }
[ "public", "function", "processNode", "(", "Node", "$", "node", ",", "Scope", "$", "scope", ")", ":", "array", "{", "if", "(", "!", "$", "node", "->", "extends", "instanceof", "Node", "\\", "Name", ")", "{", "return", "[", "]", ";", "}", "$", "exten...
@param Node\Stmt\Class_ $node @param Scope $scope @return array
[ "@param", "Node", "\\", "Stmt", "\\", "Class_", "$node", "@param", "Scope", "$scope" ]
train
https://github.com/localheinz/phpstan-rules/blob/f5a704c4df465338025783b5d74a94648320b31b/src/Classes/NoExtendsRule.php#L58-L86
localheinz/phpstan-rules
src/Closures/NoParameterWithNullDefaultValueRule.php
NoParameterWithNullDefaultValueRule.processNode
public function processNode(Node $node, Scope $scope): array { if (0 === \count($node->params)) { return []; } $params = \array_filter($node->params, static function (Node\Param $node): bool { if (!$node->default instanceof Node\Expr\ConstFetch) { return false; } return 'null' === $node->default->name->toLowerString(); }); if (0 === \count($params)) { return []; } return \array_map(static function (Node\Param $node): string { /** @var Node\Expr\Variable $variable */ $variable = $node->var; /** @var string $parameterName */ $parameterName = $variable->name; return \sprintf( 'Closure has parameter $%s with null as default value.', $parameterName ); }, $params); }
php
public function processNode(Node $node, Scope $scope): array { if (0 === \count($node->params)) { return []; } $params = \array_filter($node->params, static function (Node\Param $node): bool { if (!$node->default instanceof Node\Expr\ConstFetch) { return false; } return 'null' === $node->default->name->toLowerString(); }); if (0 === \count($params)) { return []; } return \array_map(static function (Node\Param $node): string { /** @var Node\Expr\Variable $variable */ $variable = $node->var; /** @var string $parameterName */ $parameterName = $variable->name; return \sprintf( 'Closure has parameter $%s with null as default value.', $parameterName ); }, $params); }
[ "public", "function", "processNode", "(", "Node", "$", "node", ",", "Scope", "$", "scope", ")", ":", "array", "{", "if", "(", "0", "===", "\\", "count", "(", "$", "node", "->", "params", ")", ")", "{", "return", "[", "]", ";", "}", "$", "params",...
@param Node\Expr\Closure $node @param Scope $scope @return array
[ "@param", "Node", "\\", "Expr", "\\", "Closure", "$node", "@param", "Scope", "$scope" ]
train
https://github.com/localheinz/phpstan-rules/blob/f5a704c4df465338025783b5d74a94648320b31b/src/Closures/NoParameterWithNullDefaultValueRule.php#L33-L63
igaster/laravel_cities
src/Geo.php
Geo.searchNames
public static function searchNames($name, Geo $parent =null){ $query = self::search($name)->orderBy('name', 'ASC'); if ($parent){ $query->areDescentants($parent); } return $query->get(); }
php
public static function searchNames($name, Geo $parent =null){ $query = self::search($name)->orderBy('name', 'ASC'); if ($parent){ $query->areDescentants($parent); } return $query->get(); }
[ "public", "static", "function", "searchNames", "(", "$", "name", ",", "Geo", "$", "parent", "=", "null", ")", "{", "$", "query", "=", "self", "::", "search", "(", "$", "name", ")", "->", "orderBy", "(", "'name'", ",", "'ASC'", ")", ";", "if", "(", ...
search in `name` and `alternames` / return collection
[ "search", "in", "name", "and", "alternames", "/", "return", "collection" ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/Geo.php#L106-L114
igaster/laravel_cities
src/Geo.php
Geo.isChildOf
public function isChildOf(Geo $item){ return ($this->left > $item->left) && ($this->right < $item->right) && ($this->depth == $item->depth+1); }
php
public function isChildOf(Geo $item){ return ($this->left > $item->left) && ($this->right < $item->right) && ($this->depth == $item->depth+1); }
[ "public", "function", "isChildOf", "(", "Geo", "$", "item", ")", "{", "return", "(", "$", "this", "->", "left", ">", "$", "item", "->", "left", ")", "&&", "(", "$", "this", "->", "right", "<", "$", "item", "->", "right", ")", "&&", "(", "$", "t...
is imediate Child of $item ?
[ "is", "imediate", "Child", "of", "$item", "?" ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/Geo.php#L132-L134
igaster/laravel_cities
src/Geo.php
Geo.isParentOf
public function isParentOf(Geo $item){ return ($this->left < $item->left) && ($this->right > $item->right) && ($this->depth == $item->depth-1); }
php
public function isParentOf(Geo $item){ return ($this->left < $item->left) && ($this->right > $item->right) && ($this->depth == $item->depth-1); }
[ "public", "function", "isParentOf", "(", "Geo", "$", "item", ")", "{", "return", "(", "$", "this", "->", "left", "<", "$", "item", "->", "left", ")", "&&", "(", "$", "this", "->", "right", ">", "$", "item", "->", "right", ")", "&&", "(", "$", "...
is imediate Parent of $item ?
[ "is", "imediate", "Parent", "of", "$item", "?" ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/Geo.php#L137-L139
igaster/laravel_cities
src/Geo.php
Geo.isDescendantOf
public function isDescendantOf(Geo $item){ return ($this->left > $item->left) && ($this->right < $item->right); }
php
public function isDescendantOf(Geo $item){ return ($this->left > $item->left) && ($this->right < $item->right); }
[ "public", "function", "isDescendantOf", "(", "Geo", "$", "item", ")", "{", "return", "(", "$", "this", "->", "left", ">", "$", "item", "->", "left", ")", "&&", "(", "$", "this", "->", "right", "<", "$", "item", "->", "right", ")", ";", "}" ]
is Child of $item (any depth) ?
[ "is", "Child", "of", "$item", "(", "any", "depth", ")", "?" ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/Geo.php#L142-L144
igaster/laravel_cities
src/Geo.php
Geo.isAncenstorOf
public function isAncenstorOf(Geo $item){ return ($this->left < $item->left) && ($this->right > $item->right); }
php
public function isAncenstorOf(Geo $item){ return ($this->left < $item->left) && ($this->right > $item->right); }
[ "public", "function", "isAncenstorOf", "(", "Geo", "$", "item", ")", "{", "return", "(", "$", "this", "->", "left", "<", "$", "item", "->", "left", ")", "&&", "(", "$", "this", "->", "right", ">", "$", "item", "->", "right", ")", ";", "}" ]
is Parent of $item (any depth) ?
[ "is", "Parent", "of", "$item", "(", "any", "depth", ")", "?" ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/Geo.php#L147-L149
igaster/laravel_cities
src/Geo.php
Geo.fliterFields
public function fliterFields($fields = null){ if (is_string($fields)){ // Comma Seperated List (eg Url Param) $fields = explode(',', $fields); } if(empty($fields)){ $this->hidden = []; } else { $this->hidden = ['id','parent_id','left','right','depth','name','alternames','country','level','population','lat','long']; foreach ($fields as $field) { $index = array_search($field, $this->hidden); if($index !== false){ unset($this->hidden[$index]); } }; $this->hidden = array_values($this->hidden); } return $this; }
php
public function fliterFields($fields = null){ if (is_string($fields)){ // Comma Seperated List (eg Url Param) $fields = explode(',', $fields); } if(empty($fields)){ $this->hidden = []; } else { $this->hidden = ['id','parent_id','left','right','depth','name','alternames','country','level','population','lat','long']; foreach ($fields as $field) { $index = array_search($field, $this->hidden); if($index !== false){ unset($this->hidden[$index]); } }; $this->hidden = array_values($this->hidden); } return $this; }
[ "public", "function", "fliterFields", "(", "$", "fields", "=", "null", ")", "{", "if", "(", "is_string", "(", "$", "fields", ")", ")", "{", "// Comma Seperated List (eg Url Param)\r", "$", "fields", "=", "explode", "(", "','", ",", "$", "fields", ")", ";",...
Return only $fields as Json. null = Show all
[ "Return", "only", "$fields", "as", "Json", ".", "null", "=", "Show", "all" ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/Geo.php#L179-L199
igaster/laravel_cities
src/Geo.php
Geo.ApiRoutes
public static function ApiRoutes(){ Route::group(['prefix' => 'geo'], function(){ Route::get('search/{name}/{parent_id?}', '\Igaster\LaravelCities\GeoController@search'); Route::get('item/{id}', '\Igaster\LaravelCities\GeoController@item'); Route::get('items/{ids}', '\Igaster\LaravelCities\GeoController@items'); Route::get('children/{id}', '\Igaster\LaravelCities\GeoController@children'); Route::get('parent/{id}', '\Igaster\LaravelCities\GeoController@parent'); Route::get('country/{code}', '\Igaster\LaravelCities\GeoController@country'); Route::get('countries', '\Igaster\LaravelCities\GeoController@countries'); }); }
php
public static function ApiRoutes(){ Route::group(['prefix' => 'geo'], function(){ Route::get('search/{name}/{parent_id?}', '\Igaster\LaravelCities\GeoController@search'); Route::get('item/{id}', '\Igaster\LaravelCities\GeoController@item'); Route::get('items/{ids}', '\Igaster\LaravelCities\GeoController@items'); Route::get('children/{id}', '\Igaster\LaravelCities\GeoController@children'); Route::get('parent/{id}', '\Igaster\LaravelCities\GeoController@parent'); Route::get('country/{code}', '\Igaster\LaravelCities\GeoController@country'); Route::get('countries', '\Igaster\LaravelCities\GeoController@countries'); }); }
[ "public", "static", "function", "ApiRoutes", "(", ")", "{", "Route", "::", "group", "(", "[", "'prefix'", "=>", "'geo'", "]", ",", "function", "(", ")", "{", "Route", "::", "get", "(", "'search/{name}/{parent_id?}'", ",", "'\\Igaster\\LaravelCities\\GeoControlle...
----------------------------------------------
[ "----------------------------------------------" ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/Geo.php#L205-L215
igaster/laravel_cities
src/GeoServiceProvider.php
GeoServiceProvider.boot
public function boot() { // Load migrations $this->loadMigrationsFrom(__DIR__.'/migrations'); // Load Routes // $this->loadRoutesFrom(__DIR__.'/routes.php'); $this->publishes([ __DIR__.'/vue' => resource_path('LaravelCities'), ], 'vue'); // Register Commands if ($this->app->runningInConsole()) { $this->commands([ \Igaster\LaravelCities\commands\seedGeoFile::class, \Igaster\LaravelCities\commands\seedJsonFile::class, ]); } }
php
public function boot() { // Load migrations $this->loadMigrationsFrom(__DIR__.'/migrations'); // Load Routes // $this->loadRoutesFrom(__DIR__.'/routes.php'); $this->publishes([ __DIR__.'/vue' => resource_path('LaravelCities'), ], 'vue'); // Register Commands if ($this->app->runningInConsole()) { $this->commands([ \Igaster\LaravelCities\commands\seedGeoFile::class, \Igaster\LaravelCities\commands\seedJsonFile::class, ]); } }
[ "public", "function", "boot", "(", ")", "{", "// Load migrations\r", "$", "this", "->", "loadMigrationsFrom", "(", "__DIR__", ".", "'/migrations'", ")", ";", "// Load Routes\r", "// $this->loadRoutesFrom(__DIR__.'/routes.php');\r", "$", "this", "->", "publishes", "(", ...
Bootstrap any application services. @return void
[ "Bootstrap", "any", "application", "services", "." ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/GeoServiceProvider.php#L21-L42
igaster/laravel_cities
src/GeoController.php
GeoController.applyFilter
protected function applyFilter($geo){ if (request()->has('fields')){ if(get_class($geo) == \Illuminate\Database\Eloquent\Collection::class){ foreach ($geo as $item) { $this->applyFilter($item); }; return $geo; } $fields = request()->input('fields'); if($fields == 'all'){ $geo->fliterFields(); } else { $fields = explode(',', $fields); array_walk($fields, function(&$item){ $item = strtolower(trim($item)); }); $geo->fliterFields($fields); } } return $geo; }
php
protected function applyFilter($geo){ if (request()->has('fields')){ if(get_class($geo) == \Illuminate\Database\Eloquent\Collection::class){ foreach ($geo as $item) { $this->applyFilter($item); }; return $geo; } $fields = request()->input('fields'); if($fields == 'all'){ $geo->fliterFields(); } else { $fields = explode(',', $fields); array_walk($fields, function(&$item){ $item = strtolower(trim($item)); }); $geo->fliterFields($fields); } } return $geo; }
[ "protected", "function", "applyFilter", "(", "$", "geo", ")", "{", "if", "(", "request", "(", ")", "->", "has", "(", "'fields'", ")", ")", "{", "if", "(", "get_class", "(", "$", "geo", ")", "==", "\\", "Illuminate", "\\", "Database", "\\", "Eloquent"...
api/call?fields=field1,field2
[ "api", "/", "call?fields", "=", "field1", "field2" ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/GeoController.php#L9-L31
igaster/laravel_cities
src/GeoController.php
GeoController.item
public function item($id){ $geo = Geo::find($id); $this->applyFilter($geo); return \Response::json($geo); }
php
public function item($id){ $geo = Geo::find($id); $this->applyFilter($geo); return \Response::json($geo); }
[ "public", "function", "item", "(", "$", "id", ")", "{", "$", "geo", "=", "Geo", "::", "find", "(", "$", "id", ")", ";", "$", "this", "->", "applyFilter", "(", "$", "geo", ")", ";", "return", "\\", "Response", "::", "json", "(", "$", "geo", ")",...
[Geo] Get an item by $id
[ "[", "Geo", "]", "Get", "an", "item", "by", "$id" ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/GeoController.php#L34-L38
igaster/laravel_cities
src/GeoController.php
GeoController.items
public function items($ids = []){ if(is_string($ids)){ $ids=explode(',', $ids); } $items = Geo::getByIds($ids); return \Response::json($items); }
php
public function items($ids = []){ if(is_string($ids)){ $ids=explode(',', $ids); } $items = Geo::getByIds($ids); return \Response::json($items); }
[ "public", "function", "items", "(", "$", "ids", "=", "[", "]", ")", "{", "if", "(", "is_string", "(", "$", "ids", ")", ")", "{", "$", "ids", "=", "explode", "(", "','", ",", "$", "ids", ")", ";", "}", "$", "items", "=", "Geo", "::", "getByIds...
[Collection] Get multiple items by ids (comma seperated string or array)
[ "[", "Collection", "]", "Get", "multiple", "items", "by", "ids", "(", "comma", "seperated", "string", "or", "array", ")" ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/GeoController.php#L41-L48
igaster/laravel_cities
src/GeoController.php
GeoController.parent
public function parent($id){ $geo = Geo::find($id)->getParent(); $this->applyFilter($geo); return \Response::json($geo); }
php
public function parent($id){ $geo = Geo::find($id)->getParent(); $this->applyFilter($geo); return \Response::json($geo); }
[ "public", "function", "parent", "(", "$", "id", ")", "{", "$", "geo", "=", "Geo", "::", "find", "(", "$", "id", ")", "->", "getParent", "(", ")", ";", "$", "this", "->", "applyFilter", "(", "$", "geo", ")", ";", "return", "\\", "Response", "::", ...
[Geo] Get parent of $id
[ "[", "Geo", "]", "Get", "parent", "of", "$id" ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/GeoController.php#L56-L60
igaster/laravel_cities
src/GeoController.php
GeoController.country
public function country($code){ $geo = Geo::getCountry($code); $this->applyFilter($geo); return \Response::json($geo); }
php
public function country($code){ $geo = Geo::getCountry($code); $this->applyFilter($geo); return \Response::json($geo); }
[ "public", "function", "country", "(", "$", "code", ")", "{", "$", "geo", "=", "Geo", "::", "getCountry", "(", "$", "code", ")", ";", "$", "this", "->", "applyFilter", "(", "$", "geo", ")", ";", "return", "\\", "Response", "::", "json", "(", "$", ...
[Geo] Get country by $code (two letter code)
[ "[", "Geo", "]", "Get", "country", "by", "$code", "(", "two", "letter", "code", ")" ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/GeoController.php#L63-L67
igaster/laravel_cities
src/GeoController.php
GeoController.search
public function search($name,$parent_id = null){ if ($parent_id) return $this->applyFilter(Geo::searchNames($name, Geo::find($parent_id))); else return $this->applyFilter(Geo::searchNames($name)); }
php
public function search($name,$parent_id = null){ if ($parent_id) return $this->applyFilter(Geo::searchNames($name, Geo::find($parent_id))); else return $this->applyFilter(Geo::searchNames($name)); }
[ "public", "function", "search", "(", "$", "name", ",", "$", "parent_id", "=", "null", ")", "{", "if", "(", "$", "parent_id", ")", "return", "$", "this", "->", "applyFilter", "(", "Geo", "::", "searchNames", "(", "$", "name", ",", "Geo", "::", "find",...
[Collection] Search for %$name% in 'name' and 'alternames'. Optional filter to children of $parent_id
[ "[", "Collection", "]", "Search", "for", "%$name%", "in", "name", "and", "alternames", ".", "Optional", "filter", "to", "children", "of", "$parent_id" ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/GeoController.php#L75-L80
igaster/laravel_cities
src/migrations/2017_02_13_090952_geo.php
Geo.up
public function up() { if (!Schema::hasTable('geo')) { Schema::create('geo', function (Blueprint $table) { $table->increments('id'); $table->integer('parent_id')->nullable(); $table->integer('left')->nullable(); $table->integer('right')->nullable(); $table->integer('depth')->default(0); // $table->integer('geoid'); $table->char('name', 60); $table->json('alternames'); $table->char('country', 2); $table->char('level', 10); $table->bigInteger('population'); $table->decimal('lat',9,6); $table->decimal('long',9,6); }); } }
php
public function up() { if (!Schema::hasTable('geo')) { Schema::create('geo', function (Blueprint $table) { $table->increments('id'); $table->integer('parent_id')->nullable(); $table->integer('left')->nullable(); $table->integer('right')->nullable(); $table->integer('depth')->default(0); // $table->integer('geoid'); $table->char('name', 60); $table->json('alternames'); $table->char('country', 2); $table->char('level', 10); $table->bigInteger('population'); $table->decimal('lat',9,6); $table->decimal('long',9,6); }); } }
[ "public", "function", "up", "(", ")", "{", "if", "(", "!", "Schema", "::", "hasTable", "(", "'geo'", ")", ")", "{", "Schema", "::", "create", "(", "'geo'", ",", "function", "(", "Blueprint", "$", "table", ")", "{", "$", "table", "->", "increments", ...
Run the migrations. @return void
[ "Run", "the", "migrations", "." ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/migrations/2017_02_13_090952_geo.php#L14-L33
igaster/laravel_cities
src/dbTree/EloquentTreeItem.php
EloquentTreeItem.getItem
private static function getItem($id){ if(!isset(self::$items[$id])) throw new \Exception("Item $id not found"); return self::$items[$id]; }
php
private static function getItem($id){ if(!isset(self::$items[$id])) throw new \Exception("Item $id not found"); return self::$items[$id]; }
[ "private", "static", "function", "getItem", "(", "$", "id", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "items", "[", "$", "id", "]", ")", ")", "throw", "new", "\\", "Exception", "(", "\"Item $id not found\"", ")", ";", "return", "self...
Get item by id
[ "Get", "item", "by", "id" ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/dbTree/EloquentTreeItem.php#L57-L62
igaster/laravel_cities
src/commands/truncTable.php
truncTable.handle
public function handle() { /* * Some Time You need to have relation to this model * So first Laravel should ignore this. */ \Eloquent::unguard(); \DB::statement('SET FOREIGN_KEY_CHECKS=0;'); $this->info('Relation checks disabled'); \DB::table('geo')->truncate(); $this->info('Table "geo" is empty now.'); }
php
public function handle() { /* * Some Time You need to have relation to this model * So first Laravel should ignore this. */ \Eloquent::unguard(); \DB::statement('SET FOREIGN_KEY_CHECKS=0;'); $this->info('Relation checks disabled'); \DB::table('geo')->truncate(); $this->info('Table "geo" is empty now.'); }
[ "public", "function", "handle", "(", ")", "{", "/*\n * Some Time You need to have relation to this model\n * So first Laravel should ignore this.\n */", "\\", "Eloquent", "::", "unguard", "(", ")", ";", "\\", "DB", "::", "statement", "(", "'SET FOREIGN...
Execute the console command. @return mixed
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/igaster/laravel_cities/blob/d420c16813149af3257438097b0ccf6325e8f51e/src/commands/truncTable.php#L36-L47
wohali/oauth2-discord-new
src/Provider/Discord.php
Discord.checkResponse
protected function checkResponse(ResponseInterface $response, $data) { if ($response->getStatusCode() >= 400) { throw DiscordIdentityProviderException::clientException($response, $data); } }
php
protected function checkResponse(ResponseInterface $response, $data) { if ($response->getStatusCode() >= 400) { throw DiscordIdentityProviderException::clientException($response, $data); } }
[ "protected", "function", "checkResponse", "(", "ResponseInterface", "$", "response", ",", "$", "data", ")", "{", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", ">=", "400", ")", "{", "throw", "DiscordIdentityProviderException", "::", "clientExcepti...
Check a provider response for errors. @throws IdentityProviderException @param ResponseInterface @response @param array $data Parsed response data @return void
[ "Check", "a", "provider", "response", "for", "errors", "." ]
train
https://github.com/wohali/oauth2-discord-new/blob/1a799f8e4183390e6905be7198bc4f45f3981f38/src/Provider/Discord.php#L107-L112
wohali/oauth2-discord-new
src/Provider/Exception/DiscordIdentityProviderException.php
DiscordIdentityProviderException.clientException
public static function clientException(ResponseInterface $response, $data) { return static::fromResponse( $response, isset($data['message']) ? $data['message'] : json_encode($data) ); }
php
public static function clientException(ResponseInterface $response, $data) { return static::fromResponse( $response, isset($data['message']) ? $data['message'] : json_encode($data) ); }
[ "public", "static", "function", "clientException", "(", "ResponseInterface", "$", "response", ",", "$", "data", ")", "{", "return", "static", "::", "fromResponse", "(", "$", "response", ",", "isset", "(", "$", "data", "[", "'message'", "]", ")", "?", "$", ...
Creates client exception from response @param ResponseInterface $response @param array $data Parsed response data @return IdentityProviderException
[ "Creates", "client", "exception", "from", "response" ]
train
https://github.com/wohali/oauth2-discord-new/blob/1a799f8e4183390e6905be7198bc4f45f3981f38/src/Provider/Exception/DiscordIdentityProviderException.php#L29-L35
thenbsp/wechat
src/Payment/Qrcode/Forever.php
Forever.getPayurl
public function getPayurl($productId, array $defaults = []) { $defaultOptions = [ 'appid' => $this['appid'], 'mch_id' => $this['mch_id'], 'time_stamp' => Util::getTimestamp(), 'nonce_str' => Util::getRandomString(), ]; $options = array_replace($defaultOptions, $defaults); $options['product_id'] = $productId; // 按 ASCII 码排序 ksort($options); $signature = urldecode(http_build_query($options)); $signature = strtoupper(md5($signature.'&key='.$this->key)); $options['sign'] = $signature; $query = http_build_query($options); return self::PAYMENT_URL.'?'.urlencode($query); }
php
public function getPayurl($productId, array $defaults = []) { $defaultOptions = [ 'appid' => $this['appid'], 'mch_id' => $this['mch_id'], 'time_stamp' => Util::getTimestamp(), 'nonce_str' => Util::getRandomString(), ]; $options = array_replace($defaultOptions, $defaults); $options['product_id'] = $productId; // 按 ASCII 码排序 ksort($options); $signature = urldecode(http_build_query($options)); $signature = strtoupper(md5($signature.'&key='.$this->key)); $options['sign'] = $signature; $query = http_build_query($options); return self::PAYMENT_URL.'?'.urlencode($query); }
[ "public", "function", "getPayurl", "(", "$", "productId", ",", "array", "$", "defaults", "=", "[", "]", ")", "{", "$", "defaultOptions", "=", "[", "'appid'", "=>", "$", "this", "[", "'appid'", "]", ",", "'mch_id'", "=>", "$", "this", "[", "'mch_id'", ...
获取支付链接.
[ "获取支付链接", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/Payment/Qrcode/Forever.php#L34-L57
thenbsp/wechat
src/OAuth/AccessToken.php
AccessToken.getUser
public function getUser($lang = 'zh_CN') { if (!$this->isValid()) { $this->refresh(); } $query = [ 'access_token' => $this['access_token'], 'openid' => $this['openid'], 'lang' => $lang, ]; $response = Http::request('GET', static::USERINFO) ->withQuery($query) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return $response; }
php
public function getUser($lang = 'zh_CN') { if (!$this->isValid()) { $this->refresh(); } $query = [ 'access_token' => $this['access_token'], 'openid' => $this['openid'], 'lang' => $lang, ]; $response = Http::request('GET', static::USERINFO) ->withQuery($query) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return $response; }
[ "public", "function", "getUser", "(", "$", "lang", "=", "'zh_CN'", ")", "{", "if", "(", "!", "$", "this", "->", "isValid", "(", ")", ")", "{", "$", "this", "->", "refresh", "(", ")", ";", "}", "$", "query", "=", "[", "'access_token'", "=>", "$", ...
获取用户信息.
[ "获取用户信息", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/OAuth/AccessToken.php#L51-L72
thenbsp/wechat
src/OAuth/AccessToken.php
AccessToken.refresh
public function refresh() { $query = [ 'appid' => $this->appid, 'grant_type' => 'refresh_token', 'refresh_token' => $this['refresh_token'], ]; $response = Http::request('GET', static::REFRESH) ->withQuery($query) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } // update new access_token from ArrayCollection parent::__construct($response->toArray()); return $this; }
php
public function refresh() { $query = [ 'appid' => $this->appid, 'grant_type' => 'refresh_token', 'refresh_token' => $this['refresh_token'], ]; $response = Http::request('GET', static::REFRESH) ->withQuery($query) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } // update new access_token from ArrayCollection parent::__construct($response->toArray()); return $this; }
[ "public", "function", "refresh", "(", ")", "{", "$", "query", "=", "[", "'appid'", "=>", "$", "this", "->", "appid", ",", "'grant_type'", "=>", "'refresh_token'", ",", "'refresh_token'", "=>", "$", "this", "[", "'refresh_token'", "]", ",", "]", ";", "$",...
刷新用户 access_token.
[ "刷新用户", "access_token", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/OAuth/AccessToken.php#L77-L97
thenbsp/wechat
src/OAuth/AccessToken.php
AccessToken.isValid
public function isValid() { $query = [ 'access_token' => $this['access_token'], 'openid' => $this['openid'], ]; $response = Http::request('GET', static::IS_VALID) ->withQuery($query) ->send(); return 'ok' === $response['errmsg']; }
php
public function isValid() { $query = [ 'access_token' => $this['access_token'], 'openid' => $this['openid'], ]; $response = Http::request('GET', static::IS_VALID) ->withQuery($query) ->send(); return 'ok' === $response['errmsg']; }
[ "public", "function", "isValid", "(", ")", "{", "$", "query", "=", "[", "'access_token'", "=>", "$", "this", "[", "'access_token'", "]", ",", "'openid'", "=>", "$", "this", "[", "'openid'", "]", ",", "]", ";", "$", "response", "=", "Http", "::", "req...
检测用户 access_token 是否有效.
[ "检测用户", "access_token", "是否有效", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/OAuth/AccessToken.php#L102-L114
thenbsp/wechat
src/Wechat/Jsapi/Ticket.php
Ticket.getTicketString
public function getTicketString() { $cacheId = $this->getCacheId(); if ($this->cache && $data = $this->cache->fetch($cacheId)) { return $data['ticket']; } $response = $this->getTicketResponse(); if ($this->cache) { $this->cache->save($cacheId, $response, $response['expires_in']); } return $response['ticket']; }
php
public function getTicketString() { $cacheId = $this->getCacheId(); if ($this->cache && $data = $this->cache->fetch($cacheId)) { return $data['ticket']; } $response = $this->getTicketResponse(); if ($this->cache) { $this->cache->save($cacheId, $response, $response['expires_in']); } return $response['ticket']; }
[ "public", "function", "getTicketString", "(", ")", "{", "$", "cacheId", "=", "$", "this", "->", "getCacheId", "(", ")", ";", "if", "(", "$", "this", "->", "cache", "&&", "$", "data", "=", "$", "this", "->", "cache", "->", "fetch", "(", "$", "cacheI...
获取 Jsapi 票据(调用缓存,返回 String).
[ "获取", "Jsapi", "票据(调用缓存,返回", "String)", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/Wechat/Jsapi/Ticket.php#L45-L60
thenbsp/wechat
src/Wechat/Jsapi/Ticket.php
Ticket.getTicketResponse
public function getTicketResponse() { $response = Http::request('GET', static::JSAPI_TICKET) ->withAccessToken($this->accessToken) ->withQuery(['type' => 'jsapi']) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return $response; }
php
public function getTicketResponse() { $response = Http::request('GET', static::JSAPI_TICKET) ->withAccessToken($this->accessToken) ->withQuery(['type' => 'jsapi']) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return $response; }
[ "public", "function", "getTicketResponse", "(", ")", "{", "$", "response", "=", "Http", "::", "request", "(", "'GET'", ",", "static", "::", "JSAPI_TICKET", ")", "->", "withAccessToken", "(", "$", "this", "->", "accessToken", ")", "->", "withQuery", "(", "[...
获取 Jsapi 票据(不缓存,返回原始数据).
[ "获取", "Jsapi", "票据(不缓存,返回原始数据)", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/Wechat/Jsapi/Ticket.php#L65-L77
thenbsp/wechat
src/Payment/Qrcode/ForeverCallback.php
ForeverCallback.success
public function success(Unifiedorder $unifiedorder) { $unifiedorder->set('trade_type', 'NATIVE'); $response = $unifiedorder->getResponse(); $options = [ 'appid' => $unifiedorder['appid'], 'mch_id' => $unifiedorder['mch_id'], 'prepay_id' => $response['prepay_id'], 'nonce_str' => Util::getRandomString(), 'return_code' => static::SUCCESS, 'result_code' => static::SUCCESS, ]; // 按 ASCII 码排序 ksort($options); $signature = urldecode(http_build_query($options)); $signature = strtoupper(md5($signature.'&key='.$unifiedorder->getKey())); $options['sign'] = $signature; $this->xmlResponse($options); }
php
public function success(Unifiedorder $unifiedorder) { $unifiedorder->set('trade_type', 'NATIVE'); $response = $unifiedorder->getResponse(); $options = [ 'appid' => $unifiedorder['appid'], 'mch_id' => $unifiedorder['mch_id'], 'prepay_id' => $response['prepay_id'], 'nonce_str' => Util::getRandomString(), 'return_code' => static::SUCCESS, 'result_code' => static::SUCCESS, ]; // 按 ASCII 码排序 ksort($options); $signature = urldecode(http_build_query($options)); $signature = strtoupper(md5($signature.'&key='.$unifiedorder->getKey())); $options['sign'] = $signature; $this->xmlResponse($options); }
[ "public", "function", "success", "(", "Unifiedorder", "$", "unifiedorder", ")", "{", "$", "unifiedorder", "->", "set", "(", "'trade_type'", ",", "'NATIVE'", ")", ";", "$", "response", "=", "$", "unifiedorder", "->", "getResponse", "(", ")", ";", "$", "opti...
成功响应.
[ "成功响应", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/Payment/Qrcode/ForeverCallback.php#L58-L82
thenbsp/wechat
src/Menu/ButtonCollection.php
ButtonCollection.addChild
public function addChild(ButtonInterface $button) { if (count($this->child) > (static::MAX_COUNT - 1)) { throw new \InvalidArgumentException(sprintf( '子菜单不能超过 %d 个', static::MAX_COUNT )); } array_push($this->child, $button); }
php
public function addChild(ButtonInterface $button) { if (count($this->child) > (static::MAX_COUNT - 1)) { throw new \InvalidArgumentException(sprintf( '子菜单不能超过 %d 个', static::MAX_COUNT )); } array_push($this->child, $button); }
[ "public", "function", "addChild", "(", "ButtonInterface", "$", "button", ")", "{", "if", "(", "count", "(", "$", "this", "->", "child", ")", ">", "(", "static", "::", "MAX_COUNT", "-", "1", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException",...
添加子菜单.
[ "添加子菜单", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/Menu/ButtonCollection.php#L33-L42
thenbsp/wechat
src/Menu/ButtonCollection.php
ButtonCollection.getData
public function getData() { $data = [ 'name' => $this->name, ]; if ($this->hasChild()) { foreach ($this->child as $k => $v) { $data['sub_button'][] = $v->getData(); } } return $data; }
php
public function getData() { $data = [ 'name' => $this->name, ]; if ($this->hasChild()) { foreach ($this->child as $k => $v) { $data['sub_button'][] = $v->getData(); } } return $data; }
[ "public", "function", "getData", "(", ")", "{", "$", "data", "=", "[", "'name'", "=>", "$", "this", "->", "name", ",", "]", ";", "if", "(", "$", "this", "->", "hasChild", "(", ")", ")", "{", "foreach", "(", "$", "this", "->", "child", "as", "$"...
获取菜单数据.
[ "获取菜单数据", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/Menu/ButtonCollection.php#L63-L76
thenbsp/wechat
src/Event/EventListener.php
EventListener.trigger
public function trigger($handler, Event $event) { if ($listener = $this->getListener($handler)) { return call_user_func_array($listener, [$event]); } }
php
public function trigger($handler, Event $event) { if ($listener = $this->getListener($handler)) { return call_user_func_array($listener, [$event]); } }
[ "public", "function", "trigger", "(", "$", "handler", ",", "Event", "$", "event", ")", "{", "if", "(", "$", "listener", "=", "$", "this", "->", "getListener", "(", "$", "handler", ")", ")", "{", "return", "call_user_func_array", "(", "$", "listener", "...
trigger event.
[ "trigger", "event", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/Event/EventListener.php#L15-L20
thenbsp/wechat
src/Event/EventListener.php
EventListener.addListener
public function addListener($handler, callable $callable) { if (!class_exists($handler)) { throw new \InvalidArgumentException(sprintf('Invlaid Handler "%s"', $handler)); } if (!is_subclass_of($handler, Event::class)) { throw new \InvalidArgumentException(sprintf( 'The Handler "%s" must be extends "%s"', $handler, Event::class)); } $this->listeners[$handler] = $callable; return $this; }
php
public function addListener($handler, callable $callable) { if (!class_exists($handler)) { throw new \InvalidArgumentException(sprintf('Invlaid Handler "%s"', $handler)); } if (!is_subclass_of($handler, Event::class)) { throw new \InvalidArgumentException(sprintf( 'The Handler "%s" must be extends "%s"', $handler, Event::class)); } $this->listeners[$handler] = $callable; return $this; }
[ "public", "function", "addListener", "(", "$", "handler", ",", "callable", "$", "callable", ")", "{", "if", "(", "!", "class_exists", "(", "$", "handler", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Invlaid Handler...
add listener.
[ "add", "listener", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/Event/EventListener.php#L25-L39
thenbsp/wechat
src/Wechat/ServerIp.php
ServerIp.getIps
public function getIps($cacheLifeTime = 86400) { $cacheId = $this->getCacheId(); if ($this->cache && $data = $this->cache->fetch($cacheId)) { return $data['ip_list']; } $response = Http::request('GET', static::SERVER_IP) ->withAccessToken($this->accessToken) ->send(); if ($response->containsKey('errcode')) { throw new \Exception($response['errmsg'], $response['errcode']); } if ($this->cache) { $this->cache->save($cacheId, $response, $cacheLifeTime); } return $response['ip_list']; }
php
public function getIps($cacheLifeTime = 86400) { $cacheId = $this->getCacheId(); if ($this->cache && $data = $this->cache->fetch($cacheId)) { return $data['ip_list']; } $response = Http::request('GET', static::SERVER_IP) ->withAccessToken($this->accessToken) ->send(); if ($response->containsKey('errcode')) { throw new \Exception($response['errmsg'], $response['errcode']); } if ($this->cache) { $this->cache->save($cacheId, $response, $cacheLifeTime); } return $response['ip_list']; }
[ "public", "function", "getIps", "(", "$", "cacheLifeTime", "=", "86400", ")", "{", "$", "cacheId", "=", "$", "this", "->", "getCacheId", "(", ")", ";", "if", "(", "$", "this", "->", "cache", "&&", "$", "data", "=", "$", "this", "->", "cache", "->",...
获取微信服务器 IP(默认缓存 1 天).
[ "获取微信服务器", "IP(默认缓存", "1", "天)", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/Wechat/ServerIp.php#L36-L57
thenbsp/wechat
src/Payment/Query.php
Query.doQuery
public function doQuery(array $by) { $options = array_merge($this->toArray(), $by); $options['nonce_str'] = Util::getRandomString(); // 按 ASCII 码排序 ksort($options); $signature = urldecode(http_build_query($options)); $signature = strtoupper(md5($signature.'&key='.$this->key)); $options['sign'] = $signature; $response = Http::request('POST', static::QUERY) ->withXmlBody($options) ->send(); if ('FAIL' === $response['result_code']) { throw new \Exception($response['err_code_des']); } if ('FAIL' === $response['return_code']) { throw new \Exception($response['return_msg']); } return $response; }
php
public function doQuery(array $by) { $options = array_merge($this->toArray(), $by); $options['nonce_str'] = Util::getRandomString(); // 按 ASCII 码排序 ksort($options); $signature = urldecode(http_build_query($options)); $signature = strtoupper(md5($signature.'&key='.$this->key)); $options['sign'] = $signature; $response = Http::request('POST', static::QUERY) ->withXmlBody($options) ->send(); if ('FAIL' === $response['result_code']) { throw new \Exception($response['err_code_des']); } if ('FAIL' === $response['return_code']) { throw new \Exception($response['return_msg']); } return $response; }
[ "public", "function", "doQuery", "(", "array", "$", "by", ")", "{", "$", "options", "=", "array_merge", "(", "$", "this", "->", "toArray", "(", ")", ",", "$", "by", ")", ";", "$", "options", "[", "'nonce_str'", "]", "=", "Util", "::", "getRandomStrin...
查询订单.
[ "查询订单", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/Payment/Query.php#L51-L77
thenbsp/wechat
src/User/Group.php
Group.query
public function query() { $response = Http::request('GET', static::SELECT) ->withAccessToken($this->accessToken) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return new ArrayCollection($response['groups']); }
php
public function query() { $response = Http::request('GET', static::SELECT) ->withAccessToken($this->accessToken) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return new ArrayCollection($response['groups']); }
[ "public", "function", "query", "(", ")", "{", "$", "response", "=", "Http", "::", "request", "(", "'GET'", ",", "static", "::", "SELECT", ")", "->", "withAccessToken", "(", "$", "this", "->", "accessToken", ")", "->", "send", "(", ")", ";", "if", "("...
查询全部分组.
[ "查询全部分组", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/User/Group.php#L35-L46
thenbsp/wechat
src/User/Group.php
Group.create
public function create($name) { $body = [ 'group' => ['name' => $name], ]; $response = Http::request('POST', static::CREATE) ->withAccessToken($this->accessToken) ->withBody($body) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return new ArrayCollection($response['group']); }
php
public function create($name) { $body = [ 'group' => ['name' => $name], ]; $response = Http::request('POST', static::CREATE) ->withAccessToken($this->accessToken) ->withBody($body) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return new ArrayCollection($response['group']); }
[ "public", "function", "create", "(", "$", "name", ")", "{", "$", "body", "=", "[", "'group'", "=>", "[", "'name'", "=>", "$", "name", "]", ",", "]", ";", "$", "response", "=", "Http", "::", "request", "(", "'POST'", ",", "static", "::", "CREATE", ...
创建新分组.
[ "创建新分组", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/User/Group.php#L51-L67
thenbsp/wechat
src/User/Group.php
Group.update
public function update($id, $newName) { $body = [ 'group' => [ 'id' => $id, 'name' => $newName, ], ]; $response = Http::request('POST', static::UPDAET) ->withAccessToken($this->accessToken) ->withBody($body) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return true; }
php
public function update($id, $newName) { $body = [ 'group' => [ 'id' => $id, 'name' => $newName, ], ]; $response = Http::request('POST', static::UPDAET) ->withAccessToken($this->accessToken) ->withBody($body) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return true; }
[ "public", "function", "update", "(", "$", "id", ",", "$", "newName", ")", "{", "$", "body", "=", "[", "'group'", "=>", "[", "'id'", "=>", "$", "id", ",", "'name'", "=>", "$", "newName", ",", "]", ",", "]", ";", "$", "response", "=", "Http", "::...
修改分组名称.
[ "修改分组名称", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/User/Group.php#L72-L91
thenbsp/wechat
src/User/Group.php
Group.delete
public function delete($id) { $body = [ 'group' => ['id' => $id], ]; $response = Http::request('POST', static::DELETE) ->withAccessToken($this->accessToken) ->withBody($body) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return true; }
php
public function delete($id) { $body = [ 'group' => ['id' => $id], ]; $response = Http::request('POST', static::DELETE) ->withAccessToken($this->accessToken) ->withBody($body) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return true; }
[ "public", "function", "delete", "(", "$", "id", ")", "{", "$", "body", "=", "[", "'group'", "=>", "[", "'id'", "=>", "$", "id", "]", ",", "]", ";", "$", "response", "=", "Http", "::", "request", "(", "'POST'", ",", "static", "::", "DELETE", ")", ...
删除分组.
[ "删除分组", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/User/Group.php#L96-L112
thenbsp/wechat
src/User/Group.php
Group.queryUserGroup
public function queryUserGroup($openid) { $body = ['openid' => $openid]; $response = Http::request('POST', static::QUERY_USER_GROUP) ->withAccessToken($this->accessToken) ->withBody($body) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return $response['groupid']; }
php
public function queryUserGroup($openid) { $body = ['openid' => $openid]; $response = Http::request('POST', static::QUERY_USER_GROUP) ->withAccessToken($this->accessToken) ->withBody($body) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return $response['groupid']; }
[ "public", "function", "queryUserGroup", "(", "$", "openid", ")", "{", "$", "body", "=", "[", "'openid'", "=>", "$", "openid", "]", ";", "$", "response", "=", "Http", "::", "request", "(", "'POST'", ",", "static", "::", "QUERY_USER_GROUP", ")", "->", "w...
查询指定用户所在分组.
[ "查询指定用户所在分组", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/User/Group.php#L117-L131
thenbsp/wechat
src/User/Group.php
Group.updateUserGroup
public function updateUserGroup($openid, $newId) { $key = is_array($openid) ? 'openid_list' : 'openid'; $api = is_array($openid) ? static::BETCH_UPDATE_USER_GROUP : static::UPDATE_USER_GROUP; $body = [$key => $openid, 'to_groupid' => $newId]; $response = Http::request('POST', $api) ->withAccessToken($this->accessToken) ->withBody($body) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return true; }
php
public function updateUserGroup($openid, $newId) { $key = is_array($openid) ? 'openid_list' : 'openid'; $api = is_array($openid) ? static::BETCH_UPDATE_USER_GROUP : static::UPDATE_USER_GROUP; $body = [$key => $openid, 'to_groupid' => $newId]; $response = Http::request('POST', $api) ->withAccessToken($this->accessToken) ->withBody($body) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return true; }
[ "public", "function", "updateUserGroup", "(", "$", "openid", ",", "$", "newId", ")", "{", "$", "key", "=", "is_array", "(", "$", "openid", ")", "?", "'openid_list'", ":", "'openid'", ";", "$", "api", "=", "is_array", "(", "$", "openid", ")", "?", "st...
移动用户分组.
[ "移动用户分组", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/User/Group.php#L136-L158
thenbsp/wechat
src/Payment/Coupon/Cash.php
Cash.setSSLCert
public function setSSLCert($sslCert, $sslKey) { if (!file_exists($sslCert)) { throw new \InvalidArgumentException(sprintf('File "%s" Not Found', $sslCert)); } if (!file_exists($sslKey)) { throw new \InvalidArgumentException(sprintf('File "%s" Not Found', $sslKey)); } $this->sslCert = $sslCert; $this->sslKey = $sslKey; }
php
public function setSSLCert($sslCert, $sslKey) { if (!file_exists($sslCert)) { throw new \InvalidArgumentException(sprintf('File "%s" Not Found', $sslCert)); } if (!file_exists($sslKey)) { throw new \InvalidArgumentException(sprintf('File "%s" Not Found', $sslKey)); } $this->sslCert = $sslCert; $this->sslKey = $sslKey; }
[ "public", "function", "setSSLCert", "(", "$", "sslCert", ",", "$", "sslKey", ")", "{", "if", "(", "!", "file_exists", "(", "$", "sslCert", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'File \"%s\" Not Found'", ",", ...
调置 SSL 证书.
[ "调置", "SSL", "证书", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/Payment/Coupon/Cash.php#L50-L62
thenbsp/wechat
src/Payment/Coupon/Cash.php
Cash.getResponse
public function getResponse() { $options = $this->resolveOptions(); // 按 ASCII 码排序 ksort($options); $signature = urldecode(http_build_query($options)); $signature = strtoupper(md5($signature.'&key='.$this->key)); $options['sign'] = $signature; $response = Http::request('POST', static::COUPON_CASH) ->withSSLCert($this->sslCert, $this->sslKey) ->withXmlBody($options) ->send(); if ('FAIL' === $response['return_code']) { throw new \Exception($response['return_msg']); } if ('FAIL' === $response['result_code']) { throw new \Exception($response['err_code_des']); } return $response; }
php
public function getResponse() { $options = $this->resolveOptions(); // 按 ASCII 码排序 ksort($options); $signature = urldecode(http_build_query($options)); $signature = strtoupper(md5($signature.'&key='.$this->key)); $options['sign'] = $signature; $response = Http::request('POST', static::COUPON_CASH) ->withSSLCert($this->sslCert, $this->sslKey) ->withXmlBody($options) ->send(); if ('FAIL' === $response['return_code']) { throw new \Exception($response['return_msg']); } if ('FAIL' === $response['result_code']) { throw new \Exception($response['err_code_des']); } return $response; }
[ "public", "function", "getResponse", "(", ")", "{", "$", "options", "=", "$", "this", "->", "resolveOptions", "(", ")", ";", "// 按 ASCII 码排序", "ksort", "(", "$", "options", ")", ";", "$", "signature", "=", "urldecode", "(", "http_build_query", "(", "$", ...
获取响应结果.
[ "获取响应结果", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/Payment/Coupon/Cash.php#L67-L93
thenbsp/wechat
src/Payment/Coupon/Cash.php
Cash.resolveOptions
public function resolveOptions() { $defaults = [ 'nonce_str' => Util::getRandomString(), 'client_ip' => Util::getClientIp(), ]; $resolver = new OptionsResolver(); $resolver ->setDefined($this->required) ->setRequired($this->required) ->setDefaults($defaults); return $resolver->resolve($this->toArray()); }
php
public function resolveOptions() { $defaults = [ 'nonce_str' => Util::getRandomString(), 'client_ip' => Util::getClientIp(), ]; $resolver = new OptionsResolver(); $resolver ->setDefined($this->required) ->setRequired($this->required) ->setDefaults($defaults); return $resolver->resolve($this->toArray()); }
[ "public", "function", "resolveOptions", "(", ")", "{", "$", "defaults", "=", "[", "'nonce_str'", "=>", "Util", "::", "getRandomString", "(", ")", ",", "'client_ip'", "=>", "Util", "::", "getClientIp", "(", ")", ",", "]", ";", "$", "resolver", "=", "new",...
合并和校验参数.
[ "合并和校验参数", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/Payment/Coupon/Cash.php#L98-L112
thenbsp/wechat
src/Bridge/Util.php
Util.getRandomString
public static function getRandomString($length = 10) { $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; return substr(str_shuffle(str_repeat($pool, ceil($length / strlen($pool)))), 0, $length); }
php
public static function getRandomString($length = 10) { $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; return substr(str_shuffle(str_repeat($pool, ceil($length / strlen($pool)))), 0, $length); }
[ "public", "static", "function", "getRandomString", "(", "$", "length", "=", "10", ")", "{", "$", "pool", "=", "'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'", ";", "return", "substr", "(", "str_shuffle", "(", "str_repeat", "(", "$", "pool", ",", ...
获取随机字符.
[ "获取随机字符", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/Bridge/Util.php#L49-L54
thenbsp/wechat
src/Menu/Create.php
Create.add
public function add(ButtonInterface $button) { if ($button instanceof ButtonCollectionInterface) { if (!$button->getChild()) { throw new \InvalidArgumentException('一级菜单不能为空'); } } if (count($this->buttons) > (static::MAX_COUNT - 1)) { throw new \InvalidArgumentException(sprintf( '一级菜单不能超过 %d 个', static::MAX_COUNT )); } $this->buttons[] = $button; }
php
public function add(ButtonInterface $button) { if ($button instanceof ButtonCollectionInterface) { if (!$button->getChild()) { throw new \InvalidArgumentException('一级菜单不能为空'); } } if (count($this->buttons) > (static::MAX_COUNT - 1)) { throw new \InvalidArgumentException(sprintf( '一级菜单不能超过 %d 个', static::MAX_COUNT )); } $this->buttons[] = $button; }
[ "public", "function", "add", "(", "ButtonInterface", "$", "button", ")", "{", "if", "(", "$", "button", "instanceof", "ButtonCollectionInterface", ")", "{", "if", "(", "!", "$", "button", "->", "getChild", "(", ")", ")", "{", "throw", "new", "\\", "Inval...
添加按钮.
[ "添加按钮", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/Menu/Create.php#L41-L56
thenbsp/wechat
src/Menu/Create.php
Create.doCreate
public function doCreate() { $response = Http::request('POST', static::CREATE_URL) ->withAccessToken($this->accessToken) ->withBody($this->getRequestBody()) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return true; }
php
public function doCreate() { $response = Http::request('POST', static::CREATE_URL) ->withAccessToken($this->accessToken) ->withBody($this->getRequestBody()) ->send(); if (0 != $response['errcode']) { throw new \Exception($response['errmsg'], $response['errcode']); } return true; }
[ "public", "function", "doCreate", "(", ")", "{", "$", "response", "=", "Http", "::", "request", "(", "'POST'", ",", "static", "::", "CREATE_URL", ")", "->", "withAccessToken", "(", "$", "this", "->", "accessToken", ")", "->", "withBody", "(", "$", "this"...
发布菜单.
[ "发布菜单", "." ]
train
https://github.com/thenbsp/wechat/blob/1eef58ac53f50dc886914ef260f55d0df067af6f/src/Menu/Create.php#L61-L73