_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q257100
JavascriptError.message
test
public function message() { $error = "One or more errors were raised in the Javascript code on the page. If you don't care about these errors, you can ignore them by setting js_errors: false in your Poltergeist configuration (see documentation for details)."; //TODO: add javascript errors $jsErrors = $this->javascriptErrors(); foreach($jsErrors as $jsError){ $error = "$error\n$jsError"; } return $error; }
php
{ "resource": "" }
q257101
TrieCompiler.compileNode
test
private function compileNode( bool $isCompilingHostTrie, TrieNode $currTrieNode, AstNode $ast, Route $route, ?TrieNode $hostTrie ): void { $astChildren = $ast->children; $numAstChildren = \count($astChildren); $isEndpoint = false; $segmentContainsVariable = false; $segmentBuffer = []; foreach ($isCompilingHostTrie ? \array_reverse($astChildren) : $astChildren as $i => $childAstNode) { /** * This isn't an endpoint if we're compiling a path trie which has a host trie * This is an endpoint if it's the last node or the last non-optional node */ $isEndpoint = $isEndpoint || ( ($isCompilingHostTrie || $hostTrie === null) && ( $i === $numAstChildren - 1 || $childAstNode->type === AstNodeTypes::OPTIONAL_ROUTE_PART || ($astChildren[$i + 1]->type === AstNodeTypes::OPTIONAL_ROUTE_PART) ) ); switch ($childAstNode->type) { case AstNodeTypes::SEGMENT_DELIMITER: // Checking if this is an endpoint handles the case of a route at the root path if ($isEndpoint || \count($segmentBuffer) > 0) { $newTrieNode = self::createTrieNode( $segmentBuffer, $segmentContainsVariable, $isEndpoint, $route, $hostTrie ); $currTrieNode->addChild($newTrieNode); $currTrieNode = $newTrieNode; } break; case AstNodeTypes::OPTIONAL_ROUTE_PART: // Handles flushing 'foo' in the case of 'foo[/bar]' if (\count($segmentBuffer) > 0) { $newTrieNode = self::createTrieNode( $segmentBuffer, $segmentContainsVariable, $isEndpoint, $route, $hostTrie ); $currTrieNode->addChild($newTrieNode); $currTrieNode = $newTrieNode; } $this->compileNode($isCompilingHostTrie, $currTrieNode, $childAstNode, $route, $hostTrie); break; case AstNodeTypes::TEXT: $segmentBuffer[] = $childAstNode->value; break; case AstNodeTypes::VARIABLE: $segmentContainsVariable = true; $segmentBuffer[] = $this->compileVariableNode($childAstNode); break; default: throw new InvalidArgumentException("Unexpected node type {$childAstNode->type}"); } } // Check if we need to flush the buffer if (\count($segmentBuffer) > 0) { $currTrieNode->addChild( self::createTrieNode($segmentBuffer, $segmentContainsVariable, $isEndpoint, $route, $hostTrie) ); } }
php
{ "resource": "" }
q257102
TrieCompiler.compileVariableNode
test
private function compileVariableNode(AstNode $astNode): RouteVariable { $rules = []; foreach ($astNode->children as $childAstNode) { if ($childAstNode->type !== AstNodeTypes::VARIABLE_RULE) { throw new InvalidArgumentException("Unexpected node type {$childAstNode->type}"); } $ruleParams = $childAstNode->hasChildren() ? $childAstNode->children[0]->value : []; $rules[] = $this->ruleFactory->createRule($childAstNode->value, $ruleParams); } return new RouteVariable($astNode->value, $rules); }
php
{ "resource": "" }
q257103
TrieCompiler.createTrieNode
test
private static function createTrieNode( array &$segmentBuffer, bool &$segmentContainsVariable, bool $isEndpoint, Route $route, ?TrieNode $hostTrie ): TrieNode { $routes = $isEndpoint ? $route : []; if ($segmentContainsVariable) { $node = new VariableTrieNode($segmentBuffer, [], $routes, $hostTrie); } else { $node = new LiteralTrieNode(\implode('', $segmentBuffer), [], $routes, $hostTrie); } // Clear the buffer data $segmentBuffer = []; $segmentContainsVariable = false; return $node; }
php
{ "resource": "" }
q257104
UriTemplateLexer.flushTextBuffer
test
private static function flushTextBuffer(string &$textBuffer, array &$tokens): void { if ($textBuffer !== '') { $tokens[] = new Token(TokenTypes::T_TEXT, $textBuffer); $textBuffer = ''; } }
php
{ "resource": "" }
q257105
UriTemplateLexer.lexNumber
test
private static function lexNumber(string $number, array &$tokens, int &$cursor): void { $floatVal = (float)$number; $intVal = (int)$number; // Determine if this was a float or not if ($floatVal && $intVal != $floatVal) { $tokens[] = new Token(TokenTypes::T_NUMBER, $floatVal); } else { $tokens[] = new Token(TokenTypes::T_NUMBER, $intVal); } $cursor += \mb_strlen($number); }
php
{ "resource": "" }
q257106
UriTemplateLexer.lexPunctuation
test
private static function lexPunctuation(string $punctuation, array &$tokens, int &$cursor): void { $tokens[] = new Token(TokenTypes::T_PUNCTUATION, $punctuation); $cursor++; }
php
{ "resource": "" }
q257107
UriTemplateLexer.lexQuotedString
test
private static function lexQuotedString(string $quotedString, array &$tokens, int &$cursor): void { $tokens[] = new Token(TokenTypes::T_QUOTED_STRING, \stripcslashes(\substr(\trim($quotedString), 1, -1))); $cursor += \mb_strlen($quotedString); }
php
{ "resource": "" }
q257108
UriTemplateLexer.lexTextChar
test
private static function lexTextChar(string $char, string &$textBuffer, int &$cursor): void { $textBuffer .= $char; $cursor++; }
php
{ "resource": "" }
q257109
UriTemplateLexer.lexVariableName
test
private static function lexVariableName(string $variableName, array &$tokens, int &$cursor): void { // Remove the colon before the variable name $trimmedVariableName = \substr($variableName, 1); if (\mb_strlen($trimmedVariableName) > self::VARIABLE_NAME_MAX_LENGTH) { throw new InvalidArgumentException("Variable name \"$trimmedVariableName\" exceeds the max length limit"); } $tokens[] = new Token(TokenTypes::T_VARIABLE, $trimmedVariableName); // We have to advance the cursor the length of the untrimmed variable name $cursor += \mb_strlen($variableName); }
php
{ "resource": "" }
q257110
RouteCollection.add
test
public function add(Route $route): void { $this->routes[] = $route; if ($route->name !== null) { $this->namedRoutes[$route->name] =& $route; } }
php
{ "resource": "" }
q257111
RouteCollection.getNamedRoute
test
public function getNamedRoute(string $name): ?Route { if (!isset($this->namedRoutes[$name])) { return null; } return $this->namedRoutes[$name]; }
php
{ "resource": "" }
q257112
TrieFactory.createTrie
test
public function createTrie(): TrieNode { if ($this->trieCache !== null && ($trie = $this->trieCache->get()) !== null) { return $trie; } // Need to generate the trie $trie = new RootTrieNode(); foreach ($this->routeFactory->createRoutes()->getAll() as $route) { foreach ($this->trieCompiler->compile($route)->getAllChildren() as $childNode) { $trie->addChild($childNode); } } // Save this to cache for next time if ($this->trieCache !== null) { $this->trieCache->set($trie); } return $trie; }
php
{ "resource": "" }
q257113
RequestHeaderParser.normalizeName
test
private static function normalizeName($name): string { $dashedName = \str_replace('_', '-', $name); if (\stripos($dashedName, 'HTTP-') === 0) { $dashedName = \substr($dashedName, 5); } return $dashedName; }
php
{ "resource": "" }
q257114
TokenStream.expect
test
public function expect(string $type, $value = null, string $message = null): void { if ($this->test($type, $value)) { return; } $currentToken = $this->getCurrent(); if ($message === null) { // Let's create a default message $formattedMessage = \sprintf( 'Expected token type %s%s', $type, $value === null ? '' : " with value \"$value\"" ); if ($currentToken === null) { $formattedMessage .= ', got end of stream'; } else { $formattedMessage .= \sprintf( ', got %s with value \"%s\"', $currentToken->type, $currentToken->value ); } } else { $formattedMessage = \sprintf( $message, $currentToken === null ? 'T_EOF' : $currentToken->type, $currentToken === null ? 'end of stream' : $currentToken->value ); } throw new InvalidArgumentException($formattedMessage); }
php
{ "resource": "" }
q257115
TokenStream.getCurrent
test
public function getCurrent(): ?Token { return \count($this->tokens) > $this->cursor ? $this->tokens[$this->cursor] : null; }
php
{ "resource": "" }
q257116
TokenStream.next
test
public function next(): ?Token { return \count($this->tokens) > ++$this->cursor ? $this->tokens[$this->cursor] : null; }
php
{ "resource": "" }
q257117
TokenStream.nextIfType
test
public function nextIfType(string $type, $value = null): bool { $currentToken = $this->getCurrent(); $typeMatches = $currentToken !== null && $currentToken->type === $type; if ($typeMatches && ($value === null || $currentToken->value === $value)) { $this->next(); return true; } return false; }
php
{ "resource": "" }
q257118
TokenStream.peek
test
public function peek(int $lookahead = 1): ?Token { if ($this->cursor + $lookahead >= \count($this->tokens)) { return null; } return $this->tokens[$this->cursor + $lookahead]; }
php
{ "resource": "" }
q257119
AstNode.addChild
test
public function addChild(AstNode $node): AstNode { $node->parent = $this; $this->children[] = $node; return $this; }
php
{ "resource": "" }
q257120
TrieNode.addChild
test
public function addChild(TrieNode $childNode): self { if ($childNode instanceof LiteralTrieNode) { $this->addLiteralChildNode($childNode); } elseif ($childNode instanceof VariableTrieNode) { $this->addVariableChildNode($childNode); } else { throw new InvalidArgumentException('Unexpected trie node type ' . \get_class($childNode)); } return $this; }
php
{ "resource": "" }
q257121
TrieNode.getAllChildren
test
public function getAllChildren(): array { $children = []; foreach ($this->literalChildrenByValue as $childNode) { $children[] = $childNode; } foreach ($this->variableChildren as $childNode) { $children[] = $childNode; } return $children; }
php
{ "resource": "" }
q257122
TrieNode.addLiteralChildNode
test
private function addLiteralChildNode(LiteralTrieNode $childNode): void { // Stringify the value in case it's a number and we don't want PHP getting confused $valueAsString = \strtolower((string)$childNode->value); if (isset($this->literalChildrenByValue[$valueAsString])) { // A literal child already exists with this value, so merge the routes and add all its children $matchingChildNode = $this->literalChildrenByValue[$valueAsString]; $matchingChildNode->routes = \array_merge( $matchingChildNode->routes, $childNode->routes ); foreach ($childNode->getAllChildren() as $grandChildNode) { $matchingChildNode->addChild($grandChildNode); } } else { $this->literalChildrenByValue[$valueAsString] = $childNode; } }
php
{ "resource": "" }
q257123
TrieNode.addVariableChildNode
test
private function addVariableChildNode(VariableTrieNode $childNode): void { // Try to find a variable child whose parts match the input child's parts // If we find one, then we merge its routes and add all its children $matchingChildNode = null; foreach ($this->variableChildren as $variableChildNode) { // Purposely doing a loose check here because we don't care about reference equality if ($variableChildNode->parts == $childNode->parts) { $matchingChildNode = $variableChildNode; $variableChildNode->routes = \array_merge($variableChildNode->routes, $childNode->routes); break; } } if ($matchingChildNode === null) { $this->variableChildren[] = $childNode; } else { foreach ($childNode->getAllChildren() as $grandChildNode) { $matchingChildNode->addChild($grandChildNode); } } }
php
{ "resource": "" }
q257124
RouteBuilderRegistry.buildAll
test
public function buildAll(): array { $builtRoutes = []; foreach ($this->routeBuilders as $routeBuilder) { $builtRoutes[] = $routeBuilder->build(); } return $builtRoutes; }
php
{ "resource": "" }
q257125
RouteBuilderRegistry.group
test
public function group(RouteGroupOptions $groupOptions, Closure $callback): void { $this->groupOptionsStack[] = $groupOptions; $callback($this); \array_pop($this->groupOptionsStack); }
php
{ "resource": "" }
q257126
RouteBuilderRegistry.map
test
public function map( $httpMethods, string $pathTemplate, string $hostTemplate = null, bool $isHttpsOnly = false ): RouteBuilder { $this->applyGroupRouteTemplates($pathTemplate, $hostTemplate, $isHttpsOnly); $routeBuilder = new RouteBuilder( (array)$httpMethods, new UriTemplate($pathTemplate, $hostTemplate, $isHttpsOnly) ); $this->applyGroupConstraints($routeBuilder); $this->applyGroupMiddleware($routeBuilder); $this->applyGroupAttributes($routeBuilder); $this->routeBuilders[] = $routeBuilder; return $routeBuilder; }
php
{ "resource": "" }
q257127
RouteBuilderRegistry.applyGroupAttributes
test
private function applyGroupAttributes(RouteBuilder $routeBuilder): void { $groupAttributes = []; foreach ($this->groupOptionsStack as $groupOptions) { $groupAttributes = \array_merge($groupAttributes, $groupOptions->attributes); } $routeBuilder->withManyAttributes($groupAttributes); }
php
{ "resource": "" }
q257128
RouteBuilderRegistry.applyGroupConstraints
test
private function applyGroupConstraints(RouteBuilder $routeBuilder): void { $groupConstraintBindings = []; foreach ($this->groupOptionsStack as $groupOptions) { $groupConstraintBindings = \array_merge($groupConstraintBindings, $groupOptions->constraints); } $routeBuilder->withManyConstraints($groupConstraintBindings); }
php
{ "resource": "" }
q257129
RouteBuilderRegistry.applyGroupMiddleware
test
private function applyGroupMiddleware(RouteBuilder $routeBuilder): void { $groupMiddlewareBindings = []; foreach ($this->groupOptionsStack as $groupOptions) { $groupMiddlewareBindings = \array_merge($groupMiddlewareBindings, $groupOptions->middlewareBindings); } $routeBuilder->withManyMiddleware($groupMiddlewareBindings); }
php
{ "resource": "" }
q257130
RouteBuilderRegistry.applyGroupRouteTemplates
test
private function applyGroupRouteTemplates( string &$pathTemplate, string &$hostTemplate = null, bool &$isHttpsOnly = false ): void { $groupPathTemplate = ''; $groupHostTemplate = ''; $groupIsHttpsOnly = false; foreach ($this->groupOptionsStack as $groupOptions) { $groupPathTemplate .= $groupOptions->pathTemplate; $groupHostTemplate = $groupOptions->hostTemplate . $groupHostTemplate; $groupIsHttpsOnly = $groupIsHttpsOnly || $groupOptions->isHttpsOnly; } $pathTemplate = $groupPathTemplate . $pathTemplate; $hostTemplate = ($hostTemplate ?? '') . $groupHostTemplate; $isHttpsOnly = $isHttpsOnly || $groupIsHttpsOnly; }
php
{ "resource": "" }
q257131
RuleFactoryRegistrant.registerRuleFactories
test
public function registerRuleFactories(IRuleFactory $ruleFactory): IRuleFactory { $ruleFactory->registerRuleFactory(AlphaRule::getSlug(), function () { return new AlphaRule(); }); $ruleFactory->registerRuleFactory(AlphanumericRule::getSlug(), function () { return new AlphanumericRule(); }); $ruleFactory->registerRuleFactory(BetweenRule::getSlug(), function ($min, $max, bool $isInclusive = true) { return new BetweenRule($min, $max, $isInclusive); }); $ruleFactory->registerRuleFactory(DateRule::getSlug(), function ($formats) { return new DateRule($formats); }); $ruleFactory->registerRuleFactory(InRule::getSlug(), function (array $acceptableValues) { return new InRule($acceptableValues); }); $ruleFactory->registerRuleFactory(IntegerRule::getSlug(), function () { return new IntegerRule(); }); $ruleFactory->registerRuleFactory(NotInRule::getSlug(), function (array $unacceptableValues) { return new NotInRule($unacceptableValues); }); $ruleFactory->registerRuleFactory(NumericRule::getSlug(), function () { return new NumericRule(); }); $ruleFactory->registerRuleFactory(RegexRule::getSlug(), function (string $regex) { return new RegexRule($regex); }); $ruleFactory->registerRuleFactory(UuidV4Rule::getSlug(), function () { return new UuidV4Rule(); }); return $ruleFactory; }
php
{ "resource": "" }
q257132
TrieRouteMatcher.getMatchCandidates
test
private static function getMatchCandidates( TrieNode $node, array $segments, int $segmentIter, array $hostSegments, array &$routeVars ): iterable { // Base case. We iterate to 1 past the past segments there are n + 1 levels of nodes due to the root node. if ($segmentIter === \count($segments)) { if ($node->hostTrie === null) { foreach ($node->routes as $route) { yield new MatchedRouteCandidate($route, $routeVars); } } else { // We have to traverse the host trie now $routeVarsCopy = $routeVars; yield from self::getMatchCandidates($node->hostTrie, $hostSegments, 0, $hostSegments, $routeVarsCopy); } return; } $segment = $segments[$segmentIter]; // Check for a literal segment match, and recursively check its descendants if (($childNode = ($node->literalChildrenByValue[\strtolower($segment)] ?? null)) !== null) { $routeVarsCopy = $routeVars; yield from self::getMatchCandidates($childNode, $segments, $segmentIter + 1, $hostSegments, $routeVarsCopy); } // If a variable child is a match, check its descendants foreach ($node->variableChildren as $childNode) { $routeVarsCopy = $routeVars; if ($childNode->isMatch($segment, $routeVarsCopy)) { yield from self::getMatchCandidates( $childNode, $segments, $segmentIter + 1, $hostSegments, $routeVarsCopy ); } } }
php
{ "resource": "" }
q257133
RouteBuilder.build
test
public function build(): Route { if ($this->action === null) { throw new LogicException('No controller specified for route'); } return new Route( $this->uriTemplate, $this->action, $this->constraints, $this->middlewareBindings, $this->name, $this->attributes ); }
php
{ "resource": "" }
q257134
RouteBuilder.toMethod
test
public function toMethod(string $controllerClassName, string $controllerMethodName): self { $this->action = new MethodRouteAction($controllerClassName, $controllerMethodName); return $this; }
php
{ "resource": "" }
q257135
RouteBuilder.withAttribute
test
public function withAttribute(string $name, $value): self { $this->attributes[$name] = $value; return $this; }
php
{ "resource": "" }
q257136
RouteBuilder.withManyAttributes
test
public function withManyAttributes(array $attributes): self { $this->attributes = \array_merge($this->attributes, $attributes); return $this; }
php
{ "resource": "" }
q257137
RouteBuilder.withManyConstraints
test
public function withManyConstraints(array $constraints): self { $this->constraints = \array_merge($this->constraints, $constraints); return $this; }
php
{ "resource": "" }
q257138
RouteBuilder.withManyMiddleware
test
public function withManyMiddleware(array $middlewareBindings): self { foreach ($middlewareBindings as $middlewareBinding) { if (\is_string($middlewareBinding)) { $this->middlewareBindings[] = new MiddlewareBinding($middlewareBinding); } elseif ($middlewareBinding instanceof MiddlewareBinding) { $this->middlewareBindings[] = $middlewareBinding; } else { throw new InvalidArgumentException( 'Middleware binding must either be a string or an instance of ' . MiddlewareBinding::class ); } } return $this; }
php
{ "resource": "" }
q257139
RouteBuilder.withMiddleware
test
public function withMiddleware(string $middlewareClassName, array $middlewareProperties = []): self { $this->middlewareBindings[] = new MiddlewareBinding($middlewareClassName, $middlewareProperties); return $this; }
php
{ "resource": "" }
q257140
UriTemplateParser.parsePunctuation
test
private function parsePunctuation(TokenStream $tokens, AstNode &$currNode, bool $parsingPath): void { if (($token = $tokens->getCurrent()) === null) { return; } switch ($token->value) { case '/': if (!$parsingPath) { throw new InvalidArgumentException("Unexpected {$token->type} \"{$token->value}\" in host"); } $currNode->addChild(new AstNode(AstNodeTypes::SEGMENT_DELIMITER, $token->value)); $tokens->next(); break; case '.': // Periods in paths are to be treated as just text $nodeType = $parsingPath ? AstNodeTypes::TEXT : AstNodeTypes::SEGMENT_DELIMITER; $currNode->addChild(new AstNode($nodeType, $token->value)); $tokens->next(); break; case '[': $parentNodeType = $currNode->type; if ( $parentNodeType !== AstNodeTypes::HOST && $parentNodeType !== AstNodeTypes::PATH && $parentNodeType !== AstNodeTypes::OPTIONAL_ROUTE_PART ) { throw new InvalidArgumentException("Unexpected {$token->type} \"{$token->value}\""); } $optionalRoutePartNode = new AstNode(AstNodeTypes::OPTIONAL_ROUTE_PART, $token->value); $currNode->addChild($optionalRoutePartNode); $currNode = $optionalRoutePartNode; $tokens->next(); if ($parsingPath) { $tokens->expect( TokenTypes::T_PUNCTUATION, '/', 'Expected optional path part to start with \'/\', got %s' ); } break; case ']': if ($currNode->type !== AstNodeTypes::OPTIONAL_ROUTE_PART) { // Just treat this as normal text $currNode->addChild(new AstNode(AstNodeTypes::TEXT, $token->value)); $tokens->next(); break; } if (!$parsingPath) { /** * Optional parts in hosts must end with '.', eg [foo.[bar.]]example.com * So, make sure that the previous non-optional route part ends with '.' */ $isValid = false; for ($i = \count($currNode->children) - 1;$i >= 0;$i--) { $childNode = $currNode->children[$i]; if ($childNode->type !== AstNodeTypes::OPTIONAL_ROUTE_PART) { if ($childNode->type === AstNodeTypes::SEGMENT_DELIMITER) { $isValid = true; } break; } } if (!$isValid) { throw new InvalidArgumentException('Expected optional host part to end with \'.\''); } } // End this optional route part $currNode = $currNode->parent; $tokens->next(); break; default: // Since we handle punctuation inside of variables elsewhere, we'll just treat this as text $currNode->addChild(new AstNode(AstNodeTypes::TEXT, $token->value)); $tokens->next(); break; } }
php
{ "resource": "" }
q257141
UriTemplateParser.parseText
test
private function parseText(TokenStream $tokens, AstNode $currNode): void { if (($token = $tokens->getCurrent()) === null) { return; } $currNode->addChild(new AstNode(AstNodeTypes::TEXT, $token->value)); $tokens->next(); }
php
{ "resource": "" }
q257142
UriTemplateParser.parseTokens
test
private function parseTokens(TokenStream $tokens, AstNode $ast): void { $parsingPath = $ast->type === AstNodeTypes::PATH; $currNode = $ast; while (($token = $tokens->getCurrent()) !== null) { switch ($token->type) { case TokenTypes::T_TEXT: $this->parseText($tokens, $currNode); break; case TokenTypes::T_NUMBER: // Since we handle a number inside of variables elsewhere, we'll just treat this as text $this->parseText($tokens, $currNode); break; case TokenTypes::T_VARIABLE: $this->parseVariable($tokens, $currNode); break; case TokenTypes::T_PUNCTUATION: $this->parsePunctuation($tokens, $currNode, $parsingPath); break; case TokenTypes::T_QUOTED_STRING: // Since we handle a quoted string inside of variables elsewhere, we'll just treat this as text $this->parseText($tokens, $currNode); break; } } }
php
{ "resource": "" }
q257143
UriTemplateParser.parseVariable
test
private function parseVariable(TokenStream $tokens, AstNode &$currNode): void { if (($token = $tokens->getCurrent()) === null) { return; } $variableNode = new AstNode(AstNodeTypes::VARIABLE, $token->value); $currNode->addChild($variableNode); $currNode = $variableNode; $tokens->next(); // Check for the beginning of a rule list if ($tokens->nextIfType(TokenTypes::T_PUNCTUATION, '(')) { // Parse all variable rules do { $this->parseVariableRule($tokens, $variableNode); } while ($tokens->nextIfType(TokenTypes::T_PUNCTUATION, ',')); $tokens->expect(TokenTypes::T_PUNCTUATION, ')', 'Expected closing parenthesis after rules, got %s'); $tokens->next(); } if ($tokens->test(TokenTypes::T_VARIABLE)) { throw new InvalidArgumentException('Cannot have consecutive variables without a delimiter'); } $currNode = $currNode->parent; }
php
{ "resource": "" }
q257144
UriTemplateParser.parseVariableRule
test
private function parseVariableRule(TokenStream $tokens, AstNode $currNode): void { // Expect a rule name $tokens->expect(TokenTypes::T_TEXT, null, 'Expected rule name, got %s'); if (($token = $tokens->getCurrent()) === null) { return; } $variableRuleNode = new AstNode(AstNodeTypes::VARIABLE_RULE, $token->value); $tokens->next(); // Check for a parameter list for this rule if ($tokens->nextIfType(TokenTypes::T_PUNCTUATION, '(')) { $parameters = []; $currentToken = $tokens->getCurrent(); while ($currentToken !== null && !$tokens->test(TokenTypes::T_PUNCTUATION, ')')) { if (!$tokens->test(TokenTypes::T_PUNCTUATION, ',')) { $parameters[] = $currentToken->value; } $currentToken = $tokens->next(); } $variableRuleNode->addChild(new AstNode(AstNodeTypes::VARIABLE_RULE_PARAMETERS, $parameters)); $tokens->expect( TokenTypes::T_PUNCTUATION, ')', 'Expected closing parenthesis after rule parameters, got %s' ); $tokens->next(); } $currNode->addChild($variableRuleNode); }
php
{ "resource": "" }
q257145
VariableTrieNode.isMatch
test
public function isMatch(string $segmentValue, array &$routeVariables): bool { if ($this->onlyContainsVariable) { foreach ($this->parts[0]->rules as $rule) { if (!$rule->passes($segmentValue)) { return false; } } $routeVariables[$this->parts[0]->name] = $segmentValue; return true; } $matches = []; if (\preg_match($this->regex, $segmentValue, $matches, PREG_UNMATCHED_AS_NULL) !== 1) { return false; } // Don't change the actual array until we're sure all the rules pass $routeVariablesCopy = $routeVariables; foreach ($this->parts as $part) { if ($part instanceof RouteVariable) { foreach ($part->rules as $rule) { if (!$rule->passes($matches[$part->name])) { return false; } } $routeVariablesCopy[$part->name] = $matches[$part->name]; } } $routeVariables = $routeVariablesCopy; return true; }
php
{ "resource": "" }
q257146
Router.group
test
public function group(array $attributes, Closure $routes): Router { // Backup current properties $oldName = $this->currentName; $oldMiddleware = $this->currentMiddleware; $oldNamespace = $this->currentNamespace; $oldPrefix = $this->currentPrefix; $oldDomain = $this->currentDomain; $this->currentName = null; // Set middleware for the group if (isset($attributes[GroupAttributes::MIDDLEWARE])) { if (is_array($attributes[Route::MIDDLEWARE]) == false) { $attributes[GroupAttributes::MIDDLEWARE] = [$attributes[GroupAttributes::MIDDLEWARE]]; } $this->currentMiddleware = array_merge($attributes[GroupAttributes::MIDDLEWARE], $this->currentMiddleware); } // Set namespace for the group if (isset($attributes[GroupAttributes::NAMESPACE])) { $this->currentNamespace = $attributes[GroupAttributes::NAMESPACE]; } // Set prefix for the group if (isset($attributes[GroupAttributes::PREFIX])) { $this->currentPrefix = $this->currentPrefix.$attributes[GroupAttributes::PREFIX]; } // Set domain for the group if (isset($attributes[GroupAttributes::DOMAIN])) { $this->currentDomain = $attributes[GroupAttributes::DOMAIN]; } // Run the group body closure call_user_func($routes, $this); // Restore properties $this->currentName = $oldName; $this->currentDomain = $oldDomain; $this->currentPrefix = $oldPrefix; $this->currentMiddleware = $oldMiddleware; $this->currentNamespace = $oldNamespace; return $this; }
php
{ "resource": "" }
q257147
Router.map
test
public function map( ?string $method, string $route, $controller, $middleware = [], string $domain = null, string $name = null ): Router { $name = $name ?: $this->currentName; $uri = $this->currentPrefix.$route; $middleware = is_array($middleware) ? $middleware : [$middleware]; if (is_string($controller) && is_callable($controller) == false) { $controller = $this->currentNamespace."\\".$controller; } $route = new Route( $name, $uri, $method, $controller, array_merge($this->currentMiddleware, $middleware), $domain ?: $this->currentDomain ); $this->routes[] = $route; if ($name) { $this->names[$name] = $route; $this->currentName = null; } return $this; }
php
{ "resource": "" }
q257148
Router.dispatch
test
public function dispatch(): Router { $this->prepare(); $method = $this->request->getMethod(); $scheme = $this->request->getUri()->getScheme(); $domain = substr($this->request->getUri()->getHost(), strlen($scheme.'://')); $uri = $this->request->getUri()->getPath(); sort($this->routes, SORT_DESC); foreach ($this->routes as $route) { $parameters = []; if ( $this->compareMethod($route->getMethod(), $method) && $this->compareDomain($route->getDomain(), $domain) && $this->compareUri($route->getUri(), $uri, $parameters) ) { $this->currentRoute = $route; $this->publisher->publish($this->run($route, $parameters)); return $this; } } throw new RouteNotFoundException(); }
php
{ "resource": "" }
q257149
Router.compareMethod
test
private function compareMethod(?string $routeMethod, string $requestMethod): bool { return $routeMethod == null || $routeMethod == $requestMethod; }
php
{ "resource": "" }
q257150
Router.compareDomain
test
private function compareDomain(?string $routeDomain, string $requestDomain): bool { return $routeDomain == null || preg_match('@^'.$routeDomain.'$@', $requestDomain); }
php
{ "resource": "" }
q257151
Router.compareUri
test
private function compareUri(string $routeUri, string $requestUri, array &$parameters): bool { $pattern = '@^'.$this->regexUri($routeUri).'$@'; return preg_match($pattern, $requestUri, $parameters); }
php
{ "resource": "" }
q257152
Router.run
test
private function run(Route $route, array $parameters) { $controller = $route->getController(); if (count($middleware = $route->getMiddleware()) > 0) { $controllerRunner = function (ServerRequest $request) use ($controller, $parameters) { return $this->runController($controller, $parameters, $request); }; return $this->runControllerThroughMiddleware($middleware, $this->request, $controllerRunner); } else { return $this->runController($controller, $parameters, $this->request); } }
php
{ "resource": "" }
q257153
Router.arrangeMethodParameters
test
private function arrangeMethodParameters( string $class, string $method, array $parameters, ServerRequestInterface $request ) { return $this->arrangeParameters(new ReflectionMethod($class, $method), $parameters, $request); }
php
{ "resource": "" }
q257154
Router.regexUri
test
private function regexUri(string $route): string { return preg_replace_callback('@{([^}]+)}@', function (array $match) { return $this->regexParameter($match[1]); }, $route); }
php
{ "resource": "" }
q257155
Router.regexParameter
test
private function regexParameter(string $name): string { if ($name[-1] == '?') { $name = substr($name, 0, -1); $suffix = '?'; } else { $suffix = ''; } $pattern = $this->parameters[$name] ?? '[^/]+'; return '(?<'.$name.'>'.$pattern.')'.$suffix; }
php
{ "resource": "" }
q257156
Router.any
test
public function any( string $route, $controller, $middleware = [], string $domain = null, string $name = null ): Router { return $this->map(null, $route, $controller, $middleware, $domain, $name); }
php
{ "resource": "" }
q257157
Router.define
test
public function define(string $name, string $pattern): Router { $this->parameters[$name] = $pattern; return $this; }
php
{ "resource": "" }
q257158
Router.url
test
public function url(string $routeName, array $parameters = []): ?string { if (isset($this->names[$routeName]) == false) { return null; } $uri = $this->names[$routeName]->getUri(); foreach ($parameters as $name => $value) { $uri = preg_replace('/\??\{'.$name.'\??\}/', $value, $uri); } $uri = preg_replace('/{[^\}]+\?\}/', '', $uri); $uri = str_replace('/?', '', $uri); return $uri; }
php
{ "resource": "" }
q257159
Router.prepare
test
private function prepare(): void { if ($this->request == null) { $this->request = ServerRequestFactory::fromGlobals(); } if ($this->publisher == null) { $this->publisher = new Publisher(); } }
php
{ "resource": "" }
q257160
GoogleProvider.getUri
test
private function getUri(array $parameters = array()) { if ($this->apiKey) { $parameters = array_merge($parameters, array('key' => $this->apiKey)); } if (0 === count($parameters)) { return; } return sprintf('?%s', http_build_query($parameters)); }
php
{ "resource": "" }
q257161
WechatProvider.validate
test
private function validate($apiRawResponse) { $response = json_decode($apiRawResponse); if (null === $response) { throw new InvalidApiResponseException('Wechat response is probably mal-formed because cannot be json-decoded.'); } if (!property_exists($response, 'errcode')) { throw new InvalidApiResponseException('Property "errcode" does not exist within Wechat response.'); } if (0 !== $response->errcode) { throw new InvalidApiResponseException(sprintf('Wechat returned status code "%s" with message "%s"', $response->errcode, property_exists($response, 'errmsg') ? $response->errmsg : '' )); } return $response; }
php
{ "resource": "" }
q257162
BitlyProvider.validate
test
private function validate($apiRawResponse) { $response = json_decode($apiRawResponse); if (null === $response) { throw new InvalidApiResponseException('Bit.ly response is probably mal-formed because cannot be json-decoded.'); } if (!property_exists($response, 'status_code')) { throw new InvalidApiResponseException('Property "status_code" does not exist within Bit.ly response.'); } if (200 !== $response->status_code) { throw new InvalidApiResponseException(sprintf('Bit.ly returned status code "%s" with message "%s"', $response->status_code, property_exists($response, 'status_txt') ? $response->status_txt : '' )); } return $response; }
php
{ "resource": "" }
q257163
SinaProvider.validate
test
private function validate($apiRawResponse) { $response = json_decode($apiRawResponse); if (null === $response) { throw new InvalidApiResponseException('Sina response is probably mal-formed because cannot be json-decoded.'); } if (property_exists($response, 'error')) { throw new InvalidApiResponseException(sprintf( 'Sina returned status code "%s" with message "%s".', property_exists($response, 'error_code') ? $response->error_code : '', property_exists($response, 'error') ? $response->error : '' )); } if (property_exists($response, 'urls')) { if (empty($response->urls[0]->url_long)) { throw new InvalidApiResponseException('Property "longUrl" does not exist within Sina response.'); } } return $response; }
php
{ "resource": "" }
q257164
ChainProvider.getProvider
test
public function getProvider($name) { if (!$this->hasProvider($name)) { throw new \RuntimeException(sprintf('Unable to retrieve the provider named: "%s"', $name)); } return $this->providers[$name]; }
php
{ "resource": "" }
q257165
ETag.handle
test
public function handle(Request $request, Closure $next) { // If this was not a get or head request, just return if (!$request->isMethod('get') && !$request->isMethod('head')) { return $next($request); } // Get the initial method sent by client $initialMethod = $request->method(); // Force to get in order to receive content $request->setMethod('get'); // Get response $response = $next($request); // Generate Etag $etag = md5(json_encode($response->headers->get('origin')).$response->getContent()); // Load the Etag sent by client $requestEtag = str_replace('"', '', $request->getETags()); // Check to see if Etag has changed if ($requestEtag && $requestEtag[0] == $etag) { $response->setNotModified(); } // Set Etag $response->setEtag($etag); // Set back to original method $request->setMethod($initialMethod); // set back to original method // Send response return $response; }
php
{ "resource": "" }
q257166
IPinfo.getDetails
test
public function getDetails($ip_address = null) { $response_details = $this->getRequestDetails((string) $ip_address); return $this->formatDetailsObject($response_details); }
php
{ "resource": "" }
q257167
IPinfo.formatDetailsObject
test
public function formatDetailsObject($details = []) { $country = $details['country'] ?? null; $details['country_name'] = $this->countries[$country] ?? null; if (array_key_exists('loc', $details)) { $coords = explode(',', $details['loc']); $details['latitude'] = $coords[0]; $details['longitude'] = $coords[1]; } else { $details['latitude'] = null; $details['longitude'] = null; } return new Details($details); }
php
{ "resource": "" }
q257168
IPinfo.getRequestDetails
test
public function getRequestDetails(string $ip_address) { if (!$this->cache->has($ip_address)) { $url = self::API_URL; if ($ip_address) { $url .= "/$ip_address"; } try { $response = $this->http_client->request( self::REQUEST_TYPE_GET, $url, $this->buildHeaders() ); } catch (GuzzleException $e) { throw new IPinfoException($e->getMessage()); } catch (Exception $e) { throw new IPinfoException($e->getMessage()); } if ($response->getStatusCode() == self::STATUS_CODE_QUOTA_EXCEEDED) { throw new IPinfoException('IPinfo request quota exceeded.'); } elseif ($response->getStatusCode() >= 400) { throw new IPinfoException('Exception: ' . json_encode([ 'status' => $response->getStatusCode(), 'reason' => $response->getReasonPhrase(), ])); } $raw_details = json_decode($response->getBody(), true); $this->cache->set($ip_address, $raw_details); } return $this->cache->get($ip_address); }
php
{ "resource": "" }
q257169
DefaultCache.set
test
public function set(string $name, $value) { if (!$this->cache->has($name)) { $this->element_queue[] = $name; } $this->cache->set($name, $value, $this->ttl); $this->manageSize(); }
php
{ "resource": "" }
q257170
DefaultCache.manageSize
test
private function manageSize() { $overflow = count($this->element_queue) - $this->maxsize; if ($overflow > 0) { foreach (array_slice($this->element_queue, 0, $overflow) as $name) { if ($this->cache->has($name)) { $this->cache->delete($name); } } $this->element_queue = array_slice($this->element_queue, $overflow); } }
php
{ "resource": "" }
q257171
Paymentwall_GenerericApiObject.post
test
public function post($params = array(), $headers = array()) { if (empty($params)) { return null; } $this->httpAction->setApiParams($params); $this->httpAction->setApiHeaders(array_merge(array($this->getApiBaseHeader()), $headers)); return (array) $this->preparePropertiesFromResponse( $this->httpAction->post( $this->getApiUrl() ) ); }
php
{ "resource": "" }
q257172
Error.errorHtml
test
public static function errorHtml($e, $header, $debug = TRUE) { $pattern = [ '/\{\{title\}\}/', '/\{\{header\}\}/', '/\{\{exception\}\}/', ]; $title = $header; $exception = $debug ? $e : 'something error...'; $replacement = [$title, $header, $exception]; return preg_replace($pattern, $replacement, self::$_html_blade); }
php
{ "resource": "" }
q257173
Route.group
test
public static function group(array $filter, Closure $routes) { // save sttribute $tmp_prefix = self::$_filter['prefix']; $tmp_namespace = self::$_filter['namespace']; $middleware = self::$_filter['middleware']; // set filter path prefix if (isset($filter['prefix'])) { self::$_filter['prefix'] .= '/'.$filter['prefix'].'/'; } // set filter namespace prefix if (isset($filter['namespace'])) { self::$_filter['namespace'] .= '\\'.$filter['namespace'].'\\'; } // set filter middleware if (isset($filter['middleware'])) { self::$_filter['middleware'][] = $filter['middleware']; } // call route setting call_user_func($routes); // recover sttribute self::$_filter['prefix'] = $tmp_prefix; self::$_filter['namespace'] = $tmp_namespace; self::$_filter['middleware'] = $middleware; }
php
{ "resource": "" }
q257174
Route._pathParse
test
protected static function _pathParse($path) { // make path as /a/b/c mode $path = ($path == '/') ? $path : '/'.rtrim($path, '/'); $path = preg_replace('/\/+/', '/', $path); return $path; }
php
{ "resource": "" }
q257175
Route._isVariableRoute
test
protected static function _isVariableRoute($path) { $matched = []; preg_match_all(self::$_variable_regexp, $path, $matched); if (empty($matched[0])) { return FALSE; } return TRUE; }
php
{ "resource": "" }
q257176
Route._variableRouteCacheControl
test
protected static function _variableRouteCacheControl($value) { // is value in cache index list? if (FALSE !== ($index = array_search($value, self::$_variable_route_cache_index))) { // if value is tail, do nothing if ($index == (count(self::$_variable_route_cache_index) - 1)) { return; } // unset old value unset(self::$_variable_route_cache_index[$index]); // reset array index self::$_variable_route_cache_index = array_values(self::$_variable_route_cache_index); } // push value to tail array_push(self::$_variable_route_cache_index, $value); // cache index list out of range? if (count(self::$_variable_route_cache_index) > self::$_variable_route_cache_limit) { // remove head value $remove_value = array_shift(self::$_variable_route_cache_index); // unset route cache, free memory unset(self::$_variable_route_cache[$remove_value]); } }
php
{ "resource": "" }
q257177
Route._setMapTree
test
protected static function _setMapTree($method, $path, $content) { $path = self::_pathParse(self::$_filter['prefix'].$path); $callback = is_string($content) ? self::_namespaceParse('\\'.self::$_filter['namespace'].$content) : $content; if (self::_isVariableRoute($path)) { // is variable route $path = self::_variablePathReplace($path); self::$_variable_map_tree[$path][strtoupper($method)] = $callback; } else { // is usual route self::$_map_tree[$path][strtoupper($method)] = $callback; } self::$_middleware_map_tree[$path][strtoupper($method)] = self::$_filter['middleware']; }
php
{ "resource": "" }
q257178
Route._getRedirectUrl
test
protected static function _getRedirectUrl($path, $param) { $base_url = rtrim(Config::get('app.base_url'), '/'); $path = self::_pathParse($path); $url = $base_url.$path.'?'.http_build_query($param); return $url; }
php
{ "resource": "" }
q257179
Route._checkMiddleware
test
protected static function _checkMiddleware(Requests $request, $middleware_symbols) { // get all route middlewares $route_middlewares = Config::get('middleware.route'); // get current request route middlewares $request_middlewares = []; foreach ($middleware_symbols as $middleware_symbol) { // if middleware_symbol is not in route_middlewares if ( ! array_key_exists($middleware_symbol, $route_middlewares)) { throw new \InvalidArgumentException("route middleware $middleware_symbol is not exists!"); } $request_middlewares[] = $route_middlewares[$middleware_symbol]; } // run middleware flow return Middleware::run($request_middlewares, $request); }
php
{ "resource": "" }
q257180
Route._runDispatch
test
protected static function _runDispatch(Requests $request, $callback, $middleware_symbols, $params = []) { // check route middlewares $request = self::_checkMiddleware($request, $middleware_symbols); // if middlewares check is not passed if ( ! ($request instanceof Requests)) { return $request; } // is class if (is_string($callback)) { // syntax check if ( ! preg_match('/^[a-zA-Z0-9_\\\\]+@[a-zA-Z0-9_]+$/', $callback)) { throw new \LogicException("Please use controller@method define callback"); } // get controller method info $controller = explode('@', $callback); list($class, $method) = [$controller[0], $controller[1]]; // class methods exist ? if ( ! class_exists($class) || ! method_exists($class, $method)) { $e = new \BadMethodCallException("Class@method: $callback is not found!"); $e->httpCode = 404; throw $e; } // call method return IOCContainer::run($class, $method, $params); } // is callback if (is_callable($callback)) { // call function return call_user_func_array($callback, $params); } }
php
{ "resource": "" }
q257181
DB.init
test
public static function init(array $db_confs) { // connect database foreach ($db_confs as $con_name => $db_conf) { try { switch (strtolower($db_conf['driver'])) { case 'mysql': self::$_connections[$con_name] = new Mysql($db_conf); break; case 'pgsql': self::$_connections[$con_name] = new Pgsql($db_conf); break; case 'sqlite': self::$_connections[$con_name] = new Sqlite($db_conf); break; default: break; } } catch (\Exception $e) { $msg = "Database connect fail, check your database config for connection '$con_name' \n".$e->getMessage(); throw new ConnectException($msg); } } }
php
{ "resource": "" }
q257182
WorkerHttp.header
test
public static function header($headers) { if (is_array($headers)) { // if pass array foreach ($headers as $header) { if (FALSE === Http::header($header)) { throw new \InvalidArgumentException("Header $header is invalid!"); } } return; } // pass string if (FALSE === Http::header($headers)) { throw new \InvalidArgumentException("Header $headers is invalid!"); } }
php
{ "resource": "" }
q257183
WorkerHttp.getHeader
test
public static function getHeader($key) { if ( ! array_key_exists($key, HttpCache::$header)) { return NULL; } return HttpCache::$header[$key]; }
php
{ "resource": "" }
q257184
Pgsql.insertGetLastId
test
public function insertGetLastId(array $data) { // create build str $field_str = ''; $value_str = ''; foreach ($data as $key => $value) { $field_str .= ' '.self::_wrapRow($key).','; $plh = self::_getPlh(); $this->_bind_params[$plh] = $value; $value_str .= ' '.$plh.','; } $field_str = rtrim($field_str, ','); $value_str = rtrim($value_str, ','); $this->_insert_str = ' ('.$field_str.') VALUES ('.$value_str.') RETURNING id '; // execute $this->_buildInsert(); $this->_execute(); $result = $this->_pdoSt->fetch(PDO::FETCH_ASSOC); return $result['id']; }
php
{ "resource": "" }
q257185
IOCContainer._getDiParams
test
protected static function _getDiParams(array $params) { $di_params = []; foreach ($params as $param) { $class = $param->getClass(); if ($class) { // check dependency is a singleton instance or not $singleton = self::getSingleton($class->name); $di_params[] = $singleton ? $singleton : self::getInstance($class->name); } } return $di_params; }
php
{ "resource": "" }
q257186
IOCContainer.singleton
test
public static function singleton($instance, $name = NULL) { if ( ! is_object($instance)) { throw new \InvalidArgumentException("Object need!"); } $class_name = $name == NULL ? get_class($instance) : $name; // singleton not exist, create if ( ! array_key_exists($class_name, self::$_singleton)) { self::$_singleton[$class_name] = $instance; } }
php
{ "resource": "" }
q257187
IOCContainer.getSingleton
test
public static function getSingleton($class_name) { return array_key_exists($class_name, self::$_singleton) ? self::$_singleton[$class_name] : NULL; }
php
{ "resource": "" }
q257188
IOCContainer.register
test
public static function register($abstract, $concrete = NULL) { if ($concrete == NULL) { $instance = self::getInstance($abstract); self::singleton($instance); } else { $instance = self::getInstance($concrete); self::singleton($instance, $abstract); } }
php
{ "resource": "" }
q257189
IOCContainer.getInstance
test
public static function getInstance($class_name) { // get class reflector $reflector = new ReflectionClass($class_name); // get constructor $constructor = $reflector->getConstructor(); // create di params $di_params = $constructor ? self::_getDiParams($constructor->getParameters()) : []; // create instance return $reflector->newInstanceArgs($di_params); }
php
{ "resource": "" }
q257190
IOCContainer.getInstanceWithSingleton
test
public static function getInstanceWithSingleton($class_name) { // is a singleton instance? if (NULL != ($instance = self::getSingleton($class_name))) { return $instance; } $instance = self::getInstance($class_name); self::singleton($instance); return $instance; }
php
{ "resource": "" }
q257191
IOCContainer.run
test
public static function run($class_name, $method, $params = []) { // class exist ? if ( ! class_exists($class_name)) { throw new \BadMethodCallException("Class $class_name is not found!"); } // method exist ? if ( ! method_exists($class_name, $method)) { throw new \BadMethodCallException("undefined method $method in $class_name !"); } // create instance $instance = self::getInstance($class_name); /******* method Dependency injection *******/ // get class reflector $reflector = new ReflectionClass($class_name); // get method $reflectorMethod = $reflector->getMethod($method); // create di params $di_params = self::_getDiParams($reflectorMethod->getParameters()); // run method return call_user_func_array([$instance, $method], array_merge($di_params, $params)); }
php
{ "resource": "" }
q257192
App.run
test
public static function run(TcpConnection $con) { try { // build config $conf = Config::get('app'); // get request $request = new Requests(); // check global middlewares $global_middlerwares = Config::get('middleware.global'); $result = Middleware::run($global_middlerwares, $request); // middlewares check passed? if ($result instanceof Requests) { // run dispatch $result = Route::dispatch($result); } } catch (\Exception $e) { // Handle Exception $exceptionHandler = IOCContainer::getInstanceWithSingleton(ExceptionHandler::class); $result = $exceptionHandler->handle($e); } finally { // return Response data $response = Response::bulid($result, $conf); $con->send($response); } }
php
{ "resource": "" }
q257193
App.init
test
public static function init() { try { // register class self::register(); // init database DB::init(Config::get('database.db_con')); // init redis Redis::init(Config::get('database.redis')); } catch (\Exception $e) { Error::printError($e->getMessage()); } }
php
{ "resource": "" }
q257194
Pipeline.pipe
test
public function pipe($pipe) { if (FALSE === is_callable($pipe)) { throw new InvalidArgumentException('pipe should be callable.'); } $this->_pipes[] = $pipe; return $this; }
php
{ "resource": "" }
q257195
Redis.init
test
public static function init(array $rd_confs) { // create redis init params $cluster = $rd_confs['cluster']; $options = (array) $rd_confs['options']; $servers = $rd_confs['rd_con']; // get clients self::$_clients = $cluster ? self::createAggregateClient($servers, $options) : self::createSingleClients($servers, $options); // check redis connect foreach (self::$_clients as $con_name => $client) { try { $client->connect(); } catch (\Exception $e) { $msg = "Redis connect fail, check your redis config for connection '$con_name'. \n".$e->getMessage(); throw new ConnectException($msg); } } }
php
{ "resource": "" }
q257196
Redis.subscribe
test
public static function subscribe($channels, Closure $callback, $connection = 'default', $method = 'subscribe') { $loop = self::$_clients[$connection]->pubSubLoop(); call_user_func_array([$loop, $method], (array) $channels); // loop blocking, start listen redis publish messages foreach ($loop as $message) { if ($message->kind === 'message' || $message->kind === 'pmessage') { // get publish message call_user_func($callback, $message->payload, $message->channel); } } // unset Predis\PubSub\Consumer iterator unset($loop); }
php
{ "resource": "" }
q257197
Redis.psubscribe
test
public static function psubscribe($channels, Closure $callback, $connection = 'default') { return self::subscribe($channels, $callback, $connection, 'psubscribe'); }
php
{ "resource": "" }
q257198
PDODriver._reset
test
protected function _reset() { $this->_table = ''; $this->_prepare_sql = ''; $this->_cols_str = ' * '; $this->_where_str = ''; $this->_orderby_str = ''; $this->_groupby_str = ''; $this->_having_str = ''; $this->_join_str = ''; $this->_limit_str = ''; $this->_insert_str = ''; $this->_update_str = ''; $this->_bind_params = []; }
php
{ "resource": "" }
q257199
PDODriver._wrapPrepareSql
test
protected function _wrapPrepareSql() { // set table prefix $quote = static::$_quote_symbol; $prefix_pattern = '/'.$quote.'([a-zA-Z0-9_]+)'.$quote.'(\.)'.$quote.'([a-zA-Z0-9_]+)'.$quote.'/'; $prefix_replace = self::_quote($this->_wrapTable('$1')).'$2'.self::_quote('$3'); $this->_prepare_sql = preg_replace($prefix_pattern, $prefix_replace, $this->_prepare_sql); }
php
{ "resource": "" }