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
omniphx/forrest
src/Omniphx/Forrest/Repositories/RefreshTokenRepository.php
RefreshTokenRepository.get
public function get() { $this->verifyRefreshTokenExists(); $token = $this->storage->get('refresh_token'); return $this->encryptor->decrypt($token); }
php
public function get() { $this->verifyRefreshTokenExists(); $token = $this->storage->get('refresh_token'); return $this->encryptor->decrypt($token); }
[ "public", "function", "get", "(", ")", "{", "$", "this", "->", "verifyRefreshTokenExists", "(", ")", ";", "$", "token", "=", "$", "this", "->", "storage", "->", "get", "(", "'refresh_token'", ")", ";", "return", "$", "this", "->", "encryptor", "->", "d...
Get refresh token from session and decrypt it. @return mixed
[ "Get", "refresh", "token", "from", "session", "and", "decrypt", "it", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Repositories/RefreshTokenRepository.php#L44-L51
omniphx/forrest
src/Omniphx/Forrest/Providers/Laravel/LaravelEvent.php
LaravelEvent.fire
public function fire($event, $payload = [], $halt = false) { if (method_exists($this->event, 'dispatch')) { return $this->event->dispatch($event, $payload, $halt); } return $this->event->fire($event, $payload, $halt); }
php
public function fire($event, $payload = [], $halt = false) { if (method_exists($this->event, 'dispatch')) { return $this->event->dispatch($event, $payload, $halt); } return $this->event->fire($event, $payload, $halt); }
[ "public", "function", "fire", "(", "$", "event", ",", "$", "payload", "=", "[", "]", ",", "$", "halt", "=", "false", ")", "{", "if", "(", "method_exists", "(", "$", "this", "->", "event", ",", "'dispatch'", ")", ")", "{", "return", "$", "this", "...
Fire an event and call the listeners. @param string $event @param mixed $payload @param bool $halt @return array|null
[ "Fire", "an", "event", "and", "call", "the", "listeners", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Providers/Laravel/LaravelEvent.php#L26-L33
omniphx/forrest
spec/Omniphx/Forrest/Authentications/UserPasswordSpec.php
UserPasswordSpec.it_should_return_all_versions
public function it_should_return_all_versions( ClientInterface $mockedHttpClient, ResponseInterface $mockedResponse, FormatterInterface $mockedFormatter) { $mockedHttpClient->request('get', 'https://instance.salesforce.com/services/data', ['headers' => ['Authorization' => 'Oauth accessToken', 'Accept' => 'application/json', 'Content-Type' => 'application/json']])->shouldBeCalled()->willReturn($mockedResponse); $versionArray = json_decode($this->versionJSON, true); $mockedFormatter->formatResponse($mockedResponse)->shouldBeCalled()->willReturn($versionArray); $this->versions()->shouldReturn($versionArray); }
php
public function it_should_return_all_versions( ClientInterface $mockedHttpClient, ResponseInterface $mockedResponse, FormatterInterface $mockedFormatter) { $mockedHttpClient->request('get', 'https://instance.salesforce.com/services/data', ['headers' => ['Authorization' => 'Oauth accessToken', 'Accept' => 'application/json', 'Content-Type' => 'application/json']])->shouldBeCalled()->willReturn($mockedResponse); $versionArray = json_decode($this->versionJSON, true); $mockedFormatter->formatResponse($mockedResponse)->shouldBeCalled()->willReturn($versionArray); $this->versions()->shouldReturn($versionArray); }
[ "public", "function", "it_should_return_all_versions", "(", "ClientInterface", "$", "mockedHttpClient", ",", "ResponseInterface", "$", "mockedResponse", ",", "FormatterInterface", "$", "mockedFormatter", ")", "{", "$", "mockedHttpClient", "->", "request", "(", "'get'", ...
/* Specs below are for the parent class.
[ "/", "*" ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/spec/Omniphx/Forrest/Authentications/UserPasswordSpec.php#L310-L322
omniphx/forrest
src/Omniphx/Forrest/Providers/Laravel/LaravelSession.php
LaravelSession.put
public function put($key, $value) { return $this->session->put($this->path.$key, $value); }
php
public function put($key, $value) { return $this->session->put($this->path.$key, $value); }
[ "public", "function", "put", "(", "$", "key", ",", "$", "value", ")", "{", "return", "$", "this", "->", "session", "->", "put", "(", "$", "this", "->", "path", ".", "$", "key", ",", "$", "value", ")", ";", "}" ]
Store into session. @param $key @param $value @return void
[ "Store", "into", "session", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Providers/Laravel/LaravelSession.php#L29-L32
omniphx/forrest
src/Omniphx/Forrest/Providers/Laravel/LaravelSession.php
LaravelSession.get
public function get($key) { if(!$this->has($key)) { throw new MissingKeyException(sprintf('No value for requested key: %s', $key)); } return $this->session->get($this->path.$key); }
php
public function get($key) { if(!$this->has($key)) { throw new MissingKeyException(sprintf('No value for requested key: %s', $key)); } return $this->session->get($this->path.$key); }
[ "public", "function", "get", "(", "$", "key", ")", "{", "if", "(", "!", "$", "this", "->", "has", "(", "$", "key", ")", ")", "{", "throw", "new", "MissingKeyException", "(", "sprintf", "(", "'No value for requested key: %s'", ",", "$", "key", ")", ")",...
Get from session. @param $key @return mixed
[ "Get", "from", "session", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Providers/Laravel/LaravelSession.php#L41-L48
omniphx/forrest
src/Omniphx/Forrest/Providers/BaseServiceProvider.php
BaseServiceProvider.register
public function register() { $this->app->singleton('forrest', function ($app) { // Config options $settings = config('forrest'); $storageType = config('forrest.storage.type'); $authenticationType = config('forrest.authentication'); // Dependencies $httpClient = $this->getClient(); $input = new LaravelInput(app('request')); $event = new LaravelEvent(app('events')); $encryptor = new LaravelEncryptor(app('encrypter')); $redirect = $this->getRedirect(); $storage = $this->getStorage($storageType); $refreshTokenRepo = new RefreshTokenRepository($encryptor, $storage); $tokenRepo = new TokenRepository($encryptor, $storage); $resourceRepo = new ResourceRepository($storage); $versionRepo = new VersionRepository($storage); $instanceURLRepo = new InstanceURLRepository($tokenRepo, $settings); $stateRepo = new StateRepository($storage); $formatter = new JSONFormatter($tokenRepo, $settings); switch ($authenticationType) { case 'WebServer': $forrest = new WebServer( $httpClient, $encryptor, $event, $input, $redirect, $instanceURLRepo, $refreshTokenRepo, $resourceRepo, $stateRepo, $tokenRepo, $versionRepo, $formatter, $settings); break; case 'UserPassword': $forrest = new UserPassword( $httpClient, $encryptor, $event, $input, $redirect, $instanceURLRepo, $refreshTokenRepo, $resourceRepo, $stateRepo, $tokenRepo, $versionRepo, $formatter, $settings); break; default: $forrest = new WebServer( $httpClient, $encryptor, $event, $input, $redirect, $instanceURLRepo, $refreshTokenRepo, $resourceRepo, $stateRepo, $tokenRepo, $versionRepo, $formatter, $settings); break; } return $forrest; }); }
php
public function register() { $this->app->singleton('forrest', function ($app) { // Config options $settings = config('forrest'); $storageType = config('forrest.storage.type'); $authenticationType = config('forrest.authentication'); // Dependencies $httpClient = $this->getClient(); $input = new LaravelInput(app('request')); $event = new LaravelEvent(app('events')); $encryptor = new LaravelEncryptor(app('encrypter')); $redirect = $this->getRedirect(); $storage = $this->getStorage($storageType); $refreshTokenRepo = new RefreshTokenRepository($encryptor, $storage); $tokenRepo = new TokenRepository($encryptor, $storage); $resourceRepo = new ResourceRepository($storage); $versionRepo = new VersionRepository($storage); $instanceURLRepo = new InstanceURLRepository($tokenRepo, $settings); $stateRepo = new StateRepository($storage); $formatter = new JSONFormatter($tokenRepo, $settings); switch ($authenticationType) { case 'WebServer': $forrest = new WebServer( $httpClient, $encryptor, $event, $input, $redirect, $instanceURLRepo, $refreshTokenRepo, $resourceRepo, $stateRepo, $tokenRepo, $versionRepo, $formatter, $settings); break; case 'UserPassword': $forrest = new UserPassword( $httpClient, $encryptor, $event, $input, $redirect, $instanceURLRepo, $refreshTokenRepo, $resourceRepo, $stateRepo, $tokenRepo, $versionRepo, $formatter, $settings); break; default: $forrest = new WebServer( $httpClient, $encryptor, $event, $input, $redirect, $instanceURLRepo, $refreshTokenRepo, $resourceRepo, $stateRepo, $tokenRepo, $versionRepo, $formatter, $settings); break; } return $forrest; }); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "app", "->", "singleton", "(", "'forrest'", ",", "function", "(", "$", "app", ")", "{", "// Config options", "$", "settings", "=", "config", "(", "'forrest'", ")", ";", "$", "storageType...
Register the service provider. @return void
[ "Register", "the", "service", "provider", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Providers/BaseServiceProvider.php#L77-L156
omniphx/forrest
src/Omniphx/Forrest/Authentications/WebServer.php
WebServer.authenticate
public function authenticate($url = null, $stateOptions = []) { $loginURL = $url === null ? $this->credentials['loginURL'] : $url; $stateOptions['loginUrl'] = $loginURL; $state = '&state='.urlencode(json_encode($stateOptions)); $parameters = $this->settings['parameters']; $loginURL .= '/services/oauth2/authorize'; $loginURL .= '?response_type=code'; $loginURL .= '&client_id='.$this->credentials['consumerKey']; $loginURL .= '&redirect_uri='.urlencode($this->credentials['callbackURI']); $loginURL .= !empty($parameters['display']) ? '&display='.$parameters['display'] : ''; $loginURL .= $parameters['immediate'] ? '&immediate=true' : ''; $loginURL .= !empty($parameters['scope']) ? '&scope='.rawurlencode($parameters['scope']) : ''; $loginURL .= !empty($parameters['prompt']) ? '&prompt='.rawurlencode($parameters['prompt']) : ''; $loginURL .= $state; return $this->redirect->to($loginURL); }
php
public function authenticate($url = null, $stateOptions = []) { $loginURL = $url === null ? $this->credentials['loginURL'] : $url; $stateOptions['loginUrl'] = $loginURL; $state = '&state='.urlencode(json_encode($stateOptions)); $parameters = $this->settings['parameters']; $loginURL .= '/services/oauth2/authorize'; $loginURL .= '?response_type=code'; $loginURL .= '&client_id='.$this->credentials['consumerKey']; $loginURL .= '&redirect_uri='.urlencode($this->credentials['callbackURI']); $loginURL .= !empty($parameters['display']) ? '&display='.$parameters['display'] : ''; $loginURL .= $parameters['immediate'] ? '&immediate=true' : ''; $loginURL .= !empty($parameters['scope']) ? '&scope='.rawurlencode($parameters['scope']) : ''; $loginURL .= !empty($parameters['prompt']) ? '&prompt='.rawurlencode($parameters['prompt']) : ''; $loginURL .= $state; return $this->redirect->to($loginURL); }
[ "public", "function", "authenticate", "(", "$", "url", "=", "null", ",", "$", "stateOptions", "=", "[", "]", ")", "{", "$", "loginURL", "=", "$", "url", "===", "null", "?", "$", "this", "->", "credentials", "[", "'loginURL'", "]", ":", "$", "url", ...
Call this method to redirect user to login page and initiate the Web Server OAuth Authentication Flow. @param null $loginURL @return \Illuminate\Http\RedirectResponse
[ "Call", "this", "method", "to", "redirect", "user", "to", "login", "page", "and", "initiate", "the", "Web", "Server", "OAuth", "Authentication", "Flow", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Authentications/WebServer.php#L25-L44
omniphx/forrest
src/Omniphx/Forrest/Authentications/WebServer.php
WebServer.callback
public function callback() { //Salesforce sends us an authorization code as part of the Web Server OAuth Authentication Flow $code = $this->input->get('code'); $stateOptions = json_decode(urldecode($this->input->get('state')), true); //Store instance URL $loginURL = $stateOptions['loginUrl']; // Store user options so they can be used later $this->stateRepo->put($stateOptions); $tokenURL = $loginURL.'/services/oauth2/token'; $jsonResponse = $this->httpClient->request('post', $tokenURL, [ 'form_params' => [ 'code' => $code, 'grant_type' => 'authorization_code', 'client_id' => $this->credentials['consumerKey'], 'client_secret' => $this->credentials['consumerSecret'], 'redirect_uri' => $this->credentials['callbackURI'], ], ]); // Response returns an json of access_token, instance_url, id, issued_at, and signature. $response = json_decode($jsonResponse->getBody(), true); $this->handleAuthenticationErrors($response); // Encrypt token and store token in storage. $this->tokenRepo->put($response); if (isset($response['refresh_token'])) { $this->refreshTokenRepo->put($response['refresh_token']); } $this->storeVersion(); $this->storeResources(); // Return settings return $stateOptions; }
php
public function callback() { //Salesforce sends us an authorization code as part of the Web Server OAuth Authentication Flow $code = $this->input->get('code'); $stateOptions = json_decode(urldecode($this->input->get('state')), true); //Store instance URL $loginURL = $stateOptions['loginUrl']; // Store user options so they can be used later $this->stateRepo->put($stateOptions); $tokenURL = $loginURL.'/services/oauth2/token'; $jsonResponse = $this->httpClient->request('post', $tokenURL, [ 'form_params' => [ 'code' => $code, 'grant_type' => 'authorization_code', 'client_id' => $this->credentials['consumerKey'], 'client_secret' => $this->credentials['consumerSecret'], 'redirect_uri' => $this->credentials['callbackURI'], ], ]); // Response returns an json of access_token, instance_url, id, issued_at, and signature. $response = json_decode($jsonResponse->getBody(), true); $this->handleAuthenticationErrors($response); // Encrypt token and store token in storage. $this->tokenRepo->put($response); if (isset($response['refresh_token'])) { $this->refreshTokenRepo->put($response['refresh_token']); } $this->storeVersion(); $this->storeResources(); // Return settings return $stateOptions; }
[ "public", "function", "callback", "(", ")", "{", "//Salesforce sends us an authorization code as part of the Web Server OAuth Authentication Flow", "$", "code", "=", "$", "this", "->", "input", "->", "get", "(", "'code'", ")", ";", "$", "stateOptions", "=", "json_decode...
When settings up your callback route, you will need to call this method to acquire an authorization token. This token will be used for the API requests. @return RedirectInterface
[ "When", "settings", "up", "your", "callback", "route", "you", "will", "need", "to", "call", "this", "method", "to", "acquire", "an", "authorization", "token", ".", "This", "token", "will", "be", "used", "for", "the", "API", "requests", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Authentications/WebServer.php#L52-L93
omniphx/forrest
src/Omniphx/Forrest/Authentications/WebServer.php
WebServer.refresh
public function refresh() { $refreshToken = $this->refreshTokenRepo->get(); $tokenURL = $this->getLoginURL(); $tokenURL .= '/services/oauth2/token'; $response = $this->httpClient->request('post', $tokenURL, [ 'form_params' => [ 'refresh_token' => $refreshToken, 'grant_type' => 'refresh_token', 'client_id' => $this->credentials['consumerKey'], 'client_secret' => $this->credentials['consumerSecret'], ], ]); // Response returns an json of access_token, instance_url, id, issued_at, and signature. $token = json_decode($response->getBody(), true); // Encrypt token and store token and in storage. $this->tokenRepo->put($token); }
php
public function refresh() { $refreshToken = $this->refreshTokenRepo->get(); $tokenURL = $this->getLoginURL(); $tokenURL .= '/services/oauth2/token'; $response = $this->httpClient->request('post', $tokenURL, [ 'form_params' => [ 'refresh_token' => $refreshToken, 'grant_type' => 'refresh_token', 'client_id' => $this->credentials['consumerKey'], 'client_secret' => $this->credentials['consumerSecret'], ], ]); // Response returns an json of access_token, instance_url, id, issued_at, and signature. $token = json_decode($response->getBody(), true); // Encrypt token and store token and in storage. $this->tokenRepo->put($token); }
[ "public", "function", "refresh", "(", ")", "{", "$", "refreshToken", "=", "$", "this", "->", "refreshTokenRepo", "->", "get", "(", ")", ";", "$", "tokenURL", "=", "$", "this", "->", "getLoginURL", "(", ")", ";", "$", "tokenURL", ".=", "'/services/oauth2/...
Refresh authentication token. @return mixed $response
[ "Refresh", "authentication", "token", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Authentications/WebServer.php#L100-L120
omniphx/forrest
src/Omniphx/Forrest/Authentications/WebServer.php
WebServer.revoke
public function revoke() { $accessToken = $this->tokenRepo->get()['access_token']; $url = $this->getLoginURL(); $url .= '/services/oauth2/revoke'; $options['headers']['content-type'] = 'application/x-www-form-urlencoded'; $options['form_params']['token'] = $accessToken; return $this->httpClient->post($url, $options); }
php
public function revoke() { $accessToken = $this->tokenRepo->get()['access_token']; $url = $this->getLoginURL(); $url .= '/services/oauth2/revoke'; $options['headers']['content-type'] = 'application/x-www-form-urlencoded'; $options['form_params']['token'] = $accessToken; return $this->httpClient->post($url, $options); }
[ "public", "function", "revoke", "(", ")", "{", "$", "accessToken", "=", "$", "this", "->", "tokenRepo", "->", "get", "(", ")", "[", "'access_token'", "]", ";", "$", "url", "=", "$", "this", "->", "getLoginURL", "(", ")", ";", "$", "url", ".=", "'/s...
Revokes access token from Salesforce. Will not flush token from storage. @return mixed
[ "Revokes", "access", "token", "from", "Salesforce", ".", "Will", "not", "flush", "token", "from", "storage", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Authentications/WebServer.php#L127-L137
omniphx/forrest
src/Omniphx/Forrest/Repositories/InstanceURLRepository.php
InstanceURLRepository.get
public function get() { if (isset($this->settings['instanceURL']) && !empty($this->settings['instanceURL'])) { return $this->settings['instanceURL']; } else { return $this->tokenRepo->get()['instance_url']; } }
php
public function get() { if (isset($this->settings['instanceURL']) && !empty($this->settings['instanceURL'])) { return $this->settings['instanceURL']; } else { return $this->tokenRepo->get()['instance_url']; } }
[ "public", "function", "get", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "settings", "[", "'instanceURL'", "]", ")", "&&", "!", "empty", "(", "$", "this", "->", "settings", "[", "'instanceURL'", "]", ")", ")", "{", "return", "$", "th...
Get version @return mixed
[ "Get", "version" ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Repositories/InstanceURLRepository.php#L32-L39
omniphx/forrest
src/Omniphx/Forrest/Providers/Laravel/LaravelCache.php
LaravelCache.put
public function put($key, $value) { if ($this->storeForever) { return $this->cache->forever($this->path.$key, $value); } else { return $this->cache->put($this->path.$key, $value, $this->minutes); } }
php
public function put($key, $value) { if ($this->storeForever) { return $this->cache->forever($this->path.$key, $value); } else { return $this->cache->put($this->path.$key, $value, $this->minutes); } }
[ "public", "function", "put", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "$", "this", "->", "storeForever", ")", "{", "return", "$", "this", "->", "cache", "->", "forever", "(", "$", "this", "->", "path", ".", "$", "key", ",", "$", ...
Store into session. @param $key @param $value @return void
[ "Store", "into", "session", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Providers/Laravel/LaravelCache.php#L33-L40
omniphx/forrest
src/Omniphx/Forrest/Providers/Laravel/LaravelCache.php
LaravelCache.get
public function get($key) { $this->checkForKey($key); return $this->cache->get($this->path.$key); }
php
public function get($key) { $this->checkForKey($key); return $this->cache->get($this->path.$key); }
[ "public", "function", "get", "(", "$", "key", ")", "{", "$", "this", "->", "checkForKey", "(", "$", "key", ")", ";", "return", "$", "this", "->", "cache", "->", "get", "(", "$", "this", "->", "path", ".", "$", "key", ")", ";", "}" ]
Get from session. @param $key @return mixed
[ "Get", "from", "session", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Providers/Laravel/LaravelCache.php#L49-L54
omniphx/forrest
src/Omniphx/Forrest/Authentications/UserPassword.php
UserPassword.refresh
public function refresh() { $tokenURL = $this->credentials['loginURL'] . '/services/oauth2/token'; $authToken = $this->getAuthToken($tokenURL); $this->tokenRepo->put($authToken); }
php
public function refresh() { $tokenURL = $this->credentials['loginURL'] . '/services/oauth2/token'; $authToken = $this->getAuthToken($tokenURL); $this->tokenRepo->put($authToken); }
[ "public", "function", "refresh", "(", ")", "{", "$", "tokenURL", "=", "$", "this", "->", "credentials", "[", "'loginURL'", "]", ".", "'/services/oauth2/token'", ";", "$", "authToken", "=", "$", "this", "->", "getAuthToken", "(", "$", "tokenURL", ")", ";", ...
Refresh authentication token by re-authenticating. @return mixed $response
[ "Refresh", "authentication", "token", "by", "re", "-", "authenticating", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Authentications/UserPassword.php#L29-L35
omniphx/forrest
src/Omniphx/Forrest/Authentications/UserPassword.php
UserPassword.revoke
public function revoke() { $accessToken = $this->tokenRepo->get(); $url = $this->credentials['loginURL'].'/services/oauth2/revoke'; $options['headers']['content-type'] = 'application/x-www-form-urlencoded'; $options['form_params']['token'] = $accessToken; return $this->httpClient->request('post', $url, $options); }
php
public function revoke() { $accessToken = $this->tokenRepo->get(); $url = $this->credentials['loginURL'].'/services/oauth2/revoke'; $options['headers']['content-type'] = 'application/x-www-form-urlencoded'; $options['form_params']['token'] = $accessToken; return $this->httpClient->request('post', $url, $options); }
[ "public", "function", "revoke", "(", ")", "{", "$", "accessToken", "=", "$", "this", "->", "tokenRepo", "->", "get", "(", ")", ";", "$", "url", "=", "$", "this", "->", "credentials", "[", "'loginURL'", "]", ".", "'/services/oauth2/revoke'", ";", "$", "...
Revokes access token from Salesforce. Will not flush token from storage. @return mixed
[ "Revokes", "access", "token", "from", "Salesforce", ".", "Will", "not", "flush", "token", "from", "storage", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Authentications/UserPassword.php#L67-L76
omniphx/forrest
src/Omniphx/Forrest/Providers/Laravel/LaravelStorageProvider.php
LaravelStorageProvider.getTokenData
public function getTokenData() { if(!$this->has('token')) { throw new MissingTokenException(sprintf('No token available in \''.Config::get('forrest.storage.type').'\' storage')); } $token = $this->get('token'); return Crypt::decrypt($token); }
php
public function getTokenData() { if(!$this->has('token')) { throw new MissingTokenException(sprintf('No token available in \''.Config::get('forrest.storage.type').'\' storage')); } $token = $this->get('token'); return Crypt::decrypt($token); }
[ "public", "function", "getTokenData", "(", ")", "{", "if", "(", "!", "$", "this", "->", "has", "(", "'token'", ")", ")", "{", "throw", "new", "MissingTokenException", "(", "sprintf", "(", "'No token available in \\''", ".", "Config", "::", "get", "(", "'fo...
Get token from the session and decrypt it. @return mixed
[ "Get", "token", "from", "the", "session", "and", "decrypt", "it", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Providers/Laravel/LaravelStorageProvider.php#L32-L41
omniphx/forrest
src/Omniphx/Forrest/Providers/Laravel/LaravelStorageProvider.php
LaravelStorageProvider.getRefreshToken
public function getRefreshToken() { if ($this->has('refresh_token')) { $token = $this->get('refresh_token'); return Crypt::decrypt($token); } throw new MissingRefreshTokenException(sprintf('No refresh token stored in current session. Verify you have added refresh_token to your scope items on your connected app settings in Salesforce.')); }
php
public function getRefreshToken() { if ($this->has('refresh_token')) { $token = $this->get('refresh_token'); return Crypt::decrypt($token); } throw new MissingRefreshTokenException(sprintf('No refresh token stored in current session. Verify you have added refresh_token to your scope items on your connected app settings in Salesforce.')); }
[ "public", "function", "getRefreshToken", "(", ")", "{", "if", "(", "$", "this", "->", "has", "(", "'refresh_token'", ")", ")", "{", "$", "token", "=", "$", "this", "->", "get", "(", "'refresh_token'", ")", ";", "return", "Crypt", "::", "decrypt", "(", ...
Get refresh token from session and decrypt it. @return mixed
[ "Get", "refresh", "token", "from", "session", "and", "decrypt", "it", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Providers/Laravel/LaravelStorageProvider.php#L62-L71
omniphx/forrest
src/Omniphx/Forrest/Repositories/TokenRepository.php
TokenRepository.put
public function put($token) { $encryptedToken = $this->encryptor->encrypt($token); $this->storage->put('token', $encryptedToken); }
php
public function put($token) { $encryptedToken = $this->encryptor->encrypt($token); $this->storage->put('token', $encryptedToken); }
[ "public", "function", "put", "(", "$", "token", ")", "{", "$", "encryptedToken", "=", "$", "this", "->", "encryptor", "->", "encrypt", "(", "$", "token", ")", ";", "$", "this", "->", "storage", "->", "put", "(", "'token'", ",", "$", "encryptedToken", ...
Encrypt authentication token and store it in session/cache. @param array $token @return void
[ "Encrypt", "authentication", "token", "and", "store", "it", "in", "session", "/", "cache", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Repositories/TokenRepository.php#L27-L32
omniphx/forrest
src/Omniphx/Forrest/Repositories/TokenRepository.php
TokenRepository.get
public function get() { $this->verify(); $token = $this->storage->get('token'); return $this->encryptor->decrypt($token); }
php
public function get() { $this->verify(); $token = $this->storage->get('token'); return $this->encryptor->decrypt($token); }
[ "public", "function", "get", "(", ")", "{", "$", "this", "->", "verify", "(", ")", ";", "$", "token", "=", "$", "this", "->", "storage", "->", "get", "(", "'token'", ")", ";", "return", "$", "this", "->", "encryptor", "->", "decrypt", "(", "$", "...
Get refresh token from session and decrypt it. @return mixed
[ "Get", "refresh", "token", "from", "session", "and", "decrypt", "it", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Repositories/TokenRepository.php#L39-L46
omniphx/forrest
src/Omniphx/Forrest/Client.php
Client.request
public function request($url, $options) { $this->url = $url; $this->options = array_replace_recursive($this->settings['defaults'], $options); try { return $this->handleRequest(); } catch (TokenExpiredException $e) { $this->refresh(); return $this->handleRequest(); } }
php
public function request($url, $options) { $this->url = $url; $this->options = array_replace_recursive($this->settings['defaults'], $options); try { return $this->handleRequest(); } catch (TokenExpiredException $e) { $this->refresh(); return $this->handleRequest(); } }
[ "public", "function", "request", "(", "$", "url", ",", "$", "options", ")", "{", "$", "this", "->", "url", "=", "$", "url", ";", "$", "this", "->", "options", "=", "array_replace_recursive", "(", "$", "this", "->", "settings", "[", "'defaults'", "]", ...
Try requesting token, if token expired try refreshing token. @param string $url @param array $options @return mixed
[ "Try", "requesting", "token", "if", "token", "expired", "try", "refreshing", "token", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Client.php#L174-L186
omniphx/forrest
src/Omniphx/Forrest/Client.php
Client.sendRequest
private function sendRequest($path, $requestBody, $options, $method) { $url = $this->instanceURLRepo->get(); $url .= '/'.trim($path, "/\t\n\r\0\x0B"); $options['method'] = $method; if (!empty($requestBody)) { $options['body'] = $requestBody; } return $this->request($url, $options); }
php
private function sendRequest($path, $requestBody, $options, $method) { $url = $this->instanceURLRepo->get(); $url .= '/'.trim($path, "/\t\n\r\0\x0B"); $options['method'] = $method; if (!empty($requestBody)) { $options['body'] = $requestBody; } return $this->request($url, $options); }
[ "private", "function", "sendRequest", "(", "$", "path", ",", "$", "requestBody", ",", "$", "options", ",", "$", "method", ")", "{", "$", "url", "=", "$", "this", "->", "instanceURLRepo", "->", "get", "(", ")", ";", "$", "url", ".=", "'/'", ".", "tr...
Prepares options and sends the request. @param $path @param $requestBody @param $options @param $method @return mixed
[ "Prepares", "options", "and", "sends", "the", "request", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Client.php#L303-L314
omniphx/forrest
src/Omniphx/Forrest/Client.php
Client.versions
public function versions($options = []) { $url = $this->instanceURLRepo->get(); $url .= '/services/data'; $versions = $this->request($url, $options); return $versions; }
php
public function versions($options = []) { $url = $this->instanceURLRepo->get(); $url .= '/services/data'; $versions = $this->request($url, $options); return $versions; }
[ "public", "function", "versions", "(", "$", "options", "=", "[", "]", ")", "{", "$", "url", "=", "$", "this", "->", "instanceURLRepo", "->", "get", "(", ")", ";", "$", "url", ".=", "'/services/data'", ";", "$", "versions", "=", "$", "this", "->", "...
Request that returns all currently supported versions. Includes the verison, label and link to each version's root. Formats: json, xml Methods: get. @param array $options @return array $versions
[ "Request", "that", "returns", "all", "currently", "supported", "versions", ".", "Includes", "the", "verison", "label", "and", "link", "to", "each", "version", "s", "root", ".", "Formats", ":", "json", "xml", "Methods", ":", "get", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Client.php#L326-L334
omniphx/forrest
src/Omniphx/Forrest/Client.php
Client.resources
public function resources($options = []) { $url = $this->getBaseUrl(); $resources = $this->request($url, $options); return $resources; }
php
public function resources($options = []) { $url = $this->getBaseUrl(); $resources = $this->request($url, $options); return $resources; }
[ "public", "function", "resources", "(", "$", "options", "=", "[", "]", ")", "{", "$", "url", "=", "$", "this", "->", "getBaseUrl", "(", ")", ";", "$", "resources", "=", "$", "this", "->", "request", "(", "$", "url", ",", "$", "options", ")", ";",...
Lists availabe resources for specified API version. Includes resource name and URI. Formats: json, xml Methods: get. @param array $options @return array $resources
[ "Lists", "availabe", "resources", "for", "specified", "API", "version", ".", "Includes", "resource", "name", "and", "URI", ".", "Formats", ":", "json", "xml", "Methods", ":", "get", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Client.php#L346-L352
omniphx/forrest
src/Omniphx/Forrest/Client.php
Client.identity
public function identity($options = []) { $token = $this->tokenRepo->get(); $accessToken = $token['access_token']; $url = $token['id']; $options['headers']['Authorization'] = "OAuth $accessToken"; $identity = $this->request($url, $options); return $identity; }
php
public function identity($options = []) { $token = $this->tokenRepo->get(); $accessToken = $token['access_token']; $url = $token['id']; $options['headers']['Authorization'] = "OAuth $accessToken"; $identity = $this->request($url, $options); return $identity; }
[ "public", "function", "identity", "(", "$", "options", "=", "[", "]", ")", "{", "$", "token", "=", "$", "this", "->", "tokenRepo", "->", "get", "(", ")", ";", "$", "accessToken", "=", "$", "token", "[", "'access_token'", "]", ";", "$", "url", "=", ...
Returns information about the logged-in user. @param array @return array $identity
[ "Returns", "information", "about", "the", "logged", "-", "in", "user", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Client.php#L361-L372
omniphx/forrest
src/Omniphx/Forrest/Client.php
Client.limits
public function limits($options = []) { $url = $this->getBaseUrl(); $url .= '/limits'; $limits = $this->request($url, $options); return $limits; }
php
public function limits($options = []) { $url = $this->getBaseUrl(); $url .= '/limits'; $limits = $this->request($url, $options); return $limits; }
[ "public", "function", "limits", "(", "$", "options", "=", "[", "]", ")", "{", "$", "url", "=", "$", "this", "->", "getBaseUrl", "(", ")", ";", "$", "url", ".=", "'/limits'", ";", "$", "limits", "=", "$", "this", "->", "request", "(", "$", "url", ...
Lists information about organizational limits. Available for API version 29.0 and later. Returns limits for daily API calls, Data storage, etc. @param array $options @return array $limits
[ "Lists", "information", "about", "organizational", "limits", ".", "Available", "for", "API", "version", "29", ".", "0", "and", "later", ".", "Returns", "limits", "for", "daily", "API", "calls", "Data", "storage", "etc", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Client.php#L383-L391
omniphx/forrest
src/Omniphx/Forrest/Client.php
Client.describe
public function describe($object_name = null, $options = []) { $url = sprintf('%s/sobjects', $this->getBaseUrl()); if ( ! empty($object_name)) { $url .= sprintf('/%s/describe', $object_name); } return $this->request($url, $options); }
php
public function describe($object_name = null, $options = []) { $url = sprintf('%s/sobjects', $this->getBaseUrl()); if ( ! empty($object_name)) { $url .= sprintf('/%s/describe', $object_name); } return $this->request($url, $options); }
[ "public", "function", "describe", "(", "$", "object_name", "=", "null", ",", "$", "options", "=", "[", "]", ")", "{", "$", "url", "=", "sprintf", "(", "'%s/sobjects'", ",", "$", "this", "->", "getBaseUrl", "(", ")", ")", ";", "if", "(", "!", "empty...
Describes all global objects available in the organization. @param string $object_name @param array $options @return array
[ "Describes", "all", "global", "objects", "available", "in", "the", "organization", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Client.php#L400-L409
omniphx/forrest
src/Omniphx/Forrest/Client.php
Client.query
public function query($query, $options = []) { $url = $this->instanceURLRepo->get(); $url .= $this->resourceRepo->get('query'); $url .= '?q='; $url .= urlencode($query); $queryResults = $this->request($url, $options); return $queryResults; }
php
public function query($query, $options = []) { $url = $this->instanceURLRepo->get(); $url .= $this->resourceRepo->get('query'); $url .= '?q='; $url .= urlencode($query); $queryResults = $this->request($url, $options); return $queryResults; }
[ "public", "function", "query", "(", "$", "query", ",", "$", "options", "=", "[", "]", ")", "{", "$", "url", "=", "$", "this", "->", "instanceURLRepo", "->", "get", "(", ")", ";", "$", "url", ".=", "$", "this", "->", "resourceRepo", "->", "get", "...
Executes a specified SOQL query. @param string $query @param array $options @return array $queryResults
[ "Executes", "a", "specified", "SOQL", "query", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Client.php#L419-L429
omniphx/forrest
src/Omniphx/Forrest/Client.php
Client.next
public function next($nextUrl, $options = []) { $url = $this->instanceURLRepo->get(); $url .= $nextUrl; $queryResults = $this->request($url, $options); return $queryResults; }
php
public function next($nextUrl, $options = []) { $url = $this->instanceURLRepo->get(); $url .= $nextUrl; $queryResults = $this->request($url, $options); return $queryResults; }
[ "public", "function", "next", "(", "$", "nextUrl", ",", "$", "options", "=", "[", "]", ")", "{", "$", "url", "=", "$", "this", "->", "instanceURLRepo", "->", "get", "(", ")", ";", "$", "url", ".=", "$", "nextUrl", ";", "$", "queryResults", "=", "...
Calls next query. @param $nextUrl @param array $options @return mixed
[ "Calls", "next", "query", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Client.php#L439-L447
omniphx/forrest
src/Omniphx/Forrest/Client.php
Client.search
public function search($query, $options = []) { $url = $this->instanceURLRepo->get(); $url .= $this->resourceRepo->get('search'); $url .= '?q='; $url .= urlencode($query); $searchResults = $this->request($url, $options); return $searchResults; }
php
public function search($query, $options = []) { $url = $this->instanceURLRepo->get(); $url .= $this->resourceRepo->get('search'); $url .= '?q='; $url .= urlencode($query); $searchResults = $this->request($url, $options); return $searchResults; }
[ "public", "function", "search", "(", "$", "query", ",", "$", "options", "=", "[", "]", ")", "{", "$", "url", "=", "$", "this", "->", "instanceURLRepo", "->", "get", "(", ")", ";", "$", "url", ".=", "$", "this", "->", "resourceRepo", "->", "get", ...
Executes the specified SOSL query. @param string $query @param array $options @return array
[ "Executes", "the", "specified", "SOSL", "query", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Client.php#L500-L510
omniphx/forrest
src/Omniphx/Forrest/Client.php
Client.scopeOrder
public function scopeOrder($options = []) { $url = $this->instanceURLRepo->get(); $url .= $this->resourceRepo->get('search'); $url .= '/scopeOrder'; $scopeOrder = $this->request($url, $options); return $scopeOrder; }
php
public function scopeOrder($options = []) { $url = $this->instanceURLRepo->get(); $url .= $this->resourceRepo->get('search'); $url .= '/scopeOrder'; $scopeOrder = $this->request($url, $options); return $scopeOrder; }
[ "public", "function", "scopeOrder", "(", "$", "options", "=", "[", "]", ")", "{", "$", "url", "=", "$", "this", "->", "instanceURLRepo", "->", "get", "(", ")", ";", "$", "url", ".=", "$", "this", "->", "resourceRepo", "->", "get", "(", "'search'", ...
Returns an ordered list of objects in the default global search scope of a logged-in user. Global search keeps track of which objects the user interacts with and how often and arranges the search results accordingly. Objects used most frequently appear at the top of the list. @param array $options @return array
[ "Returns", "an", "ordered", "list", "of", "objects", "in", "the", "default", "global", "search", "scope", "of", "a", "logged", "-", "in", "user", ".", "Global", "search", "keeps", "track", "of", "which", "objects", "the", "user", "interacts", "with", "and"...
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Client.php#L523-L532
omniphx/forrest
src/Omniphx/Forrest/Client.php
Client.searchLayouts
public function searchLayouts($objectList, $options = []) { $url = $this->instanceURLRepo->get(); $url .= $this->resourceRepo->get('search'); $url .= '/layout/?q='; $url .= urlencode($objectList); $searchLayouts = $this->request($url, $options); return $searchLayouts; }
php
public function searchLayouts($objectList, $options = []) { $url = $this->instanceURLRepo->get(); $url .= $this->resourceRepo->get('search'); $url .= '/layout/?q='; $url .= urlencode($objectList); $searchLayouts = $this->request($url, $options); return $searchLayouts; }
[ "public", "function", "searchLayouts", "(", "$", "objectList", ",", "$", "options", "=", "[", "]", ")", "{", "$", "url", "=", "$", "this", "->", "instanceURLRepo", "->", "get", "(", ")", ";", "$", "url", ".=", "$", "this", "->", "resourceRepo", "->",...
Returns search result layout information for the objects in the query string. @param array $objectList @param array $options @return array
[ "Returns", "search", "result", "layout", "information", "for", "the", "objects", "in", "the", "query", "string", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Client.php#L542-L552
omniphx/forrest
src/Omniphx/Forrest/Client.php
Client.suggestedArticles
public function suggestedArticles($query, $options = []) { $url = $this->instanceURLRepo->get(); $url .= $this->resourceRepo->get('search'); $url .= '/suggestTitleMatches?q='; $url .= urlencode($query); $parameters = [ 'language' => $this->settings['language'], 'publishStatus' => 'Online', ]; if (isset($options['parameters'])) { $parameters = array_replace_recursive($parameters, $options['parameters']); $url .= '&'.http_build_query($parameters); } $suggestedArticles = $this->request($url, $options); return $suggestedArticles; }
php
public function suggestedArticles($query, $options = []) { $url = $this->instanceURLRepo->get(); $url .= $this->resourceRepo->get('search'); $url .= '/suggestTitleMatches?q='; $url .= urlencode($query); $parameters = [ 'language' => $this->settings['language'], 'publishStatus' => 'Online', ]; if (isset($options['parameters'])) { $parameters = array_replace_recursive($parameters, $options['parameters']); $url .= '&'.http_build_query($parameters); } $suggestedArticles = $this->request($url, $options); return $suggestedArticles; }
[ "public", "function", "suggestedArticles", "(", "$", "query", ",", "$", "options", "=", "[", "]", ")", "{", "$", "url", "=", "$", "this", "->", "instanceURLRepo", "->", "get", "(", ")", ";", "$", "url", ".=", "$", "this", "->", "resourceRepo", "->", ...
Returns a list of Salesforce Knowledge articles whose titles match the user’s search query. Provides a shortcut to navigate directly to likely relevant articles, before the user performs a search. Available for API version 30.0 or later. @param string $query @param array $options @return array
[ "Returns", "a", "list", "of", "Salesforce", "Knowledge", "articles", "whose", "titles", "match", "the", "user’s", "search", "query", ".", "Provides", "a", "shortcut", "to", "navigate", "directly", "to", "likely", "relevant", "articles", "before", "the", "user", ...
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Client.php#L565-L585
omniphx/forrest
src/Omniphx/Forrest/Client.php
Client.custom
public function custom($customURI, $options = []) { $url = $this->instanceURLRepo->get(); $url .= '/services/apexrest'; $url .= $customURI; $parameters = []; if (isset($options['parameters'])) { $parameters = array_replace_recursive($parameters, $options['parameters']); $url .= '?'.http_build_query($parameters); } return $this->request($url, $options); }
php
public function custom($customURI, $options = []) { $url = $this->instanceURLRepo->get(); $url .= '/services/apexrest'; $url .= $customURI; $parameters = []; if (isset($options['parameters'])) { $parameters = array_replace_recursive($parameters, $options['parameters']); $url .= '?'.http_build_query($parameters); } return $this->request($url, $options); }
[ "public", "function", "custom", "(", "$", "customURI", ",", "$", "options", "=", "[", "]", ")", "{", "$", "url", "=", "$", "this", "->", "instanceURLRepo", "->", "get", "(", ")", ";", "$", "url", ".=", "'/services/apexrest'", ";", "$", "url", ".=", ...
Request to a custom Apex REST endpoint. @param string $customURI @param array $options @return mixed
[ "Request", "to", "a", "custom", "Apex", "REST", "endpoint", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Client.php#L626-L640
omniphx/forrest
src/Omniphx/Forrest/Client.php
Client.storeVersion
protected function storeVersion() { $versions = $this->versions(); $this->storeConfiguredVersion($versions); $this->storeLatestVersion($versions); }
php
protected function storeVersion() { $versions = $this->versions(); $this->storeConfiguredVersion($versions); $this->storeLatestVersion($versions); }
[ "protected", "function", "storeVersion", "(", ")", "{", "$", "versions", "=", "$", "this", "->", "versions", "(", ")", ";", "$", "this", "->", "storeConfiguredVersion", "(", "$", "versions", ")", ";", "$", "this", "->", "storeLatestVersion", "(", "$", "v...
Checks to see if version is specified in configuration and if not then assign the latest version number available to the user's instance. Once a version number is determined, it will be stored in the user's storage with the 'version' key. @return void
[ "Checks", "to", "see", "if", "version", "is", "specified", "in", "configuration", "and", "if", "not", "then", "assign", "the", "latest", "version", "number", "available", "to", "the", "user", "s", "instance", ".", "Once", "a", "version", "number", "is", "d...
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Client.php#L728-L734
omniphx/forrest
src/Omniphx/Forrest/Client.php
Client.assignExceptions
private function assignExceptions(RequestException $ex) { if ($ex->hasResponse() && $ex->getResponse()->getStatusCode() == 401) { throw new TokenExpiredException('Salesforce token has expired', $ex); } elseif ($ex->hasResponse()) { throw new SalesforceException('Salesforce response error: '.$ex->getMessage(), $ex); } else { throw new SalesforceException('Invalid request: %s', $ex); } }
php
private function assignExceptions(RequestException $ex) { if ($ex->hasResponse() && $ex->getResponse()->getStatusCode() == 401) { throw new TokenExpiredException('Salesforce token has expired', $ex); } elseif ($ex->hasResponse()) { throw new SalesforceException('Salesforce response error: '.$ex->getMessage(), $ex); } else { throw new SalesforceException('Invalid request: %s', $ex); } }
[ "private", "function", "assignExceptions", "(", "RequestException", "$", "ex", ")", "{", "if", "(", "$", "ex", "->", "hasResponse", "(", ")", "&&", "$", "ex", "->", "getResponse", "(", ")", "->", "getStatusCode", "(", ")", "==", "401", ")", "{", "throw...
Method will elaborate on RequestException. @param RequestException $ex @throws SalesforceException @throws TokenExpiredException
[ "Method", "will", "elaborate", "on", "RequestException", "." ]
train
https://github.com/omniphx/forrest/blob/17c203b7ecb42f5ff8cbb4c286c4d0c55d7b1ea9/src/Omniphx/Forrest/Client.php#L786-L795
algo26-matthias/idna-convert
src/ToIdn.php
ToIdn.convert
public function convert(string $host): string { if (strlen($host) === 0) { return $host; } if (strpos('/', $host) !== false || strpos(':', $host) !== false || strpos('?', $host) !== false || strpos('@', $host) !== false ) { throw new InvalidCharacterException('Neither email addresses nor URLs are allowed', 205); } // These three punctuation characters are treated like the dot $host = str_replace(['。', '.', '。'], '.', $host); // Operate per label $hostLabels = explode('.', $host); foreach ($hostLabels as $index => $label) { $asUcs4Array = $this->unicodeTransCoder->convert( $label, $this->unicodeTransCoder::FORMAT_UTF8, $this->unicodeTransCoder::FORMAT_UCS4_ARRAY ); $encoded = $this->punycodeEncoder->convert($asUcs4Array); if ($encoded) { $hostLabels[$index] = $encoded; } } return implode('.', $hostLabels); }
php
public function convert(string $host): string { if (strlen($host) === 0) { return $host; } if (strpos('/', $host) !== false || strpos(':', $host) !== false || strpos('?', $host) !== false || strpos('@', $host) !== false ) { throw new InvalidCharacterException('Neither email addresses nor URLs are allowed', 205); } // These three punctuation characters are treated like the dot $host = str_replace(['。', '.', '。'], '.', $host); // Operate per label $hostLabels = explode('.', $host); foreach ($hostLabels as $index => $label) { $asUcs4Array = $this->unicodeTransCoder->convert( $label, $this->unicodeTransCoder::FORMAT_UTF8, $this->unicodeTransCoder::FORMAT_UCS4_ARRAY ); $encoded = $this->punycodeEncoder->convert($asUcs4Array); if ($encoded) { $hostLabels[$index] = $encoded; } } return implode('.', $hostLabels); }
[ "public", "function", "convert", "(", "string", "$", "host", ")", ":", "string", "{", "if", "(", "strlen", "(", "$", "host", ")", "===", "0", ")", "{", "return", "$", "host", ";", "}", "if", "(", "strpos", "(", "'/'", ",", "$", "host", ")", "!=...
@param string $host @return string @throws InvalidCharacterException @throws Exception\AlreadyPunycodeException
[ "@param", "string", "$host" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/ToIdn.php#L33-L65
algo26-matthias/idna-convert
src/EncodingHelper/ToUtf8.php
ToUtf8.mapWindows1252ToIso8859_1
private function mapWindows1252ToIso8859_1($string = '') { $return = ''; for ($i = 0; $i < strlen($string); ++$i) { $codePoint = ord($string{$i}); switch ($codePoint) { case 129: $return .= chr(252); break; case 132: $return .= chr(228); break; case 142: $return .= chr(196); break; case 148: $return .= chr(246); break; case 153: $return .= chr(214); break; case 154: $return .= chr(220); break; case 225: $return .= chr(223); break; default: $return .= chr($codePoint); } } return $return; }
php
private function mapWindows1252ToIso8859_1($string = '') { $return = ''; for ($i = 0; $i < strlen($string); ++$i) { $codePoint = ord($string{$i}); switch ($codePoint) { case 129: $return .= chr(252); break; case 132: $return .= chr(228); break; case 142: $return .= chr(196); break; case 148: $return .= chr(246); break; case 153: $return .= chr(214); break; case 154: $return .= chr(220); break; case 225: $return .= chr(223); break; default: $return .= chr($codePoint); } } return $return; }
[ "private", "function", "mapWindows1252ToIso8859_1", "(", "$", "string", "=", "''", ")", "{", "$", "return", "=", "''", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "strlen", "(", "$", "string", ")", ";", "++", "$", "i", ")", "{", "$...
Special treatment for our guys in Redmond Windows-1252 is basically ISO-8859-1 -- with some exceptions, which get dealt with here @param string $string Your input in Win1252 @return string The resulting ISO-8859-1 string @since 0.0.1
[ "Special", "treatment", "for", "our", "guys", "in", "Redmond", "Windows", "-", "1252", "is", "basically", "ISO", "-", "8859", "-", "1", "--", "with", "some", "exceptions", "which", "get", "dealt", "with", "here" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/EncodingHelper/ToUtf8.php#L57-L90
algo26-matthias/idna-convert
src/Punycode/AbstractPunycode.php
AbstractPunycode.byteLength
protected function byteLength($string): int { if (self::$isMbStringOverload) { return mb_strlen($string, '8bit'); } return strlen((binary) $string); }
php
protected function byteLength($string): int { if (self::$isMbStringOverload) { return mb_strlen($string, '8bit'); } return strlen((binary) $string); }
[ "protected", "function", "byteLength", "(", "$", "string", ")", ":", "int", "{", "if", "(", "self", "::", "$", "isMbStringOverload", ")", "{", "return", "mb_strlen", "(", "$", "string", ",", "'8bit'", ")", ";", "}", "return", "strlen", "(", "(", "binar...
Gets the length of a string in bytes even if mbstring function overloading is turned on @param string $string the string for which to get the length. @return integer the length of the string in bytes.
[ "Gets", "the", "length", "of", "a", "string", "in", "bytes", "even", "if", "mbstring", "function", "overloading", "is", "turned", "on" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/Punycode/AbstractPunycode.php#L59-L66
algo26-matthias/idna-convert
src/Punycode/AbstractPunycode.php
AbstractPunycode.adapt
protected function adapt($delta, $nPoints, $isFirst): int { $delta = intval($isFirst ? ($delta / self::damp) : ($delta / 2)); $delta += intval($delta / $nPoints); for ($k = 0; $delta > ((self::base - self::tMin) * self::tMax) / 2; $k += self::base) { $delta = intval($delta / (self::base - self::tMin)); } return intval($k + (self::base - self::tMin + 1) * $delta / ($delta + self::skew)); }
php
protected function adapt($delta, $nPoints, $isFirst): int { $delta = intval($isFirst ? ($delta / self::damp) : ($delta / 2)); $delta += intval($delta / $nPoints); for ($k = 0; $delta > ((self::base - self::tMin) * self::tMax) / 2; $k += self::base) { $delta = intval($delta / (self::base - self::tMin)); } return intval($k + (self::base - self::tMin + 1) * $delta / ($delta + self::skew)); }
[ "protected", "function", "adapt", "(", "$", "delta", ",", "$", "nPoints", ",", "$", "isFirst", ")", ":", "int", "{", "$", "delta", "=", "intval", "(", "$", "isFirst", "?", "(", "$", "delta", "/", "self", "::", "damp", ")", ":", "(", "$", "delta",...
Adapt the bias according to the current code point and position @param int $delta @param int $nPoints @param int $isFirst @return int
[ "Adapt", "the", "bias", "according", "to", "the", "current", "code", "point", "and", "position" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/Punycode/AbstractPunycode.php#L76-L85
algo26-matthias/idna-convert
src/NamePrep/NamePrep.php
NamePrep.do
public function do(array $inputArray): array { $outputArray = $this->applyCharacterMaps($inputArray); $outputArray = $this->hangulCompose($outputArray); $outputArray = $this->combineCodePoints($outputArray); return $outputArray; }
php
public function do(array $inputArray): array { $outputArray = $this->applyCharacterMaps($inputArray); $outputArray = $this->hangulCompose($outputArray); $outputArray = $this->combineCodePoints($outputArray); return $outputArray; }
[ "public", "function", "do", "(", "array", "$", "inputArray", ")", ":", "array", "{", "$", "outputArray", "=", "$", "this", "->", "applyCharacterMaps", "(", "$", "inputArray", ")", ";", "$", "outputArray", "=", "$", "this", "->", "hangulCompose", "(", "$"...
@param array $inputArray @return array @throws InvalidCharacterException
[ "@param", "array", "$inputArray" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/NamePrep/NamePrep.php#L52-L59
algo26-matthias/idna-convert
src/NamePrep/NamePrep.php
NamePrep.applyCharacterMaps
private function applyCharacterMaps(array $inputArray): array { $outputArray = []; foreach ($inputArray as $codePoint) { // Map to nothing == skip that code point if (in_array($codePoint, $this->namePrepData->mapToNothing)) { continue; } // Try to find prohibited input if (in_array($codePoint, $this->namePrepData->prohibit) || in_array($codePoint, $this->namePrepData->generalProhibited) ) { throw new InvalidCharacterException(sprintf('Prohibited input U+%08X', $codePoint), 101); } foreach ($this->namePrepData->prohibitRanges as $range) { if ($range[0] <= $codePoint && $codePoint <= $range[1]) { throw new InvalidCharacterException(sprintf('Prohibited input U+%08X', $codePoint), 102); } } if (0xAC00 <= $codePoint && $codePoint <= 0xD7AF) { // Hangul syllable decomposition foreach ($this->hangulDecompose($codePoint) as $decomposed) { $outputArray[] = (int) $decomposed; } } elseif (isset($this->namePrepData->replaceMaps[$codePoint])) { foreach ($this->applyCanonicalOrdering($this->namePrepData->replaceMaps[$codePoint]) as $reordered) { $outputArray[] = (int) $reordered; } } else { $outputArray[] = (int) $codePoint; } } return $outputArray; }
php
private function applyCharacterMaps(array $inputArray): array { $outputArray = []; foreach ($inputArray as $codePoint) { // Map to nothing == skip that code point if (in_array($codePoint, $this->namePrepData->mapToNothing)) { continue; } // Try to find prohibited input if (in_array($codePoint, $this->namePrepData->prohibit) || in_array($codePoint, $this->namePrepData->generalProhibited) ) { throw new InvalidCharacterException(sprintf('Prohibited input U+%08X', $codePoint), 101); } foreach ($this->namePrepData->prohibitRanges as $range) { if ($range[0] <= $codePoint && $codePoint <= $range[1]) { throw new InvalidCharacterException(sprintf('Prohibited input U+%08X', $codePoint), 102); } } if (0xAC00 <= $codePoint && $codePoint <= 0xD7AF) { // Hangul syllable decomposition foreach ($this->hangulDecompose($codePoint) as $decomposed) { $outputArray[] = (int) $decomposed; } } elseif (isset($this->namePrepData->replaceMaps[$codePoint])) { foreach ($this->applyCanonicalOrdering($this->namePrepData->replaceMaps[$codePoint]) as $reordered) { $outputArray[] = (int) $reordered; } } else { $outputArray[] = (int) $codePoint; } } return $outputArray; }
[ "private", "function", "applyCharacterMaps", "(", "array", "$", "inputArray", ")", ":", "array", "{", "$", "outputArray", "=", "[", "]", ";", "foreach", "(", "$", "inputArray", "as", "$", "codePoint", ")", "{", "// Map to nothing == skip that code point", "if", ...
@param array $inputArray @return array @throws InvalidCharacterException
[ "@param", "array", "$inputArray" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/NamePrep/NamePrep.php#L67-L102
algo26-matthias/idna-convert
src/NamePrep/NamePrep.php
NamePrep.hangulDecompose
private function hangulDecompose(int $codePoint): array { $sIndex = (int) $codePoint - self::sBase; if ($sIndex < 0 || $sIndex >= self::sCount) { return [$codePoint]; } $result = [ (int) self::lBase + $sIndex / self::nCount, (int) self::vBase + ($sIndex % self::nCount) / self::tCount, ]; $T = intval(self::tBase + $sIndex % self::tCount); if ($T != self::tBase) { $result[] = $T; } return $result; }
php
private function hangulDecompose(int $codePoint): array { $sIndex = (int) $codePoint - self::sBase; if ($sIndex < 0 || $sIndex >= self::sCount) { return [$codePoint]; } $result = [ (int) self::lBase + $sIndex / self::nCount, (int) self::vBase + ($sIndex % self::nCount) / self::tCount, ]; $T = intval(self::tBase + $sIndex % self::tCount); if ($T != self::tBase) { $result[] = $T; } return $result; }
[ "private", "function", "hangulDecompose", "(", "int", "$", "codePoint", ")", ":", "array", "{", "$", "sIndex", "=", "(", "int", ")", "$", "codePoint", "-", "self", "::", "sBase", ";", "if", "(", "$", "sIndex", "<", "0", "||", "$", "sIndex", ">=", "...
Decomposes a Hangul syllable (see http://www.unicode.org/unicode/reports/tr15/#Hangul @param integer 32bit UCS4 code point @return array Either Hangul Syllable decomposed or original 32bit value as one value array
[ "Decomposes", "a", "Hangul", "syllable", "(", "see", "http", ":", "//", "www", ".", "unicode", ".", "org", "/", "unicode", "/", "reports", "/", "tr15", "/", "#Hangul" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/NamePrep/NamePrep.php#L155-L172
algo26-matthias/idna-convert
src/NamePrep/NamePrep.php
NamePrep.hangulCompose
private function hangulCompose(array $input): array { $inputLength = count($input); if ($inputLength === 0) { return []; } $previousCharCode = (int) $input[0]; // copy first codepoint from input to output $result = [ $previousCharCode, ]; for ($i = 1; $i < $inputLength; ++$i) { $charCode = (int) $input[$i]; $sIndex = $previousCharCode - self::sBase; $lIndex = $previousCharCode - self::lBase; $vIndex = $charCode - self::vBase; $tIndex = $charCode - self::tBase; // Find out, whether two current characters are LV and T if (0 <= $sIndex && $sIndex < self::sCount && ($sIndex % self::tCount == 0) && 0 <= $tIndex && $tIndex <= self::tCount ) { // create syllable of form LVT $previousCharCode += $tIndex; $result[(count($result) - 1)] = $previousCharCode; // reset last continue; // discard char } // Find out, whether two current characters form L and V if (0 <= $lIndex && $lIndex < self::lCount && 0 <= $vIndex && $vIndex < self::vCount ) { // create syllable of form LV $previousCharCode = (int) self::sBase + ($lIndex * self::vCount + $vIndex) * self::tCount; $result[(count($result) - 1)] = $previousCharCode; // reset last continue; // discard char } // if neither case was true, just add the character $previousCharCode = $charCode; $result[] = $charCode; } return $result; }
php
private function hangulCompose(array $input): array { $inputLength = count($input); if ($inputLength === 0) { return []; } $previousCharCode = (int) $input[0]; // copy first codepoint from input to output $result = [ $previousCharCode, ]; for ($i = 1; $i < $inputLength; ++$i) { $charCode = (int) $input[$i]; $sIndex = $previousCharCode - self::sBase; $lIndex = $previousCharCode - self::lBase; $vIndex = $charCode - self::vBase; $tIndex = $charCode - self::tBase; // Find out, whether two current characters are LV and T if (0 <= $sIndex && $sIndex < self::sCount && ($sIndex % self::tCount == 0) && 0 <= $tIndex && $tIndex <= self::tCount ) { // create syllable of form LVT $previousCharCode += $tIndex; $result[(count($result) - 1)] = $previousCharCode; // reset last continue; // discard char } // Find out, whether two current characters form L and V if (0 <= $lIndex && $lIndex < self::lCount && 0 <= $vIndex && $vIndex < self::vCount ) { // create syllable of form LV $previousCharCode = (int) self::sBase + ($lIndex * self::vCount + $vIndex) * self::tCount; $result[(count($result) - 1)] = $previousCharCode; // reset last continue; // discard char } // if neither case was true, just add the character $previousCharCode = $charCode; $result[] = $charCode; } return $result; }
[ "private", "function", "hangulCompose", "(", "array", "$", "input", ")", ":", "array", "{", "$", "inputLength", "=", "count", "(", "$", "input", ")", ";", "if", "(", "$", "inputLength", "===", "0", ")", "{", "return", "[", "]", ";", "}", "$", "prev...
Compose a Hangul syllable (see http://www.unicode.org/unicode/reports/tr15/#Hangul @param array $input Decomposed UCS4 sequence @return array UCS4 sequence with syllables composed
[ "Compose", "a", "Hangul", "syllable", "(", "see", "http", ":", "//", "www", ".", "unicode", ".", "org", "/", "unicode", "/", "reports", "/", "tr15", "/", "#Hangul" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/NamePrep/NamePrep.php#L181-L234
algo26-matthias/idna-convert
src/NamePrep/NamePrep.php
NamePrep.getCombiningClass
private function getCombiningClass(int $char): int { return isset($this->namePrepData->normalizeCombiningClasses[$char]) ? $this->namePrepData->normalizeCombiningClasses[$char] : 0; }
php
private function getCombiningClass(int $char): int { return isset($this->namePrepData->normalizeCombiningClasses[$char]) ? $this->namePrepData->normalizeCombiningClasses[$char] : 0; }
[ "private", "function", "getCombiningClass", "(", "int", "$", "char", ")", ":", "int", "{", "return", "isset", "(", "$", "this", "->", "namePrepData", "->", "normalizeCombiningClasses", "[", "$", "char", "]", ")", "?", "$", "this", "->", "namePrepData", "->...
Returns the combining class of a certain wide char @param integer $char Wide char to check (32bit integer) @return integer Combining class if found, else 0
[ "Returns", "the", "combining", "class", "of", "a", "certain", "wide", "char" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/NamePrep/NamePrep.php#L241-L246
algo26-matthias/idna-convert
src/NamePrep/NamePrep.php
NamePrep.applyCanonicalOrdering
private function applyCanonicalOrdering(array $input): array { $needsSwapping = true; $inputLength = count($input); while ($needsSwapping) { $needsSwapping = false; $previousClass = $this->getCombiningClass(intval($input[0])); for ($outerIndex = 0; $outerIndex < $inputLength - 1; ++$outerIndex) { $nextClass = $this->getCombiningClass(intval($input[$outerIndex + 1])); if ($nextClass !== 0 && $previousClass > $nextClass) { // Move item leftward until it fits for ($innerIndex = $outerIndex + 1; $innerIndex > 0; --$innerIndex) { if ($this->getCombiningClass(intval($input[$innerIndex - 1])) <= $nextClass) { break; } $charToMove = intval($input[$innerIndex]); $input[$innerIndex] = intval($input[$innerIndex - 1]); $input[$innerIndex - 1] = $charToMove; $needsSwapping = true; } // Reentering the loop looking at the old character again $nextClass = $previousClass; } $previousClass = $nextClass; } } return $input; }
php
private function applyCanonicalOrdering(array $input): array { $needsSwapping = true; $inputLength = count($input); while ($needsSwapping) { $needsSwapping = false; $previousClass = $this->getCombiningClass(intval($input[0])); for ($outerIndex = 0; $outerIndex < $inputLength - 1; ++$outerIndex) { $nextClass = $this->getCombiningClass(intval($input[$outerIndex + 1])); if ($nextClass !== 0 && $previousClass > $nextClass) { // Move item leftward until it fits for ($innerIndex = $outerIndex + 1; $innerIndex > 0; --$innerIndex) { if ($this->getCombiningClass(intval($input[$innerIndex - 1])) <= $nextClass) { break; } $charToMove = intval($input[$innerIndex]); $input[$innerIndex] = intval($input[$innerIndex - 1]); $input[$innerIndex - 1] = $charToMove; $needsSwapping = true; } // Reentering the loop looking at the old character again $nextClass = $previousClass; } $previousClass = $nextClass; } } return $input; }
[ "private", "function", "applyCanonicalOrdering", "(", "array", "$", "input", ")", ":", "array", "{", "$", "needsSwapping", "=", "true", ";", "$", "inputLength", "=", "count", "(", "$", "input", ")", ";", "while", "(", "$", "needsSwapping", ")", "{", "$",...
Applies the canonical ordering of a decomposed UCS4 sequence @param array $input Decomposed UCS4 sequence @return array Ordered USC4 sequence
[ "Applies", "the", "canonical", "ordering", "of", "a", "decomposed", "UCS4", "sequence" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/NamePrep/NamePrep.php#L253-L281
algo26-matthias/idna-convert
src/NamePrep/NamePrep.php
NamePrep.combine
private function combine(array $input) { $inputLength = count($input); if (0 === $inputLength) { return false; } foreach ($this->namePrepData->replaceMaps as $namePrepSource => $namePrepTarget) { if ($namePrepTarget[0] !== $input[0]) { continue; } if (count($namePrepTarget) !== $inputLength) { continue; } $hit = false; foreach ($input as $k2 => $v2) { if ($v2 === $namePrepTarget[$k2]) { $hit = true; } else { $hit = false; break; } } if ($hit) { return $namePrepSource; } } return false; }
php
private function combine(array $input) { $inputLength = count($input); if (0 === $inputLength) { return false; } foreach ($this->namePrepData->replaceMaps as $namePrepSource => $namePrepTarget) { if ($namePrepTarget[0] !== $input[0]) { continue; } if (count($namePrepTarget) !== $inputLength) { continue; } $hit = false; foreach ($input as $k2 => $v2) { if ($v2 === $namePrepTarget[$k2]) { $hit = true; } else { $hit = false; break; } } if ($hit) { return $namePrepSource; } } return false; }
[ "private", "function", "combine", "(", "array", "$", "input", ")", "{", "$", "inputLength", "=", "count", "(", "$", "input", ")", ";", "if", "(", "0", "===", "$", "inputLength", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "this", "-...
Do composition of a sequence of starter and non-starter @param array $input UCS4 Decomposed sequence @return array|false Ordered USC4 sequence
[ "Do", "composition", "of", "a", "sequence", "of", "starter", "and", "non", "-", "starter" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/NamePrep/NamePrep.php#L288-L317
algo26-matthias/idna-convert
src/Punycode/FromPunycode.php
FromPunycode.convert
public function convert($encoded) { if (!$this->validate($encoded)) { return false; } $decoded = []; // Find last occurrence of the delimiter $delimiterPosition = strrpos($encoded, '-'); if ($delimiterPosition > self::byteLength(self::punycodePrefix)) { for ($k = $this->byteLength(self::punycodePrefix); $k < $delimiterPosition; ++$k) { $decoded[] = ord($encoded[$k]); } } $decodedLength = count($decoded); $encodedLength = $this->byteLength($encoded); // Wandering through the strings; init $isFirst = true; $bias = self::initialBias; $currentIndex = 0; $char = self::initialN; for ($encodedIndex = ($delimiterPosition) ? ($delimiterPosition + 1) : 0; $encodedIndex < $encodedLength; ++$decodedLength) { for ($oldIndex = $currentIndex, $w = 1, $k = self::base; 1; $k += self::base) { $digit = $this->decodeDigit($encoded[$encodedIndex++]); $currentIndex += $digit * $w; $t = ($k <= $bias) ? self::tMin : ( ($k >= $bias + self::tMax) ? self::tMax : ($k - $bias) ); if ($digit < $t) { break; } $w = (int) ($w * (self::base - $t)); } $bias = $this->adapt($currentIndex - $oldIndex, $decodedLength + 1, $isFirst); $isFirst = false; $char += (int) ($currentIndex / ($decodedLength + 1)); $currentIndex %= ($decodedLength + 1); if ($decodedLength > 0) { // Make room for the decoded char for ($i = $decodedLength; $i > $currentIndex; $i--) { $decoded[$i] = $decoded[($i - 1)]; } } $decoded[$currentIndex++] = $char; } return $this->unicodeTransCoder->convert( $decoded, $this->unicodeTransCoder::FORMAT_UCS4_ARRAY, $this->unicodeTransCoder::FORMAT_UTF8 ); }
php
public function convert($encoded) { if (!$this->validate($encoded)) { return false; } $decoded = []; // Find last occurrence of the delimiter $delimiterPosition = strrpos($encoded, '-'); if ($delimiterPosition > self::byteLength(self::punycodePrefix)) { for ($k = $this->byteLength(self::punycodePrefix); $k < $delimiterPosition; ++$k) { $decoded[] = ord($encoded[$k]); } } $decodedLength = count($decoded); $encodedLength = $this->byteLength($encoded); // Wandering through the strings; init $isFirst = true; $bias = self::initialBias; $currentIndex = 0; $char = self::initialN; for ($encodedIndex = ($delimiterPosition) ? ($delimiterPosition + 1) : 0; $encodedIndex < $encodedLength; ++$decodedLength) { for ($oldIndex = $currentIndex, $w = 1, $k = self::base; 1; $k += self::base) { $digit = $this->decodeDigit($encoded[$encodedIndex++]); $currentIndex += $digit * $w; $t = ($k <= $bias) ? self::tMin : ( ($k >= $bias + self::tMax) ? self::tMax : ($k - $bias) ); if ($digit < $t) { break; } $w = (int) ($w * (self::base - $t)); } $bias = $this->adapt($currentIndex - $oldIndex, $decodedLength + 1, $isFirst); $isFirst = false; $char += (int) ($currentIndex / ($decodedLength + 1)); $currentIndex %= ($decodedLength + 1); if ($decodedLength > 0) { // Make room for the decoded char for ($i = $decodedLength; $i > $currentIndex; $i--) { $decoded[$i] = $decoded[($i - 1)]; } } $decoded[$currentIndex++] = $char; } return $this->unicodeTransCoder->convert( $decoded, $this->unicodeTransCoder::FORMAT_UCS4_ARRAY, $this->unicodeTransCoder::FORMAT_UTF8 ); }
[ "public", "function", "convert", "(", "$", "encoded", ")", "{", "if", "(", "!", "$", "this", "->", "validate", "(", "$", "encoded", ")", ")", "{", "return", "false", ";", "}", "$", "decoded", "=", "[", "]", ";", "// Find last occurrence of the delimiter"...
The actual decoding algorithm @param string @return mixed
[ "The", "actual", "decoding", "algorithm" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/Punycode/FromPunycode.php#L17-L74
algo26-matthias/idna-convert
src/Punycode/FromPunycode.php
FromPunycode.validate
private function validate($encoded): bool { // Check for existence of the prefix if (strpos($encoded, self::punycodePrefix) !== 0) { return false; } // If nothing is left after the prefix, it is hopeless if (strlen(trim($encoded)) <= strlen(self::punycodePrefix)) { return false; } return true; }
php
private function validate($encoded): bool { // Check for existence of the prefix if (strpos($encoded, self::punycodePrefix) !== 0) { return false; } // If nothing is left after the prefix, it is hopeless if (strlen(trim($encoded)) <= strlen(self::punycodePrefix)) { return false; } return true; }
[ "private", "function", "validate", "(", "$", "encoded", ")", ":", "bool", "{", "// Check for existence of the prefix", "if", "(", "strpos", "(", "$", "encoded", ",", "self", "::", "punycodePrefix", ")", "!==", "0", ")", "{", "return", "false", ";", "}", "/...
Checks, whether or not the provided string is a valid punycode string @param string $encoded @return boolean
[ "Checks", "whether", "or", "not", "the", "provided", "string", "is", "a", "valid", "punycode", "string" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/Punycode/FromPunycode.php#L82-L95
algo26-matthias/idna-convert
src/EncodingHelper/FromUtf8.php
FromUtf8.mapIso8859_1ToWindows1252
private function mapIso8859_1ToWindows1252($string = '') { $return = ''; for ($i = 0; $i < strlen($string); ++$i) { $codePoint = ord($string{$i}); switch ($codePoint) { case 196: $return .= chr(142); break; case 214: $return .= chr(153); break; case 220: $return .= chr(154); break; case 223: $return .= chr(225); break; case 228: $return .= chr(132); break; case 246: $return .= chr(148); break; case 252: $return .= chr(129); break; default: $return .= chr($codePoint); } } return $return; }
php
private function mapIso8859_1ToWindows1252($string = '') { $return = ''; for ($i = 0; $i < strlen($string); ++$i) { $codePoint = ord($string{$i}); switch ($codePoint) { case 196: $return .= chr(142); break; case 214: $return .= chr(153); break; case 220: $return .= chr(154); break; case 223: $return .= chr(225); break; case 228: $return .= chr(132); break; case 246: $return .= chr(148); break; case 252: $return .= chr(129); break; default: $return .= chr($codePoint); } } return $return; }
[ "private", "function", "mapIso8859_1ToWindows1252", "(", "$", "string", "=", "''", ")", "{", "$", "return", "=", "''", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "strlen", "(", "$", "string", ")", ";", "++", "$", "i", ")", "{", "$...
Special treatment for our guys in Redmond Windows-1252 is basically ISO-8859-1 -- with some exceptions, which get dealt with here @param string $string Your input in ISO-8859-1 @return string The resulting Win1252 string @since 0.0.1
[ "Special", "treatment", "for", "our", "guys", "in", "Redmond", "Windows", "-", "1252", "is", "basically", "ISO", "-", "8859", "-", "1", "--", "with", "some", "exceptions", "which", "get", "dealt", "with", "here" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/EncodingHelper/FromUtf8.php#L57-L90
algo26-matthias/idna-convert
src/Punycode/ToPunycode.php
ToPunycode.convert
public function convert(array $decoded): string { // We cannot encode a domain name containing the Punycode prefix $checkForPrefix = array_slice($decoded, 0, self::$prefixLength); if (self::$prefixAsArray === $checkForPrefix) { throw new AlreadyPunycodeException('This is already a Punycode string', 100); } // We will not try to encode strings consisting of basic code points only $canEncode = false; foreach ($decoded as $k => $v) { if ($v > 0x7a) { $canEncode = true; break; } } if (!$canEncode) { return false; } // Do NAMEPREP $decoded = $this->namePrep->do($decoded); if (!$decoded || !is_array($decoded)) { return false; // NAMEPREP failed } $decodedLength = count($decoded); if (!$decodedLength) { return false; // Empty array } $codeCount = 0; // How many chars have been consumed $encoded = ''; // Copy all basic code points to output for ($i = 0; $i < $decodedLength; ++$i) { $test = $decoded[$i]; // Will match [-0-9a-zA-Z] if ((0x2F < $test && $test < 0x40) || (0x40 < $test && $test < 0x5B) || (0x60 < $test && $test <= 0x7B) || (0x2D == $test) ) { $encoded .= chr($decoded[$i]); $codeCount++; } } if ($codeCount === $decodedLength) { return $encoded; // All codepoints were basic ones } // Start with the prefix; copy it to output $encoded = self::punycodePrefix . $encoded; // If we have basic code points in output, add an hyphen to the end if ($codeCount) { $encoded .= '-'; } // Now find and encode all non-basic code points $isFirst = true; $currentCode = self::initialN; $bias = self::initialBias; $delta = 0; while ($codeCount < $decodedLength) { // Find the smallest code point >= the current code point and // remember the last occurrence of it in the input for ($i = 0, $nextCode = self::maxUcs; $i < $decodedLength; $i++) { if ($decoded[$i] >= $currentCode && $decoded[$i] <= $nextCode) { $nextCode = $decoded[$i]; } } $delta += ($nextCode - $currentCode) * ($codeCount + 1); $currentCode = $nextCode; // Scan input again and encode all characters whose code point is $currentCode for ($i = 0; $i < $decodedLength; $i++) { if ($decoded[$i] < $currentCode) { $delta++; } elseif ($decoded[$i] == $currentCode) { for ($q = $delta, $k = self::base; 1; $k += self::base) { $t = ($k <= $bias) ? self::tMin : (($k >= $bias + self::tMax) ? self::tMax : $k - $bias ); if ($q < $t) { break; } $encoded .= $this->encodeDigit(intval($t + (($q - $t) % (self::base - $t)))); $q = (int) (($q - $t) / (self::base - $t)); } $encoded .= $this->encodeDigit($q); $bias = $this->adapt($delta, $codeCount + 1, $isFirst); $codeCount++; $delta = 0; $isFirst = false; } } $delta++; $currentCode++; } return $encoded; }
php
public function convert(array $decoded): string { // We cannot encode a domain name containing the Punycode prefix $checkForPrefix = array_slice($decoded, 0, self::$prefixLength); if (self::$prefixAsArray === $checkForPrefix) { throw new AlreadyPunycodeException('This is already a Punycode string', 100); } // We will not try to encode strings consisting of basic code points only $canEncode = false; foreach ($decoded as $k => $v) { if ($v > 0x7a) { $canEncode = true; break; } } if (!$canEncode) { return false; } // Do NAMEPREP $decoded = $this->namePrep->do($decoded); if (!$decoded || !is_array($decoded)) { return false; // NAMEPREP failed } $decodedLength = count($decoded); if (!$decodedLength) { return false; // Empty array } $codeCount = 0; // How many chars have been consumed $encoded = ''; // Copy all basic code points to output for ($i = 0; $i < $decodedLength; ++$i) { $test = $decoded[$i]; // Will match [-0-9a-zA-Z] if ((0x2F < $test && $test < 0x40) || (0x40 < $test && $test < 0x5B) || (0x60 < $test && $test <= 0x7B) || (0x2D == $test) ) { $encoded .= chr($decoded[$i]); $codeCount++; } } if ($codeCount === $decodedLength) { return $encoded; // All codepoints were basic ones } // Start with the prefix; copy it to output $encoded = self::punycodePrefix . $encoded; // If we have basic code points in output, add an hyphen to the end if ($codeCount) { $encoded .= '-'; } // Now find and encode all non-basic code points $isFirst = true; $currentCode = self::initialN; $bias = self::initialBias; $delta = 0; while ($codeCount < $decodedLength) { // Find the smallest code point >= the current code point and // remember the last occurrence of it in the input for ($i = 0, $nextCode = self::maxUcs; $i < $decodedLength; $i++) { if ($decoded[$i] >= $currentCode && $decoded[$i] <= $nextCode) { $nextCode = $decoded[$i]; } } $delta += ($nextCode - $currentCode) * ($codeCount + 1); $currentCode = $nextCode; // Scan input again and encode all characters whose code point is $currentCode for ($i = 0; $i < $decodedLength; $i++) { if ($decoded[$i] < $currentCode) { $delta++; } elseif ($decoded[$i] == $currentCode) { for ($q = $delta, $k = self::base; 1; $k += self::base) { $t = ($k <= $bias) ? self::tMin : (($k >= $bias + self::tMax) ? self::tMax : $k - $bias ); if ($q < $t) { break; } $encoded .= $this->encodeDigit(intval($t + (($q - $t) % (self::base - $t)))); $q = (int) (($q - $t) / (self::base - $t)); } $encoded .= $this->encodeDigit($q); $bias = $this->adapt($delta, $codeCount + 1, $isFirst); $codeCount++; $delta = 0; $isFirst = false; } } $delta++; $currentCode++; } return $encoded; }
[ "public", "function", "convert", "(", "array", "$", "decoded", ")", ":", "string", "{", "// We cannot encode a domain name containing the Punycode prefix", "$", "checkForPrefix", "=", "array_slice", "(", "$", "decoded", ",", "0", ",", "self", "::", "$", "prefixLengt...
@param array $decoded @return string @throws AlreadyPunycodeException @throws InvalidCharacterException
[ "@param", "array", "$decoded" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/Punycode/ToPunycode.php#L31-L133
algo26-matthias/idna-convert
src/AbstractIdnaConvert.php
AbstractIdnaConvert.convertEmailAddress
public function convertEmailAddress(string $emailAddress): string { if (strpos($emailAddress, '@') === false) { throw new InvalidArgumentException('The given string does not look like an email address', 206); } $parts = explode('@', $emailAddress); return sprintf( '%s@%s', $parts[0], $this->convert($parts[1]) ); }
php
public function convertEmailAddress(string $emailAddress): string { if (strpos($emailAddress, '@') === false) { throw new InvalidArgumentException('The given string does not look like an email address', 206); } $parts = explode('@', $emailAddress); return sprintf( '%s@%s', $parts[0], $this->convert($parts[1]) ); }
[ "public", "function", "convertEmailAddress", "(", "string", "$", "emailAddress", ")", ":", "string", "{", "if", "(", "strpos", "(", "$", "emailAddress", ",", "'@'", ")", "===", "false", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'The given str...
@param string $emailAddress @return string
[ "@param", "string", "$emailAddress" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/AbstractIdnaConvert.php#L16-L29
algo26-matthias/idna-convert
src/AbstractIdnaConvert.php
AbstractIdnaConvert.convertUrl
public function convertUrl(string $url): string { $parsed = parse_url($url); if ($parsed === false) { throw new InvalidArgumentException('The given string does not look like a URL', 206); } // Nothing to do if ($parsed['host'] === null) { return $url; } $parsed['host'] = $this->convert($parsed['host']); return http_build_url($parsed); }
php
public function convertUrl(string $url): string { $parsed = parse_url($url); if ($parsed === false) { throw new InvalidArgumentException('The given string does not look like a URL', 206); } // Nothing to do if ($parsed['host'] === null) { return $url; } $parsed['host'] = $this->convert($parsed['host']); return http_build_url($parsed); }
[ "public", "function", "convertUrl", "(", "string", "$", "url", ")", ":", "string", "{", "$", "parsed", "=", "parse_url", "(", "$", "url", ")", ";", "if", "(", "$", "parsed", "===", "false", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'T...
@param string $url @return string
[ "@param", "string", "$url" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/AbstractIdnaConvert.php#L36-L50
algo26-matthias/idna-convert
src/TranscodeUnicode/TranscodeUnicode.php
TranscodeUnicode.utf8_ucs4array
private function utf8_ucs4array($input) { $startByte = 0; $nextByte = 0; $output = []; $outputLength = 0; $inputLength = $this->byteLength($input); $mode = 'next'; $test = 'none'; for ($k = 0; $k < $inputLength; ++$k) { $v = ord($input{$k}); // Extract byte from input string if ($v < 128) { // We found an ASCII char - put into string as is $output[$outputLength] = $v; ++$outputLength; if ('add' === $mode) { if ($this->safeMode) { $output[$outputLength - 2] = $this->safeCodepoint; $mode = 'next'; } else { throw new InvalidCharacterException( sprintf( 'Conversion from UTF-8 to UCS-4 failed: malformed input at byte %d', $k ), 302 ); } } continue; } if ('next' === $mode) { // Try to find the next start byte; determine the width of the Unicode char $startByte = $v; $mode = 'add'; $test = 'range'; if ($v >> 5 === 6) { // &110xxxxx 10xxxxx $nextByte = 0; // How many times subsequent bit masks must rotate 6bits to the left $v = ($v - 192) << 6; } elseif ($v >> 4 === 14) { // &1110xxxx 10xxxxxx 10xxxxxx $nextByte = 1; $v = ($v - 224) << 12; } elseif ($v >> 3 === 30) { // &11110xxx 10xxxxxx 10xxxxxx 10xxxxxx $nextByte = 2; $v = ($v - 240) << 18; } elseif ($this->safeMode) { $mode = 'next'; $output[$outputLength] = $this->safeCodepoint; ++$outputLength; continue; } else { throw new InvalidCharacterException( sprintf('This might be UTF-8, but I don\'t understand it at byte %d', $k), 303 ); } if (($inputLength - $k - $nextByte) < 2) { $output[$outputLength] = $this->safeCodepoint; $mode = 'no'; continue; } if ('add' === $mode) { $output[$outputLength] = (int)$v; ++$outputLength; continue; } } if ('add' == $mode) { if (!$this->safeMode && $test === 'range') { $test = 'none'; if (($v < 0xA0 && $startByte === 0xE0) || ($v < 0x90 && $startByte === 0xF0) || ($v > 0x8F && $startByte === 0xF4) ) { throw new InvalidCharacterException( sprintf('Bogus UTF-8 character (out of legal range) at byte %d', $k), 304 ); } } if ($v >> 6 === 2) { // Bit mask must be 10xxxxxx $v = ($v - 128) << ($nextByte * 6); $output[($outputLength - 1)] += $v; --$nextByte; } else { if ($this->safeMode) { $output[$outputLength - 1] = ord($this->safeCodepoint); $k--; $mode = 'next'; continue; } else { throw new InvalidCharacterException( sprintf('Conversion from UTF-8 to UCS-4 failed: malformed input at byte %d', $k), 302 ); } } if ($nextByte < 0) { $mode = 'next'; } } } // for return $output; }
php
private function utf8_ucs4array($input) { $startByte = 0; $nextByte = 0; $output = []; $outputLength = 0; $inputLength = $this->byteLength($input); $mode = 'next'; $test = 'none'; for ($k = 0; $k < $inputLength; ++$k) { $v = ord($input{$k}); // Extract byte from input string if ($v < 128) { // We found an ASCII char - put into string as is $output[$outputLength] = $v; ++$outputLength; if ('add' === $mode) { if ($this->safeMode) { $output[$outputLength - 2] = $this->safeCodepoint; $mode = 'next'; } else { throw new InvalidCharacterException( sprintf( 'Conversion from UTF-8 to UCS-4 failed: malformed input at byte %d', $k ), 302 ); } } continue; } if ('next' === $mode) { // Try to find the next start byte; determine the width of the Unicode char $startByte = $v; $mode = 'add'; $test = 'range'; if ($v >> 5 === 6) { // &110xxxxx 10xxxxx $nextByte = 0; // How many times subsequent bit masks must rotate 6bits to the left $v = ($v - 192) << 6; } elseif ($v >> 4 === 14) { // &1110xxxx 10xxxxxx 10xxxxxx $nextByte = 1; $v = ($v - 224) << 12; } elseif ($v >> 3 === 30) { // &11110xxx 10xxxxxx 10xxxxxx 10xxxxxx $nextByte = 2; $v = ($v - 240) << 18; } elseif ($this->safeMode) { $mode = 'next'; $output[$outputLength] = $this->safeCodepoint; ++$outputLength; continue; } else { throw new InvalidCharacterException( sprintf('This might be UTF-8, but I don\'t understand it at byte %d', $k), 303 ); } if (($inputLength - $k - $nextByte) < 2) { $output[$outputLength] = $this->safeCodepoint; $mode = 'no'; continue; } if ('add' === $mode) { $output[$outputLength] = (int)$v; ++$outputLength; continue; } } if ('add' == $mode) { if (!$this->safeMode && $test === 'range') { $test = 'none'; if (($v < 0xA0 && $startByte === 0xE0) || ($v < 0x90 && $startByte === 0xF0) || ($v > 0x8F && $startByte === 0xF4) ) { throw new InvalidCharacterException( sprintf('Bogus UTF-8 character (out of legal range) at byte %d', $k), 304 ); } } if ($v >> 6 === 2) { // Bit mask must be 10xxxxxx $v = ($v - 128) << ($nextByte * 6); $output[($outputLength - 1)] += $v; --$nextByte; } else { if ($this->safeMode) { $output[$outputLength - 1] = ord($this->safeCodepoint); $k--; $mode = 'next'; continue; } else { throw new InvalidCharacterException( sprintf('Conversion from UTF-8 to UCS-4 failed: malformed input at byte %d', $k), 302 ); } } if ($nextByte < 0) { $mode = 'next'; } } } // for return $output; }
[ "private", "function", "utf8_ucs4array", "(", "$", "input", ")", "{", "$", "startByte", "=", "0", ";", "$", "nextByte", "=", "0", ";", "$", "output", "=", "[", "]", ";", "$", "outputLength", "=", "0", ";", "$", "inputLength", "=", "$", "this", "->"...
This converts an UTF-8 encoded string to its UCS-4 representation @param string $input The UTF-8 string to convert @return array Array of 32bit values representing each codepoint @throws InvalidCharacterException @access public
[ "This", "converts", "an", "UTF", "-", "8", "encoded", "string", "to", "its", "UCS", "-", "4", "representation" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/TranscodeUnicode/TranscodeUnicode.php#L87-L198
algo26-matthias/idna-convert
src/TranscodeUnicode/TranscodeUnicode.php
TranscodeUnicode.ucs4array_utf8
private function ucs4array_utf8($input) { $output = ''; foreach ($input as $k => $v) { if ($v < 128) { // 7bit are transferred literally $output .= chr($v); } elseif ($v < (1 << 11)) { // 2 bytes $output .= sprintf( '%s%s', chr(192 + ($v >> 6)), chr(128 + ($v & 63)) ); } elseif ($v < (1 << 16)) { // 3 bytes $output .= sprintf( '%s%s%s', chr(224 + ($v >> 12)), chr(128 + (($v >> 6) & 63)), chr(128 + ($v & 63)) ); } elseif ($v < (1 << 21)) { // 4 bytes $output .= sprintf( '%s%s%s%s', chr(240 + ($v >> 18)), chr(128 + (($v >> 12) & 63)), chr(128 + (($v >> 6) & 63)), chr(128 + ($v & 63)) ); } elseif ($this->safeMode) { $output .= $this->safeCodepoint; } else { throw new InvalidCharacterException( sprintf('Conversion from UCS-4 to UTF-8 failed: malformed input at byte %d', $k), 305 ); } } return $output; }
php
private function ucs4array_utf8($input) { $output = ''; foreach ($input as $k => $v) { if ($v < 128) { // 7bit are transferred literally $output .= chr($v); } elseif ($v < (1 << 11)) { // 2 bytes $output .= sprintf( '%s%s', chr(192 + ($v >> 6)), chr(128 + ($v & 63)) ); } elseif ($v < (1 << 16)) { // 3 bytes $output .= sprintf( '%s%s%s', chr(224 + ($v >> 12)), chr(128 + (($v >> 6) & 63)), chr(128 + ($v & 63)) ); } elseif ($v < (1 << 21)) { // 4 bytes $output .= sprintf( '%s%s%s%s', chr(240 + ($v >> 18)), chr(128 + (($v >> 12) & 63)), chr(128 + (($v >> 6) & 63)), chr(128 + ($v & 63)) ); } elseif ($this->safeMode) { $output .= $this->safeCodepoint; } else { throw new InvalidCharacterException( sprintf('Conversion from UCS-4 to UTF-8 failed: malformed input at byte %d', $k), 305 ); } } return $output; }
[ "private", "function", "ucs4array_utf8", "(", "$", "input", ")", "{", "$", "output", "=", "''", ";", "foreach", "(", "$", "input", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "$", "v", "<", "128", ")", "{", "// 7bit are transferred literally...
Convert UCS-4 arary into UTF-8 string See utf8_ucs4array() for details @param $input array Array of UCS-4 codepoints @return string @access public @throws InvalidCharacterException
[ "Convert", "UCS", "-", "4", "arary", "into", "UTF", "-", "8", "string", "See", "utf8_ucs4array", "()", "for", "details" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/TranscodeUnicode/TranscodeUnicode.php#L210-L248
algo26-matthias/idna-convert
src/TranscodeUnicode/TranscodeUnicode.php
TranscodeUnicode.ucs4_ucs4array
private function ucs4_ucs4array($input) { $output = []; $inputLength = $this->byteLength($input); // Input length must be dividable by 4 if ($inputLength % 4) { throw new InvalidCharacterException('Input UCS4 string is broken', 306); } // Empty input - return empty output if (!$inputLength) { return $output; } for ($i = 0, $outputLength = -1; $i < $inputLength; ++$i) { if (!($i % 4)) { // Increment output position every 4 input bytes $outputLength++; $output[$outputLength] = 0; } $output[$outputLength] += ord($input{$i}) << (8 * (3 - ($i % 4))); } return $output; }
php
private function ucs4_ucs4array($input) { $output = []; $inputLength = $this->byteLength($input); // Input length must be dividable by 4 if ($inputLength % 4) { throw new InvalidCharacterException('Input UCS4 string is broken', 306); } // Empty input - return empty output if (!$inputLength) { return $output; } for ($i = 0, $outputLength = -1; $i < $inputLength; ++$i) { if (!($i % 4)) { // Increment output position every 4 input bytes $outputLength++; $output[$outputLength] = 0; } $output[$outputLength] += ord($input{$i}) << (8 * (3 - ($i % 4))); } return $output; }
[ "private", "function", "ucs4_ucs4array", "(", "$", "input", ")", "{", "$", "output", "=", "[", "]", ";", "$", "inputLength", "=", "$", "this", "->", "byteLength", "(", "$", "input", ")", ";", "// Input length must be dividable by 4", "if", "(", "$", "input...
Convert UCS-4 string (LE ar the moment) into UCS-4 array @param $input string UCS-4 LE string @return array @access public @throws InvalidCharacterException
[ "Convert", "UCS", "-", "4", "string", "(", "LE", "ar", "the", "moment", ")", "into", "UCS", "-", "4", "array" ]
train
https://github.com/algo26-matthias/idna-convert/blob/893d5918fd99ea12a427c714f3a02031fabe60b0/src/TranscodeUnicode/TranscodeUnicode.php#L395-L418
php-cache/adapter-common
TagSupportWithArray.php
TagSupportWithArray.appendListItem
protected function appendListItem($name, $value) { $data = $this->getDirectValue($name); if (!is_array($data)) { $data = []; } $data[] = $value; $this->setDirectValue($name, $data); }
php
protected function appendListItem($name, $value) { $data = $this->getDirectValue($name); if (!is_array($data)) { $data = []; } $data[] = $value; $this->setDirectValue($name, $data); }
[ "protected", "function", "appendListItem", "(", "$", "name", ",", "$", "value", ")", "{", "$", "data", "=", "$", "this", "->", "getDirectValue", "(", "$", "name", ")", ";", "if", "(", "!", "is_array", "(", "$", "data", ")", ")", "{", "$", "data", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/TagSupportWithArray.php#L41-L49
php-cache/adapter-common
TagSupportWithArray.php
TagSupportWithArray.getList
protected function getList($name) { $data = $this->getDirectValue($name); if (!is_array($data)) { $data = []; } return $data; }
php
protected function getList($name) { $data = $this->getDirectValue($name); if (!is_array($data)) { $data = []; } return $data; }
[ "protected", "function", "getList", "(", "$", "name", ")", "{", "$", "data", "=", "$", "this", "->", "getDirectValue", "(", "$", "name", ")", ";", "if", "(", "!", "is_array", "(", "$", "data", ")", ")", "{", "$", "data", "=", "[", "]", ";", "}"...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/TagSupportWithArray.php#L54-L62
php-cache/adapter-common
TagSupportWithArray.php
TagSupportWithArray.removeListItem
protected function removeListItem($name, $key) { $data = $this->getList($name); foreach ($data as $i => $value) { if ($key === $value) { unset($data[$i]); } } return $this->setDirectValue($name, $data); }
php
protected function removeListItem($name, $key) { $data = $this->getList($name); foreach ($data as $i => $value) { if ($key === $value) { unset($data[$i]); } } return $this->setDirectValue($name, $data); }
[ "protected", "function", "removeListItem", "(", "$", "name", ",", "$", "key", ")", "{", "$", "data", "=", "$", "this", "->", "getList", "(", "$", "name", ")", ";", "foreach", "(", "$", "data", "as", "$", "i", "=>", "$", "value", ")", "{", "if", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/TagSupportWithArray.php#L77-L87
php-cache/adapter-common
CacheItem.php
CacheItem.set
public function set($value) { $this->value = $value; $this->hasValue = true; $this->callable = null; return $this; }
php
public function set($value) { $this->value = $value; $this->hasValue = true; $this->callable = null; return $this; }
[ "public", "function", "set", "(", "$", "value", ")", "{", "$", "this", "->", "value", "=", "$", "value", ";", "$", "this", "->", "hasValue", "=", "true", ";", "$", "this", "->", "callable", "=", "null", ";", "return", "$", "this", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/CacheItem.php#L90-L97
php-cache/adapter-common
CacheItem.php
CacheItem.isHit
public function isHit() { $this->initialize(); if (!$this->hasValue) { return false; } if ($this->expirationTimestamp !== null) { return $this->expirationTimestamp > time(); } return true; }
php
public function isHit() { $this->initialize(); if (!$this->hasValue) { return false; } if ($this->expirationTimestamp !== null) { return $this->expirationTimestamp > time(); } return true; }
[ "public", "function", "isHit", "(", ")", "{", "$", "this", "->", "initialize", "(", ")", ";", "if", "(", "!", "$", "this", "->", "hasValue", ")", "{", "return", "false", ";", "}", "if", "(", "$", "this", "->", "expirationTimestamp", "!==", "null", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/CacheItem.php#L114-L127
php-cache/adapter-common
CacheItem.php
CacheItem.expiresAt
public function expiresAt($expiration) { if ($expiration instanceof \DateTimeInterface) { $this->expirationTimestamp = $expiration->getTimestamp(); } elseif (is_int($expiration) || null === $expiration) { $this->expirationTimestamp = $expiration; } else { throw new InvalidArgumentException('Cache item ttl/expiresAt must be of type integer or \DateTimeInterface.'); } return $this; }
php
public function expiresAt($expiration) { if ($expiration instanceof \DateTimeInterface) { $this->expirationTimestamp = $expiration->getTimestamp(); } elseif (is_int($expiration) || null === $expiration) { $this->expirationTimestamp = $expiration; } else { throw new InvalidArgumentException('Cache item ttl/expiresAt must be of type integer or \DateTimeInterface.'); } return $this; }
[ "public", "function", "expiresAt", "(", "$", "expiration", ")", "{", "if", "(", "$", "expiration", "instanceof", "\\", "DateTimeInterface", ")", "{", "$", "this", "->", "expirationTimestamp", "=", "$", "expiration", "->", "getTimestamp", "(", ")", ";", "}", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/CacheItem.php#L140-L151
php-cache/adapter-common
CacheItem.php
CacheItem.expiresAfter
public function expiresAfter($time) { if ($time === null) { $this->expirationTimestamp = null; } elseif ($time instanceof \DateInterval) { $date = new \DateTime(); $date->add($time); $this->expirationTimestamp = $date->getTimestamp(); } elseif (is_int($time)) { $this->expirationTimestamp = time() + $time; } else { throw new InvalidArgumentException('Cache item ttl/expiresAfter must be of type integer or \DateInterval.'); } return $this; }
php
public function expiresAfter($time) { if ($time === null) { $this->expirationTimestamp = null; } elseif ($time instanceof \DateInterval) { $date = new \DateTime(); $date->add($time); $this->expirationTimestamp = $date->getTimestamp(); } elseif (is_int($time)) { $this->expirationTimestamp = time() + $time; } else { throw new InvalidArgumentException('Cache item ttl/expiresAfter must be of type integer or \DateInterval.'); } return $this; }
[ "public", "function", "expiresAfter", "(", "$", "time", ")", "{", "if", "(", "$", "time", "===", "null", ")", "{", "$", "this", "->", "expirationTimestamp", "=", "null", ";", "}", "elseif", "(", "$", "time", "instanceof", "\\", "DateInterval", ")", "{"...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/CacheItem.php#L156-L171
php-cache/adapter-common
CacheItem.php
CacheItem.tag
private function tag($tags) { $this->initialize(); if (!is_array($tags)) { $tags = [$tags]; } foreach ($tags as $tag) { if (!is_string($tag)) { throw new InvalidArgumentException(sprintf('Cache tag must be string, "%s" given', is_object($tag) ? get_class($tag) : gettype($tag))); } if (isset($this->tags[$tag])) { continue; } if (!isset($tag[0])) { throw new InvalidArgumentException('Cache tag length must be greater than zero'); } if (isset($tag[strcspn($tag, '{}()/\@:')])) { throw new InvalidArgumentException(sprintf('Cache tag "%s" contains reserved characters {}()/\@:', $tag)); } $this->tags[$tag] = $tag; } return $this; }
php
private function tag($tags) { $this->initialize(); if (!is_array($tags)) { $tags = [$tags]; } foreach ($tags as $tag) { if (!is_string($tag)) { throw new InvalidArgumentException(sprintf('Cache tag must be string, "%s" given', is_object($tag) ? get_class($tag) : gettype($tag))); } if (isset($this->tags[$tag])) { continue; } if (!isset($tag[0])) { throw new InvalidArgumentException('Cache tag length must be greater than zero'); } if (isset($tag[strcspn($tag, '{}()/\@:')])) { throw new InvalidArgumentException(sprintf('Cache tag "%s" contains reserved characters {}()/\@:', $tag)); } $this->tags[$tag] = $tag; } return $this; }
[ "private", "function", "tag", "(", "$", "tags", ")", "{", "$", "this", "->", "initialize", "(", ")", ";", "if", "(", "!", "is_array", "(", "$", "tags", ")", ")", "{", "$", "tags", "=", "[", "$", "tags", "]", ";", "}", "foreach", "(", "$", "ta...
Adds a tag to a cache item. @param string|string[] $tags A tag or array of tags @throws InvalidArgumentException When $tag is not valid. @return TaggableCacheItemInterface
[ "Adds", "a", "tag", "to", "a", "cache", "item", "." ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/CacheItem.php#L211-L235
php-cache/adapter-common
CacheItem.php
CacheItem.initialize
private function initialize() { if ($this->callable !== null) { // $func will be $adapter->fetchObjectFromCache(); $func = $this->callable; $result = $func(); $this->hasValue = $result[0]; $this->value = $result[1]; $this->prevTags = isset($result[2]) ? $result[2] : []; $this->expirationTimestamp = null; if (isset($result[3]) && is_int($result[3])) { $this->expirationTimestamp = $result[3]; } $this->callable = null; } }
php
private function initialize() { if ($this->callable !== null) { // $func will be $adapter->fetchObjectFromCache(); $func = $this->callable; $result = $func(); $this->hasValue = $result[0]; $this->value = $result[1]; $this->prevTags = isset($result[2]) ? $result[2] : []; $this->expirationTimestamp = null; if (isset($result[3]) && is_int($result[3])) { $this->expirationTimestamp = $result[3]; } $this->callable = null; } }
[ "private", "function", "initialize", "(", ")", "{", "if", "(", "$", "this", "->", "callable", "!==", "null", ")", "{", "// $func will be $adapter->fetchObjectFromCache();", "$", "func", "=", "$", "this", "->", "callable", ";", "$", "result", "=", "$", "func"...
If callable is not null, execute it an populate this object with values.
[ "If", "callable", "is", "not", "null", "execute", "it", "an", "populate", "this", "object", "with", "values", "." ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/CacheItem.php#L240-L257
php-cache/adapter-common
AbstractCachePool.php
AbstractCachePool.getItem
public function getItem($key) { $this->validateKey($key); if (isset($this->deferred[$key])) { /** @type CacheItem $item */ $item = clone $this->deferred[$key]; $item->moveTagsToPrevious(); return $item; } $func = function () use ($key) { try { return $this->fetchObjectFromCache($key); } catch (\Exception $e) { $this->handleException($e, __FUNCTION__); } }; return new CacheItem($key, $func); }
php
public function getItem($key) { $this->validateKey($key); if (isset($this->deferred[$key])) { /** @type CacheItem $item */ $item = clone $this->deferred[$key]; $item->moveTagsToPrevious(); return $item; } $func = function () use ($key) { try { return $this->fetchObjectFromCache($key); } catch (\Exception $e) { $this->handleException($e, __FUNCTION__); } }; return new CacheItem($key, $func); }
[ "public", "function", "getItem", "(", "$", "key", ")", "{", "$", "this", "->", "validateKey", "(", "$", "key", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "deferred", "[", "$", "key", "]", ")", ")", "{", "/** @type CacheItem $item */", "$",...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/AbstractCachePool.php#L120-L140
php-cache/adapter-common
AbstractCachePool.php
AbstractCachePool.hasItem
public function hasItem($key) { try { return $this->getItem($key)->isHit(); } catch (\Exception $e) { $this->handleException($e, __FUNCTION__); } }
php
public function hasItem($key) { try { return $this->getItem($key)->isHit(); } catch (\Exception $e) { $this->handleException($e, __FUNCTION__); } }
[ "public", "function", "hasItem", "(", "$", "key", ")", "{", "try", "{", "return", "$", "this", "->", "getItem", "(", "$", "key", ")", "->", "isHit", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "ha...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/AbstractCachePool.php#L158-L165
php-cache/adapter-common
AbstractCachePool.php
AbstractCachePool.deleteItems
public function deleteItems(array $keys) { $deleted = true; foreach ($keys as $key) { $this->validateKey($key); // Delete form deferred unset($this->deferred[$key]); // We have to commit here to be able to remove deferred hierarchy items $this->commit(); $this->preRemoveItem($key); if (!$this->clearOneObjectFromCache($key)) { $deleted = false; } } return $deleted; }
php
public function deleteItems(array $keys) { $deleted = true; foreach ($keys as $key) { $this->validateKey($key); // Delete form deferred unset($this->deferred[$key]); // We have to commit here to be able to remove deferred hierarchy items $this->commit(); $this->preRemoveItem($key); if (!$this->clearOneObjectFromCache($key)) { $deleted = false; } } return $deleted; }
[ "public", "function", "deleteItems", "(", "array", "$", "keys", ")", "{", "$", "deleted", "=", "true", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "this", "->", "validateKey", "(", "$", "key", ")", ";", "// Delete form deferred",...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/AbstractCachePool.php#L197-L216
php-cache/adapter-common
AbstractCachePool.php
AbstractCachePool.save
public function save(CacheItemInterface $item) { if (!$item instanceof PhpCacheItem) { $e = new InvalidArgumentException('Cache items are not transferable between pools. Item MUST implement PhpCacheItem.'); $this->handleException($e, __FUNCTION__); } $this->removeTagEntries($item); $this->saveTags($item); $timeToLive = null; if (null !== $timestamp = $item->getExpirationTimestamp()) { $timeToLive = $timestamp - time(); if ($timeToLive < 0) { return $this->deleteItem($item->getKey()); } } try { return $this->storeItemInCache($item, $timeToLive); } catch (\Exception $e) { $this->handleException($e, __FUNCTION__); } }
php
public function save(CacheItemInterface $item) { if (!$item instanceof PhpCacheItem) { $e = new InvalidArgumentException('Cache items are not transferable between pools. Item MUST implement PhpCacheItem.'); $this->handleException($e, __FUNCTION__); } $this->removeTagEntries($item); $this->saveTags($item); $timeToLive = null; if (null !== $timestamp = $item->getExpirationTimestamp()) { $timeToLive = $timestamp - time(); if ($timeToLive < 0) { return $this->deleteItem($item->getKey()); } } try { return $this->storeItemInCache($item, $timeToLive); } catch (\Exception $e) { $this->handleException($e, __FUNCTION__); } }
[ "public", "function", "save", "(", "CacheItemInterface", "$", "item", ")", "{", "if", "(", "!", "$", "item", "instanceof", "PhpCacheItem", ")", "{", "$", "e", "=", "new", "InvalidArgumentException", "(", "'Cache items are not transferable between pools. Item MUST impl...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/AbstractCachePool.php#L221-L244
php-cache/adapter-common
AbstractCachePool.php
AbstractCachePool.commit
public function commit() { $saved = true; foreach ($this->deferred as $item) { if (!$this->save($item)) { $saved = false; } } $this->deferred = []; return $saved; }
php
public function commit() { $saved = true; foreach ($this->deferred as $item) { if (!$this->save($item)) { $saved = false; } } $this->deferred = []; return $saved; }
[ "public", "function", "commit", "(", ")", "{", "$", "saved", "=", "true", ";", "foreach", "(", "$", "this", "->", "deferred", "as", "$", "item", ")", "{", "if", "(", "!", "$", "this", "->", "save", "(", "$", "item", ")", ")", "{", "$", "saved",...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/AbstractCachePool.php#L259-L270
php-cache/adapter-common
AbstractCachePool.php
AbstractCachePool.validateKey
protected function validateKey($key) { if (!is_string($key)) { $e = new InvalidArgumentException(sprintf( 'Cache key must be string, "%s" given', gettype($key) )); $this->handleException($e, __FUNCTION__); } if (!isset($key[0])) { $e = new InvalidArgumentException('Cache key cannot be an empty string'); $this->handleException($e, __FUNCTION__); } if (preg_match('|[\{\}\(\)/\\\@\:]|', $key)) { $e = new InvalidArgumentException(sprintf( 'Invalid key: "%s". The key contains one or more characters reserved for future extension: {}()/\@:', $key )); $this->handleException($e, __FUNCTION__); } }
php
protected function validateKey($key) { if (!is_string($key)) { $e = new InvalidArgumentException(sprintf( 'Cache key must be string, "%s" given', gettype($key) )); $this->handleException($e, __FUNCTION__); } if (!isset($key[0])) { $e = new InvalidArgumentException('Cache key cannot be an empty string'); $this->handleException($e, __FUNCTION__); } if (preg_match('|[\{\}\(\)/\\\@\:]|', $key)) { $e = new InvalidArgumentException(sprintf( 'Invalid key: "%s". The key contains one or more characters reserved for future extension: {}()/\@:', $key )); $this->handleException($e, __FUNCTION__); } }
[ "protected", "function", "validateKey", "(", "$", "key", ")", "{", "if", "(", "!", "is_string", "(", "$", "key", ")", ")", "{", "$", "e", "=", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Cache key must be string, \"%s\" given'", ",", "gettype", ...
@param string $key @throws InvalidArgumentException
[ "@param", "string", "$key" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/AbstractCachePool.php#L277-L296
php-cache/adapter-common
AbstractCachePool.php
AbstractCachePool.handleException
private function handleException(\Exception $e, $function) { $level = 'alert'; if ($e instanceof InvalidArgumentException) { $level = 'warning'; } $this->log($level, $e->getMessage(), ['exception' => $e]); if (!$e instanceof CacheException) { $e = new CachePoolException(sprintf('Exception thrown when executing "%s". ', $function), 0, $e); } throw $e; }
php
private function handleException(\Exception $e, $function) { $level = 'alert'; if ($e instanceof InvalidArgumentException) { $level = 'warning'; } $this->log($level, $e->getMessage(), ['exception' => $e]); if (!$e instanceof CacheException) { $e = new CachePoolException(sprintf('Exception thrown when executing "%s". ', $function), 0, $e); } throw $e; }
[ "private", "function", "handleException", "(", "\\", "Exception", "$", "e", ",", "$", "function", ")", "{", "$", "level", "=", "'alert'", ";", "if", "(", "$", "e", "instanceof", "InvalidArgumentException", ")", "{", "$", "level", "=", "'warning'", ";", "...
Log exception and rethrow it. @param \Exception $e @param string $function @throws CachePoolException
[ "Log", "exception", "and", "rethrow", "it", "." ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/AbstractCachePool.php#L328-L341
php-cache/adapter-common
AbstractCachePool.php
AbstractCachePool.invalidateTags
public function invalidateTags(array $tags) { $itemIds = []; foreach ($tags as $tag) { $itemIds = array_merge($itemIds, $this->getList($this->getTagKey($tag))); } // Remove all items with the tag $success = $this->deleteItems($itemIds); if ($success) { // Remove the tag list foreach ($tags as $tag) { $this->removeList($this->getTagKey($tag)); $l = $this->getList($this->getTagKey($tag)); } } return $success; }
php
public function invalidateTags(array $tags) { $itemIds = []; foreach ($tags as $tag) { $itemIds = array_merge($itemIds, $this->getList($this->getTagKey($tag))); } // Remove all items with the tag $success = $this->deleteItems($itemIds); if ($success) { // Remove the tag list foreach ($tags as $tag) { $this->removeList($this->getTagKey($tag)); $l = $this->getList($this->getTagKey($tag)); } } return $success; }
[ "public", "function", "invalidateTags", "(", "array", "$", "tags", ")", "{", "$", "itemIds", "=", "[", "]", ";", "foreach", "(", "$", "tags", "as", "$", "tag", ")", "{", "$", "itemIds", "=", "array_merge", "(", "$", "itemIds", ",", "$", "this", "->...
@param array $tags @return bool
[ "@param", "array", "$tags" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/AbstractCachePool.php#L348-L367
php-cache/adapter-common
AbstractCachePool.php
AbstractCachePool.getMultiple
public function getMultiple($keys, $default = null) { if (!is_array($keys)) { if (!$keys instanceof \Traversable) { throw new InvalidArgumentException('$keys is neither an array nor Traversable'); } // Since we need to throw an exception if *any* key is invalid, it doesn't // make sense to wrap iterators or something like that. $keys = iterator_to_array($keys, false); } $items = $this->getItems($keys); return $this->generateValues($default, $items); }
php
public function getMultiple($keys, $default = null) { if (!is_array($keys)) { if (!$keys instanceof \Traversable) { throw new InvalidArgumentException('$keys is neither an array nor Traversable'); } // Since we need to throw an exception if *any* key is invalid, it doesn't // make sense to wrap iterators or something like that. $keys = iterator_to_array($keys, false); } $items = $this->getItems($keys); return $this->generateValues($default, $items); }
[ "public", "function", "getMultiple", "(", "$", "keys", ",", "$", "default", "=", "null", ")", "{", "if", "(", "!", "is_array", "(", "$", "keys", ")", ")", "{", "if", "(", "!", "$", "keys", "instanceof", "\\", "Traversable", ")", "{", "throw", "new"...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/AbstractCachePool.php#L459-L474
php-cache/adapter-common
AbstractCachePool.php
AbstractCachePool.generateValues
private function generateValues($default, $items) { foreach ($items as $key => $item) { /** @type $item CacheItemInterface */ if (!$item->isHit()) { yield $key => $default; } else { yield $key => $item->get(); } } }
php
private function generateValues($default, $items) { foreach ($items as $key => $item) { /** @type $item CacheItemInterface */ if (!$item->isHit()) { yield $key => $default; } else { yield $key => $item->get(); } } }
[ "private", "function", "generateValues", "(", "$", "default", ",", "$", "items", ")", "{", "foreach", "(", "$", "items", "as", "$", "key", "=>", "$", "item", ")", "{", "/** @type $item CacheItemInterface */", "if", "(", "!", "$", "item", "->", "isHit", "...
@param $default @param $items @return \Generator
[ "@param", "$default", "@param", "$items" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/AbstractCachePool.php#L482-L492
php-cache/adapter-common
AbstractCachePool.php
AbstractCachePool.setMultiple
public function setMultiple($values, $ttl = null) { if (!is_array($values)) { if (!$values instanceof \Traversable) { throw new InvalidArgumentException('$values is neither an array nor Traversable'); } } $keys = []; $arrayValues = []; foreach ($values as $key => $value) { if (is_int($key)) { $key = (string) $key; } $this->validateKey($key); $keys[] = $key; $arrayValues[$key] = $value; } $items = $this->getItems($keys); $itemSuccess = true; foreach ($items as $key => $item) { $item->set($arrayValues[$key]); try { $item->expiresAfter($ttl); } catch (InvalidArgumentException $e) { throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); } $itemSuccess = $itemSuccess && $this->saveDeferred($item); } return $itemSuccess && $this->commit(); }
php
public function setMultiple($values, $ttl = null) { if (!is_array($values)) { if (!$values instanceof \Traversable) { throw new InvalidArgumentException('$values is neither an array nor Traversable'); } } $keys = []; $arrayValues = []; foreach ($values as $key => $value) { if (is_int($key)) { $key = (string) $key; } $this->validateKey($key); $keys[] = $key; $arrayValues[$key] = $value; } $items = $this->getItems($keys); $itemSuccess = true; foreach ($items as $key => $item) { $item->set($arrayValues[$key]); try { $item->expiresAfter($ttl); } catch (InvalidArgumentException $e) { throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); } $itemSuccess = $itemSuccess && $this->saveDeferred($item); } return $itemSuccess && $this->commit(); }
[ "public", "function", "setMultiple", "(", "$", "values", ",", "$", "ttl", "=", "null", ")", "{", "if", "(", "!", "is_array", "(", "$", "values", ")", ")", "{", "if", "(", "!", "$", "values", "instanceof", "\\", "Traversable", ")", "{", "throw", "ne...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/AbstractCachePool.php#L497-L531
php-cache/adapter-common
AbstractCachePool.php
AbstractCachePool.deleteMultiple
public function deleteMultiple($keys) { if (!is_array($keys)) { if (!$keys instanceof \Traversable) { throw new InvalidArgumentException('$keys is neither an array nor Traversable'); } // Since we need to throw an exception if *any* key is invalid, it doesn't // make sense to wrap iterators or something like that. $keys = iterator_to_array($keys, false); } return $this->deleteItems($keys); }
php
public function deleteMultiple($keys) { if (!is_array($keys)) { if (!$keys instanceof \Traversable) { throw new InvalidArgumentException('$keys is neither an array nor Traversable'); } // Since we need to throw an exception if *any* key is invalid, it doesn't // make sense to wrap iterators or something like that. $keys = iterator_to_array($keys, false); } return $this->deleteItems($keys); }
[ "public", "function", "deleteMultiple", "(", "$", "keys", ")", "{", "if", "(", "!", "is_array", "(", "$", "keys", ")", ")", "{", "if", "(", "!", "$", "keys", "instanceof", "\\", "Traversable", ")", "{", "throw", "new", "InvalidArgumentException", "(", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-cache/adapter-common/blob/6320bb5f5574cb88438059b59f8708da6b6f1d32/AbstractCachePool.php#L536-L549
php-enqueue/amqp-lib
AmqpContext.php
AmqpContext.createConsumer
public function createConsumer(Destination $destination): Consumer { $destination instanceof Topic ? InvalidDestinationException::assertDestinationInstanceOf($destination, InteropAmqpTopic::class) : InvalidDestinationException::assertDestinationInstanceOf($destination, InteropAmqpQueue::class) ; if ($destination instanceof AmqpTopic) { $queue = $this->createTemporaryQueue(); $this->bind(new AmqpBind($destination, $queue, $queue->getQueueName())); return new AmqpConsumer($this, $queue); } return new AmqpConsumer($this, $destination); }
php
public function createConsumer(Destination $destination): Consumer { $destination instanceof Topic ? InvalidDestinationException::assertDestinationInstanceOf($destination, InteropAmqpTopic::class) : InvalidDestinationException::assertDestinationInstanceOf($destination, InteropAmqpQueue::class) ; if ($destination instanceof AmqpTopic) { $queue = $this->createTemporaryQueue(); $this->bind(new AmqpBind($destination, $queue, $queue->getQueueName())); return new AmqpConsumer($this, $queue); } return new AmqpConsumer($this, $destination); }
[ "public", "function", "createConsumer", "(", "Destination", "$", "destination", ")", ":", "Consumer", "{", "$", "destination", "instanceof", "Topic", "?", "InvalidDestinationException", "::", "assertDestinationInstanceOf", "(", "$", "destination", ",", "InteropAmqpTopic...
@param InteropAmqpTopic|InteropAmqpQueue $destination @return AmqpConsumer
[ "@param", "InteropAmqpTopic|InteropAmqpQueue", "$destination" ]
train
https://github.com/php-enqueue/amqp-lib/blob/41823f7df19dc669c451e151405b4f946796b3f7/AmqpContext.php#L91-L106
spatie/laravel-blade-javascript
src/Transformers/ObjectTransformer.php
ObjectTransformer.transform
public function transform($value): string { if (method_exists($value, 'toJson')) { return $value->toJson(); } if ($value instanceof JsonSerializable || $value instanceof StdClass) { return json_encode($value); } if (! method_exists($value, '__toString')) { throw Untransformable::cannotTransformObject($value); } return "'{$value}'"; }
php
public function transform($value): string { if (method_exists($value, 'toJson')) { return $value->toJson(); } if ($value instanceof JsonSerializable || $value instanceof StdClass) { return json_encode($value); } if (! method_exists($value, '__toString')) { throw Untransformable::cannotTransformObject($value); } return "'{$value}'"; }
[ "public", "function", "transform", "(", "$", "value", ")", ":", "string", "{", "if", "(", "method_exists", "(", "$", "value", ",", "'toJson'", ")", ")", "{", "return", "$", "value", "->", "toJson", "(", ")", ";", "}", "if", "(", "$", "value", "inst...
@param mixed $value @return string @throws \Spatie\BladeJavaScript\Exceptions\Untransformable
[ "@param", "mixed", "$value" ]
train
https://github.com/spatie/laravel-blade-javascript/blob/0b1b17a8285277208667a76eff2c546e7313d03a/src/Transformers/ObjectTransformer.php#L28-L43
spatie/laravel-blade-javascript
src/Renderer.php
Renderer.render
public function render(...$arguments): string { $variables = $this->normalizeArguments($arguments); return view('bladeJavaScript::index', [ 'javaScript' => $this->buildJavaScriptSyntax($variables), ])->render(); }
php
public function render(...$arguments): string { $variables = $this->normalizeArguments($arguments); return view('bladeJavaScript::index', [ 'javaScript' => $this->buildJavaScriptSyntax($variables), ])->render(); }
[ "public", "function", "render", "(", "...", "$", "arguments", ")", ":", "string", "{", "$", "variables", "=", "$", "this", "->", "normalizeArguments", "(", "$", "arguments", ")", ";", "return", "view", "(", "'bladeJavaScript::index'", ",", "[", "'javaScript'...
@param array ...$arguments @return string @throws \Throwable
[ "@param", "array", "...", "$arguments" ]
train
https://github.com/spatie/laravel-blade-javascript/blob/0b1b17a8285277208667a76eff2c546e7313d03a/src/Renderer.php#L42-L49
spatie/laravel-blade-javascript
src/Renderer.php
Renderer.normalizeArguments
protected function normalizeArguments(array $arguments) { if (count($arguments) === 2) { return [$arguments[0] => $arguments[1]]; } if ($arguments[0] instanceof Arrayable) { return $arguments[0]->toArray(); } if (! is_array($arguments[0])) { $arguments[0] = [$arguments[0]]; } return $arguments[0]; }
php
protected function normalizeArguments(array $arguments) { if (count($arguments) === 2) { return [$arguments[0] => $arguments[1]]; } if ($arguments[0] instanceof Arrayable) { return $arguments[0]->toArray(); } if (! is_array($arguments[0])) { $arguments[0] = [$arguments[0]]; } return $arguments[0]; }
[ "protected", "function", "normalizeArguments", "(", "array", "$", "arguments", ")", "{", "if", "(", "count", "(", "$", "arguments", ")", "===", "2", ")", "{", "return", "[", "$", "arguments", "[", "0", "]", "=>", "$", "arguments", "[", "1", "]", "]",...
@param $arguments @return mixed
[ "@param", "$arguments" ]
train
https://github.com/spatie/laravel-blade-javascript/blob/0b1b17a8285277208667a76eff2c546e7313d03a/src/Renderer.php#L56-L71
spatie/laravel-blade-javascript
src/Renderer.php
Renderer.getTransformer
public function getTransformer($value): Transformer { foreach ($this->getAllTransformers() as $transformer) { if ($transformer->canTransform($value)) { return $transformer; } } throw Untransformable::noTransformerFound($value); }
php
public function getTransformer($value): Transformer { foreach ($this->getAllTransformers() as $transformer) { if ($transformer->canTransform($value)) { return $transformer; } } throw Untransformable::noTransformerFound($value); }
[ "public", "function", "getTransformer", "(", "$", "value", ")", ":", "Transformer", "{", "foreach", "(", "$", "this", "->", "getAllTransformers", "(", ")", "as", "$", "transformer", ")", "{", "if", "(", "$", "transformer", "->", "canTransform", "(", "$", ...
@param mixed $value @return \Spatie\BladeJavaScript\Transformers\Transformer @throws \Spatie\BladeJavaScript\Exceptions\Untransformable
[ "@param", "mixed", "$value" ]
train
https://github.com/spatie/laravel-blade-javascript/blob/0b1b17a8285277208667a76eff2c546e7313d03a/src/Renderer.php#L132-L141
Froiden/laravel-rest-api
src/ApiController.php
ApiController.index
public function index() { $this->validate(); $results = $this->parseRequest() ->addIncludes() ->addFilters() ->addOrdering() ->addPaging() ->modify() ->getResults() ->toArray(); $meta = $this->getMetaData(); return ApiResponse::make(null, $results, $meta); }
php
public function index() { $this->validate(); $results = $this->parseRequest() ->addIncludes() ->addFilters() ->addOrdering() ->addPaging() ->modify() ->getResults() ->toArray(); $meta = $this->getMetaData(); return ApiResponse::make(null, $results, $meta); }
[ "public", "function", "index", "(", ")", "{", "$", "this", "->", "validate", "(", ")", ";", "$", "results", "=", "$", "this", "->", "parseRequest", "(", ")", "->", "addIncludes", "(", ")", "->", "addFilters", "(", ")", "->", "addOrdering", "(", ")", ...
Process index page request @return mixed
[ "Process", "index", "page", "request" ]
train
https://github.com/Froiden/laravel-rest-api/blob/2085c3980054518d2f1926990548a33b60e7302b/src/ApiController.php#L144-L160
Froiden/laravel-rest-api
src/ApiController.php
ApiController.show
public function show(...$args) { // We need to do this in order to support multiple parameter resource routes. For example, // if we map route /user/{user}/comments/{comment} to a controller, Laravel will pass `user` // as first argument and `comment` as last argument. So, id object that we want to fetch // is the last argument. $id = last(func_get_args()); $this->validate(); $results = $this->parseRequest() ->addIncludes() ->addKeyConstraint($id) ->modify() ->getResults(true) ->first() ->toArray(); $meta = $this->getMetaData(true); return ApiResponse::make(null, $results, $meta); }
php
public function show(...$args) { // We need to do this in order to support multiple parameter resource routes. For example, // if we map route /user/{user}/comments/{comment} to a controller, Laravel will pass `user` // as first argument and `comment` as last argument. So, id object that we want to fetch // is the last argument. $id = last(func_get_args()); $this->validate(); $results = $this->parseRequest() ->addIncludes() ->addKeyConstraint($id) ->modify() ->getResults(true) ->first() ->toArray(); $meta = $this->getMetaData(true); return ApiResponse::make(null, $results, $meta); }
[ "public", "function", "show", "(", "...", "$", "args", ")", "{", "// We need to do this in order to support multiple parameter resource routes. For example,", "// if we map route /user/{user}/comments/{comment} to a controller, Laravel will pass `user`", "// as first argument and `comment` as ...
Process the show request @return mixed
[ "Process", "the", "show", "request" ]
train
https://github.com/Froiden/laravel-rest-api/blob/2085c3980054518d2f1926990548a33b60e7302b/src/ApiController.php#L167-L188
Froiden/laravel-rest-api
src/ApiController.php
ApiController.addIncludes
protected function addIncludes() { $relations = $this->parser->getRelations(); if (!empty($relations)) { $includes = []; foreach ($relations as $key => $relation) { $includes[$key] = function (Relation $q) use ($relation, $key) { $relations = $this->parser->getRelations(); $tableName = $q->getRelated()->getTable(); $primaryKey = $q->getRelated()->getKeyName(); if ($relation["userSpecifiedFields"]) { // Prefix table name so that we do not get ambiguous column errors $fields = $relation["fields"]; } else { // Add default fields, if no fields specified $related = $q->getRelated(); $fields = call_user_func(get_class($related) . "::getDefaultFields"); $fields = array_merge($fields, $relation["fields"]); $relations[$key]["fields"] = $fields; } // Remove appends from select $appends = call_user_func(get_class($q->getRelated()) . "::getAppendFields"); $relations[$key]["appends"] = $appends; if (!in_array($primaryKey, $fields)) { $fields[] = $primaryKey; } $fields = array_map(function($name) use($tableName) { return $tableName . "." . $name; }, array_diff($fields, $appends)); if ($q instanceof BelongsToMany) { // Because laravel loads all the related models of relations in many-to-many // together, limit and offset do not work. So, we have to complicate things // to make them work $innerQuery = $q->getQuery(); $innerQuery->select($fields); $innerQuery->selectRaw("@currcount := IF(@currvalue = " . $q->getQualifiedForeignPivotKeyName() . ", @currcount + 1, 1) AS rank"); $innerQuery->selectRaw("@currvalue := " . $q->getQualifiedForeignPivotKeyName() . " AS whatever"); $innerQuery->orderBy($q->getQualifiedForeignPivotKeyName(), ($relation["order"] == "chronological") ? "ASC" : "DESC"); // Inner Join causes issues when a relation for parent does not exist. // So, we change it to right join for this query $innerQuery->getQuery()->joins[0]->type = "right"; $outerQuery = $q->newPivotStatement(); $outerQuery->from(\DB::raw("(". $innerQuery->toSql() . ") as `$tableName`")) ->mergeBindings($innerQuery->getQuery()); $q->select($fields) ->join(\DB::raw("(" . $outerQuery->toSql() . ") as `outer_query`"), function ($join) use($q) { $join->on("outer_query." . $q->getRelatedKeyName(), "=", $q->getQualifiedRelatedPivotKeyName ()); $join->on("outer_query.whatever", "=", $q->getQualifiedForeignPivotKeyName()); }) ->setBindings(array_merge($q->getQuery()->getBindings(), $outerQuery->getBindings())) ->where("rank", "<=", $relation["limit"] + $relation["offset"]) ->where("rank", ">", $relation["offset"]); } else { // We need to select foreign key so that Laravel can match to which records these // need to be attached if ($q instanceof BelongsTo) { $fields[] = $q->getOwnerKey(); if (strpos($key, ".") !== false) { $parts = explode(".", $key); array_pop($parts); $relation["limit"] = $relations[implode(".", $parts)]["limit"]; } } else if ($q instanceof HasOne) { $fields[] = $q->getQualifiedForeignKeyName(); // This will be used to hide this foreign key field // in the processAppends function later $relations[$key]["foreign"] = $q->getQualifiedForeignKeyName(); } else if ($q instanceof HasMany) { $fields[] = $q->getQualifiedForeignKeyName(); $relations[$key]["foreign"] = $q->getQualifiedForeignKeyName(); $q->orderBy($primaryKey, ($relation["order"] == "chronological") ? "ASC" : "DESC"); } $q->select($fields); $q->take($relation["limit"]); if ($relation["offset"] !== 0) { $q->skip($relation["offset"]); } } $this->parser->setRelations($relations); }; } $this->query = call_user_func($this->model."::with", $includes); } else { $this->query = call_user_func($this->model."::query"); } return $this; }
php
protected function addIncludes() { $relations = $this->parser->getRelations(); if (!empty($relations)) { $includes = []; foreach ($relations as $key => $relation) { $includes[$key] = function (Relation $q) use ($relation, $key) { $relations = $this->parser->getRelations(); $tableName = $q->getRelated()->getTable(); $primaryKey = $q->getRelated()->getKeyName(); if ($relation["userSpecifiedFields"]) { // Prefix table name so that we do not get ambiguous column errors $fields = $relation["fields"]; } else { // Add default fields, if no fields specified $related = $q->getRelated(); $fields = call_user_func(get_class($related) . "::getDefaultFields"); $fields = array_merge($fields, $relation["fields"]); $relations[$key]["fields"] = $fields; } // Remove appends from select $appends = call_user_func(get_class($q->getRelated()) . "::getAppendFields"); $relations[$key]["appends"] = $appends; if (!in_array($primaryKey, $fields)) { $fields[] = $primaryKey; } $fields = array_map(function($name) use($tableName) { return $tableName . "." . $name; }, array_diff($fields, $appends)); if ($q instanceof BelongsToMany) { // Because laravel loads all the related models of relations in many-to-many // together, limit and offset do not work. So, we have to complicate things // to make them work $innerQuery = $q->getQuery(); $innerQuery->select($fields); $innerQuery->selectRaw("@currcount := IF(@currvalue = " . $q->getQualifiedForeignPivotKeyName() . ", @currcount + 1, 1) AS rank"); $innerQuery->selectRaw("@currvalue := " . $q->getQualifiedForeignPivotKeyName() . " AS whatever"); $innerQuery->orderBy($q->getQualifiedForeignPivotKeyName(), ($relation["order"] == "chronological") ? "ASC" : "DESC"); // Inner Join causes issues when a relation for parent does not exist. // So, we change it to right join for this query $innerQuery->getQuery()->joins[0]->type = "right"; $outerQuery = $q->newPivotStatement(); $outerQuery->from(\DB::raw("(". $innerQuery->toSql() . ") as `$tableName`")) ->mergeBindings($innerQuery->getQuery()); $q->select($fields) ->join(\DB::raw("(" . $outerQuery->toSql() . ") as `outer_query`"), function ($join) use($q) { $join->on("outer_query." . $q->getRelatedKeyName(), "=", $q->getQualifiedRelatedPivotKeyName ()); $join->on("outer_query.whatever", "=", $q->getQualifiedForeignPivotKeyName()); }) ->setBindings(array_merge($q->getQuery()->getBindings(), $outerQuery->getBindings())) ->where("rank", "<=", $relation["limit"] + $relation["offset"]) ->where("rank", ">", $relation["offset"]); } else { // We need to select foreign key so that Laravel can match to which records these // need to be attached if ($q instanceof BelongsTo) { $fields[] = $q->getOwnerKey(); if (strpos($key, ".") !== false) { $parts = explode(".", $key); array_pop($parts); $relation["limit"] = $relations[implode(".", $parts)]["limit"]; } } else if ($q instanceof HasOne) { $fields[] = $q->getQualifiedForeignKeyName(); // This will be used to hide this foreign key field // in the processAppends function later $relations[$key]["foreign"] = $q->getQualifiedForeignKeyName(); } else if ($q instanceof HasMany) { $fields[] = $q->getQualifiedForeignKeyName(); $relations[$key]["foreign"] = $q->getQualifiedForeignKeyName(); $q->orderBy($primaryKey, ($relation["order"] == "chronological") ? "ASC" : "DESC"); } $q->select($fields); $q->take($relation["limit"]); if ($relation["offset"] !== 0) { $q->skip($relation["offset"]); } } $this->parser->setRelations($relations); }; } $this->query = call_user_func($this->model."::with", $includes); } else { $this->query = call_user_func($this->model."::query"); } return $this; }
[ "protected", "function", "addIncludes", "(", ")", "{", "$", "relations", "=", "$", "this", "->", "parser", "->", "getRelations", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "relations", ")", ")", "{", "$", "includes", "=", "[", "]", ";", "for...
Looks for relations in the requested fields and adds with query for them @return $this current controller object for chain method calling
[ "Looks", "for", "relations", "in", "the", "requested", "fields", "and", "adds", "with", "query", "for", "them" ]
train
https://github.com/Froiden/laravel-rest-api/blob/2085c3980054518d2f1926990548a33b60e7302b/src/ApiController.php#L365-L481
Froiden/laravel-rest-api
src/ApiController.php
ApiController.addFilters
protected function addFilters() { if ($this->parser->getFilters()) { $this->query->whereRaw($this->parser->getFilters()); } return $this; }
php
protected function addFilters() { if ($this->parser->getFilters()) { $this->query->whereRaw($this->parser->getFilters()); } return $this; }
[ "protected", "function", "addFilters", "(", ")", "{", "if", "(", "$", "this", "->", "parser", "->", "getFilters", "(", ")", ")", "{", "$", "this", "->", "query", "->", "whereRaw", "(", "$", "this", "->", "parser", "->", "getFilters", "(", ")", ")", ...
Add requested filters. Filters are defined similar to normal SQL queries like (name eq "Milk" or name eq "Eggs") and price lt 2.55 The string should be enclosed in double quotes @return $this @throws NotAllowedToFilterOnThisFieldException
[ "Add", "requested", "filters", ".", "Filters", "are", "defined", "similar", "to", "normal", "SQL", "queries", "like", "(", "name", "eq", "Milk", "or", "name", "eq", "Eggs", ")", "and", "price", "lt", "2", ".", "55", "The", "string", "should", "be", "en...
train
https://github.com/Froiden/laravel-rest-api/blob/2085c3980054518d2f1926990548a33b60e7302b/src/ApiController.php#L490-L498
Froiden/laravel-rest-api
src/ApiController.php
ApiController.addOrdering
protected function addOrdering() { if ($this->parser->getOrder()) { $this->query->orderByRaw($this->parser->getOrder()); } return $this; }
php
protected function addOrdering() { if ($this->parser->getOrder()) { $this->query->orderByRaw($this->parser->getOrder()); } return $this; }
[ "protected", "function", "addOrdering", "(", ")", "{", "if", "(", "$", "this", "->", "parser", "->", "getOrder", "(", ")", ")", "{", "$", "this", "->", "query", "->", "orderByRaw", "(", "$", "this", "->", "parser", "->", "getOrder", "(", ")", ")", ...
Add sorting to the query. Sorting is similar to SQL queries @return $this
[ "Add", "sorting", "to", "the", "query", ".", "Sorting", "is", "similar", "to", "SQL", "queries" ]
train
https://github.com/Froiden/laravel-rest-api/blob/2085c3980054518d2f1926990548a33b60e7302b/src/ApiController.php#L505-L512
Froiden/laravel-rest-api
src/ApiController.php
ApiController.addPaging
protected function addPaging() { $limit = $this->parser->getLimit(); $offset = $this->parser->getOffset(); if ($offset <= 0) { $skip = 0; } else { $skip = $offset; } $this->query->skip($skip); $this->query->take($limit); return $this; }
php
protected function addPaging() { $limit = $this->parser->getLimit(); $offset = $this->parser->getOffset(); if ($offset <= 0) { $skip = 0; } else { $skip = $offset; } $this->query->skip($skip); $this->query->take($limit); return $this; }
[ "protected", "function", "addPaging", "(", ")", "{", "$", "limit", "=", "$", "this", "->", "parser", "->", "getLimit", "(", ")", ";", "$", "offset", "=", "$", "this", "->", "parser", "->", "getOffset", "(", ")", ";", "if", "(", "$", "offset", "<=",...
Adds paging limit and offset to SQL query @return $this
[ "Adds", "paging", "limit", "and", "offset", "to", "SQL", "query" ]
train
https://github.com/Froiden/laravel-rest-api/blob/2085c3980054518d2f1926990548a33b60e7302b/src/ApiController.php#L519-L536
Froiden/laravel-rest-api
src/ApiController.php
ApiController.getResults
protected function getResults($single = false) { $customAttributes = call_user_func($this->model."::getAppendFields"); // Laravel's $appends adds attributes always to the output. With this method, // we can specify which attributes are to be included $appends = []; $fields = $this->parser->getFields(); foreach ($fields as $key => $field) { if (in_array($field, $customAttributes)) { $appends[] = $field; unset($fields[$key]); } else { // Add table name to fields to prevent ambiguous column issues $fields[$key] = $this->table . "." . $field; } } $this->parser->setFields($fields); if (!$single) { /** @var Collection $results */ $results = $this->query->select($fields)->get(); } else { /** @var Collection $results */ $results = $this->query->select($fields)->skip(0)->take(1)->get(); if ($results->count() == 0) { throw new ResourceNotFoundException(); } } foreach($results as $result) { $result->setAppends($appends); } $this->processAppends($results); $this->results = $results; return $results; }
php
protected function getResults($single = false) { $customAttributes = call_user_func($this->model."::getAppendFields"); // Laravel's $appends adds attributes always to the output. With this method, // we can specify which attributes are to be included $appends = []; $fields = $this->parser->getFields(); foreach ($fields as $key => $field) { if (in_array($field, $customAttributes)) { $appends[] = $field; unset($fields[$key]); } else { // Add table name to fields to prevent ambiguous column issues $fields[$key] = $this->table . "." . $field; } } $this->parser->setFields($fields); if (!$single) { /** @var Collection $results */ $results = $this->query->select($fields)->get(); } else { /** @var Collection $results */ $results = $this->query->select($fields)->skip(0)->take(1)->get(); if ($results->count() == 0) { throw new ResourceNotFoundException(); } } foreach($results as $result) { $result->setAppends($appends); } $this->processAppends($results); $this->results = $results; return $results; }
[ "protected", "function", "getResults", "(", "$", "single", "=", "false", ")", "{", "$", "customAttributes", "=", "call_user_func", "(", "$", "this", "->", "model", ".", "\"::getAppendFields\"", ")", ";", "// Laravel's $appends adds attributes always to the output. With ...
Runs query and fetches results @param bool $single @return Collection @throws ResourceNotFoundException
[ "Runs", "query", "and", "fetches", "results" ]
train
https://github.com/Froiden/laravel-rest-api/blob/2085c3980054518d2f1926990548a33b60e7302b/src/ApiController.php#L553-L598
Froiden/laravel-rest-api
src/ApiController.php
ApiController.getMetaData
protected function getMetaData($single = false) { if (!$single) { $meta = [ "paging" => [ "links" => [ ] ] ]; $limit = $this->parser->getLimit(); $pageOffset = $this->parser->getOffset(); $current = $pageOffset; // Remove offset because setting offset does not return // result. As, there is single result in count query, // and setting offset will not return that record $offset = $this->query->getQuery()->offset; $this->query->offset(0); $totalRecords = $this->query->count($this->table . "." . $this->primaryKey); $this->query->offset($offset); $meta["paging"]["total"] = $totalRecords; if (($current + $limit) < $meta["paging"]["total"]) { $meta["paging"]["links"]["next"] = $this->getNextLink(); } if ($current >= $limit) { $meta["paging"]["links"]["previous"] = $this->getPreviousLink(); } } $meta["time"] = round(microtime(true) - $this->processingStartTime, 3); if (env("APP_DEBUG") == true) { $log = \DB::getQueryLog(); \DB::disableQueryLog(); $meta["queries"] = count($log); $meta["queries_list"] = $log; } return $meta; }
php
protected function getMetaData($single = false) { if (!$single) { $meta = [ "paging" => [ "links" => [ ] ] ]; $limit = $this->parser->getLimit(); $pageOffset = $this->parser->getOffset(); $current = $pageOffset; // Remove offset because setting offset does not return // result. As, there is single result in count query, // and setting offset will not return that record $offset = $this->query->getQuery()->offset; $this->query->offset(0); $totalRecords = $this->query->count($this->table . "." . $this->primaryKey); $this->query->offset($offset); $meta["paging"]["total"] = $totalRecords; if (($current + $limit) < $meta["paging"]["total"]) { $meta["paging"]["links"]["next"] = $this->getNextLink(); } if ($current >= $limit) { $meta["paging"]["links"]["previous"] = $this->getPreviousLink(); } } $meta["time"] = round(microtime(true) - $this->processingStartTime, 3); if (env("APP_DEBUG") == true) { $log = \DB::getQueryLog(); \DB::disableQueryLog(); $meta["queries"] = count($log); $meta["queries_list"] = $log; } return $meta; }
[ "protected", "function", "getMetaData", "(", "$", "single", "=", "false", ")", "{", "if", "(", "!", "$", "single", ")", "{", "$", "meta", "=", "[", "\"paging\"", "=>", "[", "\"links\"", "=>", "[", "]", "]", "]", ";", "$", "limit", "=", "$", "this...
Builds metadata - paging, links, time to complete request, etc @return array
[ "Builds", "metadata", "-", "paging", "links", "time", "to", "complete", "request", "etc" ]
train
https://github.com/Froiden/laravel-rest-api/blob/2085c3980054518d2f1926990548a33b60e7302b/src/ApiController.php#L661-L709
Froiden/laravel-rest-api
src/ApiController.php
ApiController.modify
private function modify() { if ($this->isIndex()) { $this->query = $this->modifyIndex($this->query); } else if ($this->isShow()) { $this->query = $this->modifyShow($this->query); } else if ($this->isDelete()) { $this->query = $this->modifyDelete($this->query); } else if ($this->isUpdate()) { $this->query = $this->modifyUpdate($this->query); } return $this; }
php
private function modify() { if ($this->isIndex()) { $this->query = $this->modifyIndex($this->query); } else if ($this->isShow()) { $this->query = $this->modifyShow($this->query); } else if ($this->isDelete()) { $this->query = $this->modifyDelete($this->query); } else if ($this->isUpdate()) { $this->query = $this->modifyUpdate($this->query); } return $this; }
[ "private", "function", "modify", "(", ")", "{", "if", "(", "$", "this", "->", "isIndex", "(", ")", ")", "{", "$", "this", "->", "query", "=", "$", "this", "->", "modifyIndex", "(", "$", "this", "->", "query", ")", ";", "}", "else", "if", "(", "...
Calls the modifyRequestType methods to modify query just before execution @return $this
[ "Calls", "the", "modifyRequestType", "methods", "to", "modify", "query", "just", "before", "execution" ]
train
https://github.com/Froiden/laravel-rest-api/blob/2085c3980054518d2f1926990548a33b60e7302b/src/ApiController.php#L806-L822
Froiden/laravel-rest-api
src/RequestParser.php
RequestParser.parseRequest
protected function parseRequest() { if (request()->limit) { if (request()->limit <= 0) { throw new InvalidLimitException(); } else if (request()->limit > config("api.maxLimit")) { throw new MaxLimitException(); } else { $this->limit = request()->limit; } } else { $this->limit = config("api.defaultLimit"); } if (request()->offset) { $this->offset = request()->offset; } else { $this->offset = 0; } $this->extractFields(); $this->extractFilters(); $this->extractOrdering(); $this->loadTableName(); $this->attributes = request()->all(); return $this; }
php
protected function parseRequest() { if (request()->limit) { if (request()->limit <= 0) { throw new InvalidLimitException(); } else if (request()->limit > config("api.maxLimit")) { throw new MaxLimitException(); } else { $this->limit = request()->limit; } } else { $this->limit = config("api.defaultLimit"); } if (request()->offset) { $this->offset = request()->offset; } else { $this->offset = 0; } $this->extractFields(); $this->extractFilters(); $this->extractOrdering(); $this->loadTableName(); $this->attributes = request()->all(); return $this; }
[ "protected", "function", "parseRequest", "(", ")", "{", "if", "(", "request", "(", ")", "->", "limit", ")", "{", "if", "(", "request", "(", ")", "->", "limit", "<=", "0", ")", "{", "throw", "new", "InvalidLimitException", "(", ")", ";", "}", "else", ...
Parse request and fill the parameters @return $this current controller object for chain method calling @throws InvalidFilterDefinitionException @throws InvalidOrderingDefinitionException @throws MaxLimitException
[ "Parse", "request", "and", "fill", "the", "parameters" ]
train
https://github.com/Froiden/laravel-rest-api/blob/2085c3980054518d2f1926990548a33b60e7302b/src/RequestParser.php#L199-L231
Froiden/laravel-rest-api
src/RequestParser.php
RequestParser.parseFields
private function parseFields($fields) { // If fields parameter is set, parse it using regex preg_match_all(static::FIELDS_REGEX, $fields, $matches); if (!empty($matches[0])) { foreach ($matches[0] as $match) { preg_match_all(static::FIELD_PARTS_REGEX, $match, $parts); $fieldName = $parts[1][0]; if (Str::contains($fieldName, ":") || call_user_func($this->model . "::relationExists", $fieldName)) { // If field name has a colon, we assume its a relations // OR // If method with field name exists in the class, we assume its a relation // This is default laravel behavior $limit = ($parts[3][0] == "") ? config("api.defaultLimit") : $parts[3][0]; $offset = ($parts[4][0] == "") ? 0 : $parts[4][0]; $order = ($parts[5][0] == "chronological") ? "chronological" : "reverse_chronological"; if (!empty($parts[7][0])) { $subFields = explode(",", $parts[7][0]); // This indicates if user specified fields for relation or not $userSpecifiedFields = true; } else { $subFields = []; $userSpecifiedFields = false; } $fieldName = str_replace(":", ".", $fieldName); if (!isset($this->relations[$fieldName])) { $this->relations[$fieldName] = [ "limit" => $limit, "offset" => $offset, "order" => $order, "fields" => $subFields, "userSpecifiedFields" => $userSpecifiedFields ]; } else { $this->relations[$fieldName]["limit"] = $limit; $this->relations[$fieldName]["offset"] = $offset; $this->relations[$fieldName]["order"] = $order; $this->relations[$fieldName]["fields"] = array_merge($this->relations[$fieldName]["fields"], $subFields); } // We also need to add the relation's foreign key field to select. If we don't, // relations always return null if (Str::contains($fieldName, ".")) { $relationNameParts = explode('.', $fieldName); $model = $this->model; $relation = null; foreach ($relationNameParts as $rp) { $relation = call_user_func([ new $model(), $rp]); $model = $relation->getRelated(); } // Its a multi level relations $fieldParts = explode(".", $fieldName); if ($relation instanceof BelongsTo) { $singular = $relation->getForeignKey(); } else if ($relation instanceof HasOne || $relation instanceof HasMany) { $singular = $relation->getForeignKeyName(); } // Unset last element of array unset($fieldParts[count($fieldParts) - 1]); $parent = implode(".", $fieldParts); if ($relation instanceof HasOne || $relation instanceof HasMany) { // For hasMany and HasOne, the foreign key is in current relation table, not in parent $this->relations[$fieldName]["fields"][] = $singular; } else { // The parent might already been set because we cannot rely on order // in which user sends relations in request if (!isset($this->relations[$parent])) { $this->relations[$parent] = [ "limit" => config("api.defaultLimit"), "offset" => 0, "order" => "chronological", "fields" => isset($singular) ? [$singular] : [], "userSpecifiedFields" => true ]; } else { if (isset($singular)) { $this->relations[$parent]["fields"][] = $singular; } } } if ($relation instanceof BelongsTo) { $this->relations[$fieldName]["limit"] = max($this->relations[$fieldName]["limit"], $this->relations[$parent]["limit"]); } else if ($relation instanceof HasMany) { $this->relations[$fieldName]["limit"] = $this->relations[$fieldName]["limit"] * $this->relations[$parent]["limit"]; } } else { $relation = call_user_func([new $this->model(), $fieldName]); if ($relation instanceof HasOne) { $keyField = explode(".", $relation->getQualifiedParentKeyName())[1]; } else if ($relation instanceof BelongsTo) { $keyField = explode(".", $relation->getQualifiedForeignKey())[1]; } if (isset($keyField) && !in_array($keyField, $this->fields)) { $this->fields[] = $keyField; } if ($relation instanceof BelongsTo) { $this->relations[$fieldName]["limit"] = max($this->relations[$fieldName]["limit"], $this->limit); } else if ($relation instanceof HasMany) { $this->relations[$fieldName]["limit"] = $this->relations[$fieldName]["limit"] * $this->limit; } } } else { // Else, its a normal field $this->fields[] = $fieldName; } } } }
php
private function parseFields($fields) { // If fields parameter is set, parse it using regex preg_match_all(static::FIELDS_REGEX, $fields, $matches); if (!empty($matches[0])) { foreach ($matches[0] as $match) { preg_match_all(static::FIELD_PARTS_REGEX, $match, $parts); $fieldName = $parts[1][0]; if (Str::contains($fieldName, ":") || call_user_func($this->model . "::relationExists", $fieldName)) { // If field name has a colon, we assume its a relations // OR // If method with field name exists in the class, we assume its a relation // This is default laravel behavior $limit = ($parts[3][0] == "") ? config("api.defaultLimit") : $parts[3][0]; $offset = ($parts[4][0] == "") ? 0 : $parts[4][0]; $order = ($parts[5][0] == "chronological") ? "chronological" : "reverse_chronological"; if (!empty($parts[7][0])) { $subFields = explode(",", $parts[7][0]); // This indicates if user specified fields for relation or not $userSpecifiedFields = true; } else { $subFields = []; $userSpecifiedFields = false; } $fieldName = str_replace(":", ".", $fieldName); if (!isset($this->relations[$fieldName])) { $this->relations[$fieldName] = [ "limit" => $limit, "offset" => $offset, "order" => $order, "fields" => $subFields, "userSpecifiedFields" => $userSpecifiedFields ]; } else { $this->relations[$fieldName]["limit"] = $limit; $this->relations[$fieldName]["offset"] = $offset; $this->relations[$fieldName]["order"] = $order; $this->relations[$fieldName]["fields"] = array_merge($this->relations[$fieldName]["fields"], $subFields); } // We also need to add the relation's foreign key field to select. If we don't, // relations always return null if (Str::contains($fieldName, ".")) { $relationNameParts = explode('.', $fieldName); $model = $this->model; $relation = null; foreach ($relationNameParts as $rp) { $relation = call_user_func([ new $model(), $rp]); $model = $relation->getRelated(); } // Its a multi level relations $fieldParts = explode(".", $fieldName); if ($relation instanceof BelongsTo) { $singular = $relation->getForeignKey(); } else if ($relation instanceof HasOne || $relation instanceof HasMany) { $singular = $relation->getForeignKeyName(); } // Unset last element of array unset($fieldParts[count($fieldParts) - 1]); $parent = implode(".", $fieldParts); if ($relation instanceof HasOne || $relation instanceof HasMany) { // For hasMany and HasOne, the foreign key is in current relation table, not in parent $this->relations[$fieldName]["fields"][] = $singular; } else { // The parent might already been set because we cannot rely on order // in which user sends relations in request if (!isset($this->relations[$parent])) { $this->relations[$parent] = [ "limit" => config("api.defaultLimit"), "offset" => 0, "order" => "chronological", "fields" => isset($singular) ? [$singular] : [], "userSpecifiedFields" => true ]; } else { if (isset($singular)) { $this->relations[$parent]["fields"][] = $singular; } } } if ($relation instanceof BelongsTo) { $this->relations[$fieldName]["limit"] = max($this->relations[$fieldName]["limit"], $this->relations[$parent]["limit"]); } else if ($relation instanceof HasMany) { $this->relations[$fieldName]["limit"] = $this->relations[$fieldName]["limit"] * $this->relations[$parent]["limit"]; } } else { $relation = call_user_func([new $this->model(), $fieldName]); if ($relation instanceof HasOne) { $keyField = explode(".", $relation->getQualifiedParentKeyName())[1]; } else if ($relation instanceof BelongsTo) { $keyField = explode(".", $relation->getQualifiedForeignKey())[1]; } if (isset($keyField) && !in_array($keyField, $this->fields)) { $this->fields[] = $keyField; } if ($relation instanceof BelongsTo) { $this->relations[$fieldName]["limit"] = max($this->relations[$fieldName]["limit"], $this->limit); } else if ($relation instanceof HasMany) { $this->relations[$fieldName]["limit"] = $this->relations[$fieldName]["limit"] * $this->limit; } } } else { // Else, its a normal field $this->fields[] = $fieldName; } } } }
[ "private", "function", "parseFields", "(", "$", "fields", ")", "{", "// If fields parameter is set, parse it using regex", "preg_match_all", "(", "static", "::", "FIELDS_REGEX", ",", "$", "fields", ",", "$", "matches", ")", ";", "if", "(", "!", "empty", "(", "$"...
Recursively parses fields to extract limit, ordering and their own fields and adds width relations @param $fields
[ "Recursively", "parses", "fields", "to", "extract", "limit", "ordering", "and", "their", "own", "fields", "and", "adds", "width", "relations" ]
train
https://github.com/Froiden/laravel-rest-api/blob/2085c3980054518d2f1926990548a33b60e7302b/src/RequestParser.php#L360-L500
Froiden/laravel-rest-api
src/ApiModel.php
ApiModel.fill
public function fill(array $attributes = []) { $this->raw = $attributes; $excludes = config("api.excludes"); foreach ($attributes as $key => $attribute) { // Guarded attributes should be removed if (in_array($key, $excludes)) { unset($attributes[$key]); } else if (method_exists($this, $key) && ((is_array($attribute) || is_null($attribute)))) { // Its a relation $this->relationAttributes[$key] = $attribute; // For belongs to relation, while filling, we need to set relation key. $relation = call_user_func([$this, $key]); if ($relation instanceof BelongsTo) { $primaryKey = $relation->getRelated()->getKeyName(); if ($attribute !== null) { // If key value is not set in request, we create new object if (!isset($attribute[$primaryKey])) { throw new RelatedResourceNotFoundException('Resource for relation "' . $key . '" not found'); } else { $model = $relation->getRelated()->find($attribute[$primaryKey]); if (!$model) { // Resource not found throw new ResourceNotFoundException(); } } } $relationKey = $relation->getForeignKey(); $this->setAttribute($relationKey, ($attribute === null) ? null : $model->getKey()); } unset($attributes[$key]); } } return parent::fill($attributes); }
php
public function fill(array $attributes = []) { $this->raw = $attributes; $excludes = config("api.excludes"); foreach ($attributes as $key => $attribute) { // Guarded attributes should be removed if (in_array($key, $excludes)) { unset($attributes[$key]); } else if (method_exists($this, $key) && ((is_array($attribute) || is_null($attribute)))) { // Its a relation $this->relationAttributes[$key] = $attribute; // For belongs to relation, while filling, we need to set relation key. $relation = call_user_func([$this, $key]); if ($relation instanceof BelongsTo) { $primaryKey = $relation->getRelated()->getKeyName(); if ($attribute !== null) { // If key value is not set in request, we create new object if (!isset($attribute[$primaryKey])) { throw new RelatedResourceNotFoundException('Resource for relation "' . $key . '" not found'); } else { $model = $relation->getRelated()->find($attribute[$primaryKey]); if (!$model) { // Resource not found throw new ResourceNotFoundException(); } } } $relationKey = $relation->getForeignKey(); $this->setAttribute($relationKey, ($attribute === null) ? null : $model->getKey()); } unset($attributes[$key]); } } return parent::fill($attributes); }
[ "public", "function", "fill", "(", "array", "$", "attributes", "=", "[", "]", ")", "{", "$", "this", "->", "raw", "=", "$", "attributes", ";", "$", "excludes", "=", "config", "(", "\"api.excludes\"", ")", ";", "foreach", "(", "$", "attributes", "as", ...
Fill the model with an array of attributes. @param array $attributes @param bool $relations If the attributes also contain relations @return Model
[ "Fill", "the", "model", "with", "an", "array", "of", "attributes", "." ]
train
https://github.com/Froiden/laravel-rest-api/blob/2085c3980054518d2f1926990548a33b60e7302b/src/ApiModel.php#L232-L278
Froiden/laravel-rest-api
src/Routing/ApiRouter.php
ApiRouter.addRoute
public function addRoute($methods, $uri, $action) { // We do not keep routes in ApiRouter. Whenever a route is added, // we add it to Laravel's primary route collection $routes = app("router")->getRoutes(); $prefix = config("api.prefix"); if (empty($this->versions)) { if (($default = config("api.default_version")) !== null) { $versions = [$default]; } else { $versions = [null]; } } else { $versions = $this->versions; } // Add version prefix foreach ($versions as $version) { // Add ApiMiddleware to all routes $route = $this->createRoute($methods, $uri, $action); $route->middleware(ApiMiddleware::class); if ($version !== null) { $route->prefix($version); $route->name("." . $version); } if (!empty($prefix)) { $route->prefix($prefix); } $routes->add($route); // Options route $route = $this->createRoute(['OPTIONS'], $uri, function () { return []; }); $route->middleware(ApiMiddleware::class); if ($version !== null) { $route->prefix($version); $route->name("." . $version); } if (!empty($prefix)) { $route->prefix($prefix); } $routes->add($route); } app("router")->setRoutes($routes); }
php
public function addRoute($methods, $uri, $action) { // We do not keep routes in ApiRouter. Whenever a route is added, // we add it to Laravel's primary route collection $routes = app("router")->getRoutes(); $prefix = config("api.prefix"); if (empty($this->versions)) { if (($default = config("api.default_version")) !== null) { $versions = [$default]; } else { $versions = [null]; } } else { $versions = $this->versions; } // Add version prefix foreach ($versions as $version) { // Add ApiMiddleware to all routes $route = $this->createRoute($methods, $uri, $action); $route->middleware(ApiMiddleware::class); if ($version !== null) { $route->prefix($version); $route->name("." . $version); } if (!empty($prefix)) { $route->prefix($prefix); } $routes->add($route); // Options route $route = $this->createRoute(['OPTIONS'], $uri, function () { return []; }); $route->middleware(ApiMiddleware::class); if ($version !== null) { $route->prefix($version); $route->name("." . $version); } if (!empty($prefix)) { $route->prefix($prefix); } $routes->add($route); } app("router")->setRoutes($routes); }
[ "public", "function", "addRoute", "(", "$", "methods", ",", "$", "uri", ",", "$", "action", ")", "{", "// We do not keep routes in ApiRouter. Whenever a route is added,", "// we add it to Laravel's primary route collection", "$", "routes", "=", "app", "(", "\"router\"", "...
Add a route to the underlying route collection. @param array|string $methods @param string $uri @param \Closure|array|string|null $action @return \Illuminate\Routing\Route
[ "Add", "a", "route", "to", "the", "underlying", "route", "collection", "." ]
train
https://github.com/Froiden/laravel-rest-api/blob/2085c3980054518d2f1926990548a33b60e7302b/src/Routing/ApiRouter.php#L58-L116
Froiden/laravel-rest-api
src/Exceptions/ApiException.php
ApiException.jsonSerialize
public function jsonSerialize() { $jsonArray = [ "error" => [ "message" => $this->getMessage(), "code" => $this->getCode() ] ]; if (isset($this->details)) { $jsonArray["error"]["details"] = $this->details; } if (isset($this->innerError)) { $jsonArray["error"]["innererror"] = [ "code" => $this->innerError ]; } return $jsonArray; }
php
public function jsonSerialize() { $jsonArray = [ "error" => [ "message" => $this->getMessage(), "code" => $this->getCode() ] ]; if (isset($this->details)) { $jsonArray["error"]["details"] = $this->details; } if (isset($this->innerError)) { $jsonArray["error"]["innererror"] = [ "code" => $this->innerError ]; } return $jsonArray; }
[ "public", "function", "jsonSerialize", "(", ")", "{", "$", "jsonArray", "=", "[", "\"error\"", "=>", "[", "\"message\"", "=>", "$", "this", "->", "getMessage", "(", ")", ",", "\"code\"", "=>", "$", "this", "->", "getCode", "(", ")", "]", "]", ";", "i...
Specify data which should be serialized to JSON @link http://php.net/manual/en/jsonserializable.jsonserialize.php @return mixed data which can be serialized by <b>json_encode</b>, which is a value of any type other than a resource.
[ "Specify", "data", "which", "should", "be", "serialized", "to", "JSON" ]
train
https://github.com/Froiden/laravel-rest-api/blob/2085c3980054518d2f1926990548a33b60e7302b/src/Exceptions/ApiException.php#L88-L108
Froiden/laravel-rest-api
src/ApiResponse.php
ApiResponse.make
public static function make($message = null, $data = null, $meta = null) { $response = []; if (!empty($message)) { $response["message"] = $message; } if ($data !== null && is_array($data)){ $response["data"] = $data; } if ($meta !== null && is_array($meta)){ $response["meta"] = $meta; } $returnResponse = \Response::make($response); return $returnResponse; }
php
public static function make($message = null, $data = null, $meta = null) { $response = []; if (!empty($message)) { $response["message"] = $message; } if ($data !== null && is_array($data)){ $response["data"] = $data; } if ($meta !== null && is_array($meta)){ $response["meta"] = $meta; } $returnResponse = \Response::make($response); return $returnResponse; }
[ "public", "static", "function", "make", "(", "$", "message", "=", "null", ",", "$", "data", "=", "null", ",", "$", "meta", "=", "null", ")", "{", "$", "response", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "message", ")", ")", "{", ...
Make new success response @param string $message @param array $data @return \Response
[ "Make", "new", "success", "response" ]
train
https://github.com/Froiden/laravel-rest-api/blob/2085c3980054518d2f1926990548a33b60e7302b/src/ApiResponse.php#L70-L89
Froiden/laravel-rest-api
src/ApiResponse.php
ApiResponse.exception
public static function exception(ApiException $exception) { $returnResponse = \Response::make($exception->jsonSerialize()); $returnResponse->setStatusCode($exception->getStatusCode()); return $returnResponse; }
php
public static function exception(ApiException $exception) { $returnResponse = \Response::make($exception->jsonSerialize()); $returnResponse->setStatusCode($exception->getStatusCode()); return $returnResponse; }
[ "public", "static", "function", "exception", "(", "ApiException", "$", "exception", ")", "{", "$", "returnResponse", "=", "\\", "Response", "::", "make", "(", "$", "exception", "->", "jsonSerialize", "(", ")", ")", ";", "$", "returnResponse", "->", "setStatu...
Handle api exception an return proper error response @param ApiException $exception @return \Illuminate\Http\Response @throws ApiException
[ "Handle", "api", "exception", "an", "return", "proper", "error", "response" ]
train
https://github.com/Froiden/laravel-rest-api/blob/2085c3980054518d2f1926990548a33b60e7302b/src/ApiResponse.php#L97-L104
mnabialek/laravel-sql-logger
src/FileName.php
FileName.createFileName
protected function createFileName($fileName) { return $this->parseFileName($fileName) . $this->suffix() . $this->config->fileExtension(); }
php
protected function createFileName($fileName) { return $this->parseFileName($fileName) . $this->suffix() . $this->config->fileExtension(); }
[ "protected", "function", "createFileName", "(", "$", "fileName", ")", "{", "return", "$", "this", "->", "parseFileName", "(", "$", "fileName", ")", ".", "$", "this", "->", "suffix", "(", ")", ".", "$", "this", "->", "config", "->", "fileExtension", "(", ...
Create file name. @param string $fileName @return string
[ "Create", "file", "name", "." ]
train
https://github.com/mnabialek/laravel-sql-logger/blob/13270fd027097b46d7a9f36dfc7498a15f7bcd63/src/FileName.php#L65-L68
mnabialek/laravel-sql-logger
src/FileName.php
FileName.parseFileName
protected function parseFileName($fileName) { return preg_replace_callback('#(\[.*\])#U', function ($matches) { $format = str_replace(['[',']'], [], $matches[1]); return $this->now->format($format); }, $fileName); }
php
protected function parseFileName($fileName) { return preg_replace_callback('#(\[.*\])#U', function ($matches) { $format = str_replace(['[',']'], [], $matches[1]); return $this->now->format($format); }, $fileName); }
[ "protected", "function", "parseFileName", "(", "$", "fileName", ")", "{", "return", "preg_replace_callback", "(", "'#(\\[.*\\])#U'", ",", "function", "(", "$", "matches", ")", "{", "$", "format", "=", "str_replace", "(", "[", "'['", ",", "']'", "]", ",", "...
Parse file name to include date in it. @param string $fileName @return string
[ "Parse", "file", "name", "to", "include", "date", "in", "it", "." ]
train
https://github.com/mnabialek/laravel-sql-logger/blob/13270fd027097b46d7a9f36dfc7498a15f7bcd63/src/FileName.php#L87-L94
mnabialek/laravel-sql-logger
src/Providers/ServiceProvider.php
ServiceProvider.register
public function register() { // merge config $this->mergeConfigFrom($this->configFileLocation(), 'sql_logger'); // register files to be published $this->publishes($this->getPublished()); // if no logging is enabled, we can stop here, nothing more should be done if (! $this->shouldLogAnything()) { return; } // create logger class $logger = $this->app->make(SqlLogger::class); // listen to database queries $this->app['db']->listen($this->getListenClosure($logger)); }
php
public function register() { // merge config $this->mergeConfigFrom($this->configFileLocation(), 'sql_logger'); // register files to be published $this->publishes($this->getPublished()); // if no logging is enabled, we can stop here, nothing more should be done if (! $this->shouldLogAnything()) { return; } // create logger class $logger = $this->app->make(SqlLogger::class); // listen to database queries $this->app['db']->listen($this->getListenClosure($logger)); }
[ "public", "function", "register", "(", ")", "{", "// merge config", "$", "this", "->", "mergeConfigFrom", "(", "$", "this", "->", "configFileLocation", "(", ")", ",", "'sql_logger'", ")", ";", "// register files to be published", "$", "this", "->", "publishes", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/mnabialek/laravel-sql-logger/blob/13270fd027097b46d7a9f36dfc7498a15f7bcd63/src/Providers/ServiceProvider.php#L27-L45