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
spiral/framework
src/Http/Middleware/ErrorHandlerMiddleware.php
ErrorHandlerMiddleware.process
public function process(Request $request, Handler $handler): Response { try { return $handler->handle($request); } catch (ClientException|RouteNotFoundException $e) { if ($e instanceof ClientException) { $code = $e->getCode(); } else { $code = 404; } } catch (\Throwable $e) { if (!$this->suppressErrors) { throw $e; } if ($this->snapshotter !== null) { $this->snapshotter->register($e); } $code = 500; } $this->logError($request, $code, $e->getMessage()); return $this->renderer->renderException($request, $code, $e->getMessage()); }
php
public function process(Request $request, Handler $handler): Response { try { return $handler->handle($request); } catch (ClientException|RouteNotFoundException $e) { if ($e instanceof ClientException) { $code = $e->getCode(); } else { $code = 404; } } catch (\Throwable $e) { if (!$this->suppressErrors) { throw $e; } if ($this->snapshotter !== null) { $this->snapshotter->register($e); } $code = 500; } $this->logError($request, $code, $e->getMessage()); return $this->renderer->renderException($request, $code, $e->getMessage()); }
[ "public", "function", "process", "(", "Request", "$", "request", ",", "Handler", "$", "handler", ")", ":", "Response", "{", "try", "{", "return", "$", "handler", "->", "handle", "(", "$", "request", ")", ";", "}", "catch", "(", "ClientException", "|", ...
@inheritdoc @throws \Throwable
[ "@inheritdoc" ]
train
https://github.com/spiral/framework/blob/cd425681c470ddaec43d3ca32028132475738317/src/Http/Middleware/ErrorHandlerMiddleware.php#L58-L83
spiral/framework
src/Translator/Views/LocaleProcessor.php
LocaleProcessor.process
public function process(ViewSource $source, ContextInterface $context): ViewSource { //Translator options must automatically route this view name to specific domain $domain = $this->translator->resolveDomain(sprintf( "%s-%s-%s", self::PREFIX, str_replace(['/', '\\'], '-', $source->getNamespace()), str_replace(['/', '\\'], '-', $source->getName()) )); //We are not forcing locale for now return $source->withCode(preg_replace_callback( self::REGEXP, function ($matches) use ($domain, $context) { return $this->translator->trans( $matches[1], [], $domain, $context->resolveValue(LocaleDependency::NAME) ); }, $source->getCode() )); }
php
public function process(ViewSource $source, ContextInterface $context): ViewSource { //Translator options must automatically route this view name to specific domain $domain = $this->translator->resolveDomain(sprintf( "%s-%s-%s", self::PREFIX, str_replace(['/', '\\'], '-', $source->getNamespace()), str_replace(['/', '\\'], '-', $source->getName()) )); //We are not forcing locale for now return $source->withCode(preg_replace_callback( self::REGEXP, function ($matches) use ($domain, $context) { return $this->translator->trans( $matches[1], [], $domain, $context->resolveValue(LocaleDependency::NAME) ); }, $source->getCode() )); }
[ "public", "function", "process", "(", "ViewSource", "$", "source", ",", "ContextInterface", "$", "context", ")", ":", "ViewSource", "{", "//Translator options must automatically route this view name to specific domain", "$", "domain", "=", "$", "this", "->", "translator",...
{@inheritdoc}
[ "{" ]
train
https://github.com/spiral/framework/blob/cd425681c470ddaec43d3ca32028132475738317/src/Translator/Views/LocaleProcessor.php#L39-L62
spiral/framework
src/Controller/Traits/AuthorizesTrait.php
AuthorizesTrait.authorize
protected function authorize(string $permission, array $context = []): bool { if (!$this->allows($permission, $context)) { $name = $this->resolvePermission($permission); throw new ControllerException( "Unauthorized permission '{$name}'", ControllerException::FORBIDDEN ); } return true; }
php
protected function authorize(string $permission, array $context = []): bool { if (!$this->allows($permission, $context)) { $name = $this->resolvePermission($permission); throw new ControllerException( "Unauthorized permission '{$name}'", ControllerException::FORBIDDEN ); } return true; }
[ "protected", "function", "authorize", "(", "string", "$", "permission", ",", "array", "$", "context", "=", "[", "]", ")", ":", "bool", "{", "if", "(", "!", "$", "this", "->", "allows", "(", "$", "permission", ",", "$", "context", ")", ")", "{", "$"...
Authorize permission or thrown controller exception. @param string $permission @param array $context @return bool @throws ControllerException
[ "Authorize", "permission", "or", "thrown", "controller", "exception", "." ]
train
https://github.com/spiral/framework/blob/cd425681c470ddaec43d3ca32028132475738317/src/Controller/Traits/AuthorizesTrait.php#L31-L43
UniSharp/laravel-jwt
src/Http/Middleware/JWTRefresh.php
JWTRefresh.handle
public function handle($request, \Closure $next) { $token = $this->authenticate($request); $response = $next($request); if ($token) { $response->header('Authorization', 'Bearer ' . $token); } return $response; }
php
public function handle($request, \Closure $next) { $token = $this->authenticate($request); $response = $next($request); if ($token) { $response->header('Authorization', 'Bearer ' . $token); } return $response; }
[ "public", "function", "handle", "(", "$", "request", ",", "\\", "Closure", "$", "next", ")", "{", "$", "token", "=", "$", "this", "->", "authenticate", "(", "$", "request", ")", ";", "$", "response", "=", "$", "next", "(", "$", "request", ")", ";",...
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
[ "Handle", "an", "incoming", "request", "." ]
train
https://github.com/UniSharp/laravel-jwt/blob/2004b50ad073ee4d3a45688492b73fcf57cc319d/src/Http/Middleware/JWTRefresh.php#L30-L40
UniSharp/laravel-jwt
src/Http/Middleware/JWTRefresh.php
JWTRefresh.authenticate
public function authenticate(Request $request) { if (Auth::user()) { return false; } $this->checkForToken($request); try { if (!JWTAuth::parseToken()->authenticate()) { throw new UnauthorizedHttpException('jwt-auth', 'User not found'); } } catch (TokenExpiredException $e) { // If the token is expired, then it will be refreshed and added to the headers try { return Auth::refresh(); } catch (TokenExpiredException $e) { throw new UnauthorizedHttpException('jwt-auth', 'Refresh token has expired.'); } } catch (TokenBlacklistedException $e) { throw new TokenBlacklistedException($e->getMessage(), 401); } catch (JWTException $e) { throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode()); } }
php
public function authenticate(Request $request) { if (Auth::user()) { return false; } $this->checkForToken($request); try { if (!JWTAuth::parseToken()->authenticate()) { throw new UnauthorizedHttpException('jwt-auth', 'User not found'); } } catch (TokenExpiredException $e) { // If the token is expired, then it will be refreshed and added to the headers try { return Auth::refresh(); } catch (TokenExpiredException $e) { throw new UnauthorizedHttpException('jwt-auth', 'Refresh token has expired.'); } } catch (TokenBlacklistedException $e) { throw new TokenBlacklistedException($e->getMessage(), 401); } catch (JWTException $e) { throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode()); } }
[ "public", "function", "authenticate", "(", "Request", "$", "request", ")", "{", "if", "(", "Auth", "::", "user", "(", ")", ")", "{", "return", "false", ";", "}", "$", "this", "->", "checkForToken", "(", "$", "request", ")", ";", "try", "{", "if", "...
Attempt to authenticate a user via the token in the request. @param \Illuminate\Http\Request $request @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException @return void
[ "Attempt", "to", "authenticate", "a", "user", "via", "the", "token", "in", "the", "request", "." ]
train
https://github.com/UniSharp/laravel-jwt/blob/2004b50ad073ee4d3a45688492b73fcf57cc319d/src/Http/Middleware/JWTRefresh.php#L67-L91
UniSharp/laravel-jwt
src/JWTServiceProvider.php
JWTServiceProvider.registerMiddleware
protected function registerMiddleware() { if ($this->isLumen()) { $this->app->routeMiddleware($this->middlewareAliases); } else { $this->aliasMiddleware(); } }
php
protected function registerMiddleware() { if ($this->isLumen()) { $this->app->routeMiddleware($this->middlewareAliases); } else { $this->aliasMiddleware(); } }
[ "protected", "function", "registerMiddleware", "(", ")", "{", "if", "(", "$", "this", "->", "isLumen", "(", ")", ")", "{", "$", "this", "->", "app", "->", "routeMiddleware", "(", "$", "this", "->", "middlewareAliases", ")", ";", "}", "else", "{", "$", ...
Register middleware. @return void
[ "Register", "middleware", "." ]
train
https://github.com/UniSharp/laravel-jwt/blob/2004b50ad073ee4d3a45688492b73fcf57cc319d/src/JWTServiceProvider.php#L64-L71
UniSharp/laravel-jwt
src/Auth/Guards/JWTAuthGuard.php
JWTAuthGuard.user
public function user() { if (!is_null($this->user)) { return $this->user; } $token = $this->jwt->setRequest($this->request)->getToken(); if (!$token) { return null; } // get cached freshed token if exists for concurrency requests if ($this->getCachedToken()) { $this->jwt = $this->jwt->setToken($this->getCachedToken()); } // token validation if ($this->getToken() && ($payload = $this->jwt->check(true)) && $this->validateSubject() ) { return $this->user = $this->provider->retrieveById($payload['sub']); } return $this->user; }
php
public function user() { if (!is_null($this->user)) { return $this->user; } $token = $this->jwt->setRequest($this->request)->getToken(); if (!$token) { return null; } // get cached freshed token if exists for concurrency requests if ($this->getCachedToken()) { $this->jwt = $this->jwt->setToken($this->getCachedToken()); } // token validation if ($this->getToken() && ($payload = $this->jwt->check(true)) && $this->validateSubject() ) { return $this->user = $this->provider->retrieveById($payload['sub']); } return $this->user; }
[ "public", "function", "user", "(", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "user", ")", ")", "{", "return", "$", "this", "->", "user", ";", "}", "$", "token", "=", "$", "this", "->", "jwt", "->", "setRequest", "(", "$", "th...
Get the currently authenticated user. @return \Illuminate\Contracts\Auth\Authenticatable|null
[ "Get", "the", "currently", "authenticated", "user", "." ]
train
https://github.com/UniSharp/laravel-jwt/blob/2004b50ad073ee4d3a45688492b73fcf57cc319d/src/Auth/Guards/JWTAuthGuard.php#L35-L60
UniSharp/laravel-jwt
src/Auth/Guards/JWTAuthGuard.php
JWTAuthGuard.getCachedToken
public function getCachedToken() { if ($this->cachedToken) { return $this->cachedToken; } $key = md5($this->jwt->parser()->parseToken()); $this->cachedToken = Cache::get($key); return $this->cachedToken; }
php
public function getCachedToken() { if ($this->cachedToken) { return $this->cachedToken; } $key = md5($this->jwt->parser()->parseToken()); $this->cachedToken = Cache::get($key); return $this->cachedToken; }
[ "public", "function", "getCachedToken", "(", ")", "{", "if", "(", "$", "this", "->", "cachedToken", ")", "{", "return", "$", "this", "->", "cachedToken", ";", "}", "$", "key", "=", "md5", "(", "$", "this", "->", "jwt", "->", "parser", "(", ")", "->...
Return cached token. @return string
[ "Return", "cached", "token", "." ]
train
https://github.com/UniSharp/laravel-jwt/blob/2004b50ad073ee4d3a45688492b73fcf57cc319d/src/Auth/Guards/JWTAuthGuard.php#L84-L94
UniSharp/laravel-jwt
src/Auth/Guards/JWTAuthGuard.php
JWTAuthGuard.setCachedToken
public function setCachedToken($key, $refreshToken, $expiresAt = null) { if (is_null($expiresAt)) { $expiresAt = ((int) Config::get('laravel_jwt.cache_ttl') / 60); } Cache::put($key, $refreshToken, $expiresAt); $this->cachedToken = $refreshToken; return $this; }
php
public function setCachedToken($key, $refreshToken, $expiresAt = null) { if (is_null($expiresAt)) { $expiresAt = ((int) Config::get('laravel_jwt.cache_ttl') / 60); } Cache::put($key, $refreshToken, $expiresAt); $this->cachedToken = $refreshToken; return $this; }
[ "public", "function", "setCachedToken", "(", "$", "key", ",", "$", "refreshToken", ",", "$", "expiresAt", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "expiresAt", ")", ")", "{", "$", "expiresAt", "=", "(", "(", "int", ")", "Config", "::", ...
Set cached token. @return this
[ "Set", "cached", "token", "." ]
train
https://github.com/UniSharp/laravel-jwt/blob/2004b50ad073ee4d3a45688492b73fcf57cc319d/src/Auth/Guards/JWTAuthGuard.php#L101-L110
UniSharp/laravel-jwt
src/Auth/Guards/JWTAuthGuard.php
JWTAuthGuard.refresh
public function refresh($forceForever = false, $resetClaims = false) { if ($cache = $this->getCachedToken()) { return $cache; } // refresh token $token = $this->jwt->parser()->parseToken(); $key = md5($token); $refreshToken = JWTAuth::refresh($token, $forceForever, $resetClaims); // cache newly refreshed token $this->setCachedToken($key, $refreshToken); return $this->cachedToken; }
php
public function refresh($forceForever = false, $resetClaims = false) { if ($cache = $this->getCachedToken()) { return $cache; } // refresh token $token = $this->jwt->parser()->parseToken(); $key = md5($token); $refreshToken = JWTAuth::refresh($token, $forceForever, $resetClaims); // cache newly refreshed token $this->setCachedToken($key, $refreshToken); return $this->cachedToken; }
[ "public", "function", "refresh", "(", "$", "forceForever", "=", "false", ",", "$", "resetClaims", "=", "false", ")", "{", "if", "(", "$", "cache", "=", "$", "this", "->", "getCachedToken", "(", ")", ")", "{", "return", "$", "cache", ";", "}", "// ref...
Refresh current expired token. @return string
[ "Refresh", "current", "expired", "token", "." ]
train
https://github.com/UniSharp/laravel-jwt/blob/2004b50ad073ee4d3a45688492b73fcf57cc319d/src/Auth/Guards/JWTAuthGuard.php#L117-L132
pmill/aws-cognito
src/CognitoClient.php
CognitoClient.authenticate
public function authenticate($username, $password) { try { $response = $this->client->adminInitiateAuth([ 'AuthFlow' => 'ADMIN_NO_SRP_AUTH', 'AuthParameters' => [ 'USERNAME' => $username, 'PASSWORD' => $password, 'SECRET_HASH' => $this->cognitoSecretHash($username), ], 'ClientId' => $this->appClientId, 'UserPoolId' => $this->userPoolId, ]); return $this->handleAuthenticateResponse($response->toArray()); } catch (CognitoIdentityProviderException $e) { throw CognitoResponseException::createFromCognitoException($e); } }
php
public function authenticate($username, $password) { try { $response = $this->client->adminInitiateAuth([ 'AuthFlow' => 'ADMIN_NO_SRP_AUTH', 'AuthParameters' => [ 'USERNAME' => $username, 'PASSWORD' => $password, 'SECRET_HASH' => $this->cognitoSecretHash($username), ], 'ClientId' => $this->appClientId, 'UserPoolId' => $this->userPoolId, ]); return $this->handleAuthenticateResponse($response->toArray()); } catch (CognitoIdentityProviderException $e) { throw CognitoResponseException::createFromCognitoException($e); } }
[ "public", "function", "authenticate", "(", "$", "username", ",", "$", "password", ")", "{", "try", "{", "$", "response", "=", "$", "this", "->", "client", "->", "adminInitiateAuth", "(", "[", "'AuthFlow'", "=>", "'ADMIN_NO_SRP_AUTH'", ",", "'AuthParameters'", ...
@param string $username @param string $password @return array @throws ChallengeException @throws Exception
[ "@param", "string", "$username", "@param", "string", "$password" ]
train
https://github.com/pmill/aws-cognito/blob/642fecec9c32fb7f0531e440b1c461b37f5096ae/src/CognitoClient.php#L70-L88
pmill/aws-cognito
src/CognitoClient.php
CognitoClient.respondToAuthChallenge
public function respondToAuthChallenge($challengeName, array $challengeResponses, $session) { try { $response = $this->client->respondToAuthChallenge([ 'ChallengeName' => $challengeName, 'ChallengeResponses' => $challengeResponses, 'ClientId' => $this->appClientId, 'Session' => $session, ]); return $this->handleAuthenticateResponse($response->toArray()); } catch (CognitoIdentityProviderException $e) { throw CognitoResponseException::createFromCognitoException($e); } }
php
public function respondToAuthChallenge($challengeName, array $challengeResponses, $session) { try { $response = $this->client->respondToAuthChallenge([ 'ChallengeName' => $challengeName, 'ChallengeResponses' => $challengeResponses, 'ClientId' => $this->appClientId, 'Session' => $session, ]); return $this->handleAuthenticateResponse($response->toArray()); } catch (CognitoIdentityProviderException $e) { throw CognitoResponseException::createFromCognitoException($e); } }
[ "public", "function", "respondToAuthChallenge", "(", "$", "challengeName", ",", "array", "$", "challengeResponses", ",", "$", "session", ")", "{", "try", "{", "$", "response", "=", "$", "this", "->", "client", "->", "respondToAuthChallenge", "(", "[", "'Challe...
@param string $challengeName @param array $challengeResponses @param string $session @return array @throws ChallengeException @throws Exception
[ "@param", "string", "$challengeName", "@param", "array", "$challengeResponses", "@param", "string", "$session" ]
train
https://github.com/pmill/aws-cognito/blob/642fecec9c32fb7f0531e440b1c461b37f5096ae/src/CognitoClient.php#L99-L113
pmill/aws-cognito
src/CognitoClient.php
CognitoClient.getUser
public function getUser($username) { try { $response = $this->client->adminGetUser([ 'Username' => $username, 'UserPoolId' => $this->userPoolId, ]); return $response; } catch (Exception $e) { throw CognitoResponseException::createFromCognitoException($e); } }
php
public function getUser($username) { try { $response = $this->client->adminGetUser([ 'Username' => $username, 'UserPoolId' => $this->userPoolId, ]); return $response; } catch (Exception $e) { throw CognitoResponseException::createFromCognitoException($e); } }
[ "public", "function", "getUser", "(", "$", "username", ")", "{", "try", "{", "$", "response", "=", "$", "this", "->", "client", "->", "adminGetUser", "(", "[", "'Username'", "=>", "$", "username", ",", "'UserPoolId'", "=>", "$", "this", "->", "userPoolId...
/* @param string $username @return AwsResult @throws UserNotFoundException @throws CognitoResponseException
[ "/", "*" ]
train
https://github.com/pmill/aws-cognito/blob/642fecec9c32fb7f0531e440b1c461b37f5096ae/src/CognitoClient.php#L210-L221
pmill/aws-cognito
src/CognitoClient.php
CognitoClient.verifyAccessToken
public function verifyAccessToken($accessToken) { $jwtPayload = $this->decodeAccessToken($accessToken); $expectedIss = sprintf('https://cognito-idp.%s.amazonaws.com/%s', $this->region, $this->userPoolId); if ($jwtPayload['iss'] !== $expectedIss) { throw new TokenVerificationException('invalid iss'); } if ($jwtPayload['token_use'] !== 'access') { throw new TokenVerificationException('invalid token_use'); } if ($jwtPayload['exp'] < time()) { throw new TokenExpiryException('invalid exp'); } return $jwtPayload['username']; }
php
public function verifyAccessToken($accessToken) { $jwtPayload = $this->decodeAccessToken($accessToken); $expectedIss = sprintf('https://cognito-idp.%s.amazonaws.com/%s', $this->region, $this->userPoolId); if ($jwtPayload['iss'] !== $expectedIss) { throw new TokenVerificationException('invalid iss'); } if ($jwtPayload['token_use'] !== 'access') { throw new TokenVerificationException('invalid token_use'); } if ($jwtPayload['exp'] < time()) { throw new TokenExpiryException('invalid exp'); } return $jwtPayload['username']; }
[ "public", "function", "verifyAccessToken", "(", "$", "accessToken", ")", "{", "$", "jwtPayload", "=", "$", "this", "->", "decodeAccessToken", "(", "$", "accessToken", ")", ";", "$", "expectedIss", "=", "sprintf", "(", "'https://cognito-idp.%s.amazonaws.com/%s'", "...
Verifies the given access token and returns the username @param string $accessToken @throws TokenExpiryException @throws TokenVerificationException @return string
[ "Verifies", "the", "given", "access", "token", "and", "returns", "the", "username" ]
train
https://github.com/pmill/aws-cognito/blob/642fecec9c32fb7f0531e440b1c461b37f5096ae/src/CognitoClient.php#L471-L489
pmill/aws-cognito
src/CognitoClient.php
CognitoClient.getGroupsForUsername
public function getGroupsForUsername($username) { try { return $this->client->adminListGroupsForUser([ 'UserPoolId' => $this->userPoolId, 'Username' => $username ]); } catch (Exception $e) { throw CognitoResponseException::createFromCognitoException($e); } }
php
public function getGroupsForUsername($username) { try { return $this->client->adminListGroupsForUser([ 'UserPoolId' => $this->userPoolId, 'Username' => $username ]); } catch (Exception $e) { throw CognitoResponseException::createFromCognitoException($e); } }
[ "public", "function", "getGroupsForUsername", "(", "$", "username", ")", "{", "try", "{", "return", "$", "this", "->", "client", "->", "adminListGroupsForUser", "(", "[", "'UserPoolId'", "=>", "$", "this", "->", "userPoolId", ",", "'Username'", "=>", "$", "u...
@param $username @return \Aws\Result @throws Exception
[ "@param", "$username" ]
train
https://github.com/pmill/aws-cognito/blob/642fecec9c32fb7f0531e440b1c461b37f5096ae/src/CognitoClient.php#L507-L518
pmill/aws-cognito
src/CognitoClient.php
CognitoClient.hash
protected function hash($message) { $hash = hash_hmac( 'sha256', $message, $this->appClientSecret, true ); return base64_encode($hash); }
php
protected function hash($message) { $hash = hash_hmac( 'sha256', $message, $this->appClientSecret, true ); return base64_encode($hash); }
[ "protected", "function", "hash", "(", "$", "message", ")", "{", "$", "hash", "=", "hash_hmac", "(", "'sha256'", ",", "$", "message", ",", "$", "this", "->", "appClientSecret", ",", "true", ")", ";", "return", "base64_encode", "(", "$", "hash", ")", ";"...
@param string $message @return string
[ "@param", "string", "$message" ]
train
https://github.com/pmill/aws-cognito/blob/642fecec9c32fb7f0531e440b1c461b37f5096ae/src/CognitoClient.php#L525-L535
pionl/laravel-chunk-upload
src/Handler/ResumableJSUploadHandler.php
ResumableJSUploadHandler.canBeUsedForRequest
public static function canBeUsedForRequest(Request $request) { return $request->has(self::CHUNK_NUMBER_INDEX) && $request->has(self::TOTAL_CHUNKS_INDEX) && $request->has(self::CHUNK_UUID_INDEX); }
php
public static function canBeUsedForRequest(Request $request) { return $request->has(self::CHUNK_NUMBER_INDEX) && $request->has(self::TOTAL_CHUNKS_INDEX) && $request->has(self::CHUNK_UUID_INDEX); }
[ "public", "static", "function", "canBeUsedForRequest", "(", "Request", "$", "request", ")", "{", "return", "$", "request", "->", "has", "(", "self", "::", "CHUNK_NUMBER_INDEX", ")", "&&", "$", "request", "->", "has", "(", "self", "::", "TOTAL_CHUNKS_INDEX", ...
Checks if the current abstract handler can be used via HandlerFactory. @param Request $request @return bool
[ "Checks", "if", "the", "current", "abstract", "handler", "can", "be", "used", "via", "HandlerFactory", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Handler/ResumableJSUploadHandler.php#L80-L84
pionl/laravel-chunk-upload
src/Handler/HandlerFactory.php
HandlerFactory.classFromRequest
public static function classFromRequest(Request $request, $fallbackClass = null) { /** @var AbstractHandler $handlerClass */ foreach (static::$handlers as $handlerClass) { if ($handlerClass::canBeUsedForRequest($request)) { return $handlerClass; break; } } if (is_null($fallbackClass)) { // the default handler return static::$fallbackHandler; } return $fallbackClass; }
php
public static function classFromRequest(Request $request, $fallbackClass = null) { /** @var AbstractHandler $handlerClass */ foreach (static::$handlers as $handlerClass) { if ($handlerClass::canBeUsedForRequest($request)) { return $handlerClass; break; } } if (is_null($fallbackClass)) { // the default handler return static::$fallbackHandler; } return $fallbackClass; }
[ "public", "static", "function", "classFromRequest", "(", "Request", "$", "request", ",", "$", "fallbackClass", "=", "null", ")", "{", "/** @var AbstractHandler $handlerClass */", "foreach", "(", "static", "::", "$", "handlers", "as", "$", "handlerClass", ")", "{",...
Returns handler class based on the request or the fallback handler. @param Request $request @param string|null $fallbackClass @return string
[ "Returns", "handler", "class", "based", "on", "the", "request", "or", "the", "fallback", "handler", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Handler/HandlerFactory.php#L38-L54
pionl/laravel-chunk-upload
src/Handler/NgFileUploadHandler.php
NgFileUploadHandler.canBeUsedForRequest
public static function canBeUsedForRequest(Request $request) { $hasChunkParams = $request->has(static::KEY_CHUNK_NUMBER) && $request->has(static::KEY_TOTAL_SIZE) && $request->has(static::KEY_CHUNK_SIZE) && $request->has(static::KEY_CHUNK_CURRENT_SIZE); return $hasChunkParams && self::checkChunkParams($request); }
php
public static function canBeUsedForRequest(Request $request) { $hasChunkParams = $request->has(static::KEY_CHUNK_NUMBER) && $request->has(static::KEY_TOTAL_SIZE) && $request->has(static::KEY_CHUNK_SIZE) && $request->has(static::KEY_CHUNK_CURRENT_SIZE); return $hasChunkParams && self::checkChunkParams($request); }
[ "public", "static", "function", "canBeUsedForRequest", "(", "Request", "$", "request", ")", "{", "$", "hasChunkParams", "=", "$", "request", "->", "has", "(", "static", "::", "KEY_CHUNK_NUMBER", ")", "&&", "$", "request", "->", "has", "(", "static", "::", ...
Checks if the current handler can be used via HandlerFactory. @param Request $request @return bool @throws ChunkInvalidValueException
[ "Checks", "if", "the", "current", "handler", "can", "be", "used", "via", "HandlerFactory", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Handler/NgFileUploadHandler.php#L54-L62
pionl/laravel-chunk-upload
src/Handler/NgFileUploadHandler.php
NgFileUploadHandler.checkChunkParams
protected static function checkChunkParams($request) { $isInteger = ctype_digit($request->input(static::KEY_CHUNK_NUMBER)) && ctype_digit($request->input(static::KEY_TOTAL_SIZE)) && ctype_digit($request->input(static::KEY_CHUNK_SIZE)) && ctype_digit($request->input(static::KEY_CHUNK_CURRENT_SIZE)); if ($request->get(static::KEY_CHUNK_SIZE) < $request->get(static::KEY_CHUNK_CURRENT_SIZE)) { throw new ChunkInvalidValueException(); } if ($request->get(static::KEY_CHUNK_NUMBER) < 0) { throw new ChunkInvalidValueException(); } if ($request->get(static::KEY_TOTAL_SIZE) < 0) { throw new ChunkInvalidValueException(); } return $isInteger; }
php
protected static function checkChunkParams($request) { $isInteger = ctype_digit($request->input(static::KEY_CHUNK_NUMBER)) && ctype_digit($request->input(static::KEY_TOTAL_SIZE)) && ctype_digit($request->input(static::KEY_CHUNK_SIZE)) && ctype_digit($request->input(static::KEY_CHUNK_CURRENT_SIZE)); if ($request->get(static::KEY_CHUNK_SIZE) < $request->get(static::KEY_CHUNK_CURRENT_SIZE)) { throw new ChunkInvalidValueException(); } if ($request->get(static::KEY_CHUNK_NUMBER) < 0) { throw new ChunkInvalidValueException(); } if ($request->get(static::KEY_TOTAL_SIZE) < 0) { throw new ChunkInvalidValueException(); } return $isInteger; }
[ "protected", "static", "function", "checkChunkParams", "(", "$", "request", ")", "{", "$", "isInteger", "=", "ctype_digit", "(", "$", "request", "->", "input", "(", "static", "::", "KEY_CHUNK_NUMBER", ")", ")", "&&", "ctype_digit", "(", "$", "request", "->",...
@param Request $request @return bool @throws ChunkInvalidValueException
[ "@param", "Request", "$request" ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Handler/NgFileUploadHandler.php#L84-L104
pionl/laravel-chunk-upload
src/Handler/NgFileUploadHandler.php
NgFileUploadHandler.getTotalChunksFromRequest
protected function getTotalChunksFromRequest(Request $request) { if (!$request->get(static::KEY_CHUNK_SIZE)) { return 0; } return intval( ceil($request->get(static::KEY_TOTAL_SIZE) / $request->get(static::KEY_CHUNK_SIZE)) ); }
php
protected function getTotalChunksFromRequest(Request $request) { if (!$request->get(static::KEY_CHUNK_SIZE)) { return 0; } return intval( ceil($request->get(static::KEY_TOTAL_SIZE) / $request->get(static::KEY_CHUNK_SIZE)) ); }
[ "protected", "function", "getTotalChunksFromRequest", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "$", "request", "->", "get", "(", "static", "::", "KEY_CHUNK_SIZE", ")", ")", "{", "return", "0", ";", "}", "return", "intval", "(", "ceil", "...
Returns current chunk from the request. @param Request $request @return int
[ "Returns", "current", "chunk", "from", "the", "request", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Handler/NgFileUploadHandler.php#L113-L122
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
ChunkSave.getChunkDirectory
public function getChunkDirectory($absolutePath = false) { $paths = []; if ($absolutePath) { $paths[] = $this->chunkStorage()->getDiskPathPrefix(); } $paths[] = $this->chunkStorage()->directory(); return implode('', $paths); }
php
public function getChunkDirectory($absolutePath = false) { $paths = []; if ($absolutePath) { $paths[] = $this->chunkStorage()->getDiskPathPrefix(); } $paths[] = $this->chunkStorage()->directory(); return implode('', $paths); }
[ "public", "function", "getChunkDirectory", "(", "$", "absolutePath", "=", "false", ")", "{", "$", "paths", "=", "[", "]", ";", "if", "(", "$", "absolutePath", ")", "{", "$", "paths", "[", "]", "=", "$", "this", "->", "chunkStorage", "(", ")", "->", ...
Returns the folder for the cunks in the storage path on current disk instance. @param bool $absolutePath @return string
[ "Returns", "the", "folder", "for", "the", "cunks", "in", "the", "storage", "path", "on", "current", "disk", "instance", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Save/ChunkSave.php#L108-L119
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
ChunkSave.handleChunk
protected function handleChunk() { // prepare the folder and file path $this->createChunksFolderIfNeeded(); $file = $this->getChunkFilePath(); $this->handleChunkFile($file) ->tryToBuildFullFileFromChunks(); }
php
protected function handleChunk() { // prepare the folder and file path $this->createChunksFolderIfNeeded(); $file = $this->getChunkFilePath(); $this->handleChunkFile($file) ->tryToBuildFullFileFromChunks(); }
[ "protected", "function", "handleChunk", "(", ")", "{", "// prepare the folder and file path", "$", "this", "->", "createChunksFolderIfNeeded", "(", ")", ";", "$", "file", "=", "$", "this", "->", "getChunkFilePath", "(", ")", ";", "$", "this", "->", "handleChunkF...
Appends the new uploaded data to the final file. @throws ChunkSaveException
[ "Appends", "the", "new", "uploaded", "data", "to", "the", "final", "file", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Save/ChunkSave.php#L150-L158
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
ChunkSave.handleChunkFile
protected function handleChunkFile($file) { // delete the old chunk if ($this->handler()->isFirstChunk() && $this->chunkDisk()->exists($file)) { $this->chunkDisk()->delete($file); } // Append the data to the file (new FileMerger($this->getChunkFullFilePath())) ->appendFile($this->file->getPathname()) ->close(); return $this; }
php
protected function handleChunkFile($file) { // delete the old chunk if ($this->handler()->isFirstChunk() && $this->chunkDisk()->exists($file)) { $this->chunkDisk()->delete($file); } // Append the data to the file (new FileMerger($this->getChunkFullFilePath())) ->appendFile($this->file->getPathname()) ->close(); return $this; }
[ "protected", "function", "handleChunkFile", "(", "$", "file", ")", "{", "// delete the old chunk", "if", "(", "$", "this", "->", "handler", "(", ")", "->", "isFirstChunk", "(", ")", "&&", "$", "this", "->", "chunkDisk", "(", ")", "->", "exists", "(", "$"...
Appends the current uploaded file to chunk file. @param string $file Relative path to chunk @return $this @throws ChunkSaveException
[ "Appends", "the", "current", "uploaded", "file", "to", "chunk", "file", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Save/ChunkSave.php#L184-L197
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
ChunkSave.createFullChunkFile
protected function createFullChunkFile($finalPath) { return new UploadedFile( $finalPath, $this->file->getClientOriginalName(), $this->file->getClientMimeType(), filesize($finalPath), $this->file->getError(), // we must pass the true as test to force the upload file // to use a standard copy method, not move uploaded file true ); }
php
protected function createFullChunkFile($finalPath) { return new UploadedFile( $finalPath, $this->file->getClientOriginalName(), $this->file->getClientMimeType(), filesize($finalPath), $this->file->getError(), // we must pass the true as test to force the upload file // to use a standard copy method, not move uploaded file true ); }
[ "protected", "function", "createFullChunkFile", "(", "$", "finalPath", ")", "{", "return", "new", "UploadedFile", "(", "$", "finalPath", ",", "$", "this", "->", "file", "->", "getClientOriginalName", "(", ")", ",", "$", "this", "->", "file", "->", "getClient...
Creates the UploadedFile object for given chunk file. @param string $finalPath @return UploadedFile
[ "Creates", "the", "UploadedFile", "object", "for", "given", "chunk", "file", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Save/ChunkSave.php#L218-L230
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
ChunkSave.createChunksFolderIfNeeded
protected function createChunksFolderIfNeeded() { $path = $this->getChunkDirectory(true); // creates the chunks dir if (!file_exists($path)) { mkdir($path, 0777, true); } }
php
protected function createChunksFolderIfNeeded() { $path = $this->getChunkDirectory(true); // creates the chunks dir if (!file_exists($path)) { mkdir($path, 0777, true); } }
[ "protected", "function", "createChunksFolderIfNeeded", "(", ")", "{", "$", "path", "=", "$", "this", "->", "getChunkDirectory", "(", "true", ")", ";", "// creates the chunks dir", "if", "(", "!", "file_exists", "(", "$", "path", ")", ")", "{", "mkdir", "(", ...
Crates the chunks folder if doesn't exists. Uses recursive create.
[ "Crates", "the", "chunks", "folder", "if", "doesn", "t", "exists", ".", "Uses", "recursive", "create", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Save/ChunkSave.php#L255-L263
pionl/laravel-chunk-upload
src/Receiver/FileReceiver.php
FileReceiver.receive
public function receive() { if (false === is_object($this->handler)) { return false; } return $this->handler->startSaving($this->chunkStorage, $this->config); }
php
public function receive() { if (false === is_object($this->handler)) { return false; } return $this->handler->startSaving($this->chunkStorage, $this->config); }
[ "public", "function", "receive", "(", ")", "{", "if", "(", "false", "===", "is_object", "(", "$", "this", "->", "handler", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "handler", "->", "startSaving", "(", "$", "this", "->"...
Tries to handle the upload request. If the file is not uploaded, returns false. If the file is present in the request, it will create the save object. If the file in the request is chunk, it will create the `ChunkSave` object, otherwise creates the `SingleSave` which doesn't nothing at this moment. @return bool|AbstractSave
[ "Tries", "to", "handle", "the", "upload", "request", ".", "If", "the", "file", "is", "not", "uploaded", "returns", "false", ".", "If", "the", "file", "is", "present", "in", "the", "request", "it", "will", "create", "the", "save", "object", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Receiver/FileReceiver.php#L94-L101
pionl/laravel-chunk-upload
src/Storage/ChunkStorage.php
ChunkStorage.files
public function files($rejectClosure = null) { // we need to filter files we don't support, lets use the collection $filesCollection = new Collection($this->disk->files($this->directory(), false)); return $filesCollection->reject(function ($file) use ($rejectClosure) { // ensure the file ends with allowed extension $shouldReject = !preg_match('/.'.self::CHUNK_EXTENSION.'$/', $file); if ($shouldReject) { return true; } if (is_callable($rejectClosure)) { return $rejectClosure($file); } return false; }); }
php
public function files($rejectClosure = null) { // we need to filter files we don't support, lets use the collection $filesCollection = new Collection($this->disk->files($this->directory(), false)); return $filesCollection->reject(function ($file) use ($rejectClosure) { // ensure the file ends with allowed extension $shouldReject = !preg_match('/.'.self::CHUNK_EXTENSION.'$/', $file); if ($shouldReject) { return true; } if (is_callable($rejectClosure)) { return $rejectClosure($file); } return false; }); }
[ "public", "function", "files", "(", "$", "rejectClosure", "=", "null", ")", "{", "// we need to filter files we don't support, lets use the collection", "$", "filesCollection", "=", "new", "Collection", "(", "$", "this", "->", "disk", "->", "files", "(", "$", "this"...
Returns an array of files in the chunks directory. @param \Closure|null $rejectClosure @return Collection @see FilesystemAdapter::files() @see AbstractConfig::chunksStorageDirectory()
[ "Returns", "an", "array", "of", "files", "in", "the", "chunks", "directory", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Storage/ChunkStorage.php#L115-L132
pionl/laravel-chunk-upload
src/Storage/ChunkStorage.php
ChunkStorage.oldChunkFiles
public function oldChunkFiles() { $files = $this->files(); // if there are no files, lets return the empty collection if ($files->isEmpty()) { return $files; } // build the timestamp $timeToCheck = strtotime($this->config->clearTimestampString()); $collection = new Collection(); // filter the collection with files that are not correct chunk file // loop all current files and filter them by the time $files->each(function ($file) use ($timeToCheck, $collection) { // get the last modified time to check if the chunk is not new $modified = $this->disk()->lastModified($file); // delete only old chunk if ($modified < $timeToCheck) { $collection->push(new ChunkFile($file, $modified, $this)); } }); return $collection; }
php
public function oldChunkFiles() { $files = $this->files(); // if there are no files, lets return the empty collection if ($files->isEmpty()) { return $files; } // build the timestamp $timeToCheck = strtotime($this->config->clearTimestampString()); $collection = new Collection(); // filter the collection with files that are not correct chunk file // loop all current files and filter them by the time $files->each(function ($file) use ($timeToCheck, $collection) { // get the last modified time to check if the chunk is not new $modified = $this->disk()->lastModified($file); // delete only old chunk if ($modified < $timeToCheck) { $collection->push(new ChunkFile($file, $modified, $this)); } }); return $collection; }
[ "public", "function", "oldChunkFiles", "(", ")", "{", "$", "files", "=", "$", "this", "->", "files", "(", ")", ";", "// if there are no files, lets return the empty collection", "if", "(", "$", "files", "->", "isEmpty", "(", ")", ")", "{", "return", "$", "fi...
Returns the old chunk files. @return Collection<ChunkFile> collection of a ChunkFile objects
[ "Returns", "the", "old", "chunk", "files", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Storage/ChunkStorage.php#L139-L164
pionl/laravel-chunk-upload
src/Commands/ClearChunksCommand.php
ClearChunksCommand.handle
public function handle(ChunkStorage $storage) { $verbouse = OutputInterface::VERBOSITY_VERBOSE; // try to get the old chunk files $oldFiles = $storage->oldChunkFiles(); if ($oldFiles->isEmpty()) { $this->warn('Chunks: no old files'); return; } $this->info(sprintf('Found %d chunk files', $oldFiles->count()), $verbouse); $deleted = 0; /** @var ChunkFile $file */ foreach ($oldFiles as $file) { // debug the file info $this->comment('> '.$file, $verbouse); // delete the file if ($file->delete()) { ++$deleted; } else { $this->error('> chunk not deleted: '.$file); } } $this->info('Chunks: cleared '.$deleted.' '.Str::plural('file', $deleted)); }
php
public function handle(ChunkStorage $storage) { $verbouse = OutputInterface::VERBOSITY_VERBOSE; // try to get the old chunk files $oldFiles = $storage->oldChunkFiles(); if ($oldFiles->isEmpty()) { $this->warn('Chunks: no old files'); return; } $this->info(sprintf('Found %d chunk files', $oldFiles->count()), $verbouse); $deleted = 0; /** @var ChunkFile $file */ foreach ($oldFiles as $file) { // debug the file info $this->comment('> '.$file, $verbouse); // delete the file if ($file->delete()) { ++$deleted; } else { $this->error('> chunk not deleted: '.$file); } } $this->info('Chunks: cleared '.$deleted.' '.Str::plural('file', $deleted)); }
[ "public", "function", "handle", "(", "ChunkStorage", "$", "storage", ")", "{", "$", "verbouse", "=", "OutputInterface", "::", "VERBOSITY_VERBOSE", ";", "// try to get the old chunk files", "$", "oldFiles", "=", "$", "storage", "->", "oldChunkFiles", "(", ")", ";",...
Clears the chunks upload directory. @param ChunkStorage $storage injected chunk storage
[ "Clears", "the", "chunks", "upload", "directory", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Commands/ClearChunksCommand.php#L32-L62
pionl/laravel-chunk-upload
src/Handler/AbstractHandler.php
AbstractHandler.canUseSession
public static function canUseSession() { // Get the session driver and check if it was started - fully inited by laravel $session = session(); $driver = $session->getDefaultDriver(); $drivers = $session->getDrivers(); // Check if the driver is valid and started - allow using session if (isset($drivers[$driver]) && true === $drivers[$driver]->isStarted()) { return true; } return false; }
php
public static function canUseSession() { // Get the session driver and check if it was started - fully inited by laravel $session = session(); $driver = $session->getDefaultDriver(); $drivers = $session->getDrivers(); // Check if the driver is valid and started - allow using session if (isset($drivers[$driver]) && true === $drivers[$driver]->isStarted()) { return true; } return false; }
[ "public", "static", "function", "canUseSession", "(", ")", "{", "// Get the session driver and check if it was started - fully inited by laravel", "$", "session", "=", "session", "(", ")", ";", "$", "driver", "=", "$", "session", "->", "getDefaultDriver", "(", ")", ";...
Checks the current setup if session driver was booted - if not, it will generate random hash. @return bool
[ "Checks", "the", "current", "setup", "if", "session", "driver", "was", "booted", "-", "if", "not", "it", "will", "generate", "random", "hash", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Handler/AbstractHandler.php#L63-L76
pionl/laravel-chunk-upload
src/Handler/AbstractHandler.php
AbstractHandler.createChunkFileName
public function createChunkFileName($additionalName = null, $currentChunkIndex = null) { // prepare basic name structure $array = [ $this->file->getClientOriginalName(), ]; // ensure that the chunk name is for unique for the client session $useSession = $this->config->chunkUseSessionForName(); $useBrowser = $this->config->chunkUseBrowserInfoForName(); if ($useSession && false === static::canUseSession()) { $useBrowser = true; $useSession = false; } // the session needs more config on the provider if ($useSession) { $array[] = Session::getId(); } // can work without any additional setup if ($useBrowser) { $array[] = md5($this->request->ip().$this->request->header('User-Agent', 'no-browser')); } // Add additional name for more unique chunk name if (!is_null($additionalName)) { $array[] = $additionalName; } // Build the final name - parts separated by dot $namesSeparatedByDot = [ implode('-', $array), ]; // Add the chunk index for parallel upload if (null !== $currentChunkIndex) { $namesSeparatedByDot[] = $currentChunkIndex; } // Add extension $namesSeparatedByDot[] = ChunkStorage::CHUNK_EXTENSION; // build name return implode('.', $namesSeparatedByDot); }
php
public function createChunkFileName($additionalName = null, $currentChunkIndex = null) { // prepare basic name structure $array = [ $this->file->getClientOriginalName(), ]; // ensure that the chunk name is for unique for the client session $useSession = $this->config->chunkUseSessionForName(); $useBrowser = $this->config->chunkUseBrowserInfoForName(); if ($useSession && false === static::canUseSession()) { $useBrowser = true; $useSession = false; } // the session needs more config on the provider if ($useSession) { $array[] = Session::getId(); } // can work without any additional setup if ($useBrowser) { $array[] = md5($this->request->ip().$this->request->header('User-Agent', 'no-browser')); } // Add additional name for more unique chunk name if (!is_null($additionalName)) { $array[] = $additionalName; } // Build the final name - parts separated by dot $namesSeparatedByDot = [ implode('-', $array), ]; // Add the chunk index for parallel upload if (null !== $currentChunkIndex) { $namesSeparatedByDot[] = $currentChunkIndex; } // Add extension $namesSeparatedByDot[] = ChunkStorage::CHUNK_EXTENSION; // build name return implode('.', $namesSeparatedByDot); }
[ "public", "function", "createChunkFileName", "(", "$", "additionalName", "=", "null", ",", "$", "currentChunkIndex", "=", "null", ")", "{", "// prepare basic name structure", "$", "array", "=", "[", "$", "this", "->", "file", "->", "getClientOriginalName", "(", ...
Builds the chunk file name per session and the original name. You can provide custom additional name at the end of the generated file name. All chunk files has .part extension. @param string|null $additionalName Make the name more unique (example: use id from request) @param string|null $currentChunkIndex Add the chunk index for parallel upload @return string @see UploadedFile::getClientOriginalName() @see Session::getId()
[ "Builds", "the", "chunk", "file", "name", "per", "session", "and", "the", "original", "name", ".", "You", "can", "provide", "custom", "additional", "name", "at", "the", "end", "of", "the", "generated", "file", "name", ".", "All", "chunk", "files", "has", ...
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Handler/AbstractHandler.php#L91-L136
pionl/laravel-chunk-upload
src/Handler/ContentRangeUploadHandler.php
ContentRangeUploadHandler.tryToParseContentRange
protected function tryToParseContentRange($contentRange) { // try to get the content range if (preg_match("/bytes ([\d]+)-([\d]+)\/([\d]+)/", $contentRange, $matches)) { $this->chunkedUpload = true; // write the bytes values $this->bytesStart = $this->convertToNumericValue($matches[1]); $this->bytesEnd = $this->convertToNumericValue($matches[2]); $this->bytesTotal = $this->convertToNumericValue($matches[3]); } }
php
protected function tryToParseContentRange($contentRange) { // try to get the content range if (preg_match("/bytes ([\d]+)-([\d]+)\/([\d]+)/", $contentRange, $matches)) { $this->chunkedUpload = true; // write the bytes values $this->bytesStart = $this->convertToNumericValue($matches[1]); $this->bytesEnd = $this->convertToNumericValue($matches[2]); $this->bytesTotal = $this->convertToNumericValue($matches[3]); } }
[ "protected", "function", "tryToParseContentRange", "(", "$", "contentRange", ")", "{", "// try to get the content range", "if", "(", "preg_match", "(", "\"/bytes ([\\d]+)-([\\d]+)\\/([\\d]+)/\"", ",", "$", "contentRange", ",", "$", "matches", ")", ")", "{", "$", "this...
Tries to parse the content range from the string. @param string $contentRange @throws ContentRangeValueToLargeException
[ "Tries", "to", "parse", "the", "content", "range", "from", "the", "string", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Handler/ContentRangeUploadHandler.php#L110-L121
pionl/laravel-chunk-upload
src/FileMerger.php
FileMerger.appendFile
public function appendFile($sourceFilePath) { // open the new uploaded chunk if (!$in = @fopen($sourceFilePath, 'rb')) { @fclose($this->destinationFile); throw new ChunkSaveException('Failed to open input stream', 101); } // read and write in buffs while ($buff = fread($in, 4096)) { fwrite($this->destinationFile, $buff); } @fclose($in); return $this; }
php
public function appendFile($sourceFilePath) { // open the new uploaded chunk if (!$in = @fopen($sourceFilePath, 'rb')) { @fclose($this->destinationFile); throw new ChunkSaveException('Failed to open input stream', 101); } // read and write in buffs while ($buff = fread($in, 4096)) { fwrite($this->destinationFile, $buff); } @fclose($in); return $this; }
[ "public", "function", "appendFile", "(", "$", "sourceFilePath", ")", "{", "// open the new uploaded chunk", "if", "(", "!", "$", "in", "=", "@", "fopen", "(", "$", "sourceFilePath", ",", "'rb'", ")", ")", "{", "@", "fclose", "(", "$", "this", "->", "dest...
Appends given file. @param string $sourceFilePath @return $this @throws ChunkSaveException
[ "Appends", "given", "file", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/FileMerger.php#L38-L54
pionl/laravel-chunk-upload
src/Handler/DropZoneUploadHandler.php
DropZoneUploadHandler.canBeUsedForRequest
public static function canBeUsedForRequest(Request $request) { return $request->has(self::CHUNK_UUID_INDEX) && $request->has(self::CHUNK_TOTAL_INDEX) && $request->has(self::CHUNK_INDEX); }
php
public static function canBeUsedForRequest(Request $request) { return $request->has(self::CHUNK_UUID_INDEX) && $request->has(self::CHUNK_TOTAL_INDEX) && $request->has(self::CHUNK_INDEX); }
[ "public", "static", "function", "canBeUsedForRequest", "(", "Request", "$", "request", ")", "{", "return", "$", "request", "->", "has", "(", "self", "::", "CHUNK_UUID_INDEX", ")", "&&", "$", "request", "->", "has", "(", "self", "::", "CHUNK_TOTAL_INDEX", ")"...
Checks if the current abstract handler can be used via HandlerFactory. @param Request $request @return bool
[ "Checks", "if", "the", "current", "abstract", "handler", "can", "be", "used", "via", "HandlerFactory", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Handler/DropZoneUploadHandler.php#L82-L86
pionl/laravel-chunk-upload
src/Save/ParallelSave.php
ParallelSave.handleChunkFile
protected function handleChunkFile($file) { // Move the uploaded file to chunk folder $this->file->move($this->getChunkDirectory(true), $this->chunkFileName); return $this; }
php
protected function handleChunkFile($file) { // Move the uploaded file to chunk folder $this->file->move($this->getChunkDirectory(true), $this->chunkFileName); return $this; }
[ "protected", "function", "handleChunkFile", "(", "$", "file", ")", "{", "// Move the uploaded file to chunk folder", "$", "this", "->", "file", "->", "move", "(", "$", "this", "->", "getChunkDirectory", "(", "true", ")", ",", "$", "this", "->", "chunkFileName", ...
Moves the uploaded chunk file to separate chunk file for merging. @param string $file Relative path to chunk @return $this
[ "Moves", "the", "uploaded", "chunk", "file", "to", "separate", "chunk", "file", "for", "merging", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Save/ParallelSave.php#L65-L71
pionl/laravel-chunk-upload
src/Save/ParallelSave.php
ParallelSave.getSavedChunksFiles
protected function getSavedChunksFiles() { $chunkFileName = preg_replace( "/\.[\d]+\.".ChunkStorage::CHUNK_EXTENSION.'$/', '', $this->handler()->getChunkFileName() ); return $this->chunkStorage->files(function ($file) use ($chunkFileName) { return false === str_contains($file, $chunkFileName); }); }
php
protected function getSavedChunksFiles() { $chunkFileName = preg_replace( "/\.[\d]+\.".ChunkStorage::CHUNK_EXTENSION.'$/', '', $this->handler()->getChunkFileName() ); return $this->chunkStorage->files(function ($file) use ($chunkFileName) { return false === str_contains($file, $chunkFileName); }); }
[ "protected", "function", "getSavedChunksFiles", "(", ")", "{", "$", "chunkFileName", "=", "preg_replace", "(", "\"/\\.[\\d]+\\.\"", ".", "ChunkStorage", "::", "CHUNK_EXTENSION", ".", "'$/'", ",", "''", ",", "$", "this", "->", "handler", "(", ")", "->", "getChu...
Searches for all chunk files. @return \Illuminate\Support\Collection
[ "Searches", "for", "all", "chunk", "files", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Save/ParallelSave.php#L83-L92
pionl/laravel-chunk-upload
src/Providers/ChunkUploadServiceProvider.php
ChunkUploadServiceProvider.boot
public function boot() { // Get the schedule config $config = $this->app->make(AbstractConfig::class); $scheduleConfig = $config->scheduleConfig(); // Run only if schedule is enabled if (true === Arr::get($scheduleConfig, 'enabled', false)) { // Wait until the app is fully booted $this->app->booted(function () use ($scheduleConfig) { // Get the scheduler instance /** @var Schedule $schedule */ $schedule = $this->app->make(Schedule::class); // Register the clear chunks with custom schedule $schedule->command('uploads:clear') ->cron(Arr::get($scheduleConfig, 'cron', '* * * * *')); }); } $this->registerHandlers($config->handlers()); }
php
public function boot() { // Get the schedule config $config = $this->app->make(AbstractConfig::class); $scheduleConfig = $config->scheduleConfig(); // Run only if schedule is enabled if (true === Arr::get($scheduleConfig, 'enabled', false)) { // Wait until the app is fully booted $this->app->booted(function () use ($scheduleConfig) { // Get the scheduler instance /** @var Schedule $schedule */ $schedule = $this->app->make(Schedule::class); // Register the clear chunks with custom schedule $schedule->command('uploads:clear') ->cron(Arr::get($scheduleConfig, 'cron', '* * * * *')); }); } $this->registerHandlers($config->handlers()); }
[ "public", "function", "boot", "(", ")", "{", "// Get the schedule config", "$", "config", "=", "$", "this", "->", "app", "->", "make", "(", "AbstractConfig", "::", "class", ")", ";", "$", "scheduleConfig", "=", "$", "config", "->", "scheduleConfig", "(", "...
When the service is being booted.
[ "When", "the", "service", "is", "being", "booted", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Providers/ChunkUploadServiceProvider.php#L22-L43
pionl/laravel-chunk-upload
src/Providers/ChunkUploadServiceProvider.php
ChunkUploadServiceProvider.register
public function register() { // Register the commands $this->commands([ ClearChunksCommand::class, ]); // Register the config $this->registerConfig(); // Register the config via abstract instance $this->app->singleton(AbstractConfig::class, function () { return new FileConfig(); }); // Register the config via abstract instance $this->app->singleton(ChunkStorage::class, function ($app) { /** @var AbstractConfig $config */ $config = $app->make(AbstractConfig::class); // Build the chunk storage return new ChunkStorage($this->disk($config->chunksDiskName()), $config); }); /* * Bind a FileReceiver for dependency and use only the first object */ $this->app->bind(FileReceiver::class, function ($app) { /** @var Request $request */ $request = $app->make('request'); // Get the first file object - must be converted instances of UploadedFile $file = array_first($request->allFiles()); // Build the file receiver return new FileReceiver($file, $request, HandlerFactory::classFromRequest($request)); }); }
php
public function register() { // Register the commands $this->commands([ ClearChunksCommand::class, ]); // Register the config $this->registerConfig(); // Register the config via abstract instance $this->app->singleton(AbstractConfig::class, function () { return new FileConfig(); }); // Register the config via abstract instance $this->app->singleton(ChunkStorage::class, function ($app) { /** @var AbstractConfig $config */ $config = $app->make(AbstractConfig::class); // Build the chunk storage return new ChunkStorage($this->disk($config->chunksDiskName()), $config); }); /* * Bind a FileReceiver for dependency and use only the first object */ $this->app->bind(FileReceiver::class, function ($app) { /** @var Request $request */ $request = $app->make('request'); // Get the first file object - must be converted instances of UploadedFile $file = array_first($request->allFiles()); // Build the file receiver return new FileReceiver($file, $request, HandlerFactory::classFromRequest($request)); }); }
[ "public", "function", "register", "(", ")", "{", "// Register the commands", "$", "this", "->", "commands", "(", "[", "ClearChunksCommand", "::", "class", ",", "]", ")", ";", "// Register the config", "$", "this", "->", "registerConfig", "(", ")", ";", "// Reg...
Register the package requirements. @see ChunkUploadServiceProvider::registerConfig()
[ "Register", "the", "package", "requirements", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Providers/ChunkUploadServiceProvider.php#L50-L87
pionl/laravel-chunk-upload
src/Providers/ChunkUploadServiceProvider.php
ChunkUploadServiceProvider.registerConfig
protected function registerConfig() { // Config options $configIndex = FileConfig::FILE_NAME; $configFileName = FileConfig::FILE_NAME.'.php'; $configPath = __DIR__.'/../../config/'.$configFileName; // Publish the config $this->publishes([ $configPath => config_path($configFileName), ]); // Merge the default config to prevent any crash or unfilled configs $this->mergeConfigFrom( $configPath, $configIndex ); return $this; }
php
protected function registerConfig() { // Config options $configIndex = FileConfig::FILE_NAME; $configFileName = FileConfig::FILE_NAME.'.php'; $configPath = __DIR__.'/../../config/'.$configFileName; // Publish the config $this->publishes([ $configPath => config_path($configFileName), ]); // Merge the default config to prevent any crash or unfilled configs $this->mergeConfigFrom( $configPath, $configIndex ); return $this; }
[ "protected", "function", "registerConfig", "(", ")", "{", "// Config options", "$", "configIndex", "=", "FileConfig", "::", "FILE_NAME", ";", "$", "configFileName", "=", "FileConfig", "::", "FILE_NAME", ".", "'.php'", ";", "$", "configPath", "=", "__DIR__", ".",...
Publishes and mergers the config. Uses the FileConfig. Registers custom handlers. @see FileConfig @see ServiceProvider::publishes @see ServiceProvider::mergeConfigFrom @return $this
[ "Publishes", "and", "mergers", "the", "config", ".", "Uses", "the", "FileConfig", ".", "Registers", "custom", "handlers", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Providers/ChunkUploadServiceProvider.php#L110-L129
pionl/laravel-chunk-upload
src/Providers/ChunkUploadServiceProvider.php
ChunkUploadServiceProvider.registerHandlers
protected function registerHandlers(array $handlersConfig) { $overrideHandlers = Arr::get($handlersConfig, 'override', []); if (count($overrideHandlers) > 0) { HandlerFactory::setHandlers($overrideHandlers); return $this; } foreach (Arr::get($handlersConfig, 'custom', []) as $handler) { HandlerFactory::register($handler); } return $this; }
php
protected function registerHandlers(array $handlersConfig) { $overrideHandlers = Arr::get($handlersConfig, 'override', []); if (count($overrideHandlers) > 0) { HandlerFactory::setHandlers($overrideHandlers); return $this; } foreach (Arr::get($handlersConfig, 'custom', []) as $handler) { HandlerFactory::register($handler); } return $this; }
[ "protected", "function", "registerHandlers", "(", "array", "$", "handlersConfig", ")", "{", "$", "overrideHandlers", "=", "Arr", "::", "get", "(", "$", "handlersConfig", ",", "'override'", ",", "[", "]", ")", ";", "if", "(", "count", "(", "$", "overrideHan...
Registers handlers from config. @param array $handlersConfig @return $this
[ "Registers", "handlers", "from", "config", "." ]
train
https://github.com/pionl/laravel-chunk-upload/blob/1f1da75ae16a70f6fb53bdd61be4f544642f7b5e/src/Providers/ChunkUploadServiceProvider.php#L138-L152
paragonie/EasyRSA
src/PrivateKey.php
PrivateKey.getPublicKey
public function getPublicKey() { $res = \openssl_pkey_get_private($this->keyMaterial); $pubkey = \openssl_pkey_get_details($res); $public = \rtrim( \str_replace("\n", "\r\n", $pubkey['key']), "\r\n" ); return new PublicKey($public); }
php
public function getPublicKey() { $res = \openssl_pkey_get_private($this->keyMaterial); $pubkey = \openssl_pkey_get_details($res); $public = \rtrim( \str_replace("\n", "\r\n", $pubkey['key']), "\r\n" ); return new PublicKey($public); }
[ "public", "function", "getPublicKey", "(", ")", "{", "$", "res", "=", "\\", "openssl_pkey_get_private", "(", "$", "this", "->", "keyMaterial", ")", ";", "$", "pubkey", "=", "\\", "openssl_pkey_get_details", "(", "$", "res", ")", ";", "$", "public", "=", ...
return PublicKey
[ "return", "PublicKey" ]
train
https://github.com/paragonie/EasyRSA/blob/d4f3ca9896ced5d9ef03ec783dc4ca5c0c3c5980/src/PrivateKey.php#L29-L38
paragonie/EasyRSA
src/EasyRSA.php
EasyRSA.getRsa
public static function getRsa($mode) { if (self::$rsa) { $rsa = self::$rsa; } else { $rsa = new RSA(); $rsa->setMGFHash('sha256'); } $rsa->setSignatureMode($mode); return $rsa; }
php
public static function getRsa($mode) { if (self::$rsa) { $rsa = self::$rsa; } else { $rsa = new RSA(); $rsa->setMGFHash('sha256'); } $rsa->setSignatureMode($mode); return $rsa; }
[ "public", "static", "function", "getRsa", "(", "$", "mode", ")", "{", "if", "(", "self", "::", "$", "rsa", ")", "{", "$", "rsa", "=", "self", "::", "$", "rsa", ";", "}", "else", "{", "$", "rsa", "=", "new", "RSA", "(", ")", ";", "$", "rsa", ...
Get RSA @param int $mode @return RSA
[ "Get", "RSA" ]
train
https://github.com/paragonie/EasyRSA/blob/d4f3ca9896ced5d9ef03ec783dc4ca5c0c3c5980/src/EasyRSA.php#L39-L51
paragonie/EasyRSA
src/EasyRSA.php
EasyRSA.encrypt
public static function encrypt($plaintext, PublicKey $rsaPublicKey) { // Random encryption key $random_key = random_bytes(32); // Use RSA to encrypt the random key $rsaOut = self::rsaEncrypt($random_key, $rsaPublicKey); // Generate a symmetric key from the RSA output and plaintext $symmetricKey = hash_hmac( 'sha256', $rsaOut, $random_key, true ); $ephemeral = self::defuseKey( $symmetricKey ); // Now we encrypt the actual message $symmetric = Base64::encode( Crypto::encrypt($plaintext, $ephemeral, true) ); $packaged = \implode(self::SEPARATOR, array( self::VERSION_TAG, Base64::encode($rsaOut), $symmetric ) ); $checksum = \substr( \hash('sha256', $packaged), 0, 16 ); // Return the ciphertext return $packaged . self::SEPARATOR . $checksum; }
php
public static function encrypt($plaintext, PublicKey $rsaPublicKey) { // Random encryption key $random_key = random_bytes(32); // Use RSA to encrypt the random key $rsaOut = self::rsaEncrypt($random_key, $rsaPublicKey); // Generate a symmetric key from the RSA output and plaintext $symmetricKey = hash_hmac( 'sha256', $rsaOut, $random_key, true ); $ephemeral = self::defuseKey( $symmetricKey ); // Now we encrypt the actual message $symmetric = Base64::encode( Crypto::encrypt($plaintext, $ephemeral, true) ); $packaged = \implode(self::SEPARATOR, array( self::VERSION_TAG, Base64::encode($rsaOut), $symmetric ) ); $checksum = \substr( \hash('sha256', $packaged), 0, 16 ); // Return the ciphertext return $packaged . self::SEPARATOR . $checksum; }
[ "public", "static", "function", "encrypt", "(", "$", "plaintext", ",", "PublicKey", "$", "rsaPublicKey", ")", "{", "// Random encryption key", "$", "random_key", "=", "random_bytes", "(", "32", ")", ";", "// Use RSA to encrypt the random key", "$", "rsaOut", "=", ...
KEM+DEM approach to RSA encryption. @param string $plaintext @param PublicKey $rsaPublicKey @return string
[ "KEM", "+", "DEM", "approach", "to", "RSA", "encryption", "." ]
train
https://github.com/paragonie/EasyRSA/blob/d4f3ca9896ced5d9ef03ec783dc4ca5c0c3c5980/src/EasyRSA.php#L61-L101
paragonie/EasyRSA
src/EasyRSA.php
EasyRSA.decrypt
public static function decrypt($ciphertext, PrivateKey $rsaPrivateKey) { $split = explode(self::SEPARATOR, $ciphertext); if (\count($split) !== 4) { throw new InvalidCiphertextException('Invalid ciphertext message'); } if (!\hash_equals($split[0], self::VERSION_TAG)) { throw new InvalidCiphertextException('Invalid version tag'); } $checksum = \substr( \hash('sha256', implode('$', array_slice($split, 0, 3))), 0, 16 ); if (!\hash_equals($split[3], $checksum)) { throw new InvalidChecksumException('Invalid checksum'); } $rsaCipher = Base64::decode($split[1]); $rsaPlain = self::rsaDecrypt( $rsaCipher, $rsaPrivateKey ); $symmetricKey = hash_hmac( 'sha256', $rsaCipher, $rsaPlain, true ); $key = self::defuseKey($symmetricKey); return Crypto::decrypt( Base64::decode($split[2]), $key, true ); }
php
public static function decrypt($ciphertext, PrivateKey $rsaPrivateKey) { $split = explode(self::SEPARATOR, $ciphertext); if (\count($split) !== 4) { throw new InvalidCiphertextException('Invalid ciphertext message'); } if (!\hash_equals($split[0], self::VERSION_TAG)) { throw new InvalidCiphertextException('Invalid version tag'); } $checksum = \substr( \hash('sha256', implode('$', array_slice($split, 0, 3))), 0, 16 ); if (!\hash_equals($split[3], $checksum)) { throw new InvalidChecksumException('Invalid checksum'); } $rsaCipher = Base64::decode($split[1]); $rsaPlain = self::rsaDecrypt( $rsaCipher, $rsaPrivateKey ); $symmetricKey = hash_hmac( 'sha256', $rsaCipher, $rsaPlain, true ); $key = self::defuseKey($symmetricKey); return Crypto::decrypt( Base64::decode($split[2]), $key, true ); }
[ "public", "static", "function", "decrypt", "(", "$", "ciphertext", ",", "PrivateKey", "$", "rsaPrivateKey", ")", "{", "$", "split", "=", "explode", "(", "self", "::", "SEPARATOR", ",", "$", "ciphertext", ")", ";", "if", "(", "\\", "count", "(", "$", "s...
KEM+DEM approach to RSA encryption. @param string $ciphertext @param PrivateKey $rsaPrivateKey @return string @throws InvalidCiphertextException @throws InvalidChecksumException
[ "KEM", "+", "DEM", "approach", "to", "RSA", "encryption", "." ]
train
https://github.com/paragonie/EasyRSA/blob/d4f3ca9896ced5d9ef03ec783dc4ca5c0c3c5980/src/EasyRSA.php#L113-L149
paragonie/EasyRSA
src/EasyRSA.php
EasyRSA.sign
public static function sign($message, PrivateKey $rsaPrivateKey) { $rsa = self::getRsa(RSA::SIGNATURE_PSS); $return = $rsa->loadKey($rsaPrivateKey->getKey()); if ($return === false) { throw new InvalidKeyException('Signing failed due to invalid key'); } return $rsa->sign($message); }
php
public static function sign($message, PrivateKey $rsaPrivateKey) { $rsa = self::getRsa(RSA::SIGNATURE_PSS); $return = $rsa->loadKey($rsaPrivateKey->getKey()); if ($return === false) { throw new InvalidKeyException('Signing failed due to invalid key'); } return $rsa->sign($message); }
[ "public", "static", "function", "sign", "(", "$", "message", ",", "PrivateKey", "$", "rsaPrivateKey", ")", "{", "$", "rsa", "=", "self", "::", "getRsa", "(", "RSA", "::", "SIGNATURE_PSS", ")", ";", "$", "return", "=", "$", "rsa", "->", "loadKey", "(", ...
Sign with RSASS-PSS + MGF1+SHA256 @param string $message @param PrivateKey $rsaPrivateKey @return string
[ "Sign", "with", "RSASS", "-", "PSS", "+", "MGF1", "+", "SHA256" ]
train
https://github.com/paragonie/EasyRSA/blob/d4f3ca9896ced5d9ef03ec783dc4ca5c0c3c5980/src/EasyRSA.php#L158-L168
paragonie/EasyRSA
src/EasyRSA.php
EasyRSA.verify
public static function verify($message, $signature, PublicKey $rsaPublicKey) { $rsa = self::getRsa(RSA::SIGNATURE_PSS); $return = $rsa->loadKey($rsaPublicKey->getKey()); if ($return === false) { throw new InvalidKeyException('Verification failed due to invalid key'); } return $rsa->verify($message, $signature); }
php
public static function verify($message, $signature, PublicKey $rsaPublicKey) { $rsa = self::getRsa(RSA::SIGNATURE_PSS); $return = $rsa->loadKey($rsaPublicKey->getKey()); if ($return === false) { throw new InvalidKeyException('Verification failed due to invalid key'); } return $rsa->verify($message, $signature); }
[ "public", "static", "function", "verify", "(", "$", "message", ",", "$", "signature", ",", "PublicKey", "$", "rsaPublicKey", ")", "{", "$", "rsa", "=", "self", "::", "getRsa", "(", "RSA", "::", "SIGNATURE_PSS", ")", ";", "$", "return", "=", "$", "rsa",...
Verify with RSASS-PSS + MGF1+SHA256 @param string $message @param string $signature @param PublicKey $rsaPublicKey @return bool
[ "Verify", "with", "RSASS", "-", "PSS", "+", "MGF1", "+", "SHA256" ]
train
https://github.com/paragonie/EasyRSA/blob/d4f3ca9896ced5d9ef03ec783dc4ca5c0c3c5980/src/EasyRSA.php#L178-L188
paragonie/EasyRSA
src/EasyRSA.php
EasyRSA.rsaEncrypt
protected static function rsaEncrypt($plaintext, PublicKey $rsaPublicKey) { $rsa = self::getRsa(RSA::ENCRYPTION_OAEP); $return = $rsa->loadKey($rsaPublicKey->getKey()); if ($return === false) { throw new InvalidKeyException('Ecryption failed due to invalid key'); } return $rsa->encrypt($plaintext); }
php
protected static function rsaEncrypt($plaintext, PublicKey $rsaPublicKey) { $rsa = self::getRsa(RSA::ENCRYPTION_OAEP); $return = $rsa->loadKey($rsaPublicKey->getKey()); if ($return === false) { throw new InvalidKeyException('Ecryption failed due to invalid key'); } return $rsa->encrypt($plaintext); }
[ "protected", "static", "function", "rsaEncrypt", "(", "$", "plaintext", ",", "PublicKey", "$", "rsaPublicKey", ")", "{", "$", "rsa", "=", "self", "::", "getRsa", "(", "RSA", "::", "ENCRYPTION_OAEP", ")", ";", "$", "return", "=", "$", "rsa", "->", "loadKe...
Decrypt with RSAES-OAEP + MGF1+SHA256 @param string $plaintext @param PublicKey $rsaPublicKey @return string @throws InvalidCiphertextException
[ "Decrypt", "with", "RSAES", "-", "OAEP", "+", "MGF1", "+", "SHA256" ]
train
https://github.com/paragonie/EasyRSA/blob/d4f3ca9896ced5d9ef03ec783dc4ca5c0c3c5980/src/EasyRSA.php#L198-L208
paragonie/EasyRSA
src/EasyRSA.php
EasyRSA.rsaDecrypt
protected static function rsaDecrypt($ciphertext, PrivateKey $rsaPrivateKey) { $rsa = self::getRsa(RSA::ENCRYPTION_OAEP); $return = $rsa->loadKey($rsaPrivateKey->getKey()); if ($return === false) { throw new InvalidKeyException('Decryption failed due to invalid key'); } $return = @$rsa->decrypt($ciphertext); if ($return === false) { throw new InvalidCiphertextException('Decryption failed'); } return $return; }
php
protected static function rsaDecrypt($ciphertext, PrivateKey $rsaPrivateKey) { $rsa = self::getRsa(RSA::ENCRYPTION_OAEP); $return = $rsa->loadKey($rsaPrivateKey->getKey()); if ($return === false) { throw new InvalidKeyException('Decryption failed due to invalid key'); } $return = @$rsa->decrypt($ciphertext); if ($return === false) { throw new InvalidCiphertextException('Decryption failed'); } return $return; }
[ "protected", "static", "function", "rsaDecrypt", "(", "$", "ciphertext", ",", "PrivateKey", "$", "rsaPrivateKey", ")", "{", "$", "rsa", "=", "self", "::", "getRsa", "(", "RSA", "::", "ENCRYPTION_OAEP", ")", ";", "$", "return", "=", "$", "rsa", "->", "loa...
Decrypt with RSAES-OAEP + MGF1+SHA256 @param string $ciphertext @param PrivateKey $rsaPrivateKey @return string @throws InvalidCiphertextException
[ "Decrypt", "with", "RSAES", "-", "OAEP", "+", "MGF1", "+", "SHA256" ]
train
https://github.com/paragonie/EasyRSA/blob/d4f3ca9896ced5d9ef03ec783dc4ca5c0c3c5980/src/EasyRSA.php#L218-L232
paragonie/EasyRSA
src/KeyPair.php
KeyPair.generateKeyPair
public static function generateKeyPair($size = 2048) { if ($size < 2048) { throw new InvalidKeyException('Key size must be at least 2048 bits.'); } $rsa = new RSA(); $keypair = $rsa->createKey($size); return new KeyPair( new PrivateKey($keypair['privatekey']), new PublicKey($keypair['publickey']) ); }
php
public static function generateKeyPair($size = 2048) { if ($size < 2048) { throw new InvalidKeyException('Key size must be at least 2048 bits.'); } $rsa = new RSA(); $keypair = $rsa->createKey($size); return new KeyPair( new PrivateKey($keypair['privatekey']), new PublicKey($keypair['publickey']) ); }
[ "public", "static", "function", "generateKeyPair", "(", "$", "size", "=", "2048", ")", "{", "if", "(", "$", "size", "<", "2048", ")", "{", "throw", "new", "InvalidKeyException", "(", "'Key size must be at least 2048 bits.'", ")", ";", "}", "$", "rsa", "=", ...
Generate a private/public RSA key pair @param int $size Key size @param string $passphrase Optional - password-protected private key @return self @throws InvalidKeyException
[ "Generate", "a", "private", "/", "public", "RSA", "key", "pair" ]
train
https://github.com/paragonie/EasyRSA/blob/d4f3ca9896ced5d9ef03ec783dc4ca5c0c3c5980/src/KeyPair.php#L30-L41
paragonie/EasyRSA
src/Kludge.php
Kludge.defuseKey
public function defuseKey($randomBytes) { $key = Key::createNewRandomKey(); $func = function ($bytes) { $this->key_bytes = $bytes; }; $helper = $func->bindTo($key, $key); $helper($randomBytes); return $key; }
php
public function defuseKey($randomBytes) { $key = Key::createNewRandomKey(); $func = function ($bytes) { $this->key_bytes = $bytes; }; $helper = $func->bindTo($key, $key); $helper($randomBytes); return $key; }
[ "public", "function", "defuseKey", "(", "$", "randomBytes", ")", "{", "$", "key", "=", "Key", "::", "createNewRandomKey", "(", ")", ";", "$", "func", "=", "function", "(", "$", "bytes", ")", "{", "$", "this", "->", "key_bytes", "=", "$", "bytes", ";"...
Use an internally generated key in a Defuse context @param string $randomBytes @return Key
[ "Use", "an", "internally", "generated", "key", "in", "a", "Defuse", "context" ]
train
https://github.com/paragonie/EasyRSA/blob/d4f3ca9896ced5d9ef03ec783dc4ca5c0c3c5980/src/Kludge.php#L14-L23
morrislaptop/firestore-php
src/CollectionReference.php
CollectionReference.document
public function document(string $path): DocumentReference { $childPath = sprintf('%s/%s', trim($this->uri->getPath(), '/'), trim($path, '/')); try { return new DocumentReference($this->uri->withPath($childPath), $this->apiClient, $this->valueMapper); } catch (\InvalidArgumentException $e) { throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); } }
php
public function document(string $path): DocumentReference { $childPath = sprintf('%s/%s', trim($this->uri->getPath(), '/'), trim($path, '/')); try { return new DocumentReference($this->uri->withPath($childPath), $this->apiClient, $this->valueMapper); } catch (\InvalidArgumentException $e) { throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); } }
[ "public", "function", "document", "(", "string", "$", "path", ")", ":", "DocumentReference", "{", "$", "childPath", "=", "sprintf", "(", "'%s/%s'", ",", "trim", "(", "$", "this", "->", "uri", "->", "getPath", "(", ")", ",", "'/'", ")", ",", "trim", "...
Gets a Reference for the location at the specified relative path. The relative path can either be a simple child name (for example, "ada") or a deeper slash-separated path (for example, "ada/name/first"). @see https://firebase.google.com/docs/reference/js/firebase.database.Reference#child @param string $path @throws InvalidArgumentException if the path is invalid @return Reference
[ "Gets", "a", "Reference", "for", "the", "location", "at", "the", "specified", "relative", "path", "." ]
train
https://github.com/morrislaptop/firestore-php/blob/18c30a99b02d847aa84cd77a0acb03cbf5fc0213/src/CollectionReference.php#L65-L74
morrislaptop/firestore-php
src/ValueMapper.php
ValueMapper.escapeFieldPath
public function escapeFieldPath($fieldPath) { if ($fieldPath instanceof FieldPath) { $parts = $fieldPath->path(); $out = []; foreach ($parts as $part) { $out[] = $this->escapePathPart($part); } $fieldPath = implode('.', $out); } else { if (!preg_match(self::VALID_FIELD_PATH, $fieldPath)) { throw new \InvalidArgumentException('Paths cannot be empty and must not contain `*~/[]\`.'); } } $this->validateFieldPath($fieldPath); return $fieldPath; }
php
public function escapeFieldPath($fieldPath) { if ($fieldPath instanceof FieldPath) { $parts = $fieldPath->path(); $out = []; foreach ($parts as $part) { $out[] = $this->escapePathPart($part); } $fieldPath = implode('.', $out); } else { if (!preg_match(self::VALID_FIELD_PATH, $fieldPath)) { throw new \InvalidArgumentException('Paths cannot be empty and must not contain `*~/[]\`.'); } } $this->validateFieldPath($fieldPath); return $fieldPath; }
[ "public", "function", "escapeFieldPath", "(", "$", "fieldPath", ")", "{", "if", "(", "$", "fieldPath", "instanceof", "FieldPath", ")", "{", "$", "parts", "=", "$", "fieldPath", "->", "path", "(", ")", ";", "$", "out", "=", "[", "]", ";", "foreach", "...
Escape a field path and return it as a string. @param string|FieldPath $fieldPath @return string @throws \InvalidArgumentException If the path is a string, and is invalid.
[ "Escape", "a", "field", "path", "and", "return", "it", "as", "a", "string", "." ]
train
https://github.com/morrislaptop/firestore-php/blob/18c30a99b02d847aa84cd77a0acb03cbf5fc0213/src/ValueMapper.php#L113-L132
morrislaptop/firestore-php
src/ValueMapper.php
ValueMapper.encodeFieldPaths
public function encodeFieldPaths(array $fields, $parentPath = '') { $output = []; foreach ($fields as $key => $val) { $key = $this->escapePathPart($key); if (is_array($val) && $this->isAssoc($val)) { $nestedParentPath = $parentPath ? $parentPath . '.' . $key : $key; $output = array_merge($output, $this->encodeFieldPaths($val, $nestedParentPath)); } else { $output[] = $parentPath ? $parentPath . '.' . $key : $key; } } return $output; }
php
public function encodeFieldPaths(array $fields, $parentPath = '') { $output = []; foreach ($fields as $key => $val) { $key = $this->escapePathPart($key); if (is_array($val) && $this->isAssoc($val)) { $nestedParentPath = $parentPath ? $parentPath . '.' . $key : $key; $output = array_merge($output, $this->encodeFieldPaths($val, $nestedParentPath)); } else { $output[] = $parentPath ? $parentPath . '.' . $key : $key; } } return $output; }
[ "public", "function", "encodeFieldPaths", "(", "array", "$", "fields", ",", "$", "parentPath", "=", "''", ")", "{", "$", "output", "=", "[", "]", ";", "foreach", "(", "$", "fields", "as", "$", "key", "=>", "$", "val", ")", "{", "$", "key", "=", "...
Create a list of fields paths from field data. The return value of this method does not include the field values. It merely provides a list of field paths which were included in the input. @param array $fields A list of fields to map as paths. @param string $parentPath The parent path (used internally). @return array
[ "Create", "a", "list", "of", "fields", "paths", "from", "field", "data", "." ]
train
https://github.com/morrislaptop/firestore-php/blob/18c30a99b02d847aa84cd77a0acb03cbf5fc0213/src/ValueMapper.php#L144-L165
morrislaptop/firestore-php
src/ValueMapper.php
ValueMapper.buildDocumentFromPathsAndValues
public function buildDocumentFromPathsAndValues(array $paths, array $values) { $this->validateBatch($paths, FieldPath::class); $output = []; foreach ($paths as $pathIndex => $path) { $keys = $path->path(); $num = count($keys); $val = $values[$pathIndex]; foreach (array_reverse($keys) as $index => $key) { if ($num >= $index+1) { $val = [ $key => $val ]; } } $output = $this->arrayMergeRecursive($output, $val); } return $output; }
php
public function buildDocumentFromPathsAndValues(array $paths, array $values) { $this->validateBatch($paths, FieldPath::class); $output = []; foreach ($paths as $pathIndex => $path) { $keys = $path->path(); $num = count($keys); $val = $values[$pathIndex]; foreach (array_reverse($keys) as $index => $key) { if ($num >= $index+1) { $val = [ $key => $val ]; } } $output = $this->arrayMergeRecursive($output, $val); } return $output; }
[ "public", "function", "buildDocumentFromPathsAndValues", "(", "array", "$", "paths", ",", "array", "$", "values", ")", "{", "$", "this", "->", "validateBatch", "(", "$", "paths", ",", "FieldPath", "::", "class", ")", ";", "$", "output", "=", "[", "]", ";...
Accepts a list of field paths and a list of values, and constructs a nested array of fields and values. @param FieldPath[] $paths The field paths. @param array $values The field values. @return array @todo less recursion
[ "Accepts", "a", "list", "of", "field", "paths", "and", "a", "list", "of", "values", "and", "constructs", "a", "nested", "array", "of", "fields", "and", "values", "." ]
train
https://github.com/morrislaptop/firestore-php/blob/18c30a99b02d847aa84cd77a0acb03cbf5fc0213/src/ValueMapper.php#L176-L199
morrislaptop/firestore-php
src/ValueMapper.php
ValueMapper.findSentinels
public function findSentinels(array $fields) { $timestamps = []; $deletes = []; $fields = $this->removeSentinel($fields, $timestamps, $deletes); return [$fields, $timestamps, $deletes]; }
php
public function findSentinels(array $fields) { $timestamps = []; $deletes = []; $fields = $this->removeSentinel($fields, $timestamps, $deletes); return [$fields, $timestamps, $deletes]; }
[ "public", "function", "findSentinels", "(", "array", "$", "fields", ")", "{", "$", "timestamps", "=", "[", "]", ";", "$", "deletes", "=", "[", "]", ";", "$", "fields", "=", "$", "this", "->", "removeSentinel", "(", "$", "fields", ",", "$", "timestamp...
Search an array for sentinel values, returning the array of fields with sentinels removed, and a list of delete and server timestamp value field paths. @param array $fields The input field data. @return array `[$fields, $timestamps, $deletes]`
[ "Search", "an", "array", "for", "sentinel", "values", "returning", "the", "array", "of", "fields", "with", "sentinels", "removed", "and", "a", "list", "of", "delete", "and", "server", "timestamp", "value", "field", "paths", "." ]
train
https://github.com/morrislaptop/firestore-php/blob/18c30a99b02d847aa84cd77a0acb03cbf5fc0213/src/ValueMapper.php#L209-L216
morrislaptop/firestore-php
src/ValueMapper.php
ValueMapper.removeSentinel
private function removeSentinel(array $fields, array &$timestamps, array &$deletes, $path = '') { if ($path !== '') { $path .= '.'; } foreach ($fields as $key => $value) { $currPath = $path . (string) $this->escapePathPart($key); if (is_array($value)) { $fields[$key] = $this->removeSentinel($value, $timestamps, $deletes, $currPath); } else { if ($value === FieldValue::deleteField() || $value === FieldValue::serverTimestamp()) { if ($value === FieldValue::deleteField()) { $deletes[] = $currPath; } if ($value === FieldValue::serverTimestamp()) { $timestamps[] = $currPath; } unset($fields[$key]); } } } return $fields; }
php
private function removeSentinel(array $fields, array &$timestamps, array &$deletes, $path = '') { if ($path !== '') { $path .= '.'; } foreach ($fields as $key => $value) { $currPath = $path . (string) $this->escapePathPart($key); if (is_array($value)) { $fields[$key] = $this->removeSentinel($value, $timestamps, $deletes, $currPath); } else { if ($value === FieldValue::deleteField() || $value === FieldValue::serverTimestamp()) { if ($value === FieldValue::deleteField()) { $deletes[] = $currPath; } if ($value === FieldValue::serverTimestamp()) { $timestamps[] = $currPath; } unset($fields[$key]); } } } return $fields; }
[ "private", "function", "removeSentinel", "(", "array", "$", "fields", ",", "array", "&", "$", "timestamps", ",", "array", "&", "$", "deletes", ",", "$", "path", "=", "''", ")", "{", "if", "(", "$", "path", "!==", "''", ")", "{", "$", "path", ".=", ...
Recurse through fields and find and remove sentinel values. @param array $fields The input field data. @param array $timestamps The timestamps field paths. (reference) @param array $deletes the deletes field paths. (reference) @param string $path The current field path. @return array
[ "Recurse", "through", "fields", "and", "find", "and", "remove", "sentinel", "values", "." ]
train
https://github.com/morrislaptop/firestore-php/blob/18c30a99b02d847aa84cd77a0acb03cbf5fc0213/src/ValueMapper.php#L227-L253
morrislaptop/firestore-php
src/ValueMapper.php
ValueMapper.decodeValue
private function decodeValue($type, $value) { switch ($type) { case 'booleanValue': case 'nullValue': case 'stringValue': case 'doubleValue': return $value; break; case 'bytesValue': return new Blob($value); case 'integerValue': return $this->returnInt64AsObject ? new Int64($value) : (int) $value; case 'timestampValue': $time = $this->parseTimeString($value); return new Timestamp($time[0], $time[1]); break; case 'geoPointValue': $value += [ 'latitude' => null, 'longitude' => null ]; return new GeoPoint($value['latitude'], $value['longitude']); break; case 'arrayValue': $res = []; if (!empty($value['fields'])) foreach ($value['values'] as $val) { $type = array_keys($val)[0]; $res[] = $this->decodeValue($type, current($val)); } return $res; break; case 'mapValue': $res = []; if (!empty($value['fields'])) foreach ($value['fields'] as $key => $val) { $type = array_keys($val)[0]; $res[$key] = $this->decodeValue($type, current($val)); } return $res; break; case 'referenceValue': return new DocumentReference(uri_for($value), null, $this); default: throw new \RuntimeException(sprintf( 'unexpected value type %s!', $type )); break; } }
php
private function decodeValue($type, $value) { switch ($type) { case 'booleanValue': case 'nullValue': case 'stringValue': case 'doubleValue': return $value; break; case 'bytesValue': return new Blob($value); case 'integerValue': return $this->returnInt64AsObject ? new Int64($value) : (int) $value; case 'timestampValue': $time = $this->parseTimeString($value); return new Timestamp($time[0], $time[1]); break; case 'geoPointValue': $value += [ 'latitude' => null, 'longitude' => null ]; return new GeoPoint($value['latitude'], $value['longitude']); break; case 'arrayValue': $res = []; if (!empty($value['fields'])) foreach ($value['values'] as $val) { $type = array_keys($val)[0]; $res[] = $this->decodeValue($type, current($val)); } return $res; break; case 'mapValue': $res = []; if (!empty($value['fields'])) foreach ($value['fields'] as $key => $val) { $type = array_keys($val)[0]; $res[$key] = $this->decodeValue($type, current($val)); } return $res; break; case 'referenceValue': return new DocumentReference(uri_for($value), null, $this); default: throw new \RuntimeException(sprintf( 'unexpected value type %s!', $type )); break; } }
[ "private", "function", "decodeValue", "(", "$", "type", ",", "$", "value", ")", "{", "switch", "(", "$", "type", ")", "{", "case", "'booleanValue'", ":", "case", "'nullValue'", ":", "case", "'stringValue'", ":", "case", "'doubleValue'", ":", "return", "$",...
Convert a Firestore value to a Google Cloud PHP value. @see https://firebase.google.com/docs/firestore/reference/rpc/google.firestore.v1beta1#value Value @param string $type The Firestore value type. @param mixed $value The firestore value. @return mixed @throws \RuntimeException if an unknown value is encountered.
[ "Convert", "a", "Firestore", "value", "to", "a", "Google", "Cloud", "PHP", "value", "." ]
train
https://github.com/morrislaptop/firestore-php/blob/18c30a99b02d847aa84cd77a0acb03cbf5fc0213/src/ValueMapper.php#L264-L331
morrislaptop/firestore-php
src/ValueMapper.php
ValueMapper.encodeArrayValue
private function encodeArrayValue(array $value) { $out = []; foreach ($value as $item) { if (is_array($item) && !$this->isAssoc($item)) { throw new \RuntimeException('Nested array values are not permitted.'); } $out[] = $this->encodeValue($item); } return ['arrayValue' => ['values' => $out]]; }
php
private function encodeArrayValue(array $value) { $out = []; foreach ($value as $item) { if (is_array($item) && !$this->isAssoc($item)) { throw new \RuntimeException('Nested array values are not permitted.'); } $out[] = $this->encodeValue($item); } return ['arrayValue' => ['values' => $out]]; }
[ "private", "function", "encodeArrayValue", "(", "array", "$", "value", ")", "{", "$", "out", "=", "[", "]", ";", "foreach", "(", "$", "value", "as", "$", "item", ")", "{", "if", "(", "is_array", "(", "$", "item", ")", "&&", "!", "$", "this", "->"...
Encode a simple array as a Firestore array value. @codingStandardsIgnoreStart @param array $value @return array [ArrayValue](https://firebase.google.com/docs/firestore/reference/rpc/google.firestore.v1beta1#google.firestore.v1beta1.ArrayValue) @throws \RuntimeException If the array contains a nested array. @codingStandardsIgnoreEnd
[ "Encode", "a", "simple", "array", "as", "a", "Firestore", "array", "value", "." ]
train
https://github.com/morrislaptop/firestore-php/blob/18c30a99b02d847aa84cd77a0acb03cbf5fc0213/src/ValueMapper.php#L469-L481
morrislaptop/firestore-php
src/ValueMapper.php
ValueMapper.escapePathPart
private function escapePathPart($part) { return preg_match(self::UNESCAPED_FIELD_NAME, $part) ? $part : '`' . str_replace('`', '\\`', str_replace('\\', '\\\\', $part)) . '`'; }
php
private function escapePathPart($part) { return preg_match(self::UNESCAPED_FIELD_NAME, $part) ? $part : '`' . str_replace('`', '\\`', str_replace('\\', '\\\\', $part)) . '`'; }
[ "private", "function", "escapePathPart", "(", "$", "part", ")", "{", "return", "preg_match", "(", "self", "::", "UNESCAPED_FIELD_NAME", ",", "$", "part", ")", "?", "$", "part", ":", "'`'", ".", "str_replace", "(", "'`'", ",", "'\\\\`'", ",", "str_replace",...
Test a field path component, checking for any special characters, and escaping as required. @param string $part The raw field path component. @return string
[ "Test", "a", "field", "path", "component", "checking", "for", "any", "special", "characters", "and", "escaping", "as", "required", "." ]
train
https://github.com/morrislaptop/firestore-php/blob/18c30a99b02d847aa84cd77a0acb03cbf5fc0213/src/ValueMapper.php#L490-L495
morrislaptop/firestore-php
src/ValueMapper.php
ValueMapper.validateFieldPath
private function validateFieldPath($fieldPath) { if (strpos($fieldPath, '..')) { throw new \InvalidArgumentException('Paths cannot contain `..`.'); } if (strpos($fieldPath, '.') === 0 || strpos(strrev($fieldPath), '.') === 0) { throw new \InvalidArgumentException('Paths cannot begin or end with `.`.'); } }
php
private function validateFieldPath($fieldPath) { if (strpos($fieldPath, '..')) { throw new \InvalidArgumentException('Paths cannot contain `..`.'); } if (strpos($fieldPath, '.') === 0 || strpos(strrev($fieldPath), '.') === 0) { throw new \InvalidArgumentException('Paths cannot begin or end with `.`.'); } }
[ "private", "function", "validateFieldPath", "(", "$", "fieldPath", ")", "{", "if", "(", "strpos", "(", "$", "fieldPath", ",", "'..'", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Paths cannot contain `..`.'", ")", ";", "}", "if", "...
Check if a given string field path is valid. @param string $fieldPath @throws \InvalidArgumentException
[ "Check", "if", "a", "given", "string", "field", "path", "is", "valid", "." ]
train
https://github.com/morrislaptop/firestore-php/blob/18c30a99b02d847aa84cd77a0acb03cbf5fc0213/src/ValueMapper.php#L503-L512
morrislaptop/firestore-php
src/DocumentReference.php
DocumentReference.set
public function set($value, $merge = false): self { $payload = [ 'name' => basename($this->uri->getPath()), 'fields' => $this->valueMapper->encodeValues($value), ]; if ($merge) { $paths = $this->valueMapper->encodeFieldPaths($value); $prefix = '&updateMask.fieldPaths='; $query = $prefix . implode($prefix, $paths); $uri = $this->uri->withQuery("updateMask.fieldPaths=message$query"); } else { $uri = $this->uri; } $this->apiClient->patch($uri, $payload); return $this; }
php
public function set($value, $merge = false): self { $payload = [ 'name' => basename($this->uri->getPath()), 'fields' => $this->valueMapper->encodeValues($value), ]; if ($merge) { $paths = $this->valueMapper->encodeFieldPaths($value); $prefix = '&updateMask.fieldPaths='; $query = $prefix . implode($prefix, $paths); $uri = $this->uri->withQuery("updateMask.fieldPaths=message$query"); } else { $uri = $this->uri; } $this->apiClient->patch($uri, $payload); return $this; }
[ "public", "function", "set", "(", "$", "value", ",", "$", "merge", "=", "false", ")", ":", "self", "{", "$", "payload", "=", "[", "'name'", "=>", "basename", "(", "$", "this", "->", "uri", "->", "getPath", "(", ")", ")", ",", "'fields'", "=>", "$...
Write data to this database location. This will overwrite any data at this location and all child locations. Passing null for the new value is equivalent to calling {@see remove()}: all data at this location or any child location will be deleted. @param mixed $value @throws ApiException if the API reported an error @return Reference
[ "Write", "data", "to", "this", "database", "location", "." ]
train
https://github.com/morrislaptop/firestore-php/blob/18c30a99b02d847aa84cd77a0acb03cbf5fc0213/src/DocumentReference.php#L65-L85
morrislaptop/firestore-php
src/DocumentReference.php
DocumentReference.snapshot
public function snapshot(): DocumentSnapshot { $value = $this->apiClient->get($this->uri); $data = $this->valueMapper->decodeValues($value['fields']); return new DocumentSnapshot($this, [], $data, true); }
php
public function snapshot(): DocumentSnapshot { $value = $this->apiClient->get($this->uri); $data = $this->valueMapper->decodeValues($value['fields']); return new DocumentSnapshot($this, [], $data, true); }
[ "public", "function", "snapshot", "(", ")", ":", "DocumentSnapshot", "{", "$", "value", "=", "$", "this", "->", "apiClient", "->", "get", "(", "$", "this", "->", "uri", ")", ";", "$", "data", "=", "$", "this", "->", "valueMapper", "->", "decodeValues",...
Returns a data snapshot of the current location. @throws ApiException if the API reported an error @return Snapshot
[ "Returns", "a", "data", "snapshot", "of", "the", "current", "location", "." ]
train
https://github.com/morrislaptop/firestore-php/blob/18c30a99b02d847aa84cd77a0acb03cbf5fc0213/src/DocumentReference.php#L94-L101
morrislaptop/firestore-php
src/Firestore.php
Firestore.collection
public function collection(string $path = ''): CollectionReference { try { return new CollectionReference(Uri::resolve($this->uri, $path), $this->client); } catch (\InvalidArgumentException $e) { throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); } }
php
public function collection(string $path = ''): CollectionReference { try { return new CollectionReference(Uri::resolve($this->uri, $path), $this->client); } catch (\InvalidArgumentException $e) { throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); } }
[ "public", "function", "collection", "(", "string", "$", "path", "=", "''", ")", ":", "CollectionReference", "{", "try", "{", "return", "new", "CollectionReference", "(", "Uri", "::", "resolve", "(", "$", "this", "->", "uri", ",", "$", "path", ")", ",", ...
Returns a collection. @param string $name @throws InvalidArgumentException @return Reference
[ "Returns", "a", "collection", "." ]
train
https://github.com/morrislaptop/firestore-php/blob/18c30a99b02d847aa84cd77a0acb03cbf5fc0213/src/Firestore.php#L47-L54
morrislaptop/firestore-php
src/Firestore.php
Firestore.collections
public function collections() { $uri = $this->uri->withPath($this->uri->getPath() . ':listCollectionIds'); $value = $this->client->post($uri, null); $collections = []; foreach ($value['collectionIds'] as $id) { $collections[] = $this->collection($id); } return $collections; }
php
public function collections() { $uri = $this->uri->withPath($this->uri->getPath() . ':listCollectionIds'); $value = $this->client->post($uri, null); $collections = []; foreach ($value['collectionIds'] as $id) { $collections[] = $this->collection($id); } return $collections; }
[ "public", "function", "collections", "(", ")", "{", "$", "uri", "=", "$", "this", "->", "uri", "->", "withPath", "(", "$", "this", "->", "uri", "->", "getPath", "(", ")", ".", "':listCollectionIds'", ")", ";", "$", "value", "=", "$", "this", "->", ...
Returns the root collections.
[ "Returns", "the", "root", "collections", "." ]
train
https://github.com/morrislaptop/firestore-php/blob/18c30a99b02d847aa84cd77a0acb03cbf5fc0213/src/Firestore.php#L59-L70
msurguy/Honeypot
src/Msurguy/Honeypot/Honeypot.php
Honeypot.generate
public function generate($honey_name, $honey_time) { // Encrypt the current time $honey_time_encrypted = $this->getEncryptedTime(); $html = '<div class="' . $honey_name . '_wrap" style="display:none;"><input name="' . $honey_name . '" type="text" value="" id="' . $honey_name . '"/><input name="' . $honey_time . '" type="text" value="' . $honey_time_encrypted . '"/></div>'; return $html; }
php
public function generate($honey_name, $honey_time) { // Encrypt the current time $honey_time_encrypted = $this->getEncryptedTime(); $html = '<div class="' . $honey_name . '_wrap" style="display:none;"><input name="' . $honey_name . '" type="text" value="" id="' . $honey_name . '"/><input name="' . $honey_time . '" type="text" value="' . $honey_time_encrypted . '"/></div>'; return $html; }
[ "public", "function", "generate", "(", "$", "honey_name", ",", "$", "honey_time", ")", "{", "// Encrypt the current time", "$", "honey_time_encrypted", "=", "$", "this", "->", "getEncryptedTime", "(", ")", ";", "$", "html", "=", "'<div class=\"'", ".", "$", "h...
Generate a new honeypot and return the form HTML @param string $honey_name @param string $honey_time @return string
[ "Generate", "a", "new", "honeypot", "and", "return", "the", "form", "HTML" ]
train
https://github.com/msurguy/Honeypot/blob/06cba45261b9f7d4dfa8cba3cf37b4b3f032b053/src/Msurguy/Honeypot/Honeypot.php#L31-L39
msurguy/Honeypot
src/Msurguy/Honeypot/Honeypot.php
Honeypot.validateHoneytime
public function validateHoneytime($attribute, $value, $parameters) { if ($this->disabled) { return true; } // Get the decrypted time $value = $this->decryptTime($value); // The current time should be greater than the time the form was built + the speed option return ( is_numeric($value) && time() > ($value + $parameters[0]) ); }
php
public function validateHoneytime($attribute, $value, $parameters) { if ($this->disabled) { return true; } // Get the decrypted time $value = $this->decryptTime($value); // The current time should be greater than the time the form was built + the speed option return ( is_numeric($value) && time() > ($value + $parameters[0]) ); }
[ "public", "function", "validateHoneytime", "(", "$", "attribute", ",", "$", "value", ",", "$", "parameters", ")", "{", "if", "(", "$", "this", "->", "disabled", ")", "{", "return", "true", ";", "}", "// Get the decrypted time", "$", "value", "=", "$", "t...
Validate honey time was within the time limit @param string $attribute @param mixed $value @param array $parameters @return boolean
[ "Validate", "honey", "time", "was", "within", "the", "time", "limit" ]
train
https://github.com/msurguy/Honeypot/blob/06cba45261b9f7d4dfa8cba3cf37b4b3f032b053/src/Msurguy/Honeypot/Honeypot.php#L66-L77
msurguy/Honeypot
src/Msurguy/Honeypot/HoneypotServiceProvider.php
HoneypotServiceProvider.boot
public function boot() { if ($this->isLaravelVersion('4')) { $this->package('msurguy/honeypot'); } elseif ($this->isLaravelVersion('5')) { $this->loadTranslationsFrom(__DIR__ . '/../../lang', 'honeypot'); } $this->app->booted(function($app) { // Get validator and translator $validator = $app['validator']; $translator = $app['translator']; // Add honeypot and honeytime custom validation rules $validator->extend('honeypot', 'honeypot@validateHoneypot', $translator->get('honeypot::validation.honeypot')); $validator->extend('honeytime', 'honeypot@validateHoneytime', $translator->get('honeypot::validation.honeytime')); }); }
php
public function boot() { if ($this->isLaravelVersion('4')) { $this->package('msurguy/honeypot'); } elseif ($this->isLaravelVersion('5')) { $this->loadTranslationsFrom(__DIR__ . '/../../lang', 'honeypot'); } $this->app->booted(function($app) { // Get validator and translator $validator = $app['validator']; $translator = $app['translator']; // Add honeypot and honeytime custom validation rules $validator->extend('honeypot', 'honeypot@validateHoneypot', $translator->get('honeypot::validation.honeypot')); $validator->extend('honeytime', 'honeypot@validateHoneytime', $translator->get('honeypot::validation.honeytime')); }); }
[ "public", "function", "boot", "(", ")", "{", "if", "(", "$", "this", "->", "isLaravelVersion", "(", "'4'", ")", ")", "{", "$", "this", "->", "package", "(", "'msurguy/honeypot'", ")", ";", "}", "elseif", "(", "$", "this", "->", "isLaravelVersion", "(",...
Bootstrap the application events. @return void
[ "Bootstrap", "the", "application", "events", "." ]
train
https://github.com/msurguy/Honeypot/blob/06cba45261b9f7d4dfa8cba3cf37b4b3f032b053/src/Msurguy/Honeypot/HoneypotServiceProvider.php#L34-L56
larsjanssen6/underconstruction
src/Commands/SetCodeCommand.php
SetCodeCommand.handle
public function handle() { $code = $this->argument('code'); if ($this->validate($code)) { $hash = Hash::make($code); $this->setHashInEnvironmentFile($hash); $this->info(sprintf('Code: "%s" is set successfully.', $code)); } else { $this->error(sprintf('Wrong input. Code should contain %s numbers (see config file), and can\'t be greater then 6.', $this->config['total_digits'])); } }
php
public function handle() { $code = $this->argument('code'); if ($this->validate($code)) { $hash = Hash::make($code); $this->setHashInEnvironmentFile($hash); $this->info(sprintf('Code: "%s" is set successfully.', $code)); } else { $this->error(sprintf('Wrong input. Code should contain %s numbers (see config file), and can\'t be greater then 6.', $this->config['total_digits'])); } }
[ "public", "function", "handle", "(", ")", "{", "$", "code", "=", "$", "this", "->", "argument", "(", "'code'", ")", ";", "if", "(", "$", "this", "->", "validate", "(", "$", "code", ")", ")", "{", "$", "hash", "=", "Hash", "::", "make", "(", "$"...
Execute the console command. @return mixed @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/larsjanssen6/underconstruction/blob/7c705995449e2439497a0b41ba18327749691b5a/src/Commands/SetCodeCommand.php#L57-L68
larsjanssen6/underconstruction
src/Commands/SetCodeCommand.php
SetCodeCommand.setHashInEnvironmentFile
protected function setHashInEnvironmentFile($hash) { $envPath = $this->laravel->environmentFilePath(); $envContent = $this->filesystem->get($envPath); $regex = '/UNDER_CONSTRUCTION_HASH=\S+/'; if (preg_match($regex, $envContent)) { $hash = str_replace(['\\', '$'], ['', '\$'], $hash); $envContent = preg_replace($regex, $this->newLine($hash), $envContent); } else { $envContent .= "\n".$this->newLine($hash)."\n"; } $this->filesystem->put($envPath, $envContent); }
php
protected function setHashInEnvironmentFile($hash) { $envPath = $this->laravel->environmentFilePath(); $envContent = $this->filesystem->get($envPath); $regex = '/UNDER_CONSTRUCTION_HASH=\S+/'; if (preg_match($regex, $envContent)) { $hash = str_replace(['\\', '$'], ['', '\$'], $hash); $envContent = preg_replace($regex, $this->newLine($hash), $envContent); } else { $envContent .= "\n".$this->newLine($hash)."\n"; } $this->filesystem->put($envPath, $envContent); }
[ "protected", "function", "setHashInEnvironmentFile", "(", "$", "hash", ")", "{", "$", "envPath", "=", "$", "this", "->", "laravel", "->", "environmentFilePath", "(", ")", ";", "$", "envContent", "=", "$", "this", "->", "filesystem", "->", "get", "(", "$", ...
Set the hash in .env file. @param $hash @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
[ "Set", "the", "hash", "in", ".", "env", "file", "." ]
train
https://github.com/larsjanssen6/underconstruction/blob/7c705995449e2439497a0b41ba18327749691b5a/src/Commands/SetCodeCommand.php#L76-L91
larsjanssen6/underconstruction
src/Commands/SetCodeCommand.php
SetCodeCommand.validate
public function validate($code): bool { $codeLength = strlen($code); return ctype_digit($code) && $codeLength == $this->config['total_digits'] && strlen($code) <= 6; }
php
public function validate($code): bool { $codeLength = strlen($code); return ctype_digit($code) && $codeLength == $this->config['total_digits'] && strlen($code) <= 6; }
[ "public", "function", "validate", "(", "$", "code", ")", ":", "bool", "{", "$", "codeLength", "=", "strlen", "(", "$", "code", ")", ";", "return", "ctype_digit", "(", "$", "code", ")", "&&", "$", "codeLength", "==", "$", "this", "->", "config", "[", ...
Check if given code is valid. @param $code @return bool
[ "Check", "if", "given", "code", "is", "valid", "." ]
train
https://github.com/larsjanssen6/underconstruction/blob/7c705995449e2439497a0b41ba18327749691b5a/src/Commands/SetCodeCommand.php#L109-L114
larsjanssen6/underconstruction
src/UnderConstructionServiceProvider.php
UnderConstructionServiceProvider.register
public function register() { $this->commands('LarsJanssen\UnderConstruction\Commands\SetCodeCommand'); $this->mergeConfigFrom(__DIR__.'/../config/under-construction.php', 'under-construction'); $this->app->bind('TransFormer', function ($app) { return new TransFormer(); }); $routeConfig = [ 'namespace' => 'LarsJanssen\UnderConstruction\Controllers', 'prefix' => 'under', 'middleware' => [ 'web', ], ]; $this->getRouter()->group($routeConfig, function ($router) { $router->post('check', [ 'uses' => 'CodeController@check', 'as' => 'underconstruction.check', ]); $router->post('checkiflimited', [ 'uses' => 'CodeController@checkIfLimited', 'as' => 'underconstruction.checkiflimited', ]); $router->get('construction', [ 'uses' => 'CodeController@index', 'as' => 'underconstruction.index', ]); $router->get('js', [ 'uses' => 'AssetController@js', 'as' => 'underconstruction.js', ]); }); }
php
public function register() { $this->commands('LarsJanssen\UnderConstruction\Commands\SetCodeCommand'); $this->mergeConfigFrom(__DIR__.'/../config/under-construction.php', 'under-construction'); $this->app->bind('TransFormer', function ($app) { return new TransFormer(); }); $routeConfig = [ 'namespace' => 'LarsJanssen\UnderConstruction\Controllers', 'prefix' => 'under', 'middleware' => [ 'web', ], ]; $this->getRouter()->group($routeConfig, function ($router) { $router->post('check', [ 'uses' => 'CodeController@check', 'as' => 'underconstruction.check', ]); $router->post('checkiflimited', [ 'uses' => 'CodeController@checkIfLimited', 'as' => 'underconstruction.checkiflimited', ]); $router->get('construction', [ 'uses' => 'CodeController@index', 'as' => 'underconstruction.index', ]); $router->get('js', [ 'uses' => 'AssetController@js', 'as' => 'underconstruction.js', ]); }); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "commands", "(", "'LarsJanssen\\UnderConstruction\\Commands\\SetCodeCommand'", ")", ";", "$", "this", "->", "mergeConfigFrom", "(", "__DIR__", ".", "'/../config/under-construction.php'", ",", "'under-co...
Register the application services.
[ "Register", "the", "application", "services", "." ]
train
https://github.com/larsjanssen6/underconstruction/blob/7c705995449e2439497a0b41ba18327749691b5a/src/UnderConstructionServiceProvider.php#L24-L62
larsjanssen6/underconstruction
src/Controllers/CodeController.php
CodeController.check
public function check(Request $request) { $request->validate(['code' => 'required|numeric']); if (Hash::check($request->code, $this->getHash())) { session(['can_visit' => true]); return response([ 'status' => 'success', ]); } $this->incrementLoginAttempts($request); if ($this->hasTooManyLoginAttempts($request) && $this->throttleIsActive()) { return response([ 'too_many_attempts' => true, 'seconds_message' => TransFormer::transform($this->getBlockedSeconds($request), $this->config['seconds_message']), ], 401); } return response([ 'too_many_attempts' => false, 'attempts_left' => $this->showAttempts($request), ], 401); }
php
public function check(Request $request) { $request->validate(['code' => 'required|numeric']); if (Hash::check($request->code, $this->getHash())) { session(['can_visit' => true]); return response([ 'status' => 'success', ]); } $this->incrementLoginAttempts($request); if ($this->hasTooManyLoginAttempts($request) && $this->throttleIsActive()) { return response([ 'too_many_attempts' => true, 'seconds_message' => TransFormer::transform($this->getBlockedSeconds($request), $this->config['seconds_message']), ], 401); } return response([ 'too_many_attempts' => false, 'attempts_left' => $this->showAttempts($request), ], 401); }
[ "public", "function", "check", "(", "Request", "$", "request", ")", "{", "$", "request", "->", "validate", "(", "[", "'code'", "=>", "'required|numeric'", "]", ")", ";", "if", "(", "Hash", "::", "check", "(", "$", "request", "->", "code", ",", "$", "...
Check if the given code is correct, then return the proper response. @param Request $request @throws Exception @return \Symfony\Component\HttpFoundation\Response
[ "Check", "if", "the", "given", "code", "is", "correct", "then", "return", "the", "proper", "response", "." ]
train
https://github.com/larsjanssen6/underconstruction/blob/7c705995449e2439497a0b41ba18327749691b5a/src/Controllers/CodeController.php#L76-L101
larsjanssen6/underconstruction
src/Controllers/CodeController.php
CodeController.showAttempts
private function showAttempts(Request $request) { if ($this->config['show_attempts_left'] && $this->config['throttle']) { return TransFormer::transform($this->retriesLeft($request), $this->config['attempts_message']); } return false; }
php
private function showAttempts(Request $request) { if ($this->config['show_attempts_left'] && $this->config['throttle']) { return TransFormer::transform($this->retriesLeft($request), $this->config['attempts_message']); } return false; }
[ "private", "function", "showAttempts", "(", "Request", "$", "request", ")", "{", "if", "(", "$", "this", "->", "config", "[", "'show_attempts_left'", "]", "&&", "$", "this", "->", "config", "[", "'throttle'", "]", ")", "{", "return", "TransFormer", "::", ...
Determine attempts that are left. @param Request $request @return int | bool
[ "Determine", "attempts", "that", "are", "left", "." ]
train
https://github.com/larsjanssen6/underconstruction/blob/7c705995449e2439497a0b41ba18327749691b5a/src/Controllers/CodeController.php#L134-L141
larsjanssen6/underconstruction
src/Throttle.php
Throttle.retriesLeft
protected function retriesLeft(Request $request) { return $this->limiter()->retriesLeft($this->throttleKey($request), $this->maxAttempts()); }
php
protected function retriesLeft(Request $request) { return $this->limiter()->retriesLeft($this->throttleKey($request), $this->maxAttempts()); }
[ "protected", "function", "retriesLeft", "(", "Request", "$", "request", ")", "{", "return", "$", "this", "->", "limiter", "(", ")", "->", "retriesLeft", "(", "$", "this", "->", "throttleKey", "(", "$", "request", ")", ",", "$", "this", "->", "maxAttempts...
Get the number of attempts left. @param \Illuminate\Http\Request $request @return bool
[ "Get", "the", "number", "of", "attempts", "left", "." ]
train
https://github.com/larsjanssen6/underconstruction/blob/7c705995449e2439497a0b41ba18327749691b5a/src/Throttle.php#L17-L20
larsjanssen6/underconstruction
src/Throttle.php
Throttle.incrementLoginAttempts
protected function incrementLoginAttempts(Request $request) { $this->limiter()->hit( $this->throttleKey($request), $this->decayMinutes() ); }
php
protected function incrementLoginAttempts(Request $request) { $this->limiter()->hit( $this->throttleKey($request), $this->decayMinutes() ); }
[ "protected", "function", "incrementLoginAttempts", "(", "Request", "$", "request", ")", "{", "$", "this", "->", "limiter", "(", ")", "->", "hit", "(", "$", "this", "->", "throttleKey", "(", "$", "request", ")", ",", "$", "this", "->", "decayMinutes", "("...
Increment the login attempts for the user. @param \Illuminate\Http\Request $request @return void
[ "Increment", "the", "login", "attempts", "for", "the", "user", "." ]
train
https://github.com/larsjanssen6/underconstruction/blob/7c705995449e2439497a0b41ba18327749691b5a/src/Throttle.php#L43-L48
Seldaek/phar-utils
src/Timestamps.php
Timestamps.updateTimestamps
public function updateTimestamps($timestamp = null) { if ($timestamp instanceof \DateTime) { $timestamp = $timestamp->getTimestamp(); } elseif (is_string($timestamp)) { $timestamp = strtotime($timestamp); } elseif (!is_int($timestamp)) { $timestamp = strtotime('1984-12-24T00:00:00Z'); } // detect manifest offset / end of stub if (!preg_match('{__HALT_COMPILER\(\);(?: +\?>)?\r?\n}', $this->contents, $match, PREG_OFFSET_CAPTURE)) { throw new \RuntimeException('Could not detect the stub\'s end in the phar'); } // set starting position and skip past manifest length $pos = $match[0][1] + strlen($match[0][0]); $stubEnd = $pos + $this->readUint($pos, 4); $pos += 4; $numFiles = $this->readUint($pos, 4); $pos += 4; // skip API version (YOLO) $pos += 2; // skip PHAR flags $pos += 4; $aliasLength = $this->readUint($pos, 4); $pos += 4 + $aliasLength; $metadataLength = $this->readUint($pos, 4); $pos += 4 + $metadataLength; while ($pos < $stubEnd) { $filenameLength = $this->readUint($pos, 4); $pos += 4 + $filenameLength; // skip filesize $pos += 4; // update timestamp to a fixed value $this->contents = substr_replace($this->contents, pack('L', $timestamp), $pos, 4); // skip timestamp, compressed file size, crc32 checksum and file flags $pos += 4*4; $metadataLength = $this->readUint($pos, 4); $pos += 4 + $metadataLength; $numFiles--; } if ($numFiles !== 0) { throw new \LogicException('All files were not processed, something must have gone wrong'); } }
php
public function updateTimestamps($timestamp = null) { if ($timestamp instanceof \DateTime) { $timestamp = $timestamp->getTimestamp(); } elseif (is_string($timestamp)) { $timestamp = strtotime($timestamp); } elseif (!is_int($timestamp)) { $timestamp = strtotime('1984-12-24T00:00:00Z'); } // detect manifest offset / end of stub if (!preg_match('{__HALT_COMPILER\(\);(?: +\?>)?\r?\n}', $this->contents, $match, PREG_OFFSET_CAPTURE)) { throw new \RuntimeException('Could not detect the stub\'s end in the phar'); } // set starting position and skip past manifest length $pos = $match[0][1] + strlen($match[0][0]); $stubEnd = $pos + $this->readUint($pos, 4); $pos += 4; $numFiles = $this->readUint($pos, 4); $pos += 4; // skip API version (YOLO) $pos += 2; // skip PHAR flags $pos += 4; $aliasLength = $this->readUint($pos, 4); $pos += 4 + $aliasLength; $metadataLength = $this->readUint($pos, 4); $pos += 4 + $metadataLength; while ($pos < $stubEnd) { $filenameLength = $this->readUint($pos, 4); $pos += 4 + $filenameLength; // skip filesize $pos += 4; // update timestamp to a fixed value $this->contents = substr_replace($this->contents, pack('L', $timestamp), $pos, 4); // skip timestamp, compressed file size, crc32 checksum and file flags $pos += 4*4; $metadataLength = $this->readUint($pos, 4); $pos += 4 + $metadataLength; $numFiles--; } if ($numFiles !== 0) { throw new \LogicException('All files were not processed, something must have gone wrong'); } }
[ "public", "function", "updateTimestamps", "(", "$", "timestamp", "=", "null", ")", "{", "if", "(", "$", "timestamp", "instanceof", "\\", "DateTime", ")", "{", "$", "timestamp", "=", "$", "timestamp", "->", "getTimestamp", "(", ")", ";", "}", "elseif", "(...
Updates each file's unix timestamps in the PHAR The PHAR signature can then be produced in a reproducible manner. @param int|DateTime|string $timestamp Date string or DateTime or unix timestamp to use
[ "Updates", "each", "file", "s", "unix", "timestamps", "in", "the", "PHAR" ]
train
https://github.com/Seldaek/phar-utils/blob/7009b5139491975ef6486545a39f3e6dad5ac30a/src/Timestamps.php#L33-L90
Seldaek/phar-utils
src/Timestamps.php
Timestamps.save
public function save($path, $signatureAlgo) { $pos = $this->determineSignatureBegin(); $algos = array( \Phar::MD5 => 'md5', \Phar::SHA1 => 'sha1', \Phar::SHA256 => 'sha256', \Phar::SHA512 => 'sha512', ); if (!isset($algos[$signatureAlgo])) { throw new \UnexpectedValueException('Invalid hash algorithm given: '.$signatureAlgo.' expected one of Phar::MD5, Phar::SHA1, Phar::SHA256 or Phar::SHA512'); } $algo = $algos[$signatureAlgo]; // re-sign phar // signature $signature = hash($algo, substr($this->contents, 0, $pos), true) // sig type . pack('L', $signatureAlgo) // ohai Greg & Marcus . 'GBMB'; $this->contents = substr($this->contents, 0, $pos) . $signature; return file_put_contents($path, $this->contents); }
php
public function save($path, $signatureAlgo) { $pos = $this->determineSignatureBegin(); $algos = array( \Phar::MD5 => 'md5', \Phar::SHA1 => 'sha1', \Phar::SHA256 => 'sha256', \Phar::SHA512 => 'sha512', ); if (!isset($algos[$signatureAlgo])) { throw new \UnexpectedValueException('Invalid hash algorithm given: '.$signatureAlgo.' expected one of Phar::MD5, Phar::SHA1, Phar::SHA256 or Phar::SHA512'); } $algo = $algos[$signatureAlgo]; // re-sign phar // signature $signature = hash($algo, substr($this->contents, 0, $pos), true) // sig type . pack('L', $signatureAlgo) // ohai Greg & Marcus . 'GBMB'; $this->contents = substr($this->contents, 0, $pos) . $signature; return file_put_contents($path, $this->contents); }
[ "public", "function", "save", "(", "$", "path", ",", "$", "signatureAlgo", ")", "{", "$", "pos", "=", "$", "this", "->", "determineSignatureBegin", "(", ")", ";", "$", "algos", "=", "array", "(", "\\", "Phar", "::", "MD5", "=>", "'md5'", ",", "\\", ...
Saves the updated phar file, optionally with an updated signature. @param string $path @param int $signatureAlgo One of Phar::MD5, Phar::SHA1, Phar::SHA256 or Phar::SHA512 @return bool
[ "Saves", "the", "updated", "phar", "file", "optionally", "with", "an", "updated", "signature", "." ]
train
https://github.com/Seldaek/phar-utils/blob/7009b5139491975ef6486545a39f3e6dad5ac30a/src/Timestamps.php#L99-L126
Seldaek/phar-utils
src/Timestamps.php
Timestamps.determineSignatureBegin
private function determineSignatureBegin() { // detect signature position if (!preg_match('{__HALT_COMPILER\(\);(?: +\?>)?\r?\n}', $this->contents, $match, PREG_OFFSET_CAPTURE)) { throw new \RuntimeException('Could not detect the stub\'s end in the phar'); } // set starting position and skip past manifest length $pos = $match[0][1] + strlen($match[0][0]); $stubEnd = $pos + $this->readUint($pos, 4); $pos += 4; $numFiles = $this->readUint($pos, 4); $pos += 4; // skip API version (YOLO) $pos += 2; // skip PHAR flags $pos += 4; $aliasLength = $this->readUint($pos, 4); $pos += 4 + $aliasLength; $metadataLength = $this->readUint($pos, 4); $pos += 4 + $metadataLength; $compressedSizes = 0; while ($pos < $stubEnd) { $filenameLength = $this->readUint($pos, 4); $pos += 4 + $filenameLength; // skip filesize and timestamp $pos += 2*4; $compressedSizes += $this->readUint($pos, 4); // skip compressed file size, crc32 checksum and file flags $pos += 3*4; $metadataLength = $this->readUint($pos, 4); $pos += 4 + $metadataLength; $numFiles--; } if ($numFiles !== 0) { throw new \LogicException('All files were not processed, something must have gone wrong'); } return $pos + $compressedSizes; }
php
private function determineSignatureBegin() { // detect signature position if (!preg_match('{__HALT_COMPILER\(\);(?: +\?>)?\r?\n}', $this->contents, $match, PREG_OFFSET_CAPTURE)) { throw new \RuntimeException('Could not detect the stub\'s end in the phar'); } // set starting position and skip past manifest length $pos = $match[0][1] + strlen($match[0][0]); $stubEnd = $pos + $this->readUint($pos, 4); $pos += 4; $numFiles = $this->readUint($pos, 4); $pos += 4; // skip API version (YOLO) $pos += 2; // skip PHAR flags $pos += 4; $aliasLength = $this->readUint($pos, 4); $pos += 4 + $aliasLength; $metadataLength = $this->readUint($pos, 4); $pos += 4 + $metadataLength; $compressedSizes = 0; while ($pos < $stubEnd) { $filenameLength = $this->readUint($pos, 4); $pos += 4 + $filenameLength; // skip filesize and timestamp $pos += 2*4; $compressedSizes += $this->readUint($pos, 4); // skip compressed file size, crc32 checksum and file flags $pos += 3*4; $metadataLength = $this->readUint($pos, 4); $pos += 4 + $metadataLength; $numFiles--; } if ($numFiles !== 0) { throw new \LogicException('All files were not processed, something must have gone wrong'); } return $pos + $compressedSizes; }
[ "private", "function", "determineSignatureBegin", "(", ")", "{", "// detect signature position", "if", "(", "!", "preg_match", "(", "'{__HALT_COMPILER\\(\\);(?: +\\?>)?\\r?\\n}'", ",", "$", "this", "->", "contents", ",", "$", "match", ",", "PREG_OFFSET_CAPTURE", ")", ...
Determine the beginning of the signature. @return int
[ "Determine", "the", "beginning", "of", "the", "signature", "." ]
train
https://github.com/Seldaek/phar-utils/blob/7009b5139491975ef6486545a39f3e6dad5ac30a/src/Timestamps.php#L140-L191
orchestral/testbench-core
src/Concerns/WithLoadMigrationsFrom.php
WithLoadMigrationsFrom.loadMigrationsFrom
protected function loadMigrationsFrom($paths): void { $options = \is_array($paths) ? $paths : ['--path' => $paths]; if (isset($options['--realpath']) && \is_string($options['--realpath'])) { $options['--path'] = [$options['--realpath']]; } $options['--realpath'] = true; $migrator = new MigrateProcessor($this, $options); $migrator->up(); $this->beforeApplicationDestroyed(function () use ($migrator) { $migrator->rollback(); }); }
php
protected function loadMigrationsFrom($paths): void { $options = \is_array($paths) ? $paths : ['--path' => $paths]; if (isset($options['--realpath']) && \is_string($options['--realpath'])) { $options['--path'] = [$options['--realpath']]; } $options['--realpath'] = true; $migrator = new MigrateProcessor($this, $options); $migrator->up(); $this->beforeApplicationDestroyed(function () use ($migrator) { $migrator->rollback(); }); }
[ "protected", "function", "loadMigrationsFrom", "(", "$", "paths", ")", ":", "void", "{", "$", "options", "=", "\\", "is_array", "(", "$", "paths", ")", "?", "$", "paths", ":", "[", "'--path'", "=>", "$", "paths", "]", ";", "if", "(", "isset", "(", ...
Define hooks to migrate the database before and after each test. @param string|array $paths @return void
[ "Define", "hooks", "to", "migrate", "the", "database", "before", "and", "after", "each", "test", "." ]
train
https://github.com/orchestral/testbench-core/blob/598caa6f7813b8a29b2f1b69912b40659dcef79b/src/Concerns/WithLoadMigrationsFrom.php#L16-L32
orchestral/testbench-core
src/Database/MigrateProcessor.php
MigrateProcessor.dispatch
protected function dispatch(string $command): void { $console = $this->testbench->artisan($command, $this->options); if ($console instanceof PendingCommand) { $console->run(); } }
php
protected function dispatch(string $command): void { $console = $this->testbench->artisan($command, $this->options); if ($console instanceof PendingCommand) { $console->run(); } }
[ "protected", "function", "dispatch", "(", "string", "$", "command", ")", ":", "void", "{", "$", "console", "=", "$", "this", "->", "testbench", "->", "artisan", "(", "$", "command", ",", "$", "this", "->", "options", ")", ";", "if", "(", "$", "consol...
Dispatch artisan command. @param string $command @return void
[ "Dispatch", "artisan", "command", "." ]
train
https://github.com/orchestral/testbench-core/blob/598caa6f7813b8a29b2f1b69912b40659dcef79b/src/Database/MigrateProcessor.php#L68-L75
orchestral/testbench-core
src/Concerns/WithLaravelMigrations.php
WithLaravelMigrations.loadLaravelMigrations
protected function loadLaravelMigrations($database = []): void { $options = \is_array($database) ? $database : ['--database' => $database]; $options['--path'] = 'migrations'; $migrator = new MigrateProcessor($this, $options); $migrator->up(); $this->app[ConsoleKernel::class]->setArtisan(null); $this->beforeApplicationDestroyed(function () use ($migrator) { $migrator->rollback(); }); }
php
protected function loadLaravelMigrations($database = []): void { $options = \is_array($database) ? $database : ['--database' => $database]; $options['--path'] = 'migrations'; $migrator = new MigrateProcessor($this, $options); $migrator->up(); $this->app[ConsoleKernel::class]->setArtisan(null); $this->beforeApplicationDestroyed(function () use ($migrator) { $migrator->rollback(); }); }
[ "protected", "function", "loadLaravelMigrations", "(", "$", "database", "=", "[", "]", ")", ":", "void", "{", "$", "options", "=", "\\", "is_array", "(", "$", "database", ")", "?", "$", "database", ":", "[", "'--database'", "=>", "$", "database", "]", ...
Migrate Laravel's default migrations. @param array|string $database @return void
[ "Migrate", "Laravel", "s", "default", "migrations", "." ]
train
https://github.com/orchestral/testbench-core/blob/598caa6f7813b8a29b2f1b69912b40659dcef79b/src/Concerns/WithLaravelMigrations.php#L17-L32
orchestral/testbench-core
src/Concerns/CreatesApplication.php
CreatesApplication.resolveApplicationBindings
final protected function resolveApplicationBindings($app): void { foreach ($this->overrideApplicationBindings($app) as $original => $replacement) { $app->bind($original, $replacement); } }
php
final protected function resolveApplicationBindings($app): void { foreach ($this->overrideApplicationBindings($app) as $original => $replacement) { $app->bind($original, $replacement); } }
[ "final", "protected", "function", "resolveApplicationBindings", "(", "$", "app", ")", ":", "void", "{", "foreach", "(", "$", "this", "->", "overrideApplicationBindings", "(", "$", "app", ")", "as", "$", "original", "=>", "$", "replacement", ")", "{", "$", ...
Resolve application bindings. @param \Illuminate\Foundation\Application $app @return void
[ "Resolve", "application", "bindings", "." ]
train
https://github.com/orchestral/testbench-core/blob/598caa6f7813b8a29b2f1b69912b40659dcef79b/src/Concerns/CreatesApplication.php#L42-L47
orchestral/testbench-core
src/Concerns/CreatesApplication.php
CreatesApplication.resolveApplicationAliases
final protected function resolveApplicationAliases($app): array { $aliases = new Collection($this->getApplicationAliases($app)); $overrides = $this->overrideApplicationAliases($app); if (! empty($overrides)) { $aliases->transform(function ($alias, $name) use ($overrides) { return $overrides[$name] ?? $alias; }); } return $aliases->merge($this->getPackageAliases($app))->all(); }
php
final protected function resolveApplicationAliases($app): array { $aliases = new Collection($this->getApplicationAliases($app)); $overrides = $this->overrideApplicationAliases($app); if (! empty($overrides)) { $aliases->transform(function ($alias, $name) use ($overrides) { return $overrides[$name] ?? $alias; }); } return $aliases->merge($this->getPackageAliases($app))->all(); }
[ "final", "protected", "function", "resolveApplicationAliases", "(", "$", "app", ")", ":", "array", "{", "$", "aliases", "=", "new", "Collection", "(", "$", "this", "->", "getApplicationAliases", "(", "$", "app", ")", ")", ";", "$", "overrides", "=", "$", ...
Resolve application aliases. @param \Illuminate\Foundation\Application $app @return array
[ "Resolve", "application", "aliases", "." ]
train
https://github.com/orchestral/testbench-core/blob/598caa6f7813b8a29b2f1b69912b40659dcef79b/src/Concerns/CreatesApplication.php#L80-L92
orchestral/testbench-core
src/Concerns/CreatesApplication.php
CreatesApplication.resolveApplicationProviders
final protected function resolveApplicationProviders($app): array { $providers = new Collection($this->getApplicationProviders($app)); $overrides = $this->overrideApplicationProviders($app); if (! empty($overrides)) { $providers->transform(function ($provider) use ($overrides) { return $overrides[$provider] ?? $provider; }); } return $providers->merge($this->getPackageProviders($app))->all(); }
php
final protected function resolveApplicationProviders($app): array { $providers = new Collection($this->getApplicationProviders($app)); $overrides = $this->overrideApplicationProviders($app); if (! empty($overrides)) { $providers->transform(function ($provider) use ($overrides) { return $overrides[$provider] ?? $provider; }); } return $providers->merge($this->getPackageProviders($app))->all(); }
[ "final", "protected", "function", "resolveApplicationProviders", "(", "$", "app", ")", ":", "array", "{", "$", "providers", "=", "new", "Collection", "(", "$", "this", "->", "getApplicationProviders", "(", "$", "app", ")", ")", ";", "$", "overrides", "=", ...
Resolve application aliases. @param \Illuminate\Foundation\Application $app @return array
[ "Resolve", "application", "aliases", "." ]
train
https://github.com/orchestral/testbench-core/blob/598caa6f7813b8a29b2f1b69912b40659dcef79b/src/Concerns/CreatesApplication.php#L149-L161
orchestral/testbench-core
src/Concerns/CreatesApplication.php
CreatesApplication.createApplication
public function createApplication() { $app = $this->resolveApplication(); $this->resolveApplicationBindings($app); $this->resolveApplicationExceptionHandler($app); $this->resolveApplicationCore($app); $this->resolveApplicationConfiguration($app); $this->resolveApplicationHttpKernel($app); $this->resolveApplicationConsoleKernel($app); $this->resolveApplicationBootstrappers($app); return $app; }
php
public function createApplication() { $app = $this->resolveApplication(); $this->resolveApplicationBindings($app); $this->resolveApplicationExceptionHandler($app); $this->resolveApplicationCore($app); $this->resolveApplicationConfiguration($app); $this->resolveApplicationHttpKernel($app); $this->resolveApplicationConsoleKernel($app); $this->resolveApplicationBootstrappers($app); return $app; }
[ "public", "function", "createApplication", "(", ")", "{", "$", "app", "=", "$", "this", "->", "resolveApplication", "(", ")", ";", "$", "this", "->", "resolveApplicationBindings", "(", "$", "app", ")", ";", "$", "this", "->", "resolveApplicationExceptionHandle...
Creates the application. Needs to be implemented by subclasses. @return \Illuminate\Foundation\Application
[ "Creates", "the", "application", "." ]
train
https://github.com/orchestral/testbench-core/blob/598caa6f7813b8a29b2f1b69912b40659dcef79b/src/Concerns/CreatesApplication.php#L192-L205
orchestral/testbench-core
src/Concerns/CreatesApplication.php
CreatesApplication.resolveApplicationConfiguration
protected function resolveApplicationConfiguration($app) { $app->make('Illuminate\Foundation\Bootstrap\LoadConfiguration')->bootstrap($app); \tap($this->getApplicationTimezone($app), function ($timezone) { ! \is_null($timezone) && \date_default_timezone_set($timezone); }); $app['config']['app.aliases'] = $this->resolveApplicationAliases($app); $app['config']['app.providers'] = $this->resolveApplicationProviders($app); }
php
protected function resolveApplicationConfiguration($app) { $app->make('Illuminate\Foundation\Bootstrap\LoadConfiguration')->bootstrap($app); \tap($this->getApplicationTimezone($app), function ($timezone) { ! \is_null($timezone) && \date_default_timezone_set($timezone); }); $app['config']['app.aliases'] = $this->resolveApplicationAliases($app); $app['config']['app.providers'] = $this->resolveApplicationProviders($app); }
[ "protected", "function", "resolveApplicationConfiguration", "(", "$", "app", ")", "{", "$", "app", "->", "make", "(", "'Illuminate\\Foundation\\Bootstrap\\LoadConfiguration'", ")", "->", "bootstrap", "(", "$", "app", ")", ";", "\\", "tap", "(", "$", "this", "->"...
Resolve application core configuration implementation. @param \Illuminate\Foundation\Application $app @return void
[ "Resolve", "application", "core", "configuration", "implementation", "." ]
train
https://github.com/orchestral/testbench-core/blob/598caa6f7813b8a29b2f1b69912b40659dcef79b/src/Concerns/CreatesApplication.php#L229-L239
orchestral/testbench-core
src/Concerns/CreatesApplication.php
CreatesApplication.resolveApplicationBootstrappers
protected function resolveApplicationBootstrappers($app) { $app->make('Illuminate\Foundation\Bootstrap\HandleExceptions')->bootstrap($app); $app->make('Illuminate\Foundation\Bootstrap\RegisterFacades')->bootstrap($app); $app->make('Illuminate\Foundation\Bootstrap\SetRequestForConsole')->bootstrap($app); $app->make('Illuminate\Foundation\Bootstrap\RegisterProviders')->bootstrap($app); $this->getEnvironmentSetUp($app); $app->make('Illuminate\Foundation\Bootstrap\BootProviders')->bootstrap($app); foreach ($this->getPackageBootstrappers($app) as $bootstrap) { $app->make($bootstrap)->bootstrap($app); } $app->make('Illuminate\Contracts\Console\Kernel')->bootstrap(); $app['router']->getRoutes()->refreshNameLookups(); $app->resolving('url', function ($url, $app) { $app['router']->getRoutes()->refreshNameLookups(); }); }
php
protected function resolveApplicationBootstrappers($app) { $app->make('Illuminate\Foundation\Bootstrap\HandleExceptions')->bootstrap($app); $app->make('Illuminate\Foundation\Bootstrap\RegisterFacades')->bootstrap($app); $app->make('Illuminate\Foundation\Bootstrap\SetRequestForConsole')->bootstrap($app); $app->make('Illuminate\Foundation\Bootstrap\RegisterProviders')->bootstrap($app); $this->getEnvironmentSetUp($app); $app->make('Illuminate\Foundation\Bootstrap\BootProviders')->bootstrap($app); foreach ($this->getPackageBootstrappers($app) as $bootstrap) { $app->make($bootstrap)->bootstrap($app); } $app->make('Illuminate\Contracts\Console\Kernel')->bootstrap(); $app['router']->getRoutes()->refreshNameLookups(); $app->resolving('url', function ($url, $app) { $app['router']->getRoutes()->refreshNameLookups(); }); }
[ "protected", "function", "resolveApplicationBootstrappers", "(", "$", "app", ")", "{", "$", "app", "->", "make", "(", "'Illuminate\\Foundation\\Bootstrap\\HandleExceptions'", ")", "->", "bootstrap", "(", "$", "app", ")", ";", "$", "app", "->", "make", "(", "'Ill...
Resolve application bootstrapper. @param \Illuminate\Foundation\Application $app @return void
[ "Resolve", "application", "bootstrapper", "." ]
train
https://github.com/orchestral/testbench-core/blob/598caa6f7813b8a29b2f1b69912b40659dcef79b/src/Concerns/CreatesApplication.php#L301-L323
thephpleague/uri-schemes
src/UriInfo.php
UriInfo.filterUri
private static function filterUri($uri) { if ($uri instanceof Psr7UriInterface || $uri instanceof UriInterface) { return $uri; } throw new TypeError(sprintf('The uri must be a valid URI object received `%s`', is_object($uri) ? get_class($uri) : gettype($uri))); }
php
private static function filterUri($uri) { if ($uri instanceof Psr7UriInterface || $uri instanceof UriInterface) { return $uri; } throw new TypeError(sprintf('The uri must be a valid URI object received `%s`', is_object($uri) ? get_class($uri) : gettype($uri))); }
[ "private", "static", "function", "filterUri", "(", "$", "uri", ")", "{", "if", "(", "$", "uri", "instanceof", "Psr7UriInterface", "||", "$", "uri", "instanceof", "UriInterface", ")", "{", "return", "$", "uri", ";", "}", "throw", "new", "TypeError", "(", ...
Filter the URI object. To be valid an URI MUST implement at least one of the following interface: - League\Uri\UriInterface - Psr\Http\Message\UriInterface @param mixed $uri the URI to validate @throws TypeError if the URI object does not implements the supported interfaces. @return Psr7UriInterface|UriInterface
[ "Filter", "the", "URI", "object", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/UriInfo.php#L49-L56
thephpleague/uri-schemes
src/UriInfo.php
UriInfo.normalize
private static function normalize($uri) { $uri = self::filterUri($uri); $null = $uri instanceof Psr7UriInterface ? '' : null; $path = $uri->getPath(); if ('/' === ($path[0] ?? '') || '' !== $uri->getScheme().$uri->getAuthority()) { $path = UriResolver::resolve($uri, $uri->withPath('')->withQuery($null))->getPath(); } $query = $uri->getQuery(); $fragment = $uri->getFragment(); $fragmentOrig = $fragment; $pairs = null === $query ? [] : explode('&', $query); sort($pairs, SORT_REGULAR); $replace = static function (array $matches): string { return rawurldecode($matches[0]); }; $retval = preg_replace_callback(self::REGEXP_ENCODED_CHARS, $replace, [$path, implode('&', $pairs), $fragment]); if (null !== $retval) { [$path, $query, $fragment] = $retval + ['', $null, $null]; } if ($null !== $uri->getAuthority() && '' === $path) { $path = '/'; } return $uri ->withHost(Uri::createFromComponents(['host' => $uri->getHost()])->getHost()) ->withPath($path) ->withQuery([] === $pairs ? $null : $query) ->withFragment($null === $fragmentOrig ? $fragmentOrig : $fragment); }
php
private static function normalize($uri) { $uri = self::filterUri($uri); $null = $uri instanceof Psr7UriInterface ? '' : null; $path = $uri->getPath(); if ('/' === ($path[0] ?? '') || '' !== $uri->getScheme().$uri->getAuthority()) { $path = UriResolver::resolve($uri, $uri->withPath('')->withQuery($null))->getPath(); } $query = $uri->getQuery(); $fragment = $uri->getFragment(); $fragmentOrig = $fragment; $pairs = null === $query ? [] : explode('&', $query); sort($pairs, SORT_REGULAR); $replace = static function (array $matches): string { return rawurldecode($matches[0]); }; $retval = preg_replace_callback(self::REGEXP_ENCODED_CHARS, $replace, [$path, implode('&', $pairs), $fragment]); if (null !== $retval) { [$path, $query, $fragment] = $retval + ['', $null, $null]; } if ($null !== $uri->getAuthority() && '' === $path) { $path = '/'; } return $uri ->withHost(Uri::createFromComponents(['host' => $uri->getHost()])->getHost()) ->withPath($path) ->withQuery([] === $pairs ? $null : $query) ->withFragment($null === $fragmentOrig ? $fragmentOrig : $fragment); }
[ "private", "static", "function", "normalize", "(", "$", "uri", ")", "{", "$", "uri", "=", "self", "::", "filterUri", "(", "$", "uri", ")", ";", "$", "null", "=", "$", "uri", "instanceof", "Psr7UriInterface", "?", "''", ":", "null", ";", "$", "path", ...
Normalize an URI for comparison. @param Psr7UriInterface|UriInterface $uri @return Psr7UriInterface|UriInterface
[ "Normalize", "an", "URI", "for", "comparison", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/UriInfo.php#L65-L99
thephpleague/uri-schemes
src/UriInfo.php
UriInfo.isAbsolute
public static function isAbsolute($uri): bool { $null = $uri instanceof Psr7UriInterface ? '' : null; return $null !== self::filterUri($uri)->getScheme(); }
php
public static function isAbsolute($uri): bool { $null = $uri instanceof Psr7UriInterface ? '' : null; return $null !== self::filterUri($uri)->getScheme(); }
[ "public", "static", "function", "isAbsolute", "(", "$", "uri", ")", ":", "bool", "{", "$", "null", "=", "$", "uri", "instanceof", "Psr7UriInterface", "?", "''", ":", "null", ";", "return", "$", "null", "!==", "self", "::", "filterUri", "(", "$", "uri",...
Tell whether the URI represents an absolute URI. @param Psr7UriInterface|UriInterface $uri
[ "Tell", "whether", "the", "URI", "represents", "an", "absolute", "URI", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/UriInfo.php#L106-L111
thephpleague/uri-schemes
src/UriInfo.php
UriInfo.isNetworkPath
public static function isNetworkPath($uri): bool { $uri = self::filterUri($uri); $null = $uri instanceof Psr7UriInterface ? '' : null; return $null === $uri->getScheme() && $null !== $uri->getAuthority(); }
php
public static function isNetworkPath($uri): bool { $uri = self::filterUri($uri); $null = $uri instanceof Psr7UriInterface ? '' : null; return $null === $uri->getScheme() && $null !== $uri->getAuthority(); }
[ "public", "static", "function", "isNetworkPath", "(", "$", "uri", ")", ":", "bool", "{", "$", "uri", "=", "self", "::", "filterUri", "(", "$", "uri", ")", ";", "$", "null", "=", "$", "uri", "instanceof", "Psr7UriInterface", "?", "''", ":", "null", ";...
Tell whether the URI represents a network path. @param Psr7UriInterface|UriInterface $uri
[ "Tell", "whether", "the", "URI", "represents", "a", "network", "path", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/UriInfo.php#L118-L124
thephpleague/uri-schemes
src/UriInfo.php
UriInfo.isRelativePath
public static function isRelativePath($uri): bool { $uri = self::filterUri($uri); $null = $uri instanceof Psr7UriInterface ? '' : null; return $null === $uri->getScheme() && $null === $uri->getAuthority() && '/' !== ($uri->getPath()[0] ?? ''); }
php
public static function isRelativePath($uri): bool { $uri = self::filterUri($uri); $null = $uri instanceof Psr7UriInterface ? '' : null; return $null === $uri->getScheme() && $null === $uri->getAuthority() && '/' !== ($uri->getPath()[0] ?? ''); }
[ "public", "static", "function", "isRelativePath", "(", "$", "uri", ")", ":", "bool", "{", "$", "uri", "=", "self", "::", "filterUri", "(", "$", "uri", ")", ";", "$", "null", "=", "$", "uri", "instanceof", "Psr7UriInterface", "?", "''", ":", "null", "...
Tell whether the URI represents a relative path. @param Psr7UriInterface|UriInterface $uri
[ "Tell", "whether", "the", "URI", "represents", "a", "relative", "path", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/UriInfo.php#L146-L154
thephpleague/uri-schemes
src/UriInfo.php
UriInfo.isSameDocument
public static function isSameDocument($uri, $base_uri): bool { $uri = self::normalize($uri); $base_uri = self::normalize($base_uri); return (string) $uri->withFragment($uri instanceof Psr7UriInterface ? '' : null) === (string) $base_uri->withFragment($base_uri instanceof Psr7UriInterface ? '' : null); }
php
public static function isSameDocument($uri, $base_uri): bool { $uri = self::normalize($uri); $base_uri = self::normalize($base_uri); return (string) $uri->withFragment($uri instanceof Psr7UriInterface ? '' : null) === (string) $base_uri->withFragment($base_uri instanceof Psr7UriInterface ? '' : null); }
[ "public", "static", "function", "isSameDocument", "(", "$", "uri", ",", "$", "base_uri", ")", ":", "bool", "{", "$", "uri", "=", "self", "::", "normalize", "(", "$", "uri", ")", ";", "$", "base_uri", "=", "self", "::", "normalize", "(", "$", "base_ur...
Tell whether both URI refers to the same document. @param Psr7UriInterface|UriInterface $uri @param Psr7UriInterface|UriInterface $base_uri
[ "Tell", "whether", "both", "URI", "refers", "to", "the", "same", "document", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/UriInfo.php#L162-L169
thephpleague/uri-schemes
src/Uri.php
Uri.formatScheme
private function formatScheme(?string $scheme): ?string { if ('' === $scheme || null === $scheme) { return $scheme; } $formatted_scheme = strtolower($scheme); if (1 === preg_match(self::REGEXP_SCHEME, $formatted_scheme)) { return $formatted_scheme; } throw new SyntaxError(sprintf('The scheme `%s` is invalid', $scheme)); }
php
private function formatScheme(?string $scheme): ?string { if ('' === $scheme || null === $scheme) { return $scheme; } $formatted_scheme = strtolower($scheme); if (1 === preg_match(self::REGEXP_SCHEME, $formatted_scheme)) { return $formatted_scheme; } throw new SyntaxError(sprintf('The scheme `%s` is invalid', $scheme)); }
[ "private", "function", "formatScheme", "(", "?", "string", "$", "scheme", ")", ":", "?", "string", "{", "if", "(", "''", "===", "$", "scheme", "||", "null", "===", "$", "scheme", ")", "{", "return", "$", "scheme", ";", "}", "$", "formatted_scheme", "...
Format the Scheme and Host component. @param ?string $scheme @throws SyntaxError if the scheme is invalid
[ "Format", "the", "Scheme", "and", "Host", "component", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L285-L297
thephpleague/uri-schemes
src/Uri.php
Uri.formatUserInfo
private function formatUserInfo(?string $user, ?string $password): ?string { if (null === $user) { return $user; } static $user_pattern = '/(?:[^%'.self::REGEXP_CHARS_UNRESERVED.self::REGEXP_CHARS_SUBDELIM.']++|%(?![A-Fa-f0-9]{2}))/'; $user = preg_replace_callback($user_pattern, [Uri::class, 'urlEncodeMatch'], $user); if (null === $password) { return $user; } static $password_pattern = '/(?:[^%:'.self::REGEXP_CHARS_UNRESERVED.self::REGEXP_CHARS_SUBDELIM.']++|%(?![A-Fa-f0-9]{2}))/'; return $user.':'.preg_replace_callback($password_pattern, [Uri::class, 'urlEncodeMatch'], $password); }
php
private function formatUserInfo(?string $user, ?string $password): ?string { if (null === $user) { return $user; } static $user_pattern = '/(?:[^%'.self::REGEXP_CHARS_UNRESERVED.self::REGEXP_CHARS_SUBDELIM.']++|%(?![A-Fa-f0-9]{2}))/'; $user = preg_replace_callback($user_pattern, [Uri::class, 'urlEncodeMatch'], $user); if (null === $password) { return $user; } static $password_pattern = '/(?:[^%:'.self::REGEXP_CHARS_UNRESERVED.self::REGEXP_CHARS_SUBDELIM.']++|%(?![A-Fa-f0-9]{2}))/'; return $user.':'.preg_replace_callback($password_pattern, [Uri::class, 'urlEncodeMatch'], $password); }
[ "private", "function", "formatUserInfo", "(", "?", "string", "$", "user", ",", "?", "string", "$", "password", ")", ":", "?", "string", "{", "if", "(", "null", "===", "$", "user", ")", "{", "return", "$", "user", ";", "}", "static", "$", "user_patter...
Set the UserInfo component. @param ?string $user @param ?string $password
[ "Set", "the", "UserInfo", "component", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L305-L320
thephpleague/uri-schemes
src/Uri.php
Uri.formatHost
private function formatHost(?string $host): ?string { if (null === $host || '' === $host) { return $host; } if ('[' !== $host[0]) { return $this->formatRegisteredName($host); } return $this->formatIp($host); }
php
private function formatHost(?string $host): ?string { if (null === $host || '' === $host) { return $host; } if ('[' !== $host[0]) { return $this->formatRegisteredName($host); } return $this->formatIp($host); }
[ "private", "function", "formatHost", "(", "?", "string", "$", "host", ")", ":", "?", "string", "{", "if", "(", "null", "===", "$", "host", "||", "''", "===", "$", "host", ")", "{", "return", "$", "host", ";", "}", "if", "(", "'['", "!==", "$", ...
Validate and Format the Host component. @param ?string $host
[ "Validate", "and", "Format", "the", "Host", "component", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L335-L346
thephpleague/uri-schemes
src/Uri.php
Uri.formatRegisteredName
private function formatRegisteredName(string $host): string { // @codeCoverageIgnoreStart // added because it is not possible in travis to disabled the ext/intl extension // see travis issue https://github.com/travis-ci/travis-ci/issues/4701 static $idn_support = null; $idn_support = $idn_support ?? function_exists('idn_to_ascii') && defined('INTL_IDNA_VARIANT_UTS46'); // @codeCoverageIgnoreEnd $formatted_host = rawurldecode(strtolower($host)); if (1 === preg_match(self::REGEXP_HOST_REGNAME, $formatted_host)) { if (false === strpos($formatted_host, 'xn--')) { return $formatted_host; } // @codeCoverageIgnoreStart if (!$idn_support) { throw new IdnSupportMissing(sprintf('the host `%s` could not be processed for IDN. Verify that ext/intl is installed for IDN support and that ICU is at least version 4.6.', $host)); } // @codeCoverageIgnoreEnd $unicode = idn_to_utf8( $host, IDNA_CHECK_BIDI | IDNA_CHECK_CONTEXTJ | IDNA_NONTRANSITIONAL_TO_UNICODE, INTL_IDNA_VARIANT_UTS46, $arr ); if (0 !== $arr['errors']) { throw new SyntaxError(sprintf('The host `%s` is invalid : %s', $host, $this->getIDNAErrors($arr['errors']))); } // @codeCoverageIgnoreStart if (false === $unicode) { throw new IdnSupportMissing(sprintf('The Intl extension is misconfigured for %s, please correct this issue before proceeding.', PHP_OS)); } // @codeCoverageIgnoreEnd return $formatted_host; } if (1 === preg_match(self::REGEXP_HOST_GEN_DELIMS, $formatted_host)) { throw new SyntaxError(sprintf('The host `%s` is invalid : a registered name can not contain URI delimiters or spaces', $host)); } // @codeCoverageIgnoreStart if (!$idn_support) { throw new IdnSupportMissing(sprintf('the host `%s` could not be processed for IDN. Verify that ext/intl is installed for IDN support and that ICU is at least version 4.6.', $host)); } // @codeCoverageIgnoreEnd $formatted_host = idn_to_ascii( $formatted_host, IDNA_CHECK_BIDI | IDNA_CHECK_CONTEXTJ | IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46, $arr ); if (0 !== $arr['errors']) { throw new SyntaxError(sprintf('The host `%s` is invalid : %s', $host, $this->getIDNAErrors($arr['errors']))); } // @codeCoverageIgnoreStart if (false === $formatted_host) { throw new IdnSupportMissing(sprintf('The Intl extension is misconfigured for %s, please correct this issue before proceeding.', PHP_OS)); } // @codeCoverageIgnoreEnd return $arr['result']; }
php
private function formatRegisteredName(string $host): string { // @codeCoverageIgnoreStart // added because it is not possible in travis to disabled the ext/intl extension // see travis issue https://github.com/travis-ci/travis-ci/issues/4701 static $idn_support = null; $idn_support = $idn_support ?? function_exists('idn_to_ascii') && defined('INTL_IDNA_VARIANT_UTS46'); // @codeCoverageIgnoreEnd $formatted_host = rawurldecode(strtolower($host)); if (1 === preg_match(self::REGEXP_HOST_REGNAME, $formatted_host)) { if (false === strpos($formatted_host, 'xn--')) { return $formatted_host; } // @codeCoverageIgnoreStart if (!$idn_support) { throw new IdnSupportMissing(sprintf('the host `%s` could not be processed for IDN. Verify that ext/intl is installed for IDN support and that ICU is at least version 4.6.', $host)); } // @codeCoverageIgnoreEnd $unicode = idn_to_utf8( $host, IDNA_CHECK_BIDI | IDNA_CHECK_CONTEXTJ | IDNA_NONTRANSITIONAL_TO_UNICODE, INTL_IDNA_VARIANT_UTS46, $arr ); if (0 !== $arr['errors']) { throw new SyntaxError(sprintf('The host `%s` is invalid : %s', $host, $this->getIDNAErrors($arr['errors']))); } // @codeCoverageIgnoreStart if (false === $unicode) { throw new IdnSupportMissing(sprintf('The Intl extension is misconfigured for %s, please correct this issue before proceeding.', PHP_OS)); } // @codeCoverageIgnoreEnd return $formatted_host; } if (1 === preg_match(self::REGEXP_HOST_GEN_DELIMS, $formatted_host)) { throw new SyntaxError(sprintf('The host `%s` is invalid : a registered name can not contain URI delimiters or spaces', $host)); } // @codeCoverageIgnoreStart if (!$idn_support) { throw new IdnSupportMissing(sprintf('the host `%s` could not be processed for IDN. Verify that ext/intl is installed for IDN support and that ICU is at least version 4.6.', $host)); } // @codeCoverageIgnoreEnd $formatted_host = idn_to_ascii( $formatted_host, IDNA_CHECK_BIDI | IDNA_CHECK_CONTEXTJ | IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46, $arr ); if (0 !== $arr['errors']) { throw new SyntaxError(sprintf('The host `%s` is invalid : %s', $host, $this->getIDNAErrors($arr['errors']))); } // @codeCoverageIgnoreStart if (false === $formatted_host) { throw new IdnSupportMissing(sprintf('The Intl extension is misconfigured for %s, please correct this issue before proceeding.', PHP_OS)); } // @codeCoverageIgnoreEnd return $arr['result']; }
[ "private", "function", "formatRegisteredName", "(", "string", "$", "host", ")", ":", "string", "{", "// @codeCoverageIgnoreStart", "// added because it is not possible in travis to disabled the ext/intl extension", "// see travis issue https://github.com/travis-ci/travis-ci/issues/4701", ...
Validate and format a registered name. The host is converted to its ascii representation if needed @throws IdnSupportMissing if the submitted host required missing or misconfigured IDN support @throws SyntaxError if the submitted host is not a valid registered name
[ "Validate", "and", "format", "a", "registered", "name", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L356-L424
thephpleague/uri-schemes
src/Uri.php
Uri.getIDNAErrors
private function getIDNAErrors(int $error_byte): string { $res = []; foreach (self::IDNA_ERRORS as $error => $reason) { if ($error === ($error_byte & $error)) { $res[] = $reason; } } return [] === $res ? 'Unknown IDNA conversion error.' : implode(', ', $res).'.'; }
php
private function getIDNAErrors(int $error_byte): string { $res = []; foreach (self::IDNA_ERRORS as $error => $reason) { if ($error === ($error_byte & $error)) { $res[] = $reason; } } return [] === $res ? 'Unknown IDNA conversion error.' : implode(', ', $res).'.'; }
[ "private", "function", "getIDNAErrors", "(", "int", "$", "error_byte", ")", ":", "string", "{", "$", "res", "=", "[", "]", ";", "foreach", "(", "self", "::", "IDNA_ERRORS", "as", "$", "error", "=>", "$", "reason", ")", "{", "if", "(", "$", "error", ...
Retrieves and format IDNA conversion error message. @see http://icu-project.org/apiref/icu4j/com/ibm/icu/text/IDNA.Error.html
[ "Retrieves", "and", "format", "IDNA", "conversion", "error", "message", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L431-L441
thephpleague/uri-schemes
src/Uri.php
Uri.formatIp
private function formatIp(string $host): string { $ip = substr($host, 1, -1); if (false !== filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { return $host; } if (1 === preg_match(self::REGEXP_HOST_IPFUTURE, $ip, $matches) && !in_array($matches['version'], ['4', '6'], true)) { return $host; } $pos = strpos($ip, '%'); if (false === $pos) { throw new SyntaxError(sprintf('The host `%s` is invalid : the IP host is malformed', $host)); } if (1 === preg_match(self::REGEXP_HOST_GEN_DELIMS, rawurldecode(substr($ip, $pos)))) { throw new SyntaxError(sprintf('The host `%s` is invalid : the IP host is malformed', $host)); } $ip = substr($ip, 0, $pos); if (false === filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { throw new SyntaxError(sprintf('The host `%s` is invalid : the IP host is malformed', $host)); } //Only the address block fe80::/10 can have a Zone ID attach to //let's detect the link local significant 10 bits if (0 === strpos((string) inet_pton($ip), self::HOST_ADDRESS_BLOCK)) { return $host; } throw new SyntaxError(sprintf('The host `%s` is invalid : the IP host is malformed', $host)); }
php
private function formatIp(string $host): string { $ip = substr($host, 1, -1); if (false !== filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { return $host; } if (1 === preg_match(self::REGEXP_HOST_IPFUTURE, $ip, $matches) && !in_array($matches['version'], ['4', '6'], true)) { return $host; } $pos = strpos($ip, '%'); if (false === $pos) { throw new SyntaxError(sprintf('The host `%s` is invalid : the IP host is malformed', $host)); } if (1 === preg_match(self::REGEXP_HOST_GEN_DELIMS, rawurldecode(substr($ip, $pos)))) { throw new SyntaxError(sprintf('The host `%s` is invalid : the IP host is malformed', $host)); } $ip = substr($ip, 0, $pos); if (false === filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { throw new SyntaxError(sprintf('The host `%s` is invalid : the IP host is malformed', $host)); } //Only the address block fe80::/10 can have a Zone ID attach to //let's detect the link local significant 10 bits if (0 === strpos((string) inet_pton($ip), self::HOST_ADDRESS_BLOCK)) { return $host; } throw new SyntaxError(sprintf('The host `%s` is invalid : the IP host is malformed', $host)); }
[ "private", "function", "formatIp", "(", "string", "$", "host", ")", ":", "string", "{", "$", "ip", "=", "substr", "(", "$", "host", ",", "1", ",", "-", "1", ")", ";", "if", "(", "false", "!==", "filter_var", "(", "$", "ip", ",", "FILTER_VALIDATE_IP...
Validate and Format the IPv6/IPvfuture host. @throws SyntaxError if the submitted host is not a valid IP host
[ "Validate", "and", "Format", "the", "IPv6", "/", "IPvfuture", "host", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L448-L480