repo
stringlengths 6
63
| path
stringlengths 5
140
| func_name
stringlengths 3
151
| original_string
stringlengths 84
13k
| language
stringclasses 1
value | code
stringlengths 84
13k
| code_tokens
sequence | docstring
stringlengths 3
47.2k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 91
247
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
doctrine/orm | lib/Doctrine/ORM/Query/SqlWalker.php | SqlWalker.walkSimpleCaseExpression | public function walkSimpleCaseExpression($simpleCaseExpression)
{
$sql = 'CASE ' . $this->walkStateFieldPathExpression($simpleCaseExpression->caseOperand);
foreach ($simpleCaseExpression->simpleWhenClauses as $simpleWhenClause) {
$sql .= ' WHEN ' . $this->walkSimpleArithmeticExpression($simpleWhenClause->caseScalarExpression);
$sql .= ' THEN ' . $this->walkSimpleArithmeticExpression($simpleWhenClause->thenScalarExpression);
}
$sql .= ' ELSE ' . $this->walkSimpleArithmeticExpression($simpleCaseExpression->elseScalarExpression) . ' END';
return $sql;
} | php | public function walkSimpleCaseExpression($simpleCaseExpression)
{
$sql = 'CASE ' . $this->walkStateFieldPathExpression($simpleCaseExpression->caseOperand);
foreach ($simpleCaseExpression->simpleWhenClauses as $simpleWhenClause) {
$sql .= ' WHEN ' . $this->walkSimpleArithmeticExpression($simpleWhenClause->caseScalarExpression);
$sql .= ' THEN ' . $this->walkSimpleArithmeticExpression($simpleWhenClause->thenScalarExpression);
}
$sql .= ' ELSE ' . $this->walkSimpleArithmeticExpression($simpleCaseExpression->elseScalarExpression) . ' END';
return $sql;
} | [
"public",
"function",
"walkSimpleCaseExpression",
"(",
"$",
"simpleCaseExpression",
")",
"{",
"$",
"sql",
"=",
"'CASE '",
".",
"$",
"this",
"->",
"walkStateFieldPathExpression",
"(",
"$",
"simpleCaseExpression",
"->",
"caseOperand",
")",
";",
"foreach",
"(",
"$",
"simpleCaseExpression",
"->",
"simpleWhenClauses",
"as",
"$",
"simpleWhenClause",
")",
"{",
"$",
"sql",
".=",
"' WHEN '",
".",
"$",
"this",
"->",
"walkSimpleArithmeticExpression",
"(",
"$",
"simpleWhenClause",
"->",
"caseScalarExpression",
")",
";",
"$",
"sql",
".=",
"' THEN '",
".",
"$",
"this",
"->",
"walkSimpleArithmeticExpression",
"(",
"$",
"simpleWhenClause",
"->",
"thenScalarExpression",
")",
";",
"}",
"$",
"sql",
".=",
"' ELSE '",
".",
"$",
"this",
"->",
"walkSimpleArithmeticExpression",
"(",
"$",
"simpleCaseExpression",
"->",
"elseScalarExpression",
")",
".",
"' END'",
";",
"return",
"$",
"sql",
";",
"}"
] | Walks down a SimpleCaseExpression AST node and generates the corresponding SQL.
@param AST\SimpleCaseExpression $simpleCaseExpression
@return string The SQL. | [
"Walks",
"down",
"a",
"SimpleCaseExpression",
"AST",
"node",
"and",
"generates",
"the",
"corresponding",
"SQL",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query/SqlWalker.php#L1311-L1323 | train |
doctrine/orm | lib/Doctrine/ORM/Query/SqlWalker.php | SqlWalker.walkArithmeticPrimary | public function walkArithmeticPrimary($primary)
{
if ($primary instanceof AST\SimpleArithmeticExpression) {
return '(' . $this->walkSimpleArithmeticExpression($primary) . ')';
}
if ($primary instanceof AST\Node) {
return $primary->dispatch($this);
}
return $this->walkEntityIdentificationVariable($primary);
} | php | public function walkArithmeticPrimary($primary)
{
if ($primary instanceof AST\SimpleArithmeticExpression) {
return '(' . $this->walkSimpleArithmeticExpression($primary) . ')';
}
if ($primary instanceof AST\Node) {
return $primary->dispatch($this);
}
return $this->walkEntityIdentificationVariable($primary);
} | [
"public",
"function",
"walkArithmeticPrimary",
"(",
"$",
"primary",
")",
"{",
"if",
"(",
"$",
"primary",
"instanceof",
"AST",
"\\",
"SimpleArithmeticExpression",
")",
"{",
"return",
"'('",
".",
"$",
"this",
"->",
"walkSimpleArithmeticExpression",
"(",
"$",
"primary",
")",
".",
"')'",
";",
"}",
"if",
"(",
"$",
"primary",
"instanceof",
"AST",
"\\",
"Node",
")",
"{",
"return",
"$",
"primary",
"->",
"dispatch",
"(",
"$",
"this",
")",
";",
"}",
"return",
"$",
"this",
"->",
"walkEntityIdentificationVariable",
"(",
"$",
"primary",
")",
";",
"}"
] | Walks down an ArithmeticPrimary that represents an AST node, thereby generating the appropriate SQL.
@param mixed $primary
@return string The SQL. | [
"Walks",
"down",
"an",
"ArithmeticPrimary",
"that",
"represents",
"an",
"AST",
"node",
"thereby",
"generating",
"the",
"appropriate",
"SQL",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query/SqlWalker.php#L2336-L2347 | train |
doctrine/orm | lib/Doctrine/ORM/EntityRepository.php | EntityRepository.resolveMagicCall | private function resolveMagicCall($method, $by, array $arguments)
{
if (! $arguments) {
throw InvalidMagicMethodCall::onMissingParameter($method . $by);
}
$fieldName = lcfirst(Inflector::classify($by));
if ($this->class->getProperty($fieldName) === null) {
throw InvalidMagicMethodCall::becauseFieldNotFoundIn(
$this->entityName,
$fieldName,
$method . $by
);
}
return $this->{$method}([$fieldName => $arguments[0]], ...array_slice($arguments, 1));
} | php | private function resolveMagicCall($method, $by, array $arguments)
{
if (! $arguments) {
throw InvalidMagicMethodCall::onMissingParameter($method . $by);
}
$fieldName = lcfirst(Inflector::classify($by));
if ($this->class->getProperty($fieldName) === null) {
throw InvalidMagicMethodCall::becauseFieldNotFoundIn(
$this->entityName,
$fieldName,
$method . $by
);
}
return $this->{$method}([$fieldName => $arguments[0]], ...array_slice($arguments, 1));
} | [
"private",
"function",
"resolveMagicCall",
"(",
"$",
"method",
",",
"$",
"by",
",",
"array",
"$",
"arguments",
")",
"{",
"if",
"(",
"!",
"$",
"arguments",
")",
"{",
"throw",
"InvalidMagicMethodCall",
"::",
"onMissingParameter",
"(",
"$",
"method",
".",
"$",
"by",
")",
";",
"}",
"$",
"fieldName",
"=",
"lcfirst",
"(",
"Inflector",
"::",
"classify",
"(",
"$",
"by",
")",
")",
";",
"if",
"(",
"$",
"this",
"->",
"class",
"->",
"getProperty",
"(",
"$",
"fieldName",
")",
"===",
"null",
")",
"{",
"throw",
"InvalidMagicMethodCall",
"::",
"becauseFieldNotFoundIn",
"(",
"$",
"this",
"->",
"entityName",
",",
"$",
"fieldName",
",",
"$",
"method",
".",
"$",
"by",
")",
";",
"}",
"return",
"$",
"this",
"->",
"{",
"$",
"method",
"}",
"(",
"[",
"$",
"fieldName",
"=>",
"$",
"arguments",
"[",
"0",
"]",
"]",
",",
"...",
"array_slice",
"(",
"$",
"arguments",
",",
"1",
")",
")",
";",
"}"
] | Resolves a magic method call to the proper existent method at `EntityRepository`.
@param string $method The method to call
@param string $by The property name used as condition
@param mixed[] $arguments The arguments to pass at method call
@return mixed
@throws ORMException If the method called is invalid or the requested field/association does not exist. | [
"Resolves",
"a",
"magic",
"method",
"call",
"to",
"the",
"proper",
"existent",
"method",
"at",
"EntityRepository",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/EntityRepository.php#L253-L270 | train |
doctrine/orm | lib/Doctrine/ORM/Configuration.php | Configuration.setAutoGenerateProxyClasses | public function setAutoGenerateProxyClasses($autoGenerate) : void
{
$proxyManagerConfig = $this->getProxyManagerConfiguration();
switch ((int) $autoGenerate) {
case ProxyFactory::AUTOGENERATE_ALWAYS:
case ProxyFactory::AUTOGENERATE_FILE_NOT_EXISTS:
$proxyManagerConfig->setGeneratorStrategy(new FileWriterGeneratorStrategy(
new FileLocator($proxyManagerConfig->getProxiesTargetDir())
));
return;
case ProxyFactory::AUTOGENERATE_NEVER:
case ProxyFactory::AUTOGENERATE_EVAL:
default:
$proxyManagerConfig->setGeneratorStrategy(new EvaluatingGeneratorStrategy());
return;
}
} | php | public function setAutoGenerateProxyClasses($autoGenerate) : void
{
$proxyManagerConfig = $this->getProxyManagerConfiguration();
switch ((int) $autoGenerate) {
case ProxyFactory::AUTOGENERATE_ALWAYS:
case ProxyFactory::AUTOGENERATE_FILE_NOT_EXISTS:
$proxyManagerConfig->setGeneratorStrategy(new FileWriterGeneratorStrategy(
new FileLocator($proxyManagerConfig->getProxiesTargetDir())
));
return;
case ProxyFactory::AUTOGENERATE_NEVER:
case ProxyFactory::AUTOGENERATE_EVAL:
default:
$proxyManagerConfig->setGeneratorStrategy(new EvaluatingGeneratorStrategy());
return;
}
} | [
"public",
"function",
"setAutoGenerateProxyClasses",
"(",
"$",
"autoGenerate",
")",
":",
"void",
"{",
"$",
"proxyManagerConfig",
"=",
"$",
"this",
"->",
"getProxyManagerConfiguration",
"(",
")",
";",
"switch",
"(",
"(",
"int",
")",
"$",
"autoGenerate",
")",
"{",
"case",
"ProxyFactory",
"::",
"AUTOGENERATE_ALWAYS",
":",
"case",
"ProxyFactory",
"::",
"AUTOGENERATE_FILE_NOT_EXISTS",
":",
"$",
"proxyManagerConfig",
"->",
"setGeneratorStrategy",
"(",
"new",
"FileWriterGeneratorStrategy",
"(",
"new",
"FileLocator",
"(",
"$",
"proxyManagerConfig",
"->",
"getProxiesTargetDir",
"(",
")",
")",
")",
")",
";",
"return",
";",
"case",
"ProxyFactory",
"::",
"AUTOGENERATE_NEVER",
":",
"case",
"ProxyFactory",
"::",
"AUTOGENERATE_EVAL",
":",
"default",
":",
"$",
"proxyManagerConfig",
"->",
"setGeneratorStrategy",
"(",
"new",
"EvaluatingGeneratorStrategy",
"(",
")",
")",
";",
"return",
";",
"}",
"}"
] | Sets the strategy for automatically generating proxy classes.
@param bool|int $autoGenerate Possible values are constants of Doctrine\ORM\Proxy\Factory\ProxyFactory.
True is converted to AUTOGENERATE_ALWAYS, false to AUTOGENERATE_NEVER. | [
"Sets",
"the",
"strategy",
"for",
"automatically",
"generating",
"proxy",
"classes",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Configuration.php#L117-L136 | train |
doctrine/orm | lib/Doctrine/ORM/Configuration.php | Configuration.newDefaultAnnotationDriver | public function newDefaultAnnotationDriver(array $paths = []) : AnnotationDriver
{
AnnotationRegistry::registerFile(__DIR__ . '/Annotation/DoctrineAnnotations.php');
$reader = new CachedReader(new AnnotationReader(), new ArrayCache());
return new AnnotationDriver($reader, $paths);
} | php | public function newDefaultAnnotationDriver(array $paths = []) : AnnotationDriver
{
AnnotationRegistry::registerFile(__DIR__ . '/Annotation/DoctrineAnnotations.php');
$reader = new CachedReader(new AnnotationReader(), new ArrayCache());
return new AnnotationDriver($reader, $paths);
} | [
"public",
"function",
"newDefaultAnnotationDriver",
"(",
"array",
"$",
"paths",
"=",
"[",
"]",
")",
":",
"AnnotationDriver",
"{",
"AnnotationRegistry",
"::",
"registerFile",
"(",
"__DIR__",
".",
"'/Annotation/DoctrineAnnotations.php'",
")",
";",
"$",
"reader",
"=",
"new",
"CachedReader",
"(",
"new",
"AnnotationReader",
"(",
")",
",",
"new",
"ArrayCache",
"(",
")",
")",
";",
"return",
"new",
"AnnotationDriver",
"(",
"$",
"reader",
",",
"$",
"paths",
")",
";",
"}"
] | Adds a new default annotation driver with a correctly configured annotation reader.
@param string[] $paths | [
"Adds",
"a",
"new",
"default",
"annotation",
"driver",
"with",
"a",
"correctly",
"configured",
"annotation",
"reader",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Configuration.php#L162-L169 | train |
doctrine/orm | lib/Doctrine/ORM/Configuration.php | Configuration.addCustomStringFunction | public function addCustomStringFunction(string $functionName, $classNameOrFactory) : void
{
$this->customStringFunctions[strtolower($functionName)] = $classNameOrFactory;
} | php | public function addCustomStringFunction(string $functionName, $classNameOrFactory) : void
{
$this->customStringFunctions[strtolower($functionName)] = $classNameOrFactory;
} | [
"public",
"function",
"addCustomStringFunction",
"(",
"string",
"$",
"functionName",
",",
"$",
"classNameOrFactory",
")",
":",
"void",
"{",
"$",
"this",
"->",
"customStringFunctions",
"[",
"strtolower",
"(",
"$",
"functionName",
")",
"]",
"=",
"$",
"classNameOrFactory",
";",
"}"
] | Registers a custom DQL function that produces a string value.
Such a function can then be used in any DQL statement in any place where string
functions are allowed.
DQL function names are case-insensitive.
@param string|callable $classNameOrFactory Class name or a callable that returns the function. | [
"Registers",
"a",
"custom",
"DQL",
"function",
"that",
"produces",
"a",
"string",
"value",
".",
"Such",
"a",
"function",
"can",
"then",
"be",
"used",
"in",
"any",
"DQL",
"statement",
"in",
"any",
"place",
"where",
"string",
"functions",
"are",
"allowed",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Configuration.php#L270-L273 | train |
doctrine/orm | lib/Doctrine/ORM/Configuration.php | Configuration.setCustomStringFunctions | public function setCustomStringFunctions(array $functions) : void
{
foreach ($functions as $name => $className) {
$this->addCustomStringFunction($name, $className);
}
} | php | public function setCustomStringFunctions(array $functions) : void
{
foreach ($functions as $name => $className) {
$this->addCustomStringFunction($name, $className);
}
} | [
"public",
"function",
"setCustomStringFunctions",
"(",
"array",
"$",
"functions",
")",
":",
"void",
"{",
"foreach",
"(",
"$",
"functions",
"as",
"$",
"name",
"=>",
"$",
"className",
")",
"{",
"$",
"this",
"->",
"addCustomStringFunction",
"(",
"$",
"name",
",",
"$",
"className",
")",
";",
"}",
"}"
] | Sets a map of custom DQL string functions.
Keys must be function names and values the FQCN of the implementing class.
The function names will be case-insensitive in DQL.
Any previously added string functions are discarded.
@param string[]|callable[] $functions The map of custom DQL string functions. | [
"Sets",
"a",
"map",
"of",
"custom",
"DQL",
"string",
"functions",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Configuration.php#L295-L300 | train |
doctrine/orm | lib/Doctrine/ORM/Configuration.php | Configuration.setCustomNumericFunctions | public function setCustomNumericFunctions(array $functions) : void
{
foreach ($functions as $name => $className) {
$this->addCustomNumericFunction($name, $className);
}
} | php | public function setCustomNumericFunctions(array $functions) : void
{
foreach ($functions as $name => $className) {
$this->addCustomNumericFunction($name, $className);
}
} | [
"public",
"function",
"setCustomNumericFunctions",
"(",
"array",
"$",
"functions",
")",
":",
"void",
"{",
"foreach",
"(",
"$",
"functions",
"as",
"$",
"name",
"=>",
"$",
"className",
")",
"{",
"$",
"this",
"->",
"addCustomNumericFunction",
"(",
"$",
"name",
",",
"$",
"className",
")",
";",
"}",
"}"
] | Sets a map of custom DQL numeric functions.
Keys must be function names and values the FQCN of the implementing class.
The function names will be case-insensitive in DQL.
Any previously added numeric functions are discarded.
@param string[]|callable[] $functions The map of custom DQL numeric functions. | [
"Sets",
"a",
"map",
"of",
"custom",
"DQL",
"numeric",
"functions",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Configuration.php#L336-L341 | train |
doctrine/orm | lib/Doctrine/ORM/Configuration.php | Configuration.addCustomHydrationMode | public function addCustomHydrationMode(string $modeName, string $hydratorClassName) : void
{
$this->customHydrationModes[$modeName] = $hydratorClassName;
} | php | public function addCustomHydrationMode(string $modeName, string $hydratorClassName) : void
{
$this->customHydrationModes[$modeName] = $hydratorClassName;
} | [
"public",
"function",
"addCustomHydrationMode",
"(",
"string",
"$",
"modeName",
",",
"string",
"$",
"hydratorClassName",
")",
":",
"void",
"{",
"$",
"this",
"->",
"customHydrationModes",
"[",
"$",
"modeName",
"]",
"=",
"$",
"hydratorClassName",
";",
"}"
] | Adds a custom hydration mode. | [
"Adds",
"a",
"custom",
"hydration",
"mode",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Configuration.php#L411-L414 | train |
doctrine/orm | lib/Doctrine/ORM/Configuration.php | Configuration.addFilter | public function addFilter(string $filterName, string $filterClassName) : void
{
$this->filters[$filterName] = $filterClassName;
} | php | public function addFilter(string $filterName, string $filterClassName) : void
{
$this->filters[$filterName] = $filterClassName;
} | [
"public",
"function",
"addFilter",
"(",
"string",
"$",
"filterName",
",",
"string",
"$",
"filterClassName",
")",
":",
"void",
"{",
"$",
"this",
"->",
"filters",
"[",
"$",
"filterName",
"]",
"=",
"$",
"filterClassName",
";",
"}"
] | Adds a filter to the list of possible filters. | [
"Adds",
"a",
"filter",
"to",
"the",
"list",
"of",
"possible",
"filters",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Configuration.php#L432-L435 | train |
doctrine/orm | lib/Doctrine/ORM/Tools/Setup.php | Setup.createXMLMetadataConfiguration | public static function createXMLMetadataConfiguration(array $paths, $isDevMode = false, $proxyDir = null, ?Cache $cache = null)
{
$config = self::createConfiguration($isDevMode, $proxyDir, $cache);
$config->setMetadataDriverImpl(new XmlDriver($paths));
return $config;
} | php | public static function createXMLMetadataConfiguration(array $paths, $isDevMode = false, $proxyDir = null, ?Cache $cache = null)
{
$config = self::createConfiguration($isDevMode, $proxyDir, $cache);
$config->setMetadataDriverImpl(new XmlDriver($paths));
return $config;
} | [
"public",
"static",
"function",
"createXMLMetadataConfiguration",
"(",
"array",
"$",
"paths",
",",
"$",
"isDevMode",
"=",
"false",
",",
"$",
"proxyDir",
"=",
"null",
",",
"?",
"Cache",
"$",
"cache",
"=",
"null",
")",
"{",
"$",
"config",
"=",
"self",
"::",
"createConfiguration",
"(",
"$",
"isDevMode",
",",
"$",
"proxyDir",
",",
"$",
"cache",
")",
";",
"$",
"config",
"->",
"setMetadataDriverImpl",
"(",
"new",
"XmlDriver",
"(",
"$",
"paths",
")",
")",
";",
"return",
"$",
"config",
";",
"}"
] | Creates a configuration with a xml metadata driver.
@param string[] $paths
@param bool $isDevMode
@param string $proxyDir
@return Configuration | [
"Creates",
"a",
"configuration",
"with",
"a",
"xml",
"metadata",
"driver",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Tools/Setup.php#L52-L58 | train |
doctrine/orm | lib/Doctrine/ORM/PersistentObject.php | PersistentObject.injectEntityManager | public function injectEntityManager(EntityManagerInterface $entityManager, ClassMetadata $classMetadata) : void
{
if ($entityManager !== self::$entityManager) {
throw new RuntimeException(
'Trying to use PersistentObject with different EntityManager instances. ' .
'Was PersistentObject::setEntityManager() called?'
);
}
$this->cm = $classMetadata;
} | php | public function injectEntityManager(EntityManagerInterface $entityManager, ClassMetadata $classMetadata) : void
{
if ($entityManager !== self::$entityManager) {
throw new RuntimeException(
'Trying to use PersistentObject with different EntityManager instances. ' .
'Was PersistentObject::setEntityManager() called?'
);
}
$this->cm = $classMetadata;
} | [
"public",
"function",
"injectEntityManager",
"(",
"EntityManagerInterface",
"$",
"entityManager",
",",
"ClassMetadata",
"$",
"classMetadata",
")",
":",
"void",
"{",
"if",
"(",
"$",
"entityManager",
"!==",
"self",
"::",
"$",
"entityManager",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Trying to use PersistentObject with different EntityManager instances. '",
".",
"'Was PersistentObject::setEntityManager() called?'",
")",
";",
"}",
"$",
"this",
"->",
"cm",
"=",
"$",
"classMetadata",
";",
"}"
] | Injects the Doctrine Object Manager.
@throws RuntimeException | [
"Injects",
"the",
"Doctrine",
"Object",
"Manager",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/PersistentObject.php#L78-L88 | train |
doctrine/orm | lib/Doctrine/ORM/PersistentObject.php | PersistentObject.set | private function set($field, $args)
{
$this->initializeDoctrine();
$property = $this->cm->getProperty($field);
if (! $property) {
throw new BadMethodCallException("no field with name '" . $field . "' exists on '" . $this->cm->getClassName() . "'");
}
switch (true) {
case $property instanceof FieldMetadata && ! $property->isPrimaryKey():
$this->{$field} = $args[0];
break;
case $property instanceof ToOneAssociationMetadata:
$targetClassName = $property->getTargetEntity();
if ($args[0] !== null && ! ($args[0] instanceof $targetClassName)) {
throw new InvalidArgumentException("Expected persistent object of type '" . $targetClassName . "'");
}
$this->{$field} = $args[0];
$this->completeOwningSide($property, $args[0]);
break;
}
return $this;
} | php | private function set($field, $args)
{
$this->initializeDoctrine();
$property = $this->cm->getProperty($field);
if (! $property) {
throw new BadMethodCallException("no field with name '" . $field . "' exists on '" . $this->cm->getClassName() . "'");
}
switch (true) {
case $property instanceof FieldMetadata && ! $property->isPrimaryKey():
$this->{$field} = $args[0];
break;
case $property instanceof ToOneAssociationMetadata:
$targetClassName = $property->getTargetEntity();
if ($args[0] !== null && ! ($args[0] instanceof $targetClassName)) {
throw new InvalidArgumentException("Expected persistent object of type '" . $targetClassName . "'");
}
$this->{$field} = $args[0];
$this->completeOwningSide($property, $args[0]);
break;
}
return $this;
} | [
"private",
"function",
"set",
"(",
"$",
"field",
",",
"$",
"args",
")",
"{",
"$",
"this",
"->",
"initializeDoctrine",
"(",
")",
";",
"$",
"property",
"=",
"$",
"this",
"->",
"cm",
"->",
"getProperty",
"(",
"$",
"field",
")",
";",
"if",
"(",
"!",
"$",
"property",
")",
"{",
"throw",
"new",
"BadMethodCallException",
"(",
"\"no field with name '\"",
".",
"$",
"field",
".",
"\"' exists on '\"",
".",
"$",
"this",
"->",
"cm",
"->",
"getClassName",
"(",
")",
".",
"\"'\"",
")",
";",
"}",
"switch",
"(",
"true",
")",
"{",
"case",
"$",
"property",
"instanceof",
"FieldMetadata",
"&&",
"!",
"$",
"property",
"->",
"isPrimaryKey",
"(",
")",
":",
"$",
"this",
"->",
"{",
"$",
"field",
"}",
"=",
"$",
"args",
"[",
"0",
"]",
";",
"break",
";",
"case",
"$",
"property",
"instanceof",
"ToOneAssociationMetadata",
":",
"$",
"targetClassName",
"=",
"$",
"property",
"->",
"getTargetEntity",
"(",
")",
";",
"if",
"(",
"$",
"args",
"[",
"0",
"]",
"!==",
"null",
"&&",
"!",
"(",
"$",
"args",
"[",
"0",
"]",
"instanceof",
"$",
"targetClassName",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Expected persistent object of type '\"",
".",
"$",
"targetClassName",
".",
"\"'\"",
")",
";",
"}",
"$",
"this",
"->",
"{",
"$",
"field",
"}",
"=",
"$",
"args",
"[",
"0",
"]",
";",
"$",
"this",
"->",
"completeOwningSide",
"(",
"$",
"property",
",",
"$",
"args",
"[",
"0",
"]",
")",
";",
"break",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Sets a persistent fields value.
@param string $field
@param mixed[] $args
@return object
@throws BadMethodCallException When no persistent field exists by that name.
@throws InvalidArgumentException When the wrong target object type is passed to an association. | [
"Sets",
"a",
"persistent",
"fields",
"value",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/PersistentObject.php#L101-L129 | train |
doctrine/orm | lib/Doctrine/ORM/PersistentObject.php | PersistentObject.get | private function get($field)
{
$this->initializeDoctrine();
$property = $this->cm->getProperty($field);
if (! $property) {
throw new BadMethodCallException("no field with name '" . $field . "' exists on '" . $this->cm->getClassName() . "'");
}
return $this->{$field};
} | php | private function get($field)
{
$this->initializeDoctrine();
$property = $this->cm->getProperty($field);
if (! $property) {
throw new BadMethodCallException("no field with name '" . $field . "' exists on '" . $this->cm->getClassName() . "'");
}
return $this->{$field};
} | [
"private",
"function",
"get",
"(",
"$",
"field",
")",
"{",
"$",
"this",
"->",
"initializeDoctrine",
"(",
")",
";",
"$",
"property",
"=",
"$",
"this",
"->",
"cm",
"->",
"getProperty",
"(",
"$",
"field",
")",
";",
"if",
"(",
"!",
"$",
"property",
")",
"{",
"throw",
"new",
"BadMethodCallException",
"(",
"\"no field with name '\"",
".",
"$",
"field",
".",
"\"' exists on '\"",
".",
"$",
"this",
"->",
"cm",
"->",
"getClassName",
"(",
")",
".",
"\"'\"",
")",
";",
"}",
"return",
"$",
"this",
"->",
"{",
"$",
"field",
"}",
";",
"}"
] | Gets a persistent field value.
@param string $field
@return mixed
@throws BadMethodCallException When no persistent field exists by that name. | [
"Gets",
"a",
"persistent",
"field",
"value",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/PersistentObject.php#L140-L151 | train |
doctrine/orm | lib/Doctrine/ORM/PersistentObject.php | PersistentObject.completeOwningSide | private function completeOwningSide(AssociationMetadata $property, $targetObject)
{
// add this object on the owning side as well, for obvious infinite recursion
// reasons this is only done when called on the inverse side.
if ($property->isOwningSide()) {
return;
}
$mappedByField = $property->getMappedBy();
$targetMetadata = self::$entityManager->getClassMetadata($property->getTargetEntity());
$targetProperty = $targetMetadata->getProperty($mappedByField);
$setterMethodName = ($targetProperty instanceof ToManyAssociationMetadata ? 'add' : 'set') . $mappedByField;
$targetObject->{$setterMethodName}($this);
} | php | private function completeOwningSide(AssociationMetadata $property, $targetObject)
{
// add this object on the owning side as well, for obvious infinite recursion
// reasons this is only done when called on the inverse side.
if ($property->isOwningSide()) {
return;
}
$mappedByField = $property->getMappedBy();
$targetMetadata = self::$entityManager->getClassMetadata($property->getTargetEntity());
$targetProperty = $targetMetadata->getProperty($mappedByField);
$setterMethodName = ($targetProperty instanceof ToManyAssociationMetadata ? 'add' : 'set') . $mappedByField;
$targetObject->{$setterMethodName}($this);
} | [
"private",
"function",
"completeOwningSide",
"(",
"AssociationMetadata",
"$",
"property",
",",
"$",
"targetObject",
")",
"{",
"// add this object on the owning side as well, for obvious infinite recursion",
"// reasons this is only done when called on the inverse side.",
"if",
"(",
"$",
"property",
"->",
"isOwningSide",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"mappedByField",
"=",
"$",
"property",
"->",
"getMappedBy",
"(",
")",
";",
"$",
"targetMetadata",
"=",
"self",
"::",
"$",
"entityManager",
"->",
"getClassMetadata",
"(",
"$",
"property",
"->",
"getTargetEntity",
"(",
")",
")",
";",
"$",
"targetProperty",
"=",
"$",
"targetMetadata",
"->",
"getProperty",
"(",
"$",
"mappedByField",
")",
";",
"$",
"setterMethodName",
"=",
"(",
"$",
"targetProperty",
"instanceof",
"ToManyAssociationMetadata",
"?",
"'add'",
":",
"'set'",
")",
".",
"$",
"mappedByField",
";",
"$",
"targetObject",
"->",
"{",
"$",
"setterMethodName",
"}",
"(",
"$",
"this",
")",
";",
"}"
] | If this is an inverse side association, completes the owning side.
@param object $targetObject | [
"If",
"this",
"is",
"an",
"inverse",
"side",
"association",
"completes",
"the",
"owning",
"side",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/PersistentObject.php#L158-L172 | train |
doctrine/orm | lib/Doctrine/ORM/PersistentObject.php | PersistentObject.add | private function add($field, $args)
{
$this->initializeDoctrine();
$property = $this->cm->getProperty($field);
if (! $property) {
throw new BadMethodCallException("no field with name '" . $field . "' exists on '" . $this->cm->getClassName() . "'");
}
if (! ($property instanceof ToManyAssociationMetadata)) {
throw new BadMethodCallException('There is no method add' . $field . '() on ' . $this->cm->getClassName());
}
$targetClassName = $property->getTargetEntity();
if (! ($args[0] instanceof $targetClassName)) {
throw new InvalidArgumentException("Expected persistent object of type '" . $targetClassName . "'");
}
if (! ($this->{$field} instanceof Collection)) {
$this->{$field} = new ArrayCollection($this->{$field} ?: []);
}
$this->{$field}->add($args[0]);
$this->completeOwningSide($property, $args[0]);
return $this;
} | php | private function add($field, $args)
{
$this->initializeDoctrine();
$property = $this->cm->getProperty($field);
if (! $property) {
throw new BadMethodCallException("no field with name '" . $field . "' exists on '" . $this->cm->getClassName() . "'");
}
if (! ($property instanceof ToManyAssociationMetadata)) {
throw new BadMethodCallException('There is no method add' . $field . '() on ' . $this->cm->getClassName());
}
$targetClassName = $property->getTargetEntity();
if (! ($args[0] instanceof $targetClassName)) {
throw new InvalidArgumentException("Expected persistent object of type '" . $targetClassName . "'");
}
if (! ($this->{$field} instanceof Collection)) {
$this->{$field} = new ArrayCollection($this->{$field} ?: []);
}
$this->{$field}->add($args[0]);
$this->completeOwningSide($property, $args[0]);
return $this;
} | [
"private",
"function",
"add",
"(",
"$",
"field",
",",
"$",
"args",
")",
"{",
"$",
"this",
"->",
"initializeDoctrine",
"(",
")",
";",
"$",
"property",
"=",
"$",
"this",
"->",
"cm",
"->",
"getProperty",
"(",
"$",
"field",
")",
";",
"if",
"(",
"!",
"$",
"property",
")",
"{",
"throw",
"new",
"BadMethodCallException",
"(",
"\"no field with name '\"",
".",
"$",
"field",
".",
"\"' exists on '\"",
".",
"$",
"this",
"->",
"cm",
"->",
"getClassName",
"(",
")",
".",
"\"'\"",
")",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"property",
"instanceof",
"ToManyAssociationMetadata",
")",
")",
"{",
"throw",
"new",
"BadMethodCallException",
"(",
"'There is no method add'",
".",
"$",
"field",
".",
"'() on '",
".",
"$",
"this",
"->",
"cm",
"->",
"getClassName",
"(",
")",
")",
";",
"}",
"$",
"targetClassName",
"=",
"$",
"property",
"->",
"getTargetEntity",
"(",
")",
";",
"if",
"(",
"!",
"(",
"$",
"args",
"[",
"0",
"]",
"instanceof",
"$",
"targetClassName",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Expected persistent object of type '\"",
".",
"$",
"targetClassName",
".",
"\"'\"",
")",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"this",
"->",
"{",
"$",
"field",
"}",
"instanceof",
"Collection",
")",
")",
"{",
"$",
"this",
"->",
"{",
"$",
"field",
"}",
"=",
"new",
"ArrayCollection",
"(",
"$",
"this",
"->",
"{",
"$",
"field",
"}",
"?",
":",
"[",
"]",
")",
";",
"}",
"$",
"this",
"->",
"{",
"$",
"field",
"}",
"->",
"add",
"(",
"$",
"args",
"[",
"0",
"]",
")",
";",
"$",
"this",
"->",
"completeOwningSide",
"(",
"$",
"property",
",",
"$",
"args",
"[",
"0",
"]",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Adds an object to a collection.
@param string $field
@param mixed[] $args
@return object
@throws BadMethodCallException
@throws InvalidArgumentException | [
"Adds",
"an",
"object",
"to",
"a",
"collection",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/PersistentObject.php#L185-L214 | train |
doctrine/orm | lib/Doctrine/ORM/PersistentObject.php | PersistentObject.initializeDoctrine | private function initializeDoctrine()
{
if ($this->cm !== null) {
return;
}
if (! self::$entityManager) {
throw new RuntimeException('No runtime entity manager set. Call PersistentObject#setEntityManager().');
}
$this->cm = self::$entityManager->getClassMetadata(static::class);
} | php | private function initializeDoctrine()
{
if ($this->cm !== null) {
return;
}
if (! self::$entityManager) {
throw new RuntimeException('No runtime entity manager set. Call PersistentObject#setEntityManager().');
}
$this->cm = self::$entityManager->getClassMetadata(static::class);
} | [
"private",
"function",
"initializeDoctrine",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"cm",
"!==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"self",
"::",
"$",
"entityManager",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'No runtime entity manager set. Call PersistentObject#setEntityManager().'",
")",
";",
"}",
"$",
"this",
"->",
"cm",
"=",
"self",
"::",
"$",
"entityManager",
"->",
"getClassMetadata",
"(",
"static",
"::",
"class",
")",
";",
"}"
] | Initializes Doctrine Metadata for this class.
@throws RuntimeException | [
"Initializes",
"Doctrine",
"Metadata",
"for",
"this",
"class",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/PersistentObject.php#L221-L232 | train |
doctrine/orm | lib/Doctrine/ORM/Query/ResultSetMapping.php | ResultSetMapping.addEntityResult | public function addEntityResult($class, $alias, $resultAlias = null)
{
$this->aliasMap[$alias] = $class;
$this->entityMappings[$alias] = $resultAlias;
if ($resultAlias !== null) {
$this->isMixed = true;
}
return $this;
} | php | public function addEntityResult($class, $alias, $resultAlias = null)
{
$this->aliasMap[$alias] = $class;
$this->entityMappings[$alias] = $resultAlias;
if ($resultAlias !== null) {
$this->isMixed = true;
}
return $this;
} | [
"public",
"function",
"addEntityResult",
"(",
"$",
"class",
",",
"$",
"alias",
",",
"$",
"resultAlias",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"aliasMap",
"[",
"$",
"alias",
"]",
"=",
"$",
"class",
";",
"$",
"this",
"->",
"entityMappings",
"[",
"$",
"alias",
"]",
"=",
"$",
"resultAlias",
";",
"if",
"(",
"$",
"resultAlias",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"isMixed",
"=",
"true",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Adds an entity result to this ResultSetMapping.
@param string $class The class name of the entity.
@param string $alias The alias for the class. The alias must be unique among all entity
results or joined entity results within this ResultSetMapping.
@param string|null $resultAlias The result alias with which the entity result should be
placed in the result structure.
@return ResultSetMapping This ResultSetMapping instance.
@todo Rename: addRootEntity | [
"Adds",
"an",
"entity",
"result",
"to",
"this",
"ResultSetMapping",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query/ResultSetMapping.php#L179-L189 | train |
doctrine/orm | lib/Doctrine/ORM/Query/ResultSetMapping.php | ResultSetMapping.setDiscriminatorColumn | public function setDiscriminatorColumn($alias, $discrColumn)
{
$this->discriminatorColumns[$alias] = $discrColumn;
$this->columnOwnerMap[$discrColumn] = $alias;
return $this;
} | php | public function setDiscriminatorColumn($alias, $discrColumn)
{
$this->discriminatorColumns[$alias] = $discrColumn;
$this->columnOwnerMap[$discrColumn] = $alias;
return $this;
} | [
"public",
"function",
"setDiscriminatorColumn",
"(",
"$",
"alias",
",",
"$",
"discrColumn",
")",
"{",
"$",
"this",
"->",
"discriminatorColumns",
"[",
"$",
"alias",
"]",
"=",
"$",
"discrColumn",
";",
"$",
"this",
"->",
"columnOwnerMap",
"[",
"$",
"discrColumn",
"]",
"=",
"$",
"alias",
";",
"return",
"$",
"this",
";",
"}"
] | Sets a discriminator column for an entity result or joined entity result.
The discriminator column will be used to determine the concrete class name to
instantiate.
@param string $alias The alias of the entity result or joined entity result the discriminator
column should be used for.
@param string $discrColumn The name of the discriminator column in the SQL result set.
@return ResultSetMapping This ResultSetMapping instance.
@todo Rename: addDiscriminatorColumn | [
"Sets",
"a",
"discriminator",
"column",
"for",
"an",
"entity",
"result",
"or",
"joined",
"entity",
"result",
".",
"The",
"discriminator",
"column",
"will",
"be",
"used",
"to",
"determine",
"the",
"concrete",
"class",
"name",
"to",
"instantiate",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query/ResultSetMapping.php#L204-L210 | train |
doctrine/orm | lib/Doctrine/ORM/Query/ResultSetMapping.php | ResultSetMapping.addIndexBy | public function addIndexBy($alias, $fieldName)
{
$found = false;
foreach (array_merge($this->metaMappings, $this->fieldMappings) as $columnName => $columnFieldName) {
if (! ($columnFieldName === $fieldName && $this->columnOwnerMap[$columnName] === $alias)) {
continue;
}
$this->addIndexByColumn($alias, $columnName);
$found = true;
break;
}
/* TODO: check if this exception can be put back, for now it's gone because of assumptions made by some ORM internals
if ( ! $found) {
$message = sprintf(
'Cannot add index by for DQL alias %s and field %s without calling addFieldResult() for them before.',
$alias,
$fieldName
);
throw new \LogicException($message);
}
*/
return $this;
} | php | public function addIndexBy($alias, $fieldName)
{
$found = false;
foreach (array_merge($this->metaMappings, $this->fieldMappings) as $columnName => $columnFieldName) {
if (! ($columnFieldName === $fieldName && $this->columnOwnerMap[$columnName] === $alias)) {
continue;
}
$this->addIndexByColumn($alias, $columnName);
$found = true;
break;
}
/* TODO: check if this exception can be put back, for now it's gone because of assumptions made by some ORM internals
if ( ! $found) {
$message = sprintf(
'Cannot add index by for DQL alias %s and field %s without calling addFieldResult() for them before.',
$alias,
$fieldName
);
throw new \LogicException($message);
}
*/
return $this;
} | [
"public",
"function",
"addIndexBy",
"(",
"$",
"alias",
",",
"$",
"fieldName",
")",
"{",
"$",
"found",
"=",
"false",
";",
"foreach",
"(",
"array_merge",
"(",
"$",
"this",
"->",
"metaMappings",
",",
"$",
"this",
"->",
"fieldMappings",
")",
"as",
"$",
"columnName",
"=>",
"$",
"columnFieldName",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"columnFieldName",
"===",
"$",
"fieldName",
"&&",
"$",
"this",
"->",
"columnOwnerMap",
"[",
"$",
"columnName",
"]",
"===",
"$",
"alias",
")",
")",
"{",
"continue",
";",
"}",
"$",
"this",
"->",
"addIndexByColumn",
"(",
"$",
"alias",
",",
"$",
"columnName",
")",
";",
"$",
"found",
"=",
"true",
";",
"break",
";",
"}",
"/* TODO: check if this exception can be put back, for now it's gone because of assumptions made by some ORM internals\n if ( ! $found) {\n $message = sprintf(\n 'Cannot add index by for DQL alias %s and field %s without calling addFieldResult() for them before.',\n $alias,\n $fieldName\n );\n\n throw new \\LogicException($message);\n }\n */",
"return",
"$",
"this",
";",
"}"
] | Sets a field to use for indexing an entity result or joined entity result.
@param string $alias The alias of an entity result or joined entity result.
@param string $fieldName The name of the field to use for indexing.
@return ResultSetMapping This ResultSetMapping instance. | [
"Sets",
"a",
"field",
"to",
"use",
"for",
"indexing",
"an",
"entity",
"result",
"or",
"joined",
"entity",
"result",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query/ResultSetMapping.php#L220-L248 | train |
doctrine/orm | lib/Doctrine/ORM/Query/ResultSetMapping.php | ResultSetMapping.addFieldResult | public function addFieldResult($alias, $columnName, $fieldName, $declaringClass = null)
{
// column name (in result set) => field name
$this->fieldMappings[$columnName] = $fieldName;
// column name => alias of owner
$this->columnOwnerMap[$columnName] = $alias;
// field name => class name of declaring class
$this->declaringClasses[$columnName] = $declaringClass ?: $this->aliasMap[$alias];
if (! $this->isMixed && $this->scalarMappings) {
$this->isMixed = true;
}
return $this;
} | php | public function addFieldResult($alias, $columnName, $fieldName, $declaringClass = null)
{
// column name (in result set) => field name
$this->fieldMappings[$columnName] = $fieldName;
// column name => alias of owner
$this->columnOwnerMap[$columnName] = $alias;
// field name => class name of declaring class
$this->declaringClasses[$columnName] = $declaringClass ?: $this->aliasMap[$alias];
if (! $this->isMixed && $this->scalarMappings) {
$this->isMixed = true;
}
return $this;
} | [
"public",
"function",
"addFieldResult",
"(",
"$",
"alias",
",",
"$",
"columnName",
",",
"$",
"fieldName",
",",
"$",
"declaringClass",
"=",
"null",
")",
"{",
"// column name (in result set) => field name",
"$",
"this",
"->",
"fieldMappings",
"[",
"$",
"columnName",
"]",
"=",
"$",
"fieldName",
";",
"// column name => alias of owner",
"$",
"this",
"->",
"columnOwnerMap",
"[",
"$",
"columnName",
"]",
"=",
"$",
"alias",
";",
"// field name => class name of declaring class",
"$",
"this",
"->",
"declaringClasses",
"[",
"$",
"columnName",
"]",
"=",
"$",
"declaringClass",
"?",
":",
"$",
"this",
"->",
"aliasMap",
"[",
"$",
"alias",
"]",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"isMixed",
"&&",
"$",
"this",
"->",
"scalarMappings",
")",
"{",
"$",
"this",
"->",
"isMixed",
"=",
"true",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Adds a field to the result that belongs to an entity or joined entity.
@param string $alias The alias of the root entity or joined entity to which the field belongs.
@param string $columnName The name of the column in the SQL result set.
@param string $fieldName The name of the field on the declaring class.
@param string|null $declaringClass The name of the class that declares/owns the specified field.
When $alias refers to a superclass in a mapped hierarchy but
the field $fieldName is defined on a subclass, specify that here.
If not specified, the field is assumed to belong to the class
designated by $alias.
@return ResultSetMapping This ResultSetMapping instance.
@todo Rename: addField | [
"Adds",
"a",
"field",
"to",
"the",
"result",
"that",
"belongs",
"to",
"an",
"entity",
"or",
"joined",
"entity",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query/ResultSetMapping.php#L325-L339 | train |
doctrine/orm | lib/Doctrine/ORM/Query/ResultSetMapping.php | ResultSetMapping.addJoinedEntityResult | public function addJoinedEntityResult($class, $alias, $parentAlias, $relation)
{
$this->aliasMap[$alias] = $class;
$this->parentAliasMap[$alias] = $parentAlias;
$this->relationMap[$alias] = $relation;
return $this;
} | php | public function addJoinedEntityResult($class, $alias, $parentAlias, $relation)
{
$this->aliasMap[$alias] = $class;
$this->parentAliasMap[$alias] = $parentAlias;
$this->relationMap[$alias] = $relation;
return $this;
} | [
"public",
"function",
"addJoinedEntityResult",
"(",
"$",
"class",
",",
"$",
"alias",
",",
"$",
"parentAlias",
",",
"$",
"relation",
")",
"{",
"$",
"this",
"->",
"aliasMap",
"[",
"$",
"alias",
"]",
"=",
"$",
"class",
";",
"$",
"this",
"->",
"parentAliasMap",
"[",
"$",
"alias",
"]",
"=",
"$",
"parentAlias",
";",
"$",
"this",
"->",
"relationMap",
"[",
"$",
"alias",
"]",
"=",
"$",
"relation",
";",
"return",
"$",
"this",
";",
"}"
] | Adds a joined entity result.
@param string $class The class name of the joined entity.
@param string $alias The unique alias to use for the joined entity.
@param string $parentAlias The alias of the entity result that is the parent of this joined result.
@param string $relation The association field that connects the parent entity result
with the joined entity result.
@return ResultSetMapping This ResultSetMapping instance.
@todo Rename: addJoinedEntity | [
"Adds",
"a",
"joined",
"entity",
"result",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query/ResultSetMapping.php#L354-L361 | train |
doctrine/orm | lib/Doctrine/ORM/Persisters/Collection/OneToManyPersister.php | OneToManyPersister.deleteJoinedEntityCollection | private function deleteJoinedEntityCollection(PersistentCollection $collection)
{
$association = $collection->getMapping();
$targetClass = $this->em->getClassMetadata($association->getTargetEntity());
$rootClass = $this->em->getClassMetadata($targetClass->getRootClassName());
$sourcePersister = $this->uow->getEntityPersister($association->getSourceEntity());
// 1) Build temporary table DDL
$tempTable = $this->platform->getTemporaryTableName($rootClass->getTemporaryIdTableName());
$idColumns = $rootClass->getIdentifierColumns($this->em);
$idColumnNameList = implode(', ', array_keys($idColumns));
$columnDefinitions = [];
foreach ($idColumns as $columnName => $column) {
$type = $column->getType();
$columnDefinitions[$columnName] = [
'notnull' => true,
'type' => $type,
];
}
$statement = $this->platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable
. ' (' . $this->platform->getColumnDeclarationListSQL($columnDefinitions) . ')';
$this->conn->executeUpdate($statement);
// 2) Build insert table records into temporary table
$dql = ' SELECT t0.' . implode(', t0.', $rootClass->getIdentifierFieldNames())
. ' FROM ' . $targetClass->getClassName() . ' t0 WHERE t0.' . $association->getMappedBy() . ' = :owner';
$query = $this->em->createQuery($dql)->setParameter('owner', $collection->getOwner());
$statement = 'INSERT INTO ' . $tempTable . ' (' . $idColumnNameList . ') ' . $query->getSQL();
$parameters = array_values($sourcePersister->getIdentifier($collection->getOwner()));
$numDeleted = $this->conn->executeUpdate($statement, $parameters);
// 3) Create statement used in DELETE ... WHERE ... IN (subselect)
$deleteSQLTemplate = sprintf(
'DELETE FROM %%s WHERE (%s) IN (SELECT %s FROM %s)',
$idColumnNameList,
$idColumnNameList,
$tempTable
);
// 4) Delete records on each table in the hierarchy
$hierarchyClasses = array_merge(
array_map(
function ($className) {
return $this->em->getClassMetadata($className);
},
array_reverse($targetClass->getSubClasses())
),
[$targetClass],
$targetClass->getAncestorsIterator()->getArrayCopy()
);
foreach ($hierarchyClasses as $class) {
$statement = sprintf($deleteSQLTemplate, $class->table->getQuotedQualifiedName($this->platform));
$this->conn->executeUpdate($statement);
}
// 5) Drop temporary table
$statement = $this->platform->getDropTemporaryTableSQL($tempTable);
$this->conn->executeUpdate($statement);
return $numDeleted;
} | php | private function deleteJoinedEntityCollection(PersistentCollection $collection)
{
$association = $collection->getMapping();
$targetClass = $this->em->getClassMetadata($association->getTargetEntity());
$rootClass = $this->em->getClassMetadata($targetClass->getRootClassName());
$sourcePersister = $this->uow->getEntityPersister($association->getSourceEntity());
// 1) Build temporary table DDL
$tempTable = $this->platform->getTemporaryTableName($rootClass->getTemporaryIdTableName());
$idColumns = $rootClass->getIdentifierColumns($this->em);
$idColumnNameList = implode(', ', array_keys($idColumns));
$columnDefinitions = [];
foreach ($idColumns as $columnName => $column) {
$type = $column->getType();
$columnDefinitions[$columnName] = [
'notnull' => true,
'type' => $type,
];
}
$statement = $this->platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable
. ' (' . $this->platform->getColumnDeclarationListSQL($columnDefinitions) . ')';
$this->conn->executeUpdate($statement);
// 2) Build insert table records into temporary table
$dql = ' SELECT t0.' . implode(', t0.', $rootClass->getIdentifierFieldNames())
. ' FROM ' . $targetClass->getClassName() . ' t0 WHERE t0.' . $association->getMappedBy() . ' = :owner';
$query = $this->em->createQuery($dql)->setParameter('owner', $collection->getOwner());
$statement = 'INSERT INTO ' . $tempTable . ' (' . $idColumnNameList . ') ' . $query->getSQL();
$parameters = array_values($sourcePersister->getIdentifier($collection->getOwner()));
$numDeleted = $this->conn->executeUpdate($statement, $parameters);
// 3) Create statement used in DELETE ... WHERE ... IN (subselect)
$deleteSQLTemplate = sprintf(
'DELETE FROM %%s WHERE (%s) IN (SELECT %s FROM %s)',
$idColumnNameList,
$idColumnNameList,
$tempTable
);
// 4) Delete records on each table in the hierarchy
$hierarchyClasses = array_merge(
array_map(
function ($className) {
return $this->em->getClassMetadata($className);
},
array_reverse($targetClass->getSubClasses())
),
[$targetClass],
$targetClass->getAncestorsIterator()->getArrayCopy()
);
foreach ($hierarchyClasses as $class) {
$statement = sprintf($deleteSQLTemplate, $class->table->getQuotedQualifiedName($this->platform));
$this->conn->executeUpdate($statement);
}
// 5) Drop temporary table
$statement = $this->platform->getDropTemporaryTableSQL($tempTable);
$this->conn->executeUpdate($statement);
return $numDeleted;
} | [
"private",
"function",
"deleteJoinedEntityCollection",
"(",
"PersistentCollection",
"$",
"collection",
")",
"{",
"$",
"association",
"=",
"$",
"collection",
"->",
"getMapping",
"(",
")",
";",
"$",
"targetClass",
"=",
"$",
"this",
"->",
"em",
"->",
"getClassMetadata",
"(",
"$",
"association",
"->",
"getTargetEntity",
"(",
")",
")",
";",
"$",
"rootClass",
"=",
"$",
"this",
"->",
"em",
"->",
"getClassMetadata",
"(",
"$",
"targetClass",
"->",
"getRootClassName",
"(",
")",
")",
";",
"$",
"sourcePersister",
"=",
"$",
"this",
"->",
"uow",
"->",
"getEntityPersister",
"(",
"$",
"association",
"->",
"getSourceEntity",
"(",
")",
")",
";",
"// 1) Build temporary table DDL",
"$",
"tempTable",
"=",
"$",
"this",
"->",
"platform",
"->",
"getTemporaryTableName",
"(",
"$",
"rootClass",
"->",
"getTemporaryIdTableName",
"(",
")",
")",
";",
"$",
"idColumns",
"=",
"$",
"rootClass",
"->",
"getIdentifierColumns",
"(",
"$",
"this",
"->",
"em",
")",
";",
"$",
"idColumnNameList",
"=",
"implode",
"(",
"', '",
",",
"array_keys",
"(",
"$",
"idColumns",
")",
")",
";",
"$",
"columnDefinitions",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"idColumns",
"as",
"$",
"columnName",
"=>",
"$",
"column",
")",
"{",
"$",
"type",
"=",
"$",
"column",
"->",
"getType",
"(",
")",
";",
"$",
"columnDefinitions",
"[",
"$",
"columnName",
"]",
"=",
"[",
"'notnull'",
"=>",
"true",
",",
"'type'",
"=>",
"$",
"type",
",",
"]",
";",
"}",
"$",
"statement",
"=",
"$",
"this",
"->",
"platform",
"->",
"getCreateTemporaryTableSnippetSQL",
"(",
")",
".",
"' '",
".",
"$",
"tempTable",
".",
"' ('",
".",
"$",
"this",
"->",
"platform",
"->",
"getColumnDeclarationListSQL",
"(",
"$",
"columnDefinitions",
")",
".",
"')'",
";",
"$",
"this",
"->",
"conn",
"->",
"executeUpdate",
"(",
"$",
"statement",
")",
";",
"// 2) Build insert table records into temporary table",
"$",
"dql",
"=",
"' SELECT t0.'",
".",
"implode",
"(",
"', t0.'",
",",
"$",
"rootClass",
"->",
"getIdentifierFieldNames",
"(",
")",
")",
".",
"' FROM '",
".",
"$",
"targetClass",
"->",
"getClassName",
"(",
")",
".",
"' t0 WHERE t0.'",
".",
"$",
"association",
"->",
"getMappedBy",
"(",
")",
".",
"' = :owner'",
";",
"$",
"query",
"=",
"$",
"this",
"->",
"em",
"->",
"createQuery",
"(",
"$",
"dql",
")",
"->",
"setParameter",
"(",
"'owner'",
",",
"$",
"collection",
"->",
"getOwner",
"(",
")",
")",
";",
"$",
"statement",
"=",
"'INSERT INTO '",
".",
"$",
"tempTable",
".",
"' ('",
".",
"$",
"idColumnNameList",
".",
"') '",
".",
"$",
"query",
"->",
"getSQL",
"(",
")",
";",
"$",
"parameters",
"=",
"array_values",
"(",
"$",
"sourcePersister",
"->",
"getIdentifier",
"(",
"$",
"collection",
"->",
"getOwner",
"(",
")",
")",
")",
";",
"$",
"numDeleted",
"=",
"$",
"this",
"->",
"conn",
"->",
"executeUpdate",
"(",
"$",
"statement",
",",
"$",
"parameters",
")",
";",
"// 3) Create statement used in DELETE ... WHERE ... IN (subselect)",
"$",
"deleteSQLTemplate",
"=",
"sprintf",
"(",
"'DELETE FROM %%s WHERE (%s) IN (SELECT %s FROM %s)'",
",",
"$",
"idColumnNameList",
",",
"$",
"idColumnNameList",
",",
"$",
"tempTable",
")",
";",
"// 4) Delete records on each table in the hierarchy",
"$",
"hierarchyClasses",
"=",
"array_merge",
"(",
"array_map",
"(",
"function",
"(",
"$",
"className",
")",
"{",
"return",
"$",
"this",
"->",
"em",
"->",
"getClassMetadata",
"(",
"$",
"className",
")",
";",
"}",
",",
"array_reverse",
"(",
"$",
"targetClass",
"->",
"getSubClasses",
"(",
")",
")",
")",
",",
"[",
"$",
"targetClass",
"]",
",",
"$",
"targetClass",
"->",
"getAncestorsIterator",
"(",
")",
"->",
"getArrayCopy",
"(",
")",
")",
";",
"foreach",
"(",
"$",
"hierarchyClasses",
"as",
"$",
"class",
")",
"{",
"$",
"statement",
"=",
"sprintf",
"(",
"$",
"deleteSQLTemplate",
",",
"$",
"class",
"->",
"table",
"->",
"getQuotedQualifiedName",
"(",
"$",
"this",
"->",
"platform",
")",
")",
";",
"$",
"this",
"->",
"conn",
"->",
"executeUpdate",
"(",
"$",
"statement",
")",
";",
"}",
"// 5) Drop temporary table",
"$",
"statement",
"=",
"$",
"this",
"->",
"platform",
"->",
"getDropTemporaryTableSQL",
"(",
"$",
"tempTable",
")",
";",
"$",
"this",
"->",
"conn",
"->",
"executeUpdate",
"(",
"$",
"statement",
")",
";",
"return",
"$",
"numDeleted",
";",
"}"
] | Delete Class Table Inheritance entities.
A temporary table is needed to keep IDs to be deleted in both parent and child class' tables.
Thanks Steve Ebersole (Hibernate) for idea on how to tackle reliably this scenario, we owe him a beer! =)
@return int
@throws DBALException | [
"Delete",
"Class",
"Table",
"Inheritance",
"entities",
".",
"A",
"temporary",
"table",
"is",
"needed",
"to",
"keep",
"IDs",
"to",
"be",
"deleted",
"in",
"both",
"parent",
"and",
"child",
"class",
"tables",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Persisters/Collection/OneToManyPersister.php#L221-L289 | train |
doctrine/orm | lib/Doctrine/ORM/LazyCriteriaCollection.php | LazyCriteriaCollection.count | public function count()
{
if ($this->isInitialized()) {
return $this->collection->count();
}
// Return cached result in case count query was already executed
if ($this->count !== null) {
return $this->count;
}
return $this->count = $this->entityPersister->count($this->criteria);
} | php | public function count()
{
if ($this->isInitialized()) {
return $this->collection->count();
}
// Return cached result in case count query was already executed
if ($this->count !== null) {
return $this->count;
}
return $this->count = $this->entityPersister->count($this->criteria);
} | [
"public",
"function",
"count",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isInitialized",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"collection",
"->",
"count",
"(",
")",
";",
"}",
"// Return cached result in case count query was already executed",
"if",
"(",
"$",
"this",
"->",
"count",
"!==",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"count",
";",
"}",
"return",
"$",
"this",
"->",
"count",
"=",
"$",
"this",
"->",
"entityPersister",
"->",
"count",
"(",
"$",
"this",
"->",
"criteria",
")",
";",
"}"
] | Do an efficient count on the collection
@return int | [
"Do",
"an",
"efficient",
"count",
"on",
"the",
"collection"
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/LazyCriteriaCollection.php#L42-L54 | train |
doctrine/orm | lib/Doctrine/ORM/LazyCriteriaCollection.php | LazyCriteriaCollection.contains | public function contains($element)
{
if ($this->isInitialized()) {
return $this->collection->contains($element);
}
return $this->entityPersister->exists($element, $this->criteria);
} | php | public function contains($element)
{
if ($this->isInitialized()) {
return $this->collection->contains($element);
}
return $this->entityPersister->exists($element, $this->criteria);
} | [
"public",
"function",
"contains",
"(",
"$",
"element",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isInitialized",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"collection",
"->",
"contains",
"(",
"$",
"element",
")",
";",
"}",
"return",
"$",
"this",
"->",
"entityPersister",
"->",
"exists",
"(",
"$",
"element",
",",
"$",
"this",
"->",
"criteria",
")",
";",
"}"
] | Do an optimized search of an element
@param object $element
@return bool | [
"Do",
"an",
"optimized",
"search",
"of",
"an",
"element"
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/LazyCriteriaCollection.php#L77-L84 | train |
doctrine/orm | lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php | ResultSetMappingBuilder.isInheritanceSupported | private function isInheritanceSupported(ClassMetadata $metadata)
{
if ($metadata->inheritanceType === InheritanceType::SINGLE_TABLE
&& in_array($metadata->getClassName(), $metadata->discriminatorMap, true)) {
return true;
}
return ! in_array($metadata->inheritanceType, [InheritanceType::SINGLE_TABLE, InheritanceType::JOINED], true);
} | php | private function isInheritanceSupported(ClassMetadata $metadata)
{
if ($metadata->inheritanceType === InheritanceType::SINGLE_TABLE
&& in_array($metadata->getClassName(), $metadata->discriminatorMap, true)) {
return true;
}
return ! in_array($metadata->inheritanceType, [InheritanceType::SINGLE_TABLE, InheritanceType::JOINED], true);
} | [
"private",
"function",
"isInheritanceSupported",
"(",
"ClassMetadata",
"$",
"metadata",
")",
"{",
"if",
"(",
"$",
"metadata",
"->",
"inheritanceType",
"===",
"InheritanceType",
"::",
"SINGLE_TABLE",
"&&",
"in_array",
"(",
"$",
"metadata",
"->",
"getClassName",
"(",
")",
",",
"$",
"metadata",
"->",
"discriminatorMap",
",",
"true",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"!",
"in_array",
"(",
"$",
"metadata",
"->",
"inheritanceType",
",",
"[",
"InheritanceType",
"::",
"SINGLE_TABLE",
",",
"InheritanceType",
"::",
"JOINED",
"]",
",",
"true",
")",
";",
"}"
] | Checks if inheritance if supported.
@return bool | [
"Checks",
"if",
"inheritance",
"if",
"supported",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php#L181-L189 | train |
doctrine/orm | lib/Doctrine/ORM/Query.php | Query.processParameterMappings | private function processParameterMappings($paramMappings)
{
$sqlParams = [];
$types = [];
foreach ($this->parameters as $parameter) {
$key = $parameter->getName();
$value = $parameter->getValue();
$rsm = $this->getResultSetMapping();
if (! isset($paramMappings[$key])) {
throw QueryException::unknownParameter($key);
}
if (isset($rsm->metadataParameterMapping[$key]) && $value instanceof ClassMetadata) {
$value = $value->getMetadataValue($rsm->metadataParameterMapping[$key]);
}
if (isset($rsm->discriminatorParameters[$key]) && $value instanceof ClassMetadata) {
$value = array_keys(HierarchyDiscriminatorResolver::resolveDiscriminatorsForClass($value, $this->em));
}
$value = $this->processParameterValue($value);
$type = $parameter->getValue() === $value
? $parameter->getType()
: ParameterTypeInferer::inferType($value);
foreach ($paramMappings[$key] as $position) {
$types[$position] = $type;
}
$sqlPositions = $paramMappings[$key];
$sqlPositionsCount = count($sqlPositions);
// optimized multi value sql positions away for now,
// they are not allowed in DQL anyways.
$value = [$value];
$countValue = count($value);
for ($i = 0, $l = $sqlPositionsCount; $i < $l; $i++) {
$sqlParams[$sqlPositions[$i]] = $value[($i % $countValue)];
}
}
if (count($sqlParams) !== count($types)) {
throw QueryException::parameterTypeMismatch();
}
if ($sqlParams) {
ksort($sqlParams);
$sqlParams = array_values($sqlParams);
ksort($types);
$types = array_values($types);
}
return [$sqlParams, $types];
} | php | private function processParameterMappings($paramMappings)
{
$sqlParams = [];
$types = [];
foreach ($this->parameters as $parameter) {
$key = $parameter->getName();
$value = $parameter->getValue();
$rsm = $this->getResultSetMapping();
if (! isset($paramMappings[$key])) {
throw QueryException::unknownParameter($key);
}
if (isset($rsm->metadataParameterMapping[$key]) && $value instanceof ClassMetadata) {
$value = $value->getMetadataValue($rsm->metadataParameterMapping[$key]);
}
if (isset($rsm->discriminatorParameters[$key]) && $value instanceof ClassMetadata) {
$value = array_keys(HierarchyDiscriminatorResolver::resolveDiscriminatorsForClass($value, $this->em));
}
$value = $this->processParameterValue($value);
$type = $parameter->getValue() === $value
? $parameter->getType()
: ParameterTypeInferer::inferType($value);
foreach ($paramMappings[$key] as $position) {
$types[$position] = $type;
}
$sqlPositions = $paramMappings[$key];
$sqlPositionsCount = count($sqlPositions);
// optimized multi value sql positions away for now,
// they are not allowed in DQL anyways.
$value = [$value];
$countValue = count($value);
for ($i = 0, $l = $sqlPositionsCount; $i < $l; $i++) {
$sqlParams[$sqlPositions[$i]] = $value[($i % $countValue)];
}
}
if (count($sqlParams) !== count($types)) {
throw QueryException::parameterTypeMismatch();
}
if ($sqlParams) {
ksort($sqlParams);
$sqlParams = array_values($sqlParams);
ksort($types);
$types = array_values($types);
}
return [$sqlParams, $types];
} | [
"private",
"function",
"processParameterMappings",
"(",
"$",
"paramMappings",
")",
"{",
"$",
"sqlParams",
"=",
"[",
"]",
";",
"$",
"types",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"parameters",
"as",
"$",
"parameter",
")",
"{",
"$",
"key",
"=",
"$",
"parameter",
"->",
"getName",
"(",
")",
";",
"$",
"value",
"=",
"$",
"parameter",
"->",
"getValue",
"(",
")",
";",
"$",
"rsm",
"=",
"$",
"this",
"->",
"getResultSetMapping",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"paramMappings",
"[",
"$",
"key",
"]",
")",
")",
"{",
"throw",
"QueryException",
"::",
"unknownParameter",
"(",
"$",
"key",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"rsm",
"->",
"metadataParameterMapping",
"[",
"$",
"key",
"]",
")",
"&&",
"$",
"value",
"instanceof",
"ClassMetadata",
")",
"{",
"$",
"value",
"=",
"$",
"value",
"->",
"getMetadataValue",
"(",
"$",
"rsm",
"->",
"metadataParameterMapping",
"[",
"$",
"key",
"]",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"rsm",
"->",
"discriminatorParameters",
"[",
"$",
"key",
"]",
")",
"&&",
"$",
"value",
"instanceof",
"ClassMetadata",
")",
"{",
"$",
"value",
"=",
"array_keys",
"(",
"HierarchyDiscriminatorResolver",
"::",
"resolveDiscriminatorsForClass",
"(",
"$",
"value",
",",
"$",
"this",
"->",
"em",
")",
")",
";",
"}",
"$",
"value",
"=",
"$",
"this",
"->",
"processParameterValue",
"(",
"$",
"value",
")",
";",
"$",
"type",
"=",
"$",
"parameter",
"->",
"getValue",
"(",
")",
"===",
"$",
"value",
"?",
"$",
"parameter",
"->",
"getType",
"(",
")",
":",
"ParameterTypeInferer",
"::",
"inferType",
"(",
"$",
"value",
")",
";",
"foreach",
"(",
"$",
"paramMappings",
"[",
"$",
"key",
"]",
"as",
"$",
"position",
")",
"{",
"$",
"types",
"[",
"$",
"position",
"]",
"=",
"$",
"type",
";",
"}",
"$",
"sqlPositions",
"=",
"$",
"paramMappings",
"[",
"$",
"key",
"]",
";",
"$",
"sqlPositionsCount",
"=",
"count",
"(",
"$",
"sqlPositions",
")",
";",
"// optimized multi value sql positions away for now,",
"// they are not allowed in DQL anyways.",
"$",
"value",
"=",
"[",
"$",
"value",
"]",
";",
"$",
"countValue",
"=",
"count",
"(",
"$",
"value",
")",
";",
"for",
"(",
"$",
"i",
"=",
"0",
",",
"$",
"l",
"=",
"$",
"sqlPositionsCount",
";",
"$",
"i",
"<",
"$",
"l",
";",
"$",
"i",
"++",
")",
"{",
"$",
"sqlParams",
"[",
"$",
"sqlPositions",
"[",
"$",
"i",
"]",
"]",
"=",
"$",
"value",
"[",
"(",
"$",
"i",
"%",
"$",
"countValue",
")",
"]",
";",
"}",
"}",
"if",
"(",
"count",
"(",
"$",
"sqlParams",
")",
"!==",
"count",
"(",
"$",
"types",
")",
")",
"{",
"throw",
"QueryException",
"::",
"parameterTypeMismatch",
"(",
")",
";",
"}",
"if",
"(",
"$",
"sqlParams",
")",
"{",
"ksort",
"(",
"$",
"sqlParams",
")",
";",
"$",
"sqlParams",
"=",
"array_values",
"(",
"$",
"sqlParams",
")",
";",
"ksort",
"(",
"$",
"types",
")",
";",
"$",
"types",
"=",
"array_values",
"(",
"$",
"types",
")",
";",
"}",
"return",
"[",
"$",
"sqlParams",
",",
"$",
"types",
"]",
";",
"}"
] | Processes query parameter mappings.
@param mixed[] $paramMappings
@return mixed[][]
@throws Query\QueryException | [
"Processes",
"query",
"parameter",
"mappings",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query.php#L361-L418 | train |
doctrine/orm | lib/Doctrine/ORM/Query.php | Query.iterate | public function iterate($parameters = null, $hydrationMode = self::HYDRATE_OBJECT)
{
$this->setHint(self::HINT_INTERNAL_ITERATION, true);
return parent::iterate($parameters, $hydrationMode);
} | php | public function iterate($parameters = null, $hydrationMode = self::HYDRATE_OBJECT)
{
$this->setHint(self::HINT_INTERNAL_ITERATION, true);
return parent::iterate($parameters, $hydrationMode);
} | [
"public",
"function",
"iterate",
"(",
"$",
"parameters",
"=",
"null",
",",
"$",
"hydrationMode",
"=",
"self",
"::",
"HYDRATE_OBJECT",
")",
"{",
"$",
"this",
"->",
"setHint",
"(",
"self",
"::",
"HINT_INTERNAL_ITERATION",
",",
"true",
")",
";",
"return",
"parent",
"::",
"iterate",
"(",
"$",
"parameters",
",",
"$",
"hydrationMode",
")",
";",
"}"
] | Executes the query and returns an IterableResult that can be used to incrementally
iterated over the result.
@param ArrayCollection|array|Parameter[]|mixed[]|null $parameters The query parameters.
@param int $hydrationMode The hydration mode to use.
@return IterableResult | [
"Executes",
"the",
"query",
"and",
"returns",
"an",
"IterableResult",
"that",
"can",
"be",
"used",
"to",
"incrementally",
"iterated",
"over",
"the",
"result",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query.php#L638-L643 | train |
doctrine/orm | lib/Doctrine/ORM/Query.php | Query.getLockMode | public function getLockMode()
{
$lockMode = $this->getHint(self::HINT_LOCK_MODE);
if ($lockMode === false) {
return null;
}
return $lockMode;
} | php | public function getLockMode()
{
$lockMode = $this->getHint(self::HINT_LOCK_MODE);
if ($lockMode === false) {
return null;
}
return $lockMode;
} | [
"public",
"function",
"getLockMode",
"(",
")",
"{",
"$",
"lockMode",
"=",
"$",
"this",
"->",
"getHint",
"(",
"self",
"::",
"HINT_LOCK_MODE",
")",
";",
"if",
"(",
"$",
"lockMode",
"===",
"false",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"lockMode",
";",
"}"
] | Get the current lock mode for this query.
@return int|null The current lock mode of this query or NULL if no specific lock mode is set. | [
"Get",
"the",
"current",
"lock",
"mode",
"for",
"this",
"query",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query.php#L694-L703 | train |
doctrine/orm | lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php | DatabaseDriver.setTables | public function setTables($entityTables, $manyToManyTables)
{
$this->tables = $this->manyToManyTables = $this->classToTableNames = [];
foreach ($entityTables as $table) {
$className = $this->getClassNameForTable($table->getName());
$this->classToTableNames[$className] = $table->getName();
$this->tables[$table->getName()] = $table;
}
foreach ($manyToManyTables as $table) {
$this->manyToManyTables[$table->getName()] = $table;
}
} | php | public function setTables($entityTables, $manyToManyTables)
{
$this->tables = $this->manyToManyTables = $this->classToTableNames = [];
foreach ($entityTables as $table) {
$className = $this->getClassNameForTable($table->getName());
$this->classToTableNames[$className] = $table->getName();
$this->tables[$table->getName()] = $table;
}
foreach ($manyToManyTables as $table) {
$this->manyToManyTables[$table->getName()] = $table;
}
} | [
"public",
"function",
"setTables",
"(",
"$",
"entityTables",
",",
"$",
"manyToManyTables",
")",
"{",
"$",
"this",
"->",
"tables",
"=",
"$",
"this",
"->",
"manyToManyTables",
"=",
"$",
"this",
"->",
"classToTableNames",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"entityTables",
"as",
"$",
"table",
")",
"{",
"$",
"className",
"=",
"$",
"this",
"->",
"getClassNameForTable",
"(",
"$",
"table",
"->",
"getName",
"(",
")",
")",
";",
"$",
"this",
"->",
"classToTableNames",
"[",
"$",
"className",
"]",
"=",
"$",
"table",
"->",
"getName",
"(",
")",
";",
"$",
"this",
"->",
"tables",
"[",
"$",
"table",
"->",
"getName",
"(",
")",
"]",
"=",
"$",
"table",
";",
"}",
"foreach",
"(",
"$",
"manyToManyTables",
"as",
"$",
"table",
")",
"{",
"$",
"this",
"->",
"manyToManyTables",
"[",
"$",
"table",
"->",
"getName",
"(",
")",
"]",
"=",
"$",
"table",
";",
"}",
"}"
] | Sets tables manually instead of relying on the reverse engineering capabilities of SchemaManager.
@param Table[] $entityTables
@param Table[] $manyToManyTables | [
"Sets",
"tables",
"manually",
"instead",
"of",
"relying",
"on",
"the",
"reverse",
"engineering",
"capabilities",
"of",
"SchemaManager",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php#L120-L134 | train |
doctrine/orm | lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php | DatabaseDriver.buildTable | private function buildTable(Mapping\ClassMetadata $metadata)
{
$tableName = $this->classToTableNames[$metadata->getClassName()];
$indexes = $this->tables[$tableName]->getIndexes();
$tableMetadata = new Mapping\TableMetadata();
$tableMetadata->setName($this->classToTableNames[$metadata->getClassName()]);
foreach ($indexes as $index) {
/** @var Index $index */
if ($index->isPrimary()) {
continue;
}
$tableMetadata->addIndex([
'name' => $index->getName(),
'columns' => $index->getColumns(),
'unique' => $index->isUnique(),
'options' => $index->getOptions(),
'flags' => $index->getFlags(),
]);
}
$metadata->setTable($tableMetadata);
} | php | private function buildTable(Mapping\ClassMetadata $metadata)
{
$tableName = $this->classToTableNames[$metadata->getClassName()];
$indexes = $this->tables[$tableName]->getIndexes();
$tableMetadata = new Mapping\TableMetadata();
$tableMetadata->setName($this->classToTableNames[$metadata->getClassName()]);
foreach ($indexes as $index) {
/** @var Index $index */
if ($index->isPrimary()) {
continue;
}
$tableMetadata->addIndex([
'name' => $index->getName(),
'columns' => $index->getColumns(),
'unique' => $index->isUnique(),
'options' => $index->getOptions(),
'flags' => $index->getFlags(),
]);
}
$metadata->setTable($tableMetadata);
} | [
"private",
"function",
"buildTable",
"(",
"Mapping",
"\\",
"ClassMetadata",
"$",
"metadata",
")",
"{",
"$",
"tableName",
"=",
"$",
"this",
"->",
"classToTableNames",
"[",
"$",
"metadata",
"->",
"getClassName",
"(",
")",
"]",
";",
"$",
"indexes",
"=",
"$",
"this",
"->",
"tables",
"[",
"$",
"tableName",
"]",
"->",
"getIndexes",
"(",
")",
";",
"$",
"tableMetadata",
"=",
"new",
"Mapping",
"\\",
"TableMetadata",
"(",
")",
";",
"$",
"tableMetadata",
"->",
"setName",
"(",
"$",
"this",
"->",
"classToTableNames",
"[",
"$",
"metadata",
"->",
"getClassName",
"(",
")",
"]",
")",
";",
"foreach",
"(",
"$",
"indexes",
"as",
"$",
"index",
")",
"{",
"/** @var Index $index */",
"if",
"(",
"$",
"index",
"->",
"isPrimary",
"(",
")",
")",
"{",
"continue",
";",
"}",
"$",
"tableMetadata",
"->",
"addIndex",
"(",
"[",
"'name'",
"=>",
"$",
"index",
"->",
"getName",
"(",
")",
",",
"'columns'",
"=>",
"$",
"index",
"->",
"getColumns",
"(",
")",
",",
"'unique'",
"=>",
"$",
"index",
"->",
"isUnique",
"(",
")",
",",
"'options'",
"=>",
"$",
"index",
"->",
"getOptions",
"(",
")",
",",
"'flags'",
"=>",
"$",
"index",
"->",
"getFlags",
"(",
")",
",",
"]",
")",
";",
"}",
"$",
"metadata",
"->",
"setTable",
"(",
"$",
"tableMetadata",
")",
";",
"}"
] | Build table from a class metadata. | [
"Build",
"table",
"from",
"a",
"class",
"metadata",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php#L286-L310 | train |
doctrine/orm | lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php | DatabaseDriver.getFieldNameForColumn | private function getFieldNameForColumn($tableName, $columnName, $fk = false)
{
if (isset($this->fieldNamesForColumns[$tableName], $this->fieldNamesForColumns[$tableName][$columnName])) {
return $this->fieldNamesForColumns[$tableName][$columnName];
}
$columnName = strtolower($columnName);
// Replace _id if it is a foreignkey column
if ($fk) {
$columnName = str_replace('_id', '', $columnName);
}
return Inflector::camelize($columnName);
} | php | private function getFieldNameForColumn($tableName, $columnName, $fk = false)
{
if (isset($this->fieldNamesForColumns[$tableName], $this->fieldNamesForColumns[$tableName][$columnName])) {
return $this->fieldNamesForColumns[$tableName][$columnName];
}
$columnName = strtolower($columnName);
// Replace _id if it is a foreignkey column
if ($fk) {
$columnName = str_replace('_id', '', $columnName);
}
return Inflector::camelize($columnName);
} | [
"private",
"function",
"getFieldNameForColumn",
"(",
"$",
"tableName",
",",
"$",
"columnName",
",",
"$",
"fk",
"=",
"false",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"fieldNamesForColumns",
"[",
"$",
"tableName",
"]",
",",
"$",
"this",
"->",
"fieldNamesForColumns",
"[",
"$",
"tableName",
"]",
"[",
"$",
"columnName",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"fieldNamesForColumns",
"[",
"$",
"tableName",
"]",
"[",
"$",
"columnName",
"]",
";",
"}",
"$",
"columnName",
"=",
"strtolower",
"(",
"$",
"columnName",
")",
";",
"// Replace _id if it is a foreignkey column",
"if",
"(",
"$",
"fk",
")",
"{",
"$",
"columnName",
"=",
"str_replace",
"(",
"'_id'",
",",
"''",
",",
"$",
"columnName",
")",
";",
"}",
"return",
"Inflector",
"::",
"camelize",
"(",
"$",
"columnName",
")",
";",
"}"
] | Return the mapped field name for a column, if it exists. Otherwise return camelized version.
@param string $tableName
@param string $columnName
@param bool $fk Whether the column is a foreignkey or not.
@return string | [
"Return",
"the",
"mapped",
"field",
"name",
"for",
"a",
"column",
"if",
"it",
"exists",
".",
"Otherwise",
"return",
"camelized",
"version",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php#L510-L524 | train |
doctrine/orm | lib/Doctrine/ORM/Mapping/Factory/ClassMetadataGenerator.php | ClassMetadataGenerator.generate | public function generate(ClassMetadataDefinition $definition) : string
{
$metadata = $this->mappingDriver->loadMetadataForClass(
$definition->entityClassName,
$definition->parentClassMetadata
);
return $this->metadataExporter->export($metadata);
} | php | public function generate(ClassMetadataDefinition $definition) : string
{
$metadata = $this->mappingDriver->loadMetadataForClass(
$definition->entityClassName,
$definition->parentClassMetadata
);
return $this->metadataExporter->export($metadata);
} | [
"public",
"function",
"generate",
"(",
"ClassMetadataDefinition",
"$",
"definition",
")",
":",
"string",
"{",
"$",
"metadata",
"=",
"$",
"this",
"->",
"mappingDriver",
"->",
"loadMetadataForClass",
"(",
"$",
"definition",
"->",
"entityClassName",
",",
"$",
"definition",
"->",
"parentClassMetadata",
")",
";",
"return",
"$",
"this",
"->",
"metadataExporter",
"->",
"export",
"(",
"$",
"metadata",
")",
";",
"}"
] | Generates class metadata code. | [
"Generates",
"class",
"metadata",
"code",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Mapping/Factory/ClassMetadataGenerator.php#L32-L40 | train |
doctrine/orm | lib/Doctrine/ORM/UnitOfWork.php | UnitOfWork.computeScheduleInsertsChangeSets | private function computeScheduleInsertsChangeSets()
{
foreach ($this->entityInsertions as $entity) {
$class = $this->em->getClassMetadata(get_class($entity));
$this->computeChangeSet($class, $entity);
}
} | php | private function computeScheduleInsertsChangeSets()
{
foreach ($this->entityInsertions as $entity) {
$class = $this->em->getClassMetadata(get_class($entity));
$this->computeChangeSet($class, $entity);
}
} | [
"private",
"function",
"computeScheduleInsertsChangeSets",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"entityInsertions",
"as",
"$",
"entity",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"em",
"->",
"getClassMetadata",
"(",
"get_class",
"(",
"$",
"entity",
")",
")",
";",
"$",
"this",
"->",
"computeChangeSet",
"(",
"$",
"class",
",",
"$",
"entity",
")",
";",
"}",
"}"
] | Computes the changesets of all entities scheduled for insertion. | [
"Computes",
"the",
"changesets",
"of",
"all",
"entities",
"scheduled",
"for",
"insertion",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/UnitOfWork.php#L451-L458 | train |
doctrine/orm | lib/Doctrine/ORM/UnitOfWork.php | UnitOfWork.executeExtraUpdates | private function executeExtraUpdates()
{
foreach ($this->extraUpdates as $oid => $update) {
[$entity, $changeset] = $update;
$this->entityChangeSets[$oid] = $changeset;
$this->getEntityPersister(get_class($entity))->update($entity);
}
$this->extraUpdates = [];
} | php | private function executeExtraUpdates()
{
foreach ($this->extraUpdates as $oid => $update) {
[$entity, $changeset] = $update;
$this->entityChangeSets[$oid] = $changeset;
$this->getEntityPersister(get_class($entity))->update($entity);
}
$this->extraUpdates = [];
} | [
"private",
"function",
"executeExtraUpdates",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"extraUpdates",
"as",
"$",
"oid",
"=>",
"$",
"update",
")",
"{",
"[",
"$",
"entity",
",",
"$",
"changeset",
"]",
"=",
"$",
"update",
";",
"$",
"this",
"->",
"entityChangeSets",
"[",
"$",
"oid",
"]",
"=",
"$",
"changeset",
";",
"$",
"this",
"->",
"getEntityPersister",
"(",
"get_class",
"(",
"$",
"entity",
")",
")",
"->",
"update",
"(",
"$",
"entity",
")",
";",
"}",
"$",
"this",
"->",
"extraUpdates",
"=",
"[",
"]",
";",
"}"
] | Executes any extra updates that have been scheduled. | [
"Executes",
"any",
"extra",
"updates",
"that",
"have",
"been",
"scheduled",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/UnitOfWork.php#L463-L474 | train |
doctrine/orm | lib/Doctrine/ORM/UnitOfWork.php | UnitOfWork.executeUpdates | private function executeUpdates($class)
{
$className = $class->getClassName();
$persister = $this->getEntityPersister($className);
$preUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preUpdate);
$postUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postUpdate);
foreach ($this->entityUpdates as $oid => $entity) {
if ($this->em->getClassMetadata(get_class($entity))->getClassName() !== $className) {
continue;
}
if ($preUpdateInvoke !== ListenersInvoker::INVOKE_NONE) {
$this->listenersInvoker->invoke($class, Events::preUpdate, $entity, new PreUpdateEventArgs($entity, $this->em, $this->getEntityChangeSet($entity)), $preUpdateInvoke);
$this->recomputeSingleEntityChangeSet($class, $entity);
}
if (! empty($this->entityChangeSets[$oid])) {
$persister->update($entity);
}
unset($this->entityUpdates[$oid]);
if ($postUpdateInvoke !== ListenersInvoker::INVOKE_NONE) {
$this->listenersInvoker->invoke($class, Events::postUpdate, $entity, new LifecycleEventArgs($entity, $this->em), $postUpdateInvoke);
}
}
} | php | private function executeUpdates($class)
{
$className = $class->getClassName();
$persister = $this->getEntityPersister($className);
$preUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preUpdate);
$postUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postUpdate);
foreach ($this->entityUpdates as $oid => $entity) {
if ($this->em->getClassMetadata(get_class($entity))->getClassName() !== $className) {
continue;
}
if ($preUpdateInvoke !== ListenersInvoker::INVOKE_NONE) {
$this->listenersInvoker->invoke($class, Events::preUpdate, $entity, new PreUpdateEventArgs($entity, $this->em, $this->getEntityChangeSet($entity)), $preUpdateInvoke);
$this->recomputeSingleEntityChangeSet($class, $entity);
}
if (! empty($this->entityChangeSets[$oid])) {
$persister->update($entity);
}
unset($this->entityUpdates[$oid]);
if ($postUpdateInvoke !== ListenersInvoker::INVOKE_NONE) {
$this->listenersInvoker->invoke($class, Events::postUpdate, $entity, new LifecycleEventArgs($entity, $this->em), $postUpdateInvoke);
}
}
} | [
"private",
"function",
"executeUpdates",
"(",
"$",
"class",
")",
"{",
"$",
"className",
"=",
"$",
"class",
"->",
"getClassName",
"(",
")",
";",
"$",
"persister",
"=",
"$",
"this",
"->",
"getEntityPersister",
"(",
"$",
"className",
")",
";",
"$",
"preUpdateInvoke",
"=",
"$",
"this",
"->",
"listenersInvoker",
"->",
"getSubscribedSystems",
"(",
"$",
"class",
",",
"Events",
"::",
"preUpdate",
")",
";",
"$",
"postUpdateInvoke",
"=",
"$",
"this",
"->",
"listenersInvoker",
"->",
"getSubscribedSystems",
"(",
"$",
"class",
",",
"Events",
"::",
"postUpdate",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"entityUpdates",
"as",
"$",
"oid",
"=>",
"$",
"entity",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"em",
"->",
"getClassMetadata",
"(",
"get_class",
"(",
"$",
"entity",
")",
")",
"->",
"getClassName",
"(",
")",
"!==",
"$",
"className",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"$",
"preUpdateInvoke",
"!==",
"ListenersInvoker",
"::",
"INVOKE_NONE",
")",
"{",
"$",
"this",
"->",
"listenersInvoker",
"->",
"invoke",
"(",
"$",
"class",
",",
"Events",
"::",
"preUpdate",
",",
"$",
"entity",
",",
"new",
"PreUpdateEventArgs",
"(",
"$",
"entity",
",",
"$",
"this",
"->",
"em",
",",
"$",
"this",
"->",
"getEntityChangeSet",
"(",
"$",
"entity",
")",
")",
",",
"$",
"preUpdateInvoke",
")",
";",
"$",
"this",
"->",
"recomputeSingleEntityChangeSet",
"(",
"$",
"class",
",",
"$",
"entity",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"entityChangeSets",
"[",
"$",
"oid",
"]",
")",
")",
"{",
"$",
"persister",
"->",
"update",
"(",
"$",
"entity",
")",
";",
"}",
"unset",
"(",
"$",
"this",
"->",
"entityUpdates",
"[",
"$",
"oid",
"]",
")",
";",
"if",
"(",
"$",
"postUpdateInvoke",
"!==",
"ListenersInvoker",
"::",
"INVOKE_NONE",
")",
"{",
"$",
"this",
"->",
"listenersInvoker",
"->",
"invoke",
"(",
"$",
"class",
",",
"Events",
"::",
"postUpdate",
",",
"$",
"entity",
",",
"new",
"LifecycleEventArgs",
"(",
"$",
"entity",
",",
"$",
"this",
"->",
"em",
")",
",",
"$",
"postUpdateInvoke",
")",
";",
"}",
"}",
"}"
] | Executes all entity updates for entities of the specified type.
@param ClassMetadata $class | [
"Executes",
"all",
"entity",
"updates",
"for",
"entities",
"of",
"the",
"specified",
"type",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/UnitOfWork.php#L990-L1018 | train |
doctrine/orm | lib/Doctrine/ORM/UnitOfWork.php | UnitOfWork.scheduleForInsert | public function scheduleForInsert($entity)
{
$oid = spl_object_id($entity);
if (isset($this->entityUpdates[$oid])) {
throw new InvalidArgumentException('Dirty entity can not be scheduled for insertion.');
}
if (isset($this->entityDeletions[$oid])) {
throw ORMInvalidArgumentException::scheduleInsertForRemovedEntity($entity);
}
if (isset($this->originalEntityData[$oid]) && ! isset($this->entityInsertions[$oid])) {
throw ORMInvalidArgumentException::scheduleInsertForManagedEntity($entity);
}
if (isset($this->entityInsertions[$oid])) {
throw ORMInvalidArgumentException::scheduleInsertTwice($entity);
}
$this->entityInsertions[$oid] = $entity;
if (isset($this->entityIdentifiers[$oid])) {
$this->addToIdentityMap($entity);
}
if ($entity instanceof NotifyPropertyChanged) {
$entity->addPropertyChangedListener($this);
}
} | php | public function scheduleForInsert($entity)
{
$oid = spl_object_id($entity);
if (isset($this->entityUpdates[$oid])) {
throw new InvalidArgumentException('Dirty entity can not be scheduled for insertion.');
}
if (isset($this->entityDeletions[$oid])) {
throw ORMInvalidArgumentException::scheduleInsertForRemovedEntity($entity);
}
if (isset($this->originalEntityData[$oid]) && ! isset($this->entityInsertions[$oid])) {
throw ORMInvalidArgumentException::scheduleInsertForManagedEntity($entity);
}
if (isset($this->entityInsertions[$oid])) {
throw ORMInvalidArgumentException::scheduleInsertTwice($entity);
}
$this->entityInsertions[$oid] = $entity;
if (isset($this->entityIdentifiers[$oid])) {
$this->addToIdentityMap($entity);
}
if ($entity instanceof NotifyPropertyChanged) {
$entity->addPropertyChangedListener($this);
}
} | [
"public",
"function",
"scheduleForInsert",
"(",
"$",
"entity",
")",
"{",
"$",
"oid",
"=",
"spl_object_id",
"(",
"$",
"entity",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"entityUpdates",
"[",
"$",
"oid",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Dirty entity can not be scheduled for insertion.'",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"entityDeletions",
"[",
"$",
"oid",
"]",
")",
")",
"{",
"throw",
"ORMInvalidArgumentException",
"::",
"scheduleInsertForRemovedEntity",
"(",
"$",
"entity",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"originalEntityData",
"[",
"$",
"oid",
"]",
")",
"&&",
"!",
"isset",
"(",
"$",
"this",
"->",
"entityInsertions",
"[",
"$",
"oid",
"]",
")",
")",
"{",
"throw",
"ORMInvalidArgumentException",
"::",
"scheduleInsertForManagedEntity",
"(",
"$",
"entity",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"entityInsertions",
"[",
"$",
"oid",
"]",
")",
")",
"{",
"throw",
"ORMInvalidArgumentException",
"::",
"scheduleInsertTwice",
"(",
"$",
"entity",
")",
";",
"}",
"$",
"this",
"->",
"entityInsertions",
"[",
"$",
"oid",
"]",
"=",
"$",
"entity",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"entityIdentifiers",
"[",
"$",
"oid",
"]",
")",
")",
"{",
"$",
"this",
"->",
"addToIdentityMap",
"(",
"$",
"entity",
")",
";",
"}",
"if",
"(",
"$",
"entity",
"instanceof",
"NotifyPropertyChanged",
")",
"{",
"$",
"entity",
"->",
"addPropertyChangedListener",
"(",
"$",
"this",
")",
";",
"}",
"}"
] | Schedules an entity for insertion into the database.
If the entity already has an identifier, it will be added to the identity map.
@param object $entity The entity to schedule for insertion.
@throws ORMInvalidArgumentException
@throws InvalidArgumentException | [
"Schedules",
"an",
"entity",
"for",
"insertion",
"into",
"the",
"database",
".",
"If",
"the",
"entity",
"already",
"has",
"an",
"identifier",
"it",
"will",
"be",
"added",
"to",
"the",
"identity",
"map",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/UnitOfWork.php#L1146-L1174 | train |
doctrine/orm | lib/Doctrine/ORM/UnitOfWork.php | UnitOfWork.scheduleForUpdate | public function scheduleForUpdate($entity) : void
{
$oid = spl_object_id($entity);
if (! isset($this->entityIdentifiers[$oid])) {
throw ORMInvalidArgumentException::entityHasNoIdentity($entity, 'scheduling for update');
}
if (isset($this->entityDeletions[$oid])) {
throw ORMInvalidArgumentException::entityIsRemoved($entity, 'schedule for update');
}
if (! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) {
$this->entityUpdates[$oid] = $entity;
}
} | php | public function scheduleForUpdate($entity) : void
{
$oid = spl_object_id($entity);
if (! isset($this->entityIdentifiers[$oid])) {
throw ORMInvalidArgumentException::entityHasNoIdentity($entity, 'scheduling for update');
}
if (isset($this->entityDeletions[$oid])) {
throw ORMInvalidArgumentException::entityIsRemoved($entity, 'schedule for update');
}
if (! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) {
$this->entityUpdates[$oid] = $entity;
}
} | [
"public",
"function",
"scheduleForUpdate",
"(",
"$",
"entity",
")",
":",
"void",
"{",
"$",
"oid",
"=",
"spl_object_id",
"(",
"$",
"entity",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"entityIdentifiers",
"[",
"$",
"oid",
"]",
")",
")",
"{",
"throw",
"ORMInvalidArgumentException",
"::",
"entityHasNoIdentity",
"(",
"$",
"entity",
",",
"'scheduling for update'",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"entityDeletions",
"[",
"$",
"oid",
"]",
")",
")",
"{",
"throw",
"ORMInvalidArgumentException",
"::",
"entityIsRemoved",
"(",
"$",
"entity",
",",
"'schedule for update'",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"entityUpdates",
"[",
"$",
"oid",
"]",
")",
"&&",
"!",
"isset",
"(",
"$",
"this",
"->",
"entityInsertions",
"[",
"$",
"oid",
"]",
")",
")",
"{",
"$",
"this",
"->",
"entityUpdates",
"[",
"$",
"oid",
"]",
"=",
"$",
"entity",
";",
"}",
"}"
] | Schedules an entity for being updated.
@param object $entity The entity to schedule for being updated.
@throws ORMInvalidArgumentException | [
"Schedules",
"an",
"entity",
"for",
"being",
"updated",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/UnitOfWork.php#L1195-L1210 | train |
doctrine/orm | lib/Doctrine/ORM/UnitOfWork.php | UnitOfWork.isEntityScheduled | public function isEntityScheduled($entity)
{
$oid = spl_object_id($entity);
return isset($this->entityInsertions[$oid])
|| isset($this->entityUpdates[$oid])
|| isset($this->entityDeletions[$oid]);
} | php | public function isEntityScheduled($entity)
{
$oid = spl_object_id($entity);
return isset($this->entityInsertions[$oid])
|| isset($this->entityUpdates[$oid])
|| isset($this->entityDeletions[$oid]);
} | [
"public",
"function",
"isEntityScheduled",
"(",
"$",
"entity",
")",
"{",
"$",
"oid",
"=",
"spl_object_id",
"(",
"$",
"entity",
")",
";",
"return",
"isset",
"(",
"$",
"this",
"->",
"entityInsertions",
"[",
"$",
"oid",
"]",
")",
"||",
"isset",
"(",
"$",
"this",
"->",
"entityUpdates",
"[",
"$",
"oid",
"]",
")",
"||",
"isset",
"(",
"$",
"this",
"->",
"entityDeletions",
"[",
"$",
"oid",
"]",
")",
";",
"}"
] | Checks whether an entity is scheduled for insertion, update or deletion.
@param object $entity
@return bool | [
"Checks",
"whether",
"an",
"entity",
"is",
"scheduled",
"for",
"insertion",
"update",
"or",
"deletion",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/UnitOfWork.php#L1316-L1323 | train |
doctrine/orm | lib/Doctrine/ORM/UnitOfWork.php | UnitOfWork.performCallbackOnCachedPersister | private function performCallbackOnCachedPersister(callable $callback)
{
if (! $this->hasCache) {
return;
}
foreach (array_merge($this->entityPersisters, $this->collectionPersisters) as $persister) {
if ($persister instanceof CachedPersister) {
$callback($persister);
}
}
} | php | private function performCallbackOnCachedPersister(callable $callback)
{
if (! $this->hasCache) {
return;
}
foreach (array_merge($this->entityPersisters, $this->collectionPersisters) as $persister) {
if ($persister instanceof CachedPersister) {
$callback($persister);
}
}
} | [
"private",
"function",
"performCallbackOnCachedPersister",
"(",
"callable",
"$",
"callback",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasCache",
")",
"{",
"return",
";",
"}",
"foreach",
"(",
"array_merge",
"(",
"$",
"this",
"->",
"entityPersisters",
",",
"$",
"this",
"->",
"collectionPersisters",
")",
"as",
"$",
"persister",
")",
"{",
"if",
"(",
"$",
"persister",
"instanceof",
"CachedPersister",
")",
"{",
"$",
"callback",
"(",
"$",
"persister",
")",
";",
"}",
"}",
"}"
] | Performs an action after the transaction. | [
"Performs",
"an",
"action",
"after",
"the",
"transaction",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/UnitOfWork.php#L2814-L2825 | train |
doctrine/orm | lib/Doctrine/ORM/Mapping/Driver/Annotation/AnnotationDriver.php | AnnotationDriver.convertTableAnnotationToTableMetadata | private function convertTableAnnotationToTableMetadata(
Annotation\Table $tableAnnot,
Mapping\TableMetadata $table
) : Mapping\TableMetadata {
if (! empty($tableAnnot->name)) {
$table->setName($tableAnnot->name);
}
if (! empty($tableAnnot->schema)) {
$table->setSchema($tableAnnot->schema);
}
foreach ($tableAnnot->options as $optionName => $optionValue) {
$table->addOption($optionName, $optionValue);
}
foreach ($tableAnnot->indexes as $indexAnnot) {
$table->addIndex([
'name' => $indexAnnot->name,
'columns' => $indexAnnot->columns,
'unique' => $indexAnnot->unique,
'options' => $indexAnnot->options,
'flags' => $indexAnnot->flags,
]);
}
foreach ($tableAnnot->uniqueConstraints as $uniqueConstraintAnnot) {
$table->addUniqueConstraint([
'name' => $uniqueConstraintAnnot->name,
'columns' => $uniqueConstraintAnnot->columns,
'options' => $uniqueConstraintAnnot->options,
'flags' => $uniqueConstraintAnnot->flags,
]);
}
return $table;
} | php | private function convertTableAnnotationToTableMetadata(
Annotation\Table $tableAnnot,
Mapping\TableMetadata $table
) : Mapping\TableMetadata {
if (! empty($tableAnnot->name)) {
$table->setName($tableAnnot->name);
}
if (! empty($tableAnnot->schema)) {
$table->setSchema($tableAnnot->schema);
}
foreach ($tableAnnot->options as $optionName => $optionValue) {
$table->addOption($optionName, $optionValue);
}
foreach ($tableAnnot->indexes as $indexAnnot) {
$table->addIndex([
'name' => $indexAnnot->name,
'columns' => $indexAnnot->columns,
'unique' => $indexAnnot->unique,
'options' => $indexAnnot->options,
'flags' => $indexAnnot->flags,
]);
}
foreach ($tableAnnot->uniqueConstraints as $uniqueConstraintAnnot) {
$table->addUniqueConstraint([
'name' => $uniqueConstraintAnnot->name,
'columns' => $uniqueConstraintAnnot->columns,
'options' => $uniqueConstraintAnnot->options,
'flags' => $uniqueConstraintAnnot->flags,
]);
}
return $table;
} | [
"private",
"function",
"convertTableAnnotationToTableMetadata",
"(",
"Annotation",
"\\",
"Table",
"$",
"tableAnnot",
",",
"Mapping",
"\\",
"TableMetadata",
"$",
"table",
")",
":",
"Mapping",
"\\",
"TableMetadata",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"tableAnnot",
"->",
"name",
")",
")",
"{",
"$",
"table",
"->",
"setName",
"(",
"$",
"tableAnnot",
"->",
"name",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"tableAnnot",
"->",
"schema",
")",
")",
"{",
"$",
"table",
"->",
"setSchema",
"(",
"$",
"tableAnnot",
"->",
"schema",
")",
";",
"}",
"foreach",
"(",
"$",
"tableAnnot",
"->",
"options",
"as",
"$",
"optionName",
"=>",
"$",
"optionValue",
")",
"{",
"$",
"table",
"->",
"addOption",
"(",
"$",
"optionName",
",",
"$",
"optionValue",
")",
";",
"}",
"foreach",
"(",
"$",
"tableAnnot",
"->",
"indexes",
"as",
"$",
"indexAnnot",
")",
"{",
"$",
"table",
"->",
"addIndex",
"(",
"[",
"'name'",
"=>",
"$",
"indexAnnot",
"->",
"name",
",",
"'columns'",
"=>",
"$",
"indexAnnot",
"->",
"columns",
",",
"'unique'",
"=>",
"$",
"indexAnnot",
"->",
"unique",
",",
"'options'",
"=>",
"$",
"indexAnnot",
"->",
"options",
",",
"'flags'",
"=>",
"$",
"indexAnnot",
"->",
"flags",
",",
"]",
")",
";",
"}",
"foreach",
"(",
"$",
"tableAnnot",
"->",
"uniqueConstraints",
"as",
"$",
"uniqueConstraintAnnot",
")",
"{",
"$",
"table",
"->",
"addUniqueConstraint",
"(",
"[",
"'name'",
"=>",
"$",
"uniqueConstraintAnnot",
"->",
"name",
",",
"'columns'",
"=>",
"$",
"uniqueConstraintAnnot",
"->",
"columns",
",",
"'options'",
"=>",
"$",
"uniqueConstraintAnnot",
"->",
"options",
",",
"'flags'",
"=>",
"$",
"uniqueConstraintAnnot",
"->",
"flags",
",",
"]",
")",
";",
"}",
"return",
"$",
"table",
";",
"}"
] | Parse the given Table as TableMetadata | [
"Parse",
"the",
"given",
"Table",
"as",
"TableMetadata"
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Mapping/Driver/Annotation/AnnotationDriver.php#L857-L893 | train |
doctrine/orm | lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php | AbstractEntityPersister.getHash | protected function getHash($query, $criteria, ?array $orderBy = null, $limit = null, $offset = null)
{
[$params] = $criteria instanceof Criteria
? $this->persister->expandCriteriaParameters($criteria)
: $this->persister->expandParameters($criteria);
return sha1($query . serialize($params) . serialize($orderBy) . $limit . $offset);
} | php | protected function getHash($query, $criteria, ?array $orderBy = null, $limit = null, $offset = null)
{
[$params] = $criteria instanceof Criteria
? $this->persister->expandCriteriaParameters($criteria)
: $this->persister->expandParameters($criteria);
return sha1($query . serialize($params) . serialize($orderBy) . $limit . $offset);
} | [
"protected",
"function",
"getHash",
"(",
"$",
"query",
",",
"$",
"criteria",
",",
"?",
"array",
"$",
"orderBy",
"=",
"null",
",",
"$",
"limit",
"=",
"null",
",",
"$",
"offset",
"=",
"null",
")",
"{",
"[",
"$",
"params",
"]",
"=",
"$",
"criteria",
"instanceof",
"Criteria",
"?",
"$",
"this",
"->",
"persister",
"->",
"expandCriteriaParameters",
"(",
"$",
"criteria",
")",
":",
"$",
"this",
"->",
"persister",
"->",
"expandParameters",
"(",
"$",
"criteria",
")",
";",
"return",
"sha1",
"(",
"$",
"query",
".",
"serialize",
"(",
"$",
"params",
")",
".",
"serialize",
"(",
"$",
"orderBy",
")",
".",
"$",
"limit",
".",
"$",
"offset",
")",
";",
"}"
] | Generates a string of currently query
@param string $query
@param string $criteria
@param mixed[] $orderBy
@param int $limit
@param int $offset
@return string | [
"Generates",
"a",
"string",
"of",
"currently",
"query"
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php#L256-L263 | train |
doctrine/orm | lib/Doctrine/ORM/Mapping/MappingException.php | MappingException.missingRequiredOption | public static function missingRequiredOption($field, $expectedOption, $hint = '')
{
$message = sprintf("The mapping of field '%s' is invalid: The option '%s' is required.", $field, $expectedOption);
if (! empty($hint)) {
$message .= ' (Hint: ' . $hint . ')';
}
return new self($message);
} | php | public static function missingRequiredOption($field, $expectedOption, $hint = '')
{
$message = sprintf("The mapping of field '%s' is invalid: The option '%s' is required.", $field, $expectedOption);
if (! empty($hint)) {
$message .= ' (Hint: ' . $hint . ')';
}
return new self($message);
} | [
"public",
"static",
"function",
"missingRequiredOption",
"(",
"$",
"field",
",",
"$",
"expectedOption",
",",
"$",
"hint",
"=",
"''",
")",
"{",
"$",
"message",
"=",
"sprintf",
"(",
"\"The mapping of field '%s' is invalid: The option '%s' is required.\"",
",",
"$",
"field",
",",
"$",
"expectedOption",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"hint",
")",
")",
"{",
"$",
"message",
".=",
"' (Hint: '",
".",
"$",
"hint",
".",
"')'",
";",
"}",
"return",
"new",
"self",
"(",
"$",
"message",
")",
";",
"}"
] | Called if a required option was not found but is required
@param string $field Which field cannot be processed?
@param string $expectedOption Which option is required
@param string $hint Can optionally be used to supply a tip for common mistakes,
e.g. "Did you think of the plural s?"
@return MappingException | [
"Called",
"if",
"a",
"required",
"option",
"was",
"not",
"found",
"but",
"is",
"required"
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Mapping/MappingException.php#L281-L290 | train |
doctrine/orm | lib/Doctrine/ORM/Query/Parser.php | Parser.match | public function match($token)
{
$lookaheadType = $this->lexer->lookahead['type'];
// Short-circuit on first condition, usually types match
if ($lookaheadType === $token) {
$this->lexer->moveNext();
return;
}
// If parameter is not identifier (1-99) must be exact match
if ($token < Lexer::T_IDENTIFIER) {
$this->syntaxError($this->lexer->getLiteral($token));
}
// If parameter is keyword (200+) must be exact match
if ($token > Lexer::T_IDENTIFIER) {
$this->syntaxError($this->lexer->getLiteral($token));
}
// If parameter is T_IDENTIFIER, then matches T_IDENTIFIER (100) and keywords (200+)
if ($token === Lexer::T_IDENTIFIER && $lookaheadType < Lexer::T_IDENTIFIER) {
$this->syntaxError($this->lexer->getLiteral($token));
}
$this->lexer->moveNext();
} | php | public function match($token)
{
$lookaheadType = $this->lexer->lookahead['type'];
// Short-circuit on first condition, usually types match
if ($lookaheadType === $token) {
$this->lexer->moveNext();
return;
}
// If parameter is not identifier (1-99) must be exact match
if ($token < Lexer::T_IDENTIFIER) {
$this->syntaxError($this->lexer->getLiteral($token));
}
// If parameter is keyword (200+) must be exact match
if ($token > Lexer::T_IDENTIFIER) {
$this->syntaxError($this->lexer->getLiteral($token));
}
// If parameter is T_IDENTIFIER, then matches T_IDENTIFIER (100) and keywords (200+)
if ($token === Lexer::T_IDENTIFIER && $lookaheadType < Lexer::T_IDENTIFIER) {
$this->syntaxError($this->lexer->getLiteral($token));
}
$this->lexer->moveNext();
} | [
"public",
"function",
"match",
"(",
"$",
"token",
")",
"{",
"$",
"lookaheadType",
"=",
"$",
"this",
"->",
"lexer",
"->",
"lookahead",
"[",
"'type'",
"]",
";",
"// Short-circuit on first condition, usually types match",
"if",
"(",
"$",
"lookaheadType",
"===",
"$",
"token",
")",
"{",
"$",
"this",
"->",
"lexer",
"->",
"moveNext",
"(",
")",
";",
"return",
";",
"}",
"// If parameter is not identifier (1-99) must be exact match",
"if",
"(",
"$",
"token",
"<",
"Lexer",
"::",
"T_IDENTIFIER",
")",
"{",
"$",
"this",
"->",
"syntaxError",
"(",
"$",
"this",
"->",
"lexer",
"->",
"getLiteral",
"(",
"$",
"token",
")",
")",
";",
"}",
"// If parameter is keyword (200+) must be exact match",
"if",
"(",
"$",
"token",
">",
"Lexer",
"::",
"T_IDENTIFIER",
")",
"{",
"$",
"this",
"->",
"syntaxError",
"(",
"$",
"this",
"->",
"lexer",
"->",
"getLiteral",
"(",
"$",
"token",
")",
")",
";",
"}",
"// If parameter is T_IDENTIFIER, then matches T_IDENTIFIER (100) and keywords (200+)",
"if",
"(",
"$",
"token",
"===",
"Lexer",
"::",
"T_IDENTIFIER",
"&&",
"$",
"lookaheadType",
"<",
"Lexer",
"::",
"T_IDENTIFIER",
")",
"{",
"$",
"this",
"->",
"syntaxError",
"(",
"$",
"this",
"->",
"lexer",
"->",
"getLiteral",
"(",
"$",
"token",
")",
")",
";",
"}",
"$",
"this",
"->",
"lexer",
"->",
"moveNext",
"(",
")",
";",
"}"
] | Attempts to match the given token with the current lookahead token.
If they match, updates the lookahead token; otherwise raises a syntax
error.
@param int $token The token type.
@throws QueryException If the tokens don't match. | [
"Attempts",
"to",
"match",
"the",
"given",
"token",
"with",
"the",
"current",
"lookahead",
"token",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query/Parser.php#L282-L309 | train |
doctrine/orm | lib/Doctrine/ORM/Query/Parser.php | Parser.free | public function free($deep = false, $position = 0)
{
// WARNING! Use this method with care. It resets the scanner!
$this->lexer->resetPosition($position);
// Deep = true cleans peek and also any previously defined errors
if ($deep) {
$this->lexer->resetPeek();
}
$this->lexer->token = null;
$this->lexer->lookahead = null;
} | php | public function free($deep = false, $position = 0)
{
// WARNING! Use this method with care. It resets the scanner!
$this->lexer->resetPosition($position);
// Deep = true cleans peek and also any previously defined errors
if ($deep) {
$this->lexer->resetPeek();
}
$this->lexer->token = null;
$this->lexer->lookahead = null;
} | [
"public",
"function",
"free",
"(",
"$",
"deep",
"=",
"false",
",",
"$",
"position",
"=",
"0",
")",
"{",
"// WARNING! Use this method with care. It resets the scanner!",
"$",
"this",
"->",
"lexer",
"->",
"resetPosition",
"(",
"$",
"position",
")",
";",
"// Deep = true cleans peek and also any previously defined errors",
"if",
"(",
"$",
"deep",
")",
"{",
"$",
"this",
"->",
"lexer",
"->",
"resetPeek",
"(",
")",
";",
"}",
"$",
"this",
"->",
"lexer",
"->",
"token",
"=",
"null",
";",
"$",
"this",
"->",
"lexer",
"->",
"lookahead",
"=",
"null",
";",
"}"
] | Frees this parser, enabling it to be reused.
@param bool $deep Whether to clean peek and reset errors.
@param int $position Position to reset. | [
"Frees",
"this",
"parser",
"enabling",
"it",
"to",
"be",
"reused",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query/Parser.php#L317-L329 | train |
doctrine/orm | lib/Doctrine/ORM/Query/Parser.php | Parser.peekBeyondClosingParenthesis | private function peekBeyondClosingParenthesis($resetPeek = true)
{
$token = $this->lexer->peek();
$numUnmatched = 1;
while ($numUnmatched > 0 && $token !== null) {
switch ($token['type']) {
case Lexer::T_OPEN_PARENTHESIS:
++$numUnmatched;
break;
case Lexer::T_CLOSE_PARENTHESIS:
--$numUnmatched;
break;
default:
// Do nothing
}
$token = $this->lexer->peek();
}
if ($resetPeek) {
$this->lexer->resetPeek();
}
return $token;
} | php | private function peekBeyondClosingParenthesis($resetPeek = true)
{
$token = $this->lexer->peek();
$numUnmatched = 1;
while ($numUnmatched > 0 && $token !== null) {
switch ($token['type']) {
case Lexer::T_OPEN_PARENTHESIS:
++$numUnmatched;
break;
case Lexer::T_CLOSE_PARENTHESIS:
--$numUnmatched;
break;
default:
// Do nothing
}
$token = $this->lexer->peek();
}
if ($resetPeek) {
$this->lexer->resetPeek();
}
return $token;
} | [
"private",
"function",
"peekBeyondClosingParenthesis",
"(",
"$",
"resetPeek",
"=",
"true",
")",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"lexer",
"->",
"peek",
"(",
")",
";",
"$",
"numUnmatched",
"=",
"1",
";",
"while",
"(",
"$",
"numUnmatched",
">",
"0",
"&&",
"$",
"token",
"!==",
"null",
")",
"{",
"switch",
"(",
"$",
"token",
"[",
"'type'",
"]",
")",
"{",
"case",
"Lexer",
"::",
"T_OPEN_PARENTHESIS",
":",
"++",
"$",
"numUnmatched",
";",
"break",
";",
"case",
"Lexer",
"::",
"T_CLOSE_PARENTHESIS",
":",
"--",
"$",
"numUnmatched",
";",
"break",
";",
"default",
":",
"// Do nothing",
"}",
"$",
"token",
"=",
"$",
"this",
"->",
"lexer",
"->",
"peek",
"(",
")",
";",
"}",
"if",
"(",
"$",
"resetPeek",
")",
"{",
"$",
"this",
"->",
"lexer",
"->",
"resetPeek",
"(",
")",
";",
"}",
"return",
"$",
"token",
";",
"}"
] | Peeks beyond the matched closing parenthesis and returns the first token after that one.
@param bool $resetPeek Reset peek after finding the closing parenthesis.
@return mixed[] | [
"Peeks",
"beyond",
"the",
"matched",
"closing",
"parenthesis",
"and",
"returns",
"the",
"first",
"token",
"after",
"that",
"one",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query/Parser.php#L480-L507 | train |
doctrine/orm | lib/Doctrine/ORM/Query/Parser.php | Parser.isMathOperator | private function isMathOperator($token)
{
return in_array($token['type'], [Lexer::T_PLUS, Lexer::T_MINUS, Lexer::T_DIVIDE, Lexer::T_MULTIPLY], true);
} | php | private function isMathOperator($token)
{
return in_array($token['type'], [Lexer::T_PLUS, Lexer::T_MINUS, Lexer::T_DIVIDE, Lexer::T_MULTIPLY], true);
} | [
"private",
"function",
"isMathOperator",
"(",
"$",
"token",
")",
"{",
"return",
"in_array",
"(",
"$",
"token",
"[",
"'type'",
"]",
",",
"[",
"Lexer",
"::",
"T_PLUS",
",",
"Lexer",
"::",
"T_MINUS",
",",
"Lexer",
"::",
"T_DIVIDE",
",",
"Lexer",
"::",
"T_MULTIPLY",
"]",
",",
"true",
")",
";",
"}"
] | Checks if the given token indicates a mathematical operator.
@param mixed[] $token
@return bool TRUE if the token is a mathematical operator, FALSE otherwise. | [
"Checks",
"if",
"the",
"given",
"token",
"indicates",
"a",
"mathematical",
"operator",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query/Parser.php#L516-L519 | train |
doctrine/orm | lib/Doctrine/ORM/Query/Parser.php | Parser.AliasIdentificationVariable | public function AliasIdentificationVariable()
{
$this->match(Lexer::T_IDENTIFIER);
$aliasIdentVariable = $this->lexer->token['value'];
$exists = isset($this->queryComponents[$aliasIdentVariable]);
if ($exists) {
$this->semanticalError(sprintf("'%s' is already defined.", $aliasIdentVariable), $this->lexer->token);
}
return $aliasIdentVariable;
} | php | public function AliasIdentificationVariable()
{
$this->match(Lexer::T_IDENTIFIER);
$aliasIdentVariable = $this->lexer->token['value'];
$exists = isset($this->queryComponents[$aliasIdentVariable]);
if ($exists) {
$this->semanticalError(sprintf("'%s' is already defined.", $aliasIdentVariable), $this->lexer->token);
}
return $aliasIdentVariable;
} | [
"public",
"function",
"AliasIdentificationVariable",
"(",
")",
"{",
"$",
"this",
"->",
"match",
"(",
"Lexer",
"::",
"T_IDENTIFIER",
")",
";",
"$",
"aliasIdentVariable",
"=",
"$",
"this",
"->",
"lexer",
"->",
"token",
"[",
"'value'",
"]",
";",
"$",
"exists",
"=",
"isset",
"(",
"$",
"this",
"->",
"queryComponents",
"[",
"$",
"aliasIdentVariable",
"]",
")",
";",
"if",
"(",
"$",
"exists",
")",
"{",
"$",
"this",
"->",
"semanticalError",
"(",
"sprintf",
"(",
"\"'%s' is already defined.\"",
",",
"$",
"aliasIdentVariable",
")",
",",
"$",
"this",
"->",
"lexer",
"->",
"token",
")",
";",
"}",
"return",
"$",
"aliasIdentVariable",
";",
"}"
] | AliasIdentificationVariable = identifier
@return string | [
"AliasIdentificationVariable",
"=",
"identifier"
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query/Parser.php#L908-L920 | train |
doctrine/orm | lib/Doctrine/ORM/Query/Parser.php | Parser.validateAbstractSchemaName | private function validateAbstractSchemaName($schemaName) : void
{
if (class_exists($schemaName, true) || interface_exists($schemaName, true)) {
return;
}
try {
$this->getEntityManager()->getClassMetadata($schemaName);
return;
} catch (MappingException $mappingException) {
$this->semanticalError(
sprintf('Class %s could not be mapped', $schemaName),
$this->lexer->token
);
}
$this->semanticalError(sprintf("Class '%s' is not defined.", $schemaName), $this->lexer->token);
} | php | private function validateAbstractSchemaName($schemaName) : void
{
if (class_exists($schemaName, true) || interface_exists($schemaName, true)) {
return;
}
try {
$this->getEntityManager()->getClassMetadata($schemaName);
return;
} catch (MappingException $mappingException) {
$this->semanticalError(
sprintf('Class %s could not be mapped', $schemaName),
$this->lexer->token
);
}
$this->semanticalError(sprintf("Class '%s' is not defined.", $schemaName), $this->lexer->token);
} | [
"private",
"function",
"validateAbstractSchemaName",
"(",
"$",
"schemaName",
")",
":",
"void",
"{",
"if",
"(",
"class_exists",
"(",
"$",
"schemaName",
",",
"true",
")",
"||",
"interface_exists",
"(",
"$",
"schemaName",
",",
"true",
")",
")",
"{",
"return",
";",
"}",
"try",
"{",
"$",
"this",
"->",
"getEntityManager",
"(",
")",
"->",
"getClassMetadata",
"(",
"$",
"schemaName",
")",
";",
"return",
";",
"}",
"catch",
"(",
"MappingException",
"$",
"mappingException",
")",
"{",
"$",
"this",
"->",
"semanticalError",
"(",
"sprintf",
"(",
"'Class %s could not be mapped'",
",",
"$",
"schemaName",
")",
",",
"$",
"this",
"->",
"lexer",
"->",
"token",
")",
";",
"}",
"$",
"this",
"->",
"semanticalError",
"(",
"sprintf",
"(",
"\"Class '%s' is not defined.\"",
",",
"$",
"schemaName",
")",
",",
"$",
"this",
"->",
"lexer",
"->",
"token",
")",
";",
"}"
] | Validates an AbstractSchemaName, making sure the class exists.
@param string $schemaName The name to validate.
@throws QueryException If the name does not exist. | [
"Validates",
"an",
"AbstractSchemaName",
"making",
"sure",
"the",
"class",
"exists",
"."
] | 8bb91280ed1d359c421f4b49ffca6d4453f1ef16 | https://github.com/doctrine/orm/blob/8bb91280ed1d359c421f4b49ffca6d4453f1ef16/lib/Doctrine/ORM/Query/Parser.php#L955-L973 | train |
barryvdh/laravel-cors | src/HandlePreflight.php | HandlePreflight.handle | public function handle($request, Closure $next)
{
if ($this->cors->isPreflightRequest($request)) {
return $this->cors->handlePreflightRequest($request);
}
return $next($request);
} | php | public function handle($request, Closure $next)
{
if ($this->cors->isPreflightRequest($request)) {
return $this->cors->handlePreflightRequest($request);
}
return $next($request);
} | [
"public",
"function",
"handle",
"(",
"$",
"request",
",",
"Closure",
"$",
"next",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"cors",
"->",
"isPreflightRequest",
"(",
"$",
"request",
")",
")",
"{",
"return",
"$",
"this",
"->",
"cors",
"->",
"handlePreflightRequest",
"(",
"$",
"request",
")",
";",
"}",
"return",
"$",
"next",
"(",
"$",
"request",
")",
";",
"}"
] | Handle an incoming Preflight request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed | [
"Handle",
"an",
"incoming",
"Preflight",
"request",
"."
] | c95ac944f2f20a17949aae6645692dfd3b402bca | https://github.com/barryvdh/laravel-cors/blob/c95ac944f2f20a17949aae6645692dfd3b402bca/src/HandlePreflight.php#L23-L30 | train |
thephpleague/oauth2-server | src/Grant/AuthCodeGrant.php | AuthCodeGrant.respondToAccessTokenRequest | public function respondToAccessTokenRequest(
ServerRequestInterface $request,
ResponseTypeInterface $responseType,
DateInterval $accessTokenTTL
) {
// Validate request
$client = $this->validateClient($request);
$encryptedAuthCode = $this->getRequestParameter('code', $request, null);
if ($encryptedAuthCode === null) {
throw OAuthServerException::invalidRequest('code');
}
try {
$authCodePayload = json_decode($this->decrypt($encryptedAuthCode));
$this->validateAuthorizationCode($authCodePayload, $client, $request);
$scopes = $this->scopeRepository->finalizeScopes(
$this->validateScopes($authCodePayload->scopes),
$this->getIdentifier(),
$client,
$authCodePayload->user_id
);
} catch (LogicException $e) {
throw OAuthServerException::invalidRequest('code', 'Cannot decrypt the authorization code', $e);
}
// Validate code challenge
if ($this->enableCodeExchangeProof === true) {
$codeVerifier = $this->getRequestParameter('code_verifier', $request, null);
if ($codeVerifier === null) {
throw OAuthServerException::invalidRequest('code_verifier');
}
// Validate code_verifier according to RFC-7636
// @see: https://tools.ietf.org/html/rfc7636#section-4.1
if (preg_match('/^[A-Za-z0-9-._~]{43,128}$/', $codeVerifier) !== 1) {
throw OAuthServerException::invalidRequest(
'code_verifier',
'Code Verifier must follow the specifications of RFC-7636.'
);
}
switch ($authCodePayload->code_challenge_method) {
case 'plain':
if (hash_equals($codeVerifier, $authCodePayload->code_challenge) === false) {
throw OAuthServerException::invalidGrant('Failed to verify `code_verifier`.');
}
break;
case 'S256':
if (
hash_equals(
strtr(rtrim(base64_encode(hash('sha256', $codeVerifier, true)), '='), '+/', '-_'),
$authCodePayload->code_challenge
) === false
) {
throw OAuthServerException::invalidGrant('Failed to verify `code_verifier`.');
}
// @codeCoverageIgnoreStart
break;
default:
throw OAuthServerException::serverError(
sprintf(
'Unsupported code challenge method `%s`',
$authCodePayload->code_challenge_method
)
);
// @codeCoverageIgnoreEnd
}
}
// Issue and persist new access token
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, $authCodePayload->user_id, $scopes);
$this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
$responseType->setAccessToken($accessToken);
// Issue and persist new refresh token if given
$refreshToken = $this->issueRefreshToken($accessToken);
if ($refreshToken !== null) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request));
$responseType->setRefreshToken($refreshToken);
}
// Revoke used auth code
$this->authCodeRepository->revokeAuthCode($authCodePayload->auth_code_id);
return $responseType;
} | php | public function respondToAccessTokenRequest(
ServerRequestInterface $request,
ResponseTypeInterface $responseType,
DateInterval $accessTokenTTL
) {
// Validate request
$client = $this->validateClient($request);
$encryptedAuthCode = $this->getRequestParameter('code', $request, null);
if ($encryptedAuthCode === null) {
throw OAuthServerException::invalidRequest('code');
}
try {
$authCodePayload = json_decode($this->decrypt($encryptedAuthCode));
$this->validateAuthorizationCode($authCodePayload, $client, $request);
$scopes = $this->scopeRepository->finalizeScopes(
$this->validateScopes($authCodePayload->scopes),
$this->getIdentifier(),
$client,
$authCodePayload->user_id
);
} catch (LogicException $e) {
throw OAuthServerException::invalidRequest('code', 'Cannot decrypt the authorization code', $e);
}
// Validate code challenge
if ($this->enableCodeExchangeProof === true) {
$codeVerifier = $this->getRequestParameter('code_verifier', $request, null);
if ($codeVerifier === null) {
throw OAuthServerException::invalidRequest('code_verifier');
}
// Validate code_verifier according to RFC-7636
// @see: https://tools.ietf.org/html/rfc7636#section-4.1
if (preg_match('/^[A-Za-z0-9-._~]{43,128}$/', $codeVerifier) !== 1) {
throw OAuthServerException::invalidRequest(
'code_verifier',
'Code Verifier must follow the specifications of RFC-7636.'
);
}
switch ($authCodePayload->code_challenge_method) {
case 'plain':
if (hash_equals($codeVerifier, $authCodePayload->code_challenge) === false) {
throw OAuthServerException::invalidGrant('Failed to verify `code_verifier`.');
}
break;
case 'S256':
if (
hash_equals(
strtr(rtrim(base64_encode(hash('sha256', $codeVerifier, true)), '='), '+/', '-_'),
$authCodePayload->code_challenge
) === false
) {
throw OAuthServerException::invalidGrant('Failed to verify `code_verifier`.');
}
// @codeCoverageIgnoreStart
break;
default:
throw OAuthServerException::serverError(
sprintf(
'Unsupported code challenge method `%s`',
$authCodePayload->code_challenge_method
)
);
// @codeCoverageIgnoreEnd
}
}
// Issue and persist new access token
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, $authCodePayload->user_id, $scopes);
$this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
$responseType->setAccessToken($accessToken);
// Issue and persist new refresh token if given
$refreshToken = $this->issueRefreshToken($accessToken);
if ($refreshToken !== null) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request));
$responseType->setRefreshToken($refreshToken);
}
// Revoke used auth code
$this->authCodeRepository->revokeAuthCode($authCodePayload->auth_code_id);
return $responseType;
} | [
"public",
"function",
"respondToAccessTokenRequest",
"(",
"ServerRequestInterface",
"$",
"request",
",",
"ResponseTypeInterface",
"$",
"responseType",
",",
"DateInterval",
"$",
"accessTokenTTL",
")",
"{",
"// Validate request",
"$",
"client",
"=",
"$",
"this",
"->",
"validateClient",
"(",
"$",
"request",
")",
";",
"$",
"encryptedAuthCode",
"=",
"$",
"this",
"->",
"getRequestParameter",
"(",
"'code'",
",",
"$",
"request",
",",
"null",
")",
";",
"if",
"(",
"$",
"encryptedAuthCode",
"===",
"null",
")",
"{",
"throw",
"OAuthServerException",
"::",
"invalidRequest",
"(",
"'code'",
")",
";",
"}",
"try",
"{",
"$",
"authCodePayload",
"=",
"json_decode",
"(",
"$",
"this",
"->",
"decrypt",
"(",
"$",
"encryptedAuthCode",
")",
")",
";",
"$",
"this",
"->",
"validateAuthorizationCode",
"(",
"$",
"authCodePayload",
",",
"$",
"client",
",",
"$",
"request",
")",
";",
"$",
"scopes",
"=",
"$",
"this",
"->",
"scopeRepository",
"->",
"finalizeScopes",
"(",
"$",
"this",
"->",
"validateScopes",
"(",
"$",
"authCodePayload",
"->",
"scopes",
")",
",",
"$",
"this",
"->",
"getIdentifier",
"(",
")",
",",
"$",
"client",
",",
"$",
"authCodePayload",
"->",
"user_id",
")",
";",
"}",
"catch",
"(",
"LogicException",
"$",
"e",
")",
"{",
"throw",
"OAuthServerException",
"::",
"invalidRequest",
"(",
"'code'",
",",
"'Cannot decrypt the authorization code'",
",",
"$",
"e",
")",
";",
"}",
"// Validate code challenge",
"if",
"(",
"$",
"this",
"->",
"enableCodeExchangeProof",
"===",
"true",
")",
"{",
"$",
"codeVerifier",
"=",
"$",
"this",
"->",
"getRequestParameter",
"(",
"'code_verifier'",
",",
"$",
"request",
",",
"null",
")",
";",
"if",
"(",
"$",
"codeVerifier",
"===",
"null",
")",
"{",
"throw",
"OAuthServerException",
"::",
"invalidRequest",
"(",
"'code_verifier'",
")",
";",
"}",
"// Validate code_verifier according to RFC-7636",
"// @see: https://tools.ietf.org/html/rfc7636#section-4.1",
"if",
"(",
"preg_match",
"(",
"'/^[A-Za-z0-9-._~]{43,128}$/'",
",",
"$",
"codeVerifier",
")",
"!==",
"1",
")",
"{",
"throw",
"OAuthServerException",
"::",
"invalidRequest",
"(",
"'code_verifier'",
",",
"'Code Verifier must follow the specifications of RFC-7636.'",
")",
";",
"}",
"switch",
"(",
"$",
"authCodePayload",
"->",
"code_challenge_method",
")",
"{",
"case",
"'plain'",
":",
"if",
"(",
"hash_equals",
"(",
"$",
"codeVerifier",
",",
"$",
"authCodePayload",
"->",
"code_challenge",
")",
"===",
"false",
")",
"{",
"throw",
"OAuthServerException",
"::",
"invalidGrant",
"(",
"'Failed to verify `code_verifier`.'",
")",
";",
"}",
"break",
";",
"case",
"'S256'",
":",
"if",
"(",
"hash_equals",
"(",
"strtr",
"(",
"rtrim",
"(",
"base64_encode",
"(",
"hash",
"(",
"'sha256'",
",",
"$",
"codeVerifier",
",",
"true",
")",
")",
",",
"'='",
")",
",",
"'+/'",
",",
"'-_'",
")",
",",
"$",
"authCodePayload",
"->",
"code_challenge",
")",
"===",
"false",
")",
"{",
"throw",
"OAuthServerException",
"::",
"invalidGrant",
"(",
"'Failed to verify `code_verifier`.'",
")",
";",
"}",
"// @codeCoverageIgnoreStart",
"break",
";",
"default",
":",
"throw",
"OAuthServerException",
"::",
"serverError",
"(",
"sprintf",
"(",
"'Unsupported code challenge method `%s`'",
",",
"$",
"authCodePayload",
"->",
"code_challenge_method",
")",
")",
";",
"// @codeCoverageIgnoreEnd",
"}",
"}",
"// Issue and persist new access token",
"$",
"accessToken",
"=",
"$",
"this",
"->",
"issueAccessToken",
"(",
"$",
"accessTokenTTL",
",",
"$",
"client",
",",
"$",
"authCodePayload",
"->",
"user_id",
",",
"$",
"scopes",
")",
";",
"$",
"this",
"->",
"getEmitter",
"(",
")",
"->",
"emit",
"(",
"new",
"RequestEvent",
"(",
"RequestEvent",
"::",
"ACCESS_TOKEN_ISSUED",
",",
"$",
"request",
")",
")",
";",
"$",
"responseType",
"->",
"setAccessToken",
"(",
"$",
"accessToken",
")",
";",
"// Issue and persist new refresh token if given",
"$",
"refreshToken",
"=",
"$",
"this",
"->",
"issueRefreshToken",
"(",
"$",
"accessToken",
")",
";",
"if",
"(",
"$",
"refreshToken",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"getEmitter",
"(",
")",
"->",
"emit",
"(",
"new",
"RequestEvent",
"(",
"RequestEvent",
"::",
"REFRESH_TOKEN_ISSUED",
",",
"$",
"request",
")",
")",
";",
"$",
"responseType",
"->",
"setRefreshToken",
"(",
"$",
"refreshToken",
")",
";",
"}",
"// Revoke used auth code",
"$",
"this",
"->",
"authCodeRepository",
"->",
"revokeAuthCode",
"(",
"$",
"authCodePayload",
"->",
"auth_code_id",
")",
";",
"return",
"$",
"responseType",
";",
"}"
] | Respond to an access token request.
@param ServerRequestInterface $request
@param ResponseTypeInterface $responseType
@param DateInterval $accessTokenTTL
@throws OAuthServerException
@return ResponseTypeInterface | [
"Respond",
"to",
"an",
"access",
"token",
"request",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Grant/AuthCodeGrant.php#L74-L165 | train |
thephpleague/oauth2-server | src/Grant/AuthCodeGrant.php | AuthCodeGrant.validateAuthorizationCode | private function validateAuthorizationCode(
$authCodePayload,
ClientEntityInterface $client,
ServerRequestInterface $request
) {
if (time() > $authCodePayload->expire_time) {
throw OAuthServerException::invalidRequest('code', 'Authorization code has expired');
}
if ($this->authCodeRepository->isAuthCodeRevoked($authCodePayload->auth_code_id) === true) {
throw OAuthServerException::invalidRequest('code', 'Authorization code has been revoked');
}
if ($authCodePayload->client_id !== $client->getIdentifier()) {
throw OAuthServerException::invalidRequest('code', 'Authorization code was not issued to this client');
}
// The redirect URI is required in this request
$redirectUri = $this->getRequestParameter('redirect_uri', $request, null);
if (empty($authCodePayload->redirect_uri) === false && $redirectUri === null) {
throw OAuthServerException::invalidRequest('redirect_uri');
}
if ($authCodePayload->redirect_uri !== $redirectUri) {
throw OAuthServerException::invalidRequest('redirect_uri', 'Invalid redirect URI');
}
} | php | private function validateAuthorizationCode(
$authCodePayload,
ClientEntityInterface $client,
ServerRequestInterface $request
) {
if (time() > $authCodePayload->expire_time) {
throw OAuthServerException::invalidRequest('code', 'Authorization code has expired');
}
if ($this->authCodeRepository->isAuthCodeRevoked($authCodePayload->auth_code_id) === true) {
throw OAuthServerException::invalidRequest('code', 'Authorization code has been revoked');
}
if ($authCodePayload->client_id !== $client->getIdentifier()) {
throw OAuthServerException::invalidRequest('code', 'Authorization code was not issued to this client');
}
// The redirect URI is required in this request
$redirectUri = $this->getRequestParameter('redirect_uri', $request, null);
if (empty($authCodePayload->redirect_uri) === false && $redirectUri === null) {
throw OAuthServerException::invalidRequest('redirect_uri');
}
if ($authCodePayload->redirect_uri !== $redirectUri) {
throw OAuthServerException::invalidRequest('redirect_uri', 'Invalid redirect URI');
}
} | [
"private",
"function",
"validateAuthorizationCode",
"(",
"$",
"authCodePayload",
",",
"ClientEntityInterface",
"$",
"client",
",",
"ServerRequestInterface",
"$",
"request",
")",
"{",
"if",
"(",
"time",
"(",
")",
">",
"$",
"authCodePayload",
"->",
"expire_time",
")",
"{",
"throw",
"OAuthServerException",
"::",
"invalidRequest",
"(",
"'code'",
",",
"'Authorization code has expired'",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"authCodeRepository",
"->",
"isAuthCodeRevoked",
"(",
"$",
"authCodePayload",
"->",
"auth_code_id",
")",
"===",
"true",
")",
"{",
"throw",
"OAuthServerException",
"::",
"invalidRequest",
"(",
"'code'",
",",
"'Authorization code has been revoked'",
")",
";",
"}",
"if",
"(",
"$",
"authCodePayload",
"->",
"client_id",
"!==",
"$",
"client",
"->",
"getIdentifier",
"(",
")",
")",
"{",
"throw",
"OAuthServerException",
"::",
"invalidRequest",
"(",
"'code'",
",",
"'Authorization code was not issued to this client'",
")",
";",
"}",
"// The redirect URI is required in this request",
"$",
"redirectUri",
"=",
"$",
"this",
"->",
"getRequestParameter",
"(",
"'redirect_uri'",
",",
"$",
"request",
",",
"null",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"authCodePayload",
"->",
"redirect_uri",
")",
"===",
"false",
"&&",
"$",
"redirectUri",
"===",
"null",
")",
"{",
"throw",
"OAuthServerException",
"::",
"invalidRequest",
"(",
"'redirect_uri'",
")",
";",
"}",
"if",
"(",
"$",
"authCodePayload",
"->",
"redirect_uri",
"!==",
"$",
"redirectUri",
")",
"{",
"throw",
"OAuthServerException",
"::",
"invalidRequest",
"(",
"'redirect_uri'",
",",
"'Invalid redirect URI'",
")",
";",
"}",
"}"
] | Validate the authorization code.
@param stdClass $authCodePayload
@param ClientEntityInterface $client
@param ServerRequestInterface $request | [
"Validate",
"the",
"authorization",
"code",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Grant/AuthCodeGrant.php#L174-L200 | train |
thephpleague/oauth2-server | src/Grant/AuthCodeGrant.php | AuthCodeGrant.getClientRedirectUri | private function getClientRedirectUri(AuthorizationRequest $authorizationRequest)
{
return \is_array($authorizationRequest->getClient()->getRedirectUri())
? $authorizationRequest->getClient()->getRedirectUri()[0]
: $authorizationRequest->getClient()->getRedirectUri();
} | php | private function getClientRedirectUri(AuthorizationRequest $authorizationRequest)
{
return \is_array($authorizationRequest->getClient()->getRedirectUri())
? $authorizationRequest->getClient()->getRedirectUri()[0]
: $authorizationRequest->getClient()->getRedirectUri();
} | [
"private",
"function",
"getClientRedirectUri",
"(",
"AuthorizationRequest",
"$",
"authorizationRequest",
")",
"{",
"return",
"\\",
"is_array",
"(",
"$",
"authorizationRequest",
"->",
"getClient",
"(",
")",
"->",
"getRedirectUri",
"(",
")",
")",
"?",
"$",
"authorizationRequest",
"->",
"getClient",
"(",
")",
"->",
"getRedirectUri",
"(",
")",
"[",
"0",
"]",
":",
"$",
"authorizationRequest",
"->",
"getClient",
"(",
")",
"->",
"getRedirectUri",
"(",
")",
";",
"}"
] | Get the client redirect URI if not set in the request.
@param AuthorizationRequest $authorizationRequest
@return string | [
"Get",
"the",
"client",
"redirect",
"URI",
"if",
"not",
"set",
"in",
"the",
"request",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Grant/AuthCodeGrant.php#L384-L389 | train |
thephpleague/oauth2-server | src/CryptTrait.php | CryptTrait.encrypt | protected function encrypt($unencryptedData)
{
try {
if ($this->encryptionKey instanceof Key) {
return Crypto::encrypt($unencryptedData, $this->encryptionKey);
}
return Crypto::encryptWithPassword($unencryptedData, $this->encryptionKey);
} catch (Exception $e) {
throw new LogicException($e->getMessage(), null, $e);
}
} | php | protected function encrypt($unencryptedData)
{
try {
if ($this->encryptionKey instanceof Key) {
return Crypto::encrypt($unencryptedData, $this->encryptionKey);
}
return Crypto::encryptWithPassword($unencryptedData, $this->encryptionKey);
} catch (Exception $e) {
throw new LogicException($e->getMessage(), null, $e);
}
} | [
"protected",
"function",
"encrypt",
"(",
"$",
"unencryptedData",
")",
"{",
"try",
"{",
"if",
"(",
"$",
"this",
"->",
"encryptionKey",
"instanceof",
"Key",
")",
"{",
"return",
"Crypto",
"::",
"encrypt",
"(",
"$",
"unencryptedData",
",",
"$",
"this",
"->",
"encryptionKey",
")",
";",
"}",
"return",
"Crypto",
"::",
"encryptWithPassword",
"(",
"$",
"unencryptedData",
",",
"$",
"this",
"->",
"encryptionKey",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"throw",
"new",
"LogicException",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
",",
"null",
",",
"$",
"e",
")",
";",
"}",
"}"
] | Encrypt data with encryptionKey.
@param string $unencryptedData
@throws LogicException
@return string | [
"Encrypt",
"data",
"with",
"encryptionKey",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/CryptTrait.php#L35-L46 | train |
thephpleague/oauth2-server | src/CryptTrait.php | CryptTrait.decrypt | protected function decrypt($encryptedData)
{
try {
if ($this->encryptionKey instanceof Key) {
return Crypto::decrypt($encryptedData, $this->encryptionKey);
}
return Crypto::decryptWithPassword($encryptedData, $this->encryptionKey);
} catch (Exception $e) {
throw new LogicException($e->getMessage(), null, $e);
}
} | php | protected function decrypt($encryptedData)
{
try {
if ($this->encryptionKey instanceof Key) {
return Crypto::decrypt($encryptedData, $this->encryptionKey);
}
return Crypto::decryptWithPassword($encryptedData, $this->encryptionKey);
} catch (Exception $e) {
throw new LogicException($e->getMessage(), null, $e);
}
} | [
"protected",
"function",
"decrypt",
"(",
"$",
"encryptedData",
")",
"{",
"try",
"{",
"if",
"(",
"$",
"this",
"->",
"encryptionKey",
"instanceof",
"Key",
")",
"{",
"return",
"Crypto",
"::",
"decrypt",
"(",
"$",
"encryptedData",
",",
"$",
"this",
"->",
"encryptionKey",
")",
";",
"}",
"return",
"Crypto",
"::",
"decryptWithPassword",
"(",
"$",
"encryptedData",
",",
"$",
"this",
"->",
"encryptionKey",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"throw",
"new",
"LogicException",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
",",
"null",
",",
"$",
"e",
")",
";",
"}",
"}"
] | Decrypt data with encryptionKey.
@param string $encryptedData
@throws LogicException
@return string | [
"Decrypt",
"data",
"with",
"encryptionKey",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/CryptTrait.php#L57-L68 | train |
thephpleague/oauth2-server | src/Exception/OAuthServerException.php | OAuthServerException.getPayload | public function getPayload()
{
$payload = $this->payload;
// The "message" property is deprecated and replaced by "error_description"
// TODO: remove "message" property
if (isset($payload['error_description']) && !isset($payload['message'])) {
$payload['message'] = $payload['error_description'];
}
return $payload;
} | php | public function getPayload()
{
$payload = $this->payload;
// The "message" property is deprecated and replaced by "error_description"
// TODO: remove "message" property
if (isset($payload['error_description']) && !isset($payload['message'])) {
$payload['message'] = $payload['error_description'];
}
return $payload;
} | [
"public",
"function",
"getPayload",
"(",
")",
"{",
"$",
"payload",
"=",
"$",
"this",
"->",
"payload",
";",
"// The \"message\" property is deprecated and replaced by \"error_description\"",
"// TODO: remove \"message\" property",
"if",
"(",
"isset",
"(",
"$",
"payload",
"[",
"'error_description'",
"]",
")",
"&&",
"!",
"isset",
"(",
"$",
"payload",
"[",
"'message'",
"]",
")",
")",
"{",
"$",
"payload",
"[",
"'message'",
"]",
"=",
"$",
"payload",
"[",
"'error_description'",
"]",
";",
"}",
"return",
"$",
"payload",
";",
"}"
] | Returns the current payload.
@return array | [
"Returns",
"the",
"current",
"payload",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Exception/OAuthServerException.php#L75-L86 | train |
thephpleague/oauth2-server | src/Exception/OAuthServerException.php | OAuthServerException.invalidRequest | public static function invalidRequest($parameter, $hint = null, Throwable $previous = null)
{
$errorMessage = 'The request is missing a required parameter, includes an invalid parameter value, ' .
'includes a parameter more than once, or is otherwise malformed.';
$hint = ($hint === null) ? sprintf('Check the `%s` parameter', $parameter) : $hint;
return new static($errorMessage, 3, 'invalid_request', 400, $hint, null, $previous);
} | php | public static function invalidRequest($parameter, $hint = null, Throwable $previous = null)
{
$errorMessage = 'The request is missing a required parameter, includes an invalid parameter value, ' .
'includes a parameter more than once, or is otherwise malformed.';
$hint = ($hint === null) ? sprintf('Check the `%s` parameter', $parameter) : $hint;
return new static($errorMessage, 3, 'invalid_request', 400, $hint, null, $previous);
} | [
"public",
"static",
"function",
"invalidRequest",
"(",
"$",
"parameter",
",",
"$",
"hint",
"=",
"null",
",",
"Throwable",
"$",
"previous",
"=",
"null",
")",
"{",
"$",
"errorMessage",
"=",
"'The request is missing a required parameter, includes an invalid parameter value, '",
".",
"'includes a parameter more than once, or is otherwise malformed.'",
";",
"$",
"hint",
"=",
"(",
"$",
"hint",
"===",
"null",
")",
"?",
"sprintf",
"(",
"'Check the `%s` parameter'",
",",
"$",
"parameter",
")",
":",
"$",
"hint",
";",
"return",
"new",
"static",
"(",
"$",
"errorMessage",
",",
"3",
",",
"'invalid_request'",
",",
"400",
",",
"$",
"hint",
",",
"null",
",",
"$",
"previous",
")",
";",
"}"
] | Invalid request error.
@param string $parameter The invalid parameter
@param null|string $hint
@param Throwable $previous Previous exception
@return static | [
"Invalid",
"request",
"error",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Exception/OAuthServerException.php#L120-L127 | train |
thephpleague/oauth2-server | src/Exception/OAuthServerException.php | OAuthServerException.invalidScope | public static function invalidScope($scope, $redirectUri = null)
{
$errorMessage = 'The requested scope is invalid, unknown, or malformed';
if (empty($scope)) {
$hint = 'Specify a scope in the request or set a default scope';
} else {
$hint = sprintf(
'Check the `%s` scope',
htmlspecialchars($scope, ENT_QUOTES, 'UTF-8', false)
);
}
return new static($errorMessage, 5, 'invalid_scope', 400, $hint, $redirectUri);
} | php | public static function invalidScope($scope, $redirectUri = null)
{
$errorMessage = 'The requested scope is invalid, unknown, or malformed';
if (empty($scope)) {
$hint = 'Specify a scope in the request or set a default scope';
} else {
$hint = sprintf(
'Check the `%s` scope',
htmlspecialchars($scope, ENT_QUOTES, 'UTF-8', false)
);
}
return new static($errorMessage, 5, 'invalid_scope', 400, $hint, $redirectUri);
} | [
"public",
"static",
"function",
"invalidScope",
"(",
"$",
"scope",
",",
"$",
"redirectUri",
"=",
"null",
")",
"{",
"$",
"errorMessage",
"=",
"'The requested scope is invalid, unknown, or malformed'",
";",
"if",
"(",
"empty",
"(",
"$",
"scope",
")",
")",
"{",
"$",
"hint",
"=",
"'Specify a scope in the request or set a default scope'",
";",
"}",
"else",
"{",
"$",
"hint",
"=",
"sprintf",
"(",
"'Check the `%s` scope'",
",",
"htmlspecialchars",
"(",
"$",
"scope",
",",
"ENT_QUOTES",
",",
"'UTF-8'",
",",
"false",
")",
")",
";",
"}",
"return",
"new",
"static",
"(",
"$",
"errorMessage",
",",
"5",
",",
"'invalid_scope'",
",",
"400",
",",
"$",
"hint",
",",
"$",
"redirectUri",
")",
";",
"}"
] | Invalid scope error.
@param string $scope The bad scope
@param null|string $redirectUri A HTTP URI to redirect the user back to
@return static | [
"Invalid",
"scope",
"error",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Exception/OAuthServerException.php#L149-L163 | train |
thephpleague/oauth2-server | src/Exception/OAuthServerException.php | OAuthServerException.accessDenied | public static function accessDenied($hint = null, $redirectUri = null, Throwable $previous = null)
{
return new static(
'The resource owner or authorization server denied the request.',
9,
'access_denied',
401,
$hint,
$redirectUri,
$previous
);
} | php | public static function accessDenied($hint = null, $redirectUri = null, Throwable $previous = null)
{
return new static(
'The resource owner or authorization server denied the request.',
9,
'access_denied',
401,
$hint,
$redirectUri,
$previous
);
} | [
"public",
"static",
"function",
"accessDenied",
"(",
"$",
"hint",
"=",
"null",
",",
"$",
"redirectUri",
"=",
"null",
",",
"Throwable",
"$",
"previous",
"=",
"null",
")",
"{",
"return",
"new",
"static",
"(",
"'The resource owner or authorization server denied the request.'",
",",
"9",
",",
"'access_denied'",
",",
"401",
",",
"$",
"hint",
",",
"$",
"redirectUri",
",",
"$",
"previous",
")",
";",
"}"
] | Access denied.
@param null|string $hint
@param null|string $redirectUri
@param Throwable $previous
@return static | [
"Access",
"denied",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Exception/OAuthServerException.php#L221-L232 | train |
thephpleague/oauth2-server | src/Exception/OAuthServerException.php | OAuthServerException.generateHttpResponse | public function generateHttpResponse(ResponseInterface $response, $useFragment = false, $jsonOptions = 0)
{
$headers = $this->getHttpHeaders();
$payload = $this->getPayload();
if ($this->redirectUri !== null) {
if ($useFragment === true) {
$this->redirectUri .= (strstr($this->redirectUri, '#') === false) ? '#' : '&';
} else {
$this->redirectUri .= (strstr($this->redirectUri, '?') === false) ? '?' : '&';
}
return $response->withStatus(302)->withHeader('Location', $this->redirectUri . http_build_query($payload));
}
foreach ($headers as $header => $content) {
$response = $response->withHeader($header, $content);
}
$response->getBody()->write(json_encode($payload, $jsonOptions));
return $response->withStatus($this->getHttpStatusCode());
} | php | public function generateHttpResponse(ResponseInterface $response, $useFragment = false, $jsonOptions = 0)
{
$headers = $this->getHttpHeaders();
$payload = $this->getPayload();
if ($this->redirectUri !== null) {
if ($useFragment === true) {
$this->redirectUri .= (strstr($this->redirectUri, '#') === false) ? '#' : '&';
} else {
$this->redirectUri .= (strstr($this->redirectUri, '?') === false) ? '?' : '&';
}
return $response->withStatus(302)->withHeader('Location', $this->redirectUri . http_build_query($payload));
}
foreach ($headers as $header => $content) {
$response = $response->withHeader($header, $content);
}
$response->getBody()->write(json_encode($payload, $jsonOptions));
return $response->withStatus($this->getHttpStatusCode());
} | [
"public",
"function",
"generateHttpResponse",
"(",
"ResponseInterface",
"$",
"response",
",",
"$",
"useFragment",
"=",
"false",
",",
"$",
"jsonOptions",
"=",
"0",
")",
"{",
"$",
"headers",
"=",
"$",
"this",
"->",
"getHttpHeaders",
"(",
")",
";",
"$",
"payload",
"=",
"$",
"this",
"->",
"getPayload",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"redirectUri",
"!==",
"null",
")",
"{",
"if",
"(",
"$",
"useFragment",
"===",
"true",
")",
"{",
"$",
"this",
"->",
"redirectUri",
".=",
"(",
"strstr",
"(",
"$",
"this",
"->",
"redirectUri",
",",
"'#'",
")",
"===",
"false",
")",
"?",
"'#'",
":",
"'&'",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"redirectUri",
".=",
"(",
"strstr",
"(",
"$",
"this",
"->",
"redirectUri",
",",
"'?'",
")",
"===",
"false",
")",
"?",
"'?'",
":",
"'&'",
";",
"}",
"return",
"$",
"response",
"->",
"withStatus",
"(",
"302",
")",
"->",
"withHeader",
"(",
"'Location'",
",",
"$",
"this",
"->",
"redirectUri",
".",
"http_build_query",
"(",
"$",
"payload",
")",
")",
";",
"}",
"foreach",
"(",
"$",
"headers",
"as",
"$",
"header",
"=>",
"$",
"content",
")",
"{",
"$",
"response",
"=",
"$",
"response",
"->",
"withHeader",
"(",
"$",
"header",
",",
"$",
"content",
")",
";",
"}",
"$",
"response",
"->",
"getBody",
"(",
")",
"->",
"write",
"(",
"json_encode",
"(",
"$",
"payload",
",",
"$",
"jsonOptions",
")",
")",
";",
"return",
"$",
"response",
"->",
"withStatus",
"(",
"$",
"this",
"->",
"getHttpStatusCode",
"(",
")",
")",
";",
"}"
] | Generate a HTTP response.
@param ResponseInterface $response
@param bool $useFragment True if errors should be in the URI fragment instead of query string
@param int $jsonOptions options passed to json_encode
@return ResponseInterface | [
"Generate",
"a",
"HTTP",
"response",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Exception/OAuthServerException.php#L271-L294 | train |
thephpleague/oauth2-server | src/Exception/OAuthServerException.php | OAuthServerException.getHttpHeaders | public function getHttpHeaders()
{
$headers = [
'Content-type' => 'application/json',
];
// Add "WWW-Authenticate" header
//
// RFC 6749, section 5.2.:
// "If the client attempted to authenticate via the 'Authorization'
// request header field, the authorization server MUST
// respond with an HTTP 401 (Unauthorized) status code and
// include the "WWW-Authenticate" response header field
// matching the authentication scheme used by the client.
// @codeCoverageIgnoreStart
if ($this->errorType === 'invalid_client' && array_key_exists('HTTP_AUTHORIZATION', $_SERVER) !== false) {
$authScheme = strpos($_SERVER['HTTP_AUTHORIZATION'], 'Bearer') === 0 ? 'Bearer' : 'Basic';
$headers['WWW-Authenticate'] = $authScheme . ' realm="OAuth"';
}
// @codeCoverageIgnoreEnd
return $headers;
} | php | public function getHttpHeaders()
{
$headers = [
'Content-type' => 'application/json',
];
// Add "WWW-Authenticate" header
//
// RFC 6749, section 5.2.:
// "If the client attempted to authenticate via the 'Authorization'
// request header field, the authorization server MUST
// respond with an HTTP 401 (Unauthorized) status code and
// include the "WWW-Authenticate" response header field
// matching the authentication scheme used by the client.
// @codeCoverageIgnoreStart
if ($this->errorType === 'invalid_client' && array_key_exists('HTTP_AUTHORIZATION', $_SERVER) !== false) {
$authScheme = strpos($_SERVER['HTTP_AUTHORIZATION'], 'Bearer') === 0 ? 'Bearer' : 'Basic';
$headers['WWW-Authenticate'] = $authScheme . ' realm="OAuth"';
}
// @codeCoverageIgnoreEnd
return $headers;
} | [
"public",
"function",
"getHttpHeaders",
"(",
")",
"{",
"$",
"headers",
"=",
"[",
"'Content-type'",
"=>",
"'application/json'",
",",
"]",
";",
"// Add \"WWW-Authenticate\" header",
"//",
"// RFC 6749, section 5.2.:",
"// \"If the client attempted to authenticate via the 'Authorization'",
"// request header field, the authorization server MUST",
"// respond with an HTTP 401 (Unauthorized) status code and",
"// include the \"WWW-Authenticate\" response header field",
"// matching the authentication scheme used by the client.",
"// @codeCoverageIgnoreStart",
"if",
"(",
"$",
"this",
"->",
"errorType",
"===",
"'invalid_client'",
"&&",
"array_key_exists",
"(",
"'HTTP_AUTHORIZATION'",
",",
"$",
"_SERVER",
")",
"!==",
"false",
")",
"{",
"$",
"authScheme",
"=",
"strpos",
"(",
"$",
"_SERVER",
"[",
"'HTTP_AUTHORIZATION'",
"]",
",",
"'Bearer'",
")",
"===",
"0",
"?",
"'Bearer'",
":",
"'Basic'",
";",
"$",
"headers",
"[",
"'WWW-Authenticate'",
"]",
"=",
"$",
"authScheme",
".",
"' realm=\"OAuth\"'",
";",
"}",
"// @codeCoverageIgnoreEnd",
"return",
"$",
"headers",
";",
"}"
] | Get all headers that have to be send with the error response.
@return array Array with header values | [
"Get",
"all",
"headers",
"that",
"have",
"to",
"be",
"send",
"with",
"the",
"error",
"response",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Exception/OAuthServerException.php#L301-L323 | train |
thephpleague/oauth2-server | src/Grant/AbstractGrant.php | AbstractGrant.validateClient | protected function validateClient(ServerRequestInterface $request)
{
list($basicAuthUser, $basicAuthPassword) = $this->getBasicAuthCredentials($request);
$clientId = $this->getRequestParameter('client_id', $request, $basicAuthUser);
if ($clientId === null) {
throw OAuthServerException::invalidRequest('client_id');
}
// If the client is confidential require the client secret
$clientSecret = $this->getRequestParameter('client_secret', $request, $basicAuthPassword);
$client = $this->clientRepository->getClientEntity(
$clientId,
$this->getIdentifier(),
$clientSecret,
true
);
if ($client instanceof ClientEntityInterface === false) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
}
$redirectUri = $this->getRequestParameter('redirect_uri', $request, null);
if ($redirectUri !== null) {
$this->validateRedirectUri($redirectUri, $client, $request);
}
return $client;
} | php | protected function validateClient(ServerRequestInterface $request)
{
list($basicAuthUser, $basicAuthPassword) = $this->getBasicAuthCredentials($request);
$clientId = $this->getRequestParameter('client_id', $request, $basicAuthUser);
if ($clientId === null) {
throw OAuthServerException::invalidRequest('client_id');
}
// If the client is confidential require the client secret
$clientSecret = $this->getRequestParameter('client_secret', $request, $basicAuthPassword);
$client = $this->clientRepository->getClientEntity(
$clientId,
$this->getIdentifier(),
$clientSecret,
true
);
if ($client instanceof ClientEntityInterface === false) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
}
$redirectUri = $this->getRequestParameter('redirect_uri', $request, null);
if ($redirectUri !== null) {
$this->validateRedirectUri($redirectUri, $client, $request);
}
return $client;
} | [
"protected",
"function",
"validateClient",
"(",
"ServerRequestInterface",
"$",
"request",
")",
"{",
"list",
"(",
"$",
"basicAuthUser",
",",
"$",
"basicAuthPassword",
")",
"=",
"$",
"this",
"->",
"getBasicAuthCredentials",
"(",
"$",
"request",
")",
";",
"$",
"clientId",
"=",
"$",
"this",
"->",
"getRequestParameter",
"(",
"'client_id'",
",",
"$",
"request",
",",
"$",
"basicAuthUser",
")",
";",
"if",
"(",
"$",
"clientId",
"===",
"null",
")",
"{",
"throw",
"OAuthServerException",
"::",
"invalidRequest",
"(",
"'client_id'",
")",
";",
"}",
"// If the client is confidential require the client secret",
"$",
"clientSecret",
"=",
"$",
"this",
"->",
"getRequestParameter",
"(",
"'client_secret'",
",",
"$",
"request",
",",
"$",
"basicAuthPassword",
")",
";",
"$",
"client",
"=",
"$",
"this",
"->",
"clientRepository",
"->",
"getClientEntity",
"(",
"$",
"clientId",
",",
"$",
"this",
"->",
"getIdentifier",
"(",
")",
",",
"$",
"clientSecret",
",",
"true",
")",
";",
"if",
"(",
"$",
"client",
"instanceof",
"ClientEntityInterface",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"getEmitter",
"(",
")",
"->",
"emit",
"(",
"new",
"RequestEvent",
"(",
"RequestEvent",
"::",
"CLIENT_AUTHENTICATION_FAILED",
",",
"$",
"request",
")",
")",
";",
"throw",
"OAuthServerException",
"::",
"invalidClient",
"(",
")",
";",
"}",
"$",
"redirectUri",
"=",
"$",
"this",
"->",
"getRequestParameter",
"(",
"'redirect_uri'",
",",
"$",
"request",
",",
"null",
")",
";",
"if",
"(",
"$",
"redirectUri",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"validateRedirectUri",
"(",
"$",
"redirectUri",
",",
"$",
"client",
",",
"$",
"request",
")",
";",
"}",
"return",
"$",
"client",
";",
"}"
] | Validate the client.
@param ServerRequestInterface $request
@throws OAuthServerException
@return ClientEntityInterface | [
"Validate",
"the",
"client",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Grant/AbstractGrant.php#L178-L209 | train |
thephpleague/oauth2-server | src/Grant/AbstractGrant.php | AbstractGrant.validateRedirectUri | protected function validateRedirectUri(
string $redirectUri,
ClientEntityInterface $client,
ServerRequestInterface $request
) {
if (\is_string($client->getRedirectUri())
&& (strcmp($client->getRedirectUri(), $redirectUri) !== 0)
) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
} elseif (\is_array($client->getRedirectUri())
&& \in_array($redirectUri, $client->getRedirectUri(), true) === false
) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
}
} | php | protected function validateRedirectUri(
string $redirectUri,
ClientEntityInterface $client,
ServerRequestInterface $request
) {
if (\is_string($client->getRedirectUri())
&& (strcmp($client->getRedirectUri(), $redirectUri) !== 0)
) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
} elseif (\is_array($client->getRedirectUri())
&& \in_array($redirectUri, $client->getRedirectUri(), true) === false
) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
}
} | [
"protected",
"function",
"validateRedirectUri",
"(",
"string",
"$",
"redirectUri",
",",
"ClientEntityInterface",
"$",
"client",
",",
"ServerRequestInterface",
"$",
"request",
")",
"{",
"if",
"(",
"\\",
"is_string",
"(",
"$",
"client",
"->",
"getRedirectUri",
"(",
")",
")",
"&&",
"(",
"strcmp",
"(",
"$",
"client",
"->",
"getRedirectUri",
"(",
")",
",",
"$",
"redirectUri",
")",
"!==",
"0",
")",
")",
"{",
"$",
"this",
"->",
"getEmitter",
"(",
")",
"->",
"emit",
"(",
"new",
"RequestEvent",
"(",
"RequestEvent",
"::",
"CLIENT_AUTHENTICATION_FAILED",
",",
"$",
"request",
")",
")",
";",
"throw",
"OAuthServerException",
"::",
"invalidClient",
"(",
")",
";",
"}",
"elseif",
"(",
"\\",
"is_array",
"(",
"$",
"client",
"->",
"getRedirectUri",
"(",
")",
")",
"&&",
"\\",
"in_array",
"(",
"$",
"redirectUri",
",",
"$",
"client",
"->",
"getRedirectUri",
"(",
")",
",",
"true",
")",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"getEmitter",
"(",
")",
"->",
"emit",
"(",
"new",
"RequestEvent",
"(",
"RequestEvent",
"::",
"CLIENT_AUTHENTICATION_FAILED",
",",
"$",
"request",
")",
")",
";",
"throw",
"OAuthServerException",
"::",
"invalidClient",
"(",
")",
";",
"}",
"}"
] | Validate redirectUri from the request.
If a redirect URI is provided ensure it matches what is pre-registered
@param string $redirectUri
@param ClientEntityInterface $client
@param ServerRequestInterface $request
@throws OAuthServerException | [
"Validate",
"redirectUri",
"from",
"the",
"request",
".",
"If",
"a",
"redirect",
"URI",
"is",
"provided",
"ensure",
"it",
"matches",
"what",
"is",
"pre",
"-",
"registered"
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Grant/AbstractGrant.php#L221-L237 | train |
thephpleague/oauth2-server | src/Grant/AbstractGrant.php | AbstractGrant.validateScopes | public function validateScopes($scopes, $redirectUri = null)
{
if (!\is_array($scopes)) {
$scopes = $this->convertScopesQueryStringToArray($scopes);
}
$validScopes = [];
foreach ($scopes as $scopeItem) {
$scope = $this->scopeRepository->getScopeEntityByIdentifier($scopeItem);
if ($scope instanceof ScopeEntityInterface === false) {
throw OAuthServerException::invalidScope($scopeItem, $redirectUri);
}
$validScopes[] = $scope;
}
return $validScopes;
} | php | public function validateScopes($scopes, $redirectUri = null)
{
if (!\is_array($scopes)) {
$scopes = $this->convertScopesQueryStringToArray($scopes);
}
$validScopes = [];
foreach ($scopes as $scopeItem) {
$scope = $this->scopeRepository->getScopeEntityByIdentifier($scopeItem);
if ($scope instanceof ScopeEntityInterface === false) {
throw OAuthServerException::invalidScope($scopeItem, $redirectUri);
}
$validScopes[] = $scope;
}
return $validScopes;
} | [
"public",
"function",
"validateScopes",
"(",
"$",
"scopes",
",",
"$",
"redirectUri",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"\\",
"is_array",
"(",
"$",
"scopes",
")",
")",
"{",
"$",
"scopes",
"=",
"$",
"this",
"->",
"convertScopesQueryStringToArray",
"(",
"$",
"scopes",
")",
";",
"}",
"$",
"validScopes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"scopes",
"as",
"$",
"scopeItem",
")",
"{",
"$",
"scope",
"=",
"$",
"this",
"->",
"scopeRepository",
"->",
"getScopeEntityByIdentifier",
"(",
"$",
"scopeItem",
")",
";",
"if",
"(",
"$",
"scope",
"instanceof",
"ScopeEntityInterface",
"===",
"false",
")",
"{",
"throw",
"OAuthServerException",
"::",
"invalidScope",
"(",
"$",
"scopeItem",
",",
"$",
"redirectUri",
")",
";",
"}",
"$",
"validScopes",
"[",
"]",
"=",
"$",
"scope",
";",
"}",
"return",
"$",
"validScopes",
";",
"}"
] | Validate scopes in the request.
@param string|array $scopes
@param string $redirectUri
@throws OAuthServerException
@return ScopeEntityInterface[] | [
"Validate",
"scopes",
"in",
"the",
"request",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Grant/AbstractGrant.php#L249-L268 | train |
thephpleague/oauth2-server | src/Grant/AbstractGrant.php | AbstractGrant.convertScopesQueryStringToArray | private function convertScopesQueryStringToArray($scopes)
{
return array_filter(explode(self::SCOPE_DELIMITER_STRING, trim($scopes)), function ($scope) {
return !empty($scope);
});
} | php | private function convertScopesQueryStringToArray($scopes)
{
return array_filter(explode(self::SCOPE_DELIMITER_STRING, trim($scopes)), function ($scope) {
return !empty($scope);
});
} | [
"private",
"function",
"convertScopesQueryStringToArray",
"(",
"$",
"scopes",
")",
"{",
"return",
"array_filter",
"(",
"explode",
"(",
"self",
"::",
"SCOPE_DELIMITER_STRING",
",",
"trim",
"(",
"$",
"scopes",
")",
")",
",",
"function",
"(",
"$",
"scope",
")",
"{",
"return",
"!",
"empty",
"(",
"$",
"scope",
")",
";",
"}",
")",
";",
"}"
] | Converts a scopes query string to an array to easily iterate for validation.
@param string $scopes
@return array | [
"Converts",
"a",
"scopes",
"query",
"string",
"to",
"an",
"array",
"to",
"easily",
"iterate",
"for",
"validation",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Grant/AbstractGrant.php#L277-L282 | train |
thephpleague/oauth2-server | src/Grant/AbstractGrant.php | AbstractGrant.getRequestParameter | protected function getRequestParameter($parameter, ServerRequestInterface $request, $default = null)
{
$requestParameters = (array) $request->getParsedBody();
return $requestParameters[$parameter] ?? $default;
} | php | protected function getRequestParameter($parameter, ServerRequestInterface $request, $default = null)
{
$requestParameters = (array) $request->getParsedBody();
return $requestParameters[$parameter] ?? $default;
} | [
"protected",
"function",
"getRequestParameter",
"(",
"$",
"parameter",
",",
"ServerRequestInterface",
"$",
"request",
",",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"requestParameters",
"=",
"(",
"array",
")",
"$",
"request",
"->",
"getParsedBody",
"(",
")",
";",
"return",
"$",
"requestParameters",
"[",
"$",
"parameter",
"]",
"??",
"$",
"default",
";",
"}"
] | Retrieve request parameter.
@param string $parameter
@param ServerRequestInterface $request
@param mixed $default
@return null|string | [
"Retrieve",
"request",
"parameter",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Grant/AbstractGrant.php#L293-L298 | train |
thephpleague/oauth2-server | src/Grant/AbstractGrant.php | AbstractGrant.getQueryStringParameter | protected function getQueryStringParameter($parameter, ServerRequestInterface $request, $default = null)
{
return isset($request->getQueryParams()[$parameter]) ? $request->getQueryParams()[$parameter] : $default;
} | php | protected function getQueryStringParameter($parameter, ServerRequestInterface $request, $default = null)
{
return isset($request->getQueryParams()[$parameter]) ? $request->getQueryParams()[$parameter] : $default;
} | [
"protected",
"function",
"getQueryStringParameter",
"(",
"$",
"parameter",
",",
"ServerRequestInterface",
"$",
"request",
",",
"$",
"default",
"=",
"null",
")",
"{",
"return",
"isset",
"(",
"$",
"request",
"->",
"getQueryParams",
"(",
")",
"[",
"$",
"parameter",
"]",
")",
"?",
"$",
"request",
"->",
"getQueryParams",
"(",
")",
"[",
"$",
"parameter",
"]",
":",
"$",
"default",
";",
"}"
] | Retrieve query string parameter.
@param string $parameter
@param ServerRequestInterface $request
@param mixed $default
@return null|string | [
"Retrieve",
"query",
"string",
"parameter",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Grant/AbstractGrant.php#L342-L345 | train |
thephpleague/oauth2-server | src/Grant/AbstractGrant.php | AbstractGrant.getCookieParameter | protected function getCookieParameter($parameter, ServerRequestInterface $request, $default = null)
{
return isset($request->getCookieParams()[$parameter]) ? $request->getCookieParams()[$parameter] : $default;
} | php | protected function getCookieParameter($parameter, ServerRequestInterface $request, $default = null)
{
return isset($request->getCookieParams()[$parameter]) ? $request->getCookieParams()[$parameter] : $default;
} | [
"protected",
"function",
"getCookieParameter",
"(",
"$",
"parameter",
",",
"ServerRequestInterface",
"$",
"request",
",",
"$",
"default",
"=",
"null",
")",
"{",
"return",
"isset",
"(",
"$",
"request",
"->",
"getCookieParams",
"(",
")",
"[",
"$",
"parameter",
"]",
")",
"?",
"$",
"request",
"->",
"getCookieParams",
"(",
")",
"[",
"$",
"parameter",
"]",
":",
"$",
"default",
";",
"}"
] | Retrieve cookie parameter.
@param string $parameter
@param ServerRequestInterface $request
@param mixed $default
@return null|string | [
"Retrieve",
"cookie",
"parameter",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Grant/AbstractGrant.php#L356-L359 | train |
thephpleague/oauth2-server | src/Grant/AbstractGrant.php | AbstractGrant.getServerParameter | protected function getServerParameter($parameter, ServerRequestInterface $request, $default = null)
{
return isset($request->getServerParams()[$parameter]) ? $request->getServerParams()[$parameter] : $default;
} | php | protected function getServerParameter($parameter, ServerRequestInterface $request, $default = null)
{
return isset($request->getServerParams()[$parameter]) ? $request->getServerParams()[$parameter] : $default;
} | [
"protected",
"function",
"getServerParameter",
"(",
"$",
"parameter",
",",
"ServerRequestInterface",
"$",
"request",
",",
"$",
"default",
"=",
"null",
")",
"{",
"return",
"isset",
"(",
"$",
"request",
"->",
"getServerParams",
"(",
")",
"[",
"$",
"parameter",
"]",
")",
"?",
"$",
"request",
"->",
"getServerParams",
"(",
")",
"[",
"$",
"parameter",
"]",
":",
"$",
"default",
";",
"}"
] | Retrieve server parameter.
@param string $parameter
@param ServerRequestInterface $request
@param mixed $default
@return null|string | [
"Retrieve",
"server",
"parameter",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Grant/AbstractGrant.php#L370-L373 | train |
thephpleague/oauth2-server | src/Grant/AbstractGrant.php | AbstractGrant.generateUniqueIdentifier | protected function generateUniqueIdentifier($length = 40)
{
try {
return bin2hex(random_bytes($length));
// @codeCoverageIgnoreStart
} catch (TypeError $e) {
throw OAuthServerException::serverError('An unexpected error has occurred', $e);
} catch (Error $e) {
throw OAuthServerException::serverError('An unexpected error has occurred', $e);
} catch (Exception $e) {
// If you get this message, the CSPRNG failed hard.
throw OAuthServerException::serverError('Could not generate a random string', $e);
}
// @codeCoverageIgnoreEnd
} | php | protected function generateUniqueIdentifier($length = 40)
{
try {
return bin2hex(random_bytes($length));
// @codeCoverageIgnoreStart
} catch (TypeError $e) {
throw OAuthServerException::serverError('An unexpected error has occurred', $e);
} catch (Error $e) {
throw OAuthServerException::serverError('An unexpected error has occurred', $e);
} catch (Exception $e) {
// If you get this message, the CSPRNG failed hard.
throw OAuthServerException::serverError('Could not generate a random string', $e);
}
// @codeCoverageIgnoreEnd
} | [
"protected",
"function",
"generateUniqueIdentifier",
"(",
"$",
"length",
"=",
"40",
")",
"{",
"try",
"{",
"return",
"bin2hex",
"(",
"random_bytes",
"(",
"$",
"length",
")",
")",
";",
"// @codeCoverageIgnoreStart",
"}",
"catch",
"(",
"TypeError",
"$",
"e",
")",
"{",
"throw",
"OAuthServerException",
"::",
"serverError",
"(",
"'An unexpected error has occurred'",
",",
"$",
"e",
")",
";",
"}",
"catch",
"(",
"Error",
"$",
"e",
")",
"{",
"throw",
"OAuthServerException",
"::",
"serverError",
"(",
"'An unexpected error has occurred'",
",",
"$",
"e",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"// If you get this message, the CSPRNG failed hard.",
"throw",
"OAuthServerException",
"::",
"serverError",
"(",
"'Could not generate a random string'",
",",
"$",
"e",
")",
";",
"}",
"// @codeCoverageIgnoreEnd",
"}"
] | Generate a new unique identifier.
@param int $length
@throws OAuthServerException
@return string | [
"Generate",
"a",
"new",
"unique",
"identifier",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/Grant/AbstractGrant.php#L513-L527 | train |
thephpleague/oauth2-server | src/AuthorizationServer.php | AuthorizationServer.enableGrantType | public function enableGrantType(GrantTypeInterface $grantType, DateInterval $accessTokenTTL = null)
{
if ($accessTokenTTL instanceof DateInterval === false) {
$accessTokenTTL = new DateInterval('PT1H');
}
$grantType->setAccessTokenRepository($this->accessTokenRepository);
$grantType->setClientRepository($this->clientRepository);
$grantType->setScopeRepository($this->scopeRepository);
$grantType->setDefaultScope($this->defaultScope);
$grantType->setPrivateKey($this->privateKey);
$grantType->setEmitter($this->getEmitter());
$grantType->setEncryptionKey($this->encryptionKey);
$this->enabledGrantTypes[$grantType->getIdentifier()] = $grantType;
$this->grantTypeAccessTokenTTL[$grantType->getIdentifier()] = $accessTokenTTL;
} | php | public function enableGrantType(GrantTypeInterface $grantType, DateInterval $accessTokenTTL = null)
{
if ($accessTokenTTL instanceof DateInterval === false) {
$accessTokenTTL = new DateInterval('PT1H');
}
$grantType->setAccessTokenRepository($this->accessTokenRepository);
$grantType->setClientRepository($this->clientRepository);
$grantType->setScopeRepository($this->scopeRepository);
$grantType->setDefaultScope($this->defaultScope);
$grantType->setPrivateKey($this->privateKey);
$grantType->setEmitter($this->getEmitter());
$grantType->setEncryptionKey($this->encryptionKey);
$this->enabledGrantTypes[$grantType->getIdentifier()] = $grantType;
$this->grantTypeAccessTokenTTL[$grantType->getIdentifier()] = $accessTokenTTL;
} | [
"public",
"function",
"enableGrantType",
"(",
"GrantTypeInterface",
"$",
"grantType",
",",
"DateInterval",
"$",
"accessTokenTTL",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"accessTokenTTL",
"instanceof",
"DateInterval",
"===",
"false",
")",
"{",
"$",
"accessTokenTTL",
"=",
"new",
"DateInterval",
"(",
"'PT1H'",
")",
";",
"}",
"$",
"grantType",
"->",
"setAccessTokenRepository",
"(",
"$",
"this",
"->",
"accessTokenRepository",
")",
";",
"$",
"grantType",
"->",
"setClientRepository",
"(",
"$",
"this",
"->",
"clientRepository",
")",
";",
"$",
"grantType",
"->",
"setScopeRepository",
"(",
"$",
"this",
"->",
"scopeRepository",
")",
";",
"$",
"grantType",
"->",
"setDefaultScope",
"(",
"$",
"this",
"->",
"defaultScope",
")",
";",
"$",
"grantType",
"->",
"setPrivateKey",
"(",
"$",
"this",
"->",
"privateKey",
")",
";",
"$",
"grantType",
"->",
"setEmitter",
"(",
"$",
"this",
"->",
"getEmitter",
"(",
")",
")",
";",
"$",
"grantType",
"->",
"setEncryptionKey",
"(",
"$",
"this",
"->",
"encryptionKey",
")",
";",
"$",
"this",
"->",
"enabledGrantTypes",
"[",
"$",
"grantType",
"->",
"getIdentifier",
"(",
")",
"]",
"=",
"$",
"grantType",
";",
"$",
"this",
"->",
"grantTypeAccessTokenTTL",
"[",
"$",
"grantType",
"->",
"getIdentifier",
"(",
")",
"]",
"=",
"$",
"accessTokenTTL",
";",
"}"
] | Enable a grant type on the server.
@param GrantTypeInterface $grantType
@param null|DateInterval $accessTokenTTL | [
"Enable",
"a",
"grant",
"type",
"on",
"the",
"server",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/AuthorizationServer.php#L126-L142 | train |
thephpleague/oauth2-server | src/AuthorizationServer.php | AuthorizationServer.validateAuthorizationRequest | public function validateAuthorizationRequest(ServerRequestInterface $request)
{
foreach ($this->enabledGrantTypes as $grantType) {
if ($grantType->canRespondToAuthorizationRequest($request)) {
return $grantType->validateAuthorizationRequest($request);
}
}
throw OAuthServerException::unsupportedGrantType();
} | php | public function validateAuthorizationRequest(ServerRequestInterface $request)
{
foreach ($this->enabledGrantTypes as $grantType) {
if ($grantType->canRespondToAuthorizationRequest($request)) {
return $grantType->validateAuthorizationRequest($request);
}
}
throw OAuthServerException::unsupportedGrantType();
} | [
"public",
"function",
"validateAuthorizationRequest",
"(",
"ServerRequestInterface",
"$",
"request",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"enabledGrantTypes",
"as",
"$",
"grantType",
")",
"{",
"if",
"(",
"$",
"grantType",
"->",
"canRespondToAuthorizationRequest",
"(",
"$",
"request",
")",
")",
"{",
"return",
"$",
"grantType",
"->",
"validateAuthorizationRequest",
"(",
"$",
"request",
")",
";",
"}",
"}",
"throw",
"OAuthServerException",
"::",
"unsupportedGrantType",
"(",
")",
";",
"}"
] | Validate an authorization request
@param ServerRequestInterface $request
@throws OAuthServerException
@return AuthorizationRequest | [
"Validate",
"an",
"authorization",
"request"
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/AuthorizationServer.php#L153-L162 | train |
thephpleague/oauth2-server | src/AuthorizationServer.php | AuthorizationServer.completeAuthorizationRequest | public function completeAuthorizationRequest(AuthorizationRequest $authRequest, ResponseInterface $response)
{
return $this->enabledGrantTypes[$authRequest->getGrantTypeId()]
->completeAuthorizationRequest($authRequest)
->generateHttpResponse($response);
} | php | public function completeAuthorizationRequest(AuthorizationRequest $authRequest, ResponseInterface $response)
{
return $this->enabledGrantTypes[$authRequest->getGrantTypeId()]
->completeAuthorizationRequest($authRequest)
->generateHttpResponse($response);
} | [
"public",
"function",
"completeAuthorizationRequest",
"(",
"AuthorizationRequest",
"$",
"authRequest",
",",
"ResponseInterface",
"$",
"response",
")",
"{",
"return",
"$",
"this",
"->",
"enabledGrantTypes",
"[",
"$",
"authRequest",
"->",
"getGrantTypeId",
"(",
")",
"]",
"->",
"completeAuthorizationRequest",
"(",
"$",
"authRequest",
")",
"->",
"generateHttpResponse",
"(",
"$",
"response",
")",
";",
"}"
] | Complete an authorization request
@param AuthorizationRequest $authRequest
@param ResponseInterface $response
@return ResponseInterface | [
"Complete",
"an",
"authorization",
"request"
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/AuthorizationServer.php#L172-L177 | train |
thephpleague/oauth2-server | src/AuthorizationServer.php | AuthorizationServer.respondToAccessTokenRequest | public function respondToAccessTokenRequest(ServerRequestInterface $request, ResponseInterface $response)
{
foreach ($this->enabledGrantTypes as $grantType) {
if (!$grantType->canRespondToAccessTokenRequest($request)) {
continue;
}
$tokenResponse = $grantType->respondToAccessTokenRequest(
$request,
$this->getResponseType(),
$this->grantTypeAccessTokenTTL[$grantType->getIdentifier()]
);
if ($tokenResponse instanceof ResponseTypeInterface) {
return $tokenResponse->generateHttpResponse($response);
}
}
throw OAuthServerException::unsupportedGrantType();
} | php | public function respondToAccessTokenRequest(ServerRequestInterface $request, ResponseInterface $response)
{
foreach ($this->enabledGrantTypes as $grantType) {
if (!$grantType->canRespondToAccessTokenRequest($request)) {
continue;
}
$tokenResponse = $grantType->respondToAccessTokenRequest(
$request,
$this->getResponseType(),
$this->grantTypeAccessTokenTTL[$grantType->getIdentifier()]
);
if ($tokenResponse instanceof ResponseTypeInterface) {
return $tokenResponse->generateHttpResponse($response);
}
}
throw OAuthServerException::unsupportedGrantType();
} | [
"public",
"function",
"respondToAccessTokenRequest",
"(",
"ServerRequestInterface",
"$",
"request",
",",
"ResponseInterface",
"$",
"response",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"enabledGrantTypes",
"as",
"$",
"grantType",
")",
"{",
"if",
"(",
"!",
"$",
"grantType",
"->",
"canRespondToAccessTokenRequest",
"(",
"$",
"request",
")",
")",
"{",
"continue",
";",
"}",
"$",
"tokenResponse",
"=",
"$",
"grantType",
"->",
"respondToAccessTokenRequest",
"(",
"$",
"request",
",",
"$",
"this",
"->",
"getResponseType",
"(",
")",
",",
"$",
"this",
"->",
"grantTypeAccessTokenTTL",
"[",
"$",
"grantType",
"->",
"getIdentifier",
"(",
")",
"]",
")",
";",
"if",
"(",
"$",
"tokenResponse",
"instanceof",
"ResponseTypeInterface",
")",
"{",
"return",
"$",
"tokenResponse",
"->",
"generateHttpResponse",
"(",
"$",
"response",
")",
";",
"}",
"}",
"throw",
"OAuthServerException",
"::",
"unsupportedGrantType",
"(",
")",
";",
"}"
] | Return an access token response.
@param ServerRequestInterface $request
@param ResponseInterface $response
@throws OAuthServerException
@return ResponseInterface | [
"Return",
"an",
"access",
"token",
"response",
"."
] | 2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf | https://github.com/thephpleague/oauth2-server/blob/2eb1cf79e59d807d89c256e7ac5e2bf8bdbd4acf/src/AuthorizationServer.php#L189-L207 | train |
laravel/socialite | src/Two/LinkedInProvider.php | LinkedInProvider.getBasicProfile | protected function getBasicProfile($token)
{
$url = 'https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))';
$response = $this->getHttpClient()->get($url, [
'headers' => [
'Authorization' => 'Bearer '.$token,
'X-RestLi-Protocol-Version' => '2.0.0',
],
]);
return (array) json_decode($response->getBody(), true);
} | php | protected function getBasicProfile($token)
{
$url = 'https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))';
$response = $this->getHttpClient()->get($url, [
'headers' => [
'Authorization' => 'Bearer '.$token,
'X-RestLi-Protocol-Version' => '2.0.0',
],
]);
return (array) json_decode($response->getBody(), true);
} | [
"protected",
"function",
"getBasicProfile",
"(",
"$",
"token",
")",
"{",
"$",
"url",
"=",
"'https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))'",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"getHttpClient",
"(",
")",
"->",
"get",
"(",
"$",
"url",
",",
"[",
"'headers'",
"=>",
"[",
"'Authorization'",
"=>",
"'Bearer '",
".",
"$",
"token",
",",
"'X-RestLi-Protocol-Version'",
"=>",
"'2.0.0'",
",",
"]",
",",
"]",
")",
";",
"return",
"(",
"array",
")",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"}"
] | Get the basic profile fields for the user.
@param string $token
@return array | [
"Get",
"the",
"basic",
"profile",
"fields",
"for",
"the",
"user",
"."
] | 690c46cb572fb2f8a1a5520ff4b2446406ce5afd | https://github.com/laravel/socialite/blob/690c46cb572fb2f8a1a5520ff4b2446406ce5afd/src/Two/LinkedInProvider.php#L67-L79 | train |
laravel/socialite | src/Two/LinkedInProvider.php | LinkedInProvider.getEmailAddress | protected function getEmailAddress($token)
{
$url = 'https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))';
$response = $this->getHttpClient()->get($url, [
'headers' => [
'Authorization' => 'Bearer '.$token,
'X-RestLi-Protocol-Version' => '2.0.0',
],
]);
return (array) Arr::get((array) json_decode($response->getBody(), true), 'elements.0.handle~');
} | php | protected function getEmailAddress($token)
{
$url = 'https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))';
$response = $this->getHttpClient()->get($url, [
'headers' => [
'Authorization' => 'Bearer '.$token,
'X-RestLi-Protocol-Version' => '2.0.0',
],
]);
return (array) Arr::get((array) json_decode($response->getBody(), true), 'elements.0.handle~');
} | [
"protected",
"function",
"getEmailAddress",
"(",
"$",
"token",
")",
"{",
"$",
"url",
"=",
"'https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))'",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"getHttpClient",
"(",
")",
"->",
"get",
"(",
"$",
"url",
",",
"[",
"'headers'",
"=>",
"[",
"'Authorization'",
"=>",
"'Bearer '",
".",
"$",
"token",
",",
"'X-RestLi-Protocol-Version'",
"=>",
"'2.0.0'",
",",
"]",
",",
"]",
")",
";",
"return",
"(",
"array",
")",
"Arr",
"::",
"get",
"(",
"(",
"array",
")",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
",",
"'elements.0.handle~'",
")",
";",
"}"
] | Get the email address for the user.
@param string $token
@return array | [
"Get",
"the",
"email",
"address",
"for",
"the",
"user",
"."
] | 690c46cb572fb2f8a1a5520ff4b2446406ce5afd | https://github.com/laravel/socialite/blob/690c46cb572fb2f8a1a5520ff4b2446406ce5afd/src/Two/LinkedInProvider.php#L87-L99 | train |
laravel/socialite | src/AbstractUser.php | AbstractUser.map | public function map(array $attributes)
{
foreach ($attributes as $key => $value) {
$this->{$key} = $value;
}
return $this;
} | php | public function map(array $attributes)
{
foreach ($attributes as $key => $value) {
$this->{$key} = $value;
}
return $this;
} | [
"public",
"function",
"map",
"(",
"array",
"$",
"attributes",
")",
"{",
"foreach",
"(",
"$",
"attributes",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"{",
"$",
"key",
"}",
"=",
"$",
"value",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Map the given array onto the user's properties.
@param array $attributes
@return $this | [
"Map",
"the",
"given",
"array",
"onto",
"the",
"user",
"s",
"properties",
"."
] | 690c46cb572fb2f8a1a5520ff4b2446406ce5afd | https://github.com/laravel/socialite/blob/690c46cb572fb2f8a1a5520ff4b2446406ce5afd/src/AbstractUser.php#L130-L137 | train |
laravel/socialite | src/One/AbstractProvider.php | AbstractProvider.userFromTokenAndSecret | public function userFromTokenAndSecret($token, $secret)
{
$tokenCredentials = new TokenCredentials();
$tokenCredentials->setIdentifier($token);
$tokenCredentials->setSecret($secret);
$user = $this->server->getUserDetails(
$tokenCredentials, $this->shouldBypassCache($token, $secret)
);
$instance = (new User)->setRaw($user->extra)
->setToken($tokenCredentials->getIdentifier(), $tokenCredentials->getSecret());
return $instance->map([
'id' => $user->uid,
'nickname' => $user->nickname,
'name' => $user->name,
'email' => $user->email,
'avatar' => $user->imageUrl,
]);
} | php | public function userFromTokenAndSecret($token, $secret)
{
$tokenCredentials = new TokenCredentials();
$tokenCredentials->setIdentifier($token);
$tokenCredentials->setSecret($secret);
$user = $this->server->getUserDetails(
$tokenCredentials, $this->shouldBypassCache($token, $secret)
);
$instance = (new User)->setRaw($user->extra)
->setToken($tokenCredentials->getIdentifier(), $tokenCredentials->getSecret());
return $instance->map([
'id' => $user->uid,
'nickname' => $user->nickname,
'name' => $user->name,
'email' => $user->email,
'avatar' => $user->imageUrl,
]);
} | [
"public",
"function",
"userFromTokenAndSecret",
"(",
"$",
"token",
",",
"$",
"secret",
")",
"{",
"$",
"tokenCredentials",
"=",
"new",
"TokenCredentials",
"(",
")",
";",
"$",
"tokenCredentials",
"->",
"setIdentifier",
"(",
"$",
"token",
")",
";",
"$",
"tokenCredentials",
"->",
"setSecret",
"(",
"$",
"secret",
")",
";",
"$",
"user",
"=",
"$",
"this",
"->",
"server",
"->",
"getUserDetails",
"(",
"$",
"tokenCredentials",
",",
"$",
"this",
"->",
"shouldBypassCache",
"(",
"$",
"token",
",",
"$",
"secret",
")",
")",
";",
"$",
"instance",
"=",
"(",
"new",
"User",
")",
"->",
"setRaw",
"(",
"$",
"user",
"->",
"extra",
")",
"->",
"setToken",
"(",
"$",
"tokenCredentials",
"->",
"getIdentifier",
"(",
")",
",",
"$",
"tokenCredentials",
"->",
"getSecret",
"(",
")",
")",
";",
"return",
"$",
"instance",
"->",
"map",
"(",
"[",
"'id'",
"=>",
"$",
"user",
"->",
"uid",
",",
"'nickname'",
"=>",
"$",
"user",
"->",
"nickname",
",",
"'name'",
"=>",
"$",
"user",
"->",
"name",
",",
"'email'",
"=>",
"$",
"user",
"->",
"email",
",",
"'avatar'",
"=>",
"$",
"user",
"->",
"imageUrl",
",",
"]",
")",
";",
"}"
] | Get a Social User instance from a known access token and secret.
@param string $token
@param string $secret
@return \Laravel\Socialite\One\User | [
"Get",
"a",
"Social",
"User",
"instance",
"from",
"a",
"known",
"access",
"token",
"and",
"secret",
"."
] | 690c46cb572fb2f8a1a5520ff4b2446406ce5afd | https://github.com/laravel/socialite/blob/690c46cb572fb2f8a1a5520ff4b2446406ce5afd/src/One/AbstractProvider.php#L99-L120 | train |
laravel/socialite | src/One/AbstractProvider.php | AbstractProvider.shouldBypassCache | protected function shouldBypassCache($token, $secret)
{
$newHash = sha1($token.'_'.$secret);
if (! empty($this->userHash) && $newHash !== $this->userHash) {
$this->userHash = $newHash;
return true;
}
$this->userHash = $this->userHash ?: $newHash;
return false;
} | php | protected function shouldBypassCache($token, $secret)
{
$newHash = sha1($token.'_'.$secret);
if (! empty($this->userHash) && $newHash !== $this->userHash) {
$this->userHash = $newHash;
return true;
}
$this->userHash = $this->userHash ?: $newHash;
return false;
} | [
"protected",
"function",
"shouldBypassCache",
"(",
"$",
"token",
",",
"$",
"secret",
")",
"{",
"$",
"newHash",
"=",
"sha1",
"(",
"$",
"token",
".",
"'_'",
".",
"$",
"secret",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"userHash",
")",
"&&",
"$",
"newHash",
"!==",
"$",
"this",
"->",
"userHash",
")",
"{",
"$",
"this",
"->",
"userHash",
"=",
"$",
"newHash",
";",
"return",
"true",
";",
"}",
"$",
"this",
"->",
"userHash",
"=",
"$",
"this",
"->",
"userHash",
"?",
":",
"$",
"newHash",
";",
"return",
"false",
";",
"}"
] | Determine if the user information cache should be bypassed.
@param string $token
@param string $secret
@return bool | [
"Determine",
"if",
"the",
"user",
"information",
"cache",
"should",
"be",
"bypassed",
"."
] | 690c46cb572fb2f8a1a5520ff4b2446406ce5afd | https://github.com/laravel/socialite/blob/690c46cb572fb2f8a1a5520ff4b2446406ce5afd/src/One/AbstractProvider.php#L153-L166 | train |
laravel/socialite | src/One/User.php | User.setToken | public function setToken($token, $tokenSecret)
{
$this->token = $token;
$this->tokenSecret = $tokenSecret;
return $this;
} | php | public function setToken($token, $tokenSecret)
{
$this->token = $token;
$this->tokenSecret = $tokenSecret;
return $this;
} | [
"public",
"function",
"setToken",
"(",
"$",
"token",
",",
"$",
"tokenSecret",
")",
"{",
"$",
"this",
"->",
"token",
"=",
"$",
"token",
";",
"$",
"this",
"->",
"tokenSecret",
"=",
"$",
"tokenSecret",
";",
"return",
"$",
"this",
";",
"}"
] | Set the token on the user.
@param string $token
@param string $tokenSecret
@return $this | [
"Set",
"the",
"token",
"on",
"the",
"user",
"."
] | 690c46cb572fb2f8a1a5520ff4b2446406ce5afd | https://github.com/laravel/socialite/blob/690c46cb572fb2f8a1a5520ff4b2446406ce5afd/src/One/User.php#L30-L36 | train |
laravel/socialite | src/SocialiteManager.php | SocialiteManager.createTwitterDriver | protected function createTwitterDriver()
{
$config = $this->app['config']['services.twitter'];
return new TwitterProvider(
$this->app['request'], new TwitterServer($this->formatConfig($config))
);
} | php | protected function createTwitterDriver()
{
$config = $this->app['config']['services.twitter'];
return new TwitterProvider(
$this->app['request'], new TwitterServer($this->formatConfig($config))
);
} | [
"protected",
"function",
"createTwitterDriver",
"(",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"app",
"[",
"'config'",
"]",
"[",
"'services.twitter'",
"]",
";",
"return",
"new",
"TwitterProvider",
"(",
"$",
"this",
"->",
"app",
"[",
"'request'",
"]",
",",
"new",
"TwitterServer",
"(",
"$",
"this",
"->",
"formatConfig",
"(",
"$",
"config",
")",
")",
")",
";",
"}"
] | Create an instance of the specified driver.
@return \Laravel\Socialite\One\AbstractProvider | [
"Create",
"an",
"instance",
"of",
"the",
"specified",
"driver",
"."
] | 690c46cb572fb2f8a1a5520ff4b2446406ce5afd | https://github.com/laravel/socialite/blob/690c46cb572fb2f8a1a5520ff4b2446406ce5afd/src/SocialiteManager.php#L136-L143 | train |
laravel/socialite | src/SocialiteManager.php | SocialiteManager.formatRedirectUrl | protected function formatRedirectUrl(array $config)
{
$redirect = value($config['redirect']);
return Str::startsWith($redirect, '/')
? $this->app['url']->to($redirect)
: $redirect;
} | php | protected function formatRedirectUrl(array $config)
{
$redirect = value($config['redirect']);
return Str::startsWith($redirect, '/')
? $this->app['url']->to($redirect)
: $redirect;
} | [
"protected",
"function",
"formatRedirectUrl",
"(",
"array",
"$",
"config",
")",
"{",
"$",
"redirect",
"=",
"value",
"(",
"$",
"config",
"[",
"'redirect'",
"]",
")",
";",
"return",
"Str",
"::",
"startsWith",
"(",
"$",
"redirect",
",",
"'/'",
")",
"?",
"$",
"this",
"->",
"app",
"[",
"'url'",
"]",
"->",
"to",
"(",
"$",
"redirect",
")",
":",
"$",
"redirect",
";",
"}"
] | Format the callback URL, resolving a relative URI if needed.
@param array $config
@return string | [
"Format",
"the",
"callback",
"URL",
"resolving",
"a",
"relative",
"URI",
"if",
"needed",
"."
] | 690c46cb572fb2f8a1a5520ff4b2446406ce5afd | https://github.com/laravel/socialite/blob/690c46cb572fb2f8a1a5520ff4b2446406ce5afd/src/SocialiteManager.php#L166-L173 | train |
laravel/socialite | src/Two/AbstractProvider.php | AbstractProvider.scopes | public function scopes($scopes)
{
$this->scopes = array_unique(array_merge($this->scopes, (array) $scopes));
return $this;
} | php | public function scopes($scopes)
{
$this->scopes = array_unique(array_merge($this->scopes, (array) $scopes));
return $this;
} | [
"public",
"function",
"scopes",
"(",
"$",
"scopes",
")",
"{",
"$",
"this",
"->",
"scopes",
"=",
"array_unique",
"(",
"array_merge",
"(",
"$",
"this",
"->",
"scopes",
",",
"(",
"array",
")",
"$",
"scopes",
")",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Merge the scopes of the requested access.
@param array|string $scopes
@return $this | [
"Merge",
"the",
"scopes",
"of",
"the",
"requested",
"access",
"."
] | 690c46cb572fb2f8a1a5520ff4b2446406ce5afd | https://github.com/laravel/socialite/blob/690c46cb572fb2f8a1a5520ff4b2446406ce5afd/src/Two/AbstractProvider.php#L303-L308 | train |
wp-cli/wp-cli | php/WP_CLI/Bootstrap/BootstrapState.php | BootstrapState.getValue | public function getValue( $key, $fallback = null ) {
return array_key_exists( $key, $this->state )
? $this->state[ $key ]
: $fallback;
} | php | public function getValue( $key, $fallback = null ) {
return array_key_exists( $key, $this->state )
? $this->state[ $key ]
: $fallback;
} | [
"public",
"function",
"getValue",
"(",
"$",
"key",
",",
"$",
"fallback",
"=",
"null",
")",
"{",
"return",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"state",
")",
"?",
"$",
"this",
"->",
"state",
"[",
"$",
"key",
"]",
":",
"$",
"fallback",
";",
"}"
] | Get the state value for a given key.
@param string $key Key to get the state from.
@param mixed $fallback Fallback value to use if the key is not defined.
@return mixed | [
"Get",
"the",
"state",
"value",
"for",
"a",
"given",
"key",
"."
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/Bootstrap/BootstrapState.php#L41-L45 | train |
wp-cli/wp-cli | php/WP_CLI/FileCache.php | FileCache.has | public function has( $key, $ttl = null ) {
if ( ! $this->enabled ) {
return false;
}
$filename = $this->filename( $key );
if ( ! file_exists( $filename ) ) {
return false;
}
// use ttl param or global ttl
if ( null === $ttl ) {
$ttl = $this->ttl;
} elseif ( $this->ttl > 0 ) {
$ttl = min( (int) $ttl, $this->ttl );
} else {
$ttl = (int) $ttl;
}
//
if ( $ttl > 0 && ( filemtime( $filename ) + $ttl ) < time() ) {
if ( $this->ttl > 0 && $ttl >= $this->ttl ) {
unlink( $filename );
}
return false;
}
return $filename;
} | php | public function has( $key, $ttl = null ) {
if ( ! $this->enabled ) {
return false;
}
$filename = $this->filename( $key );
if ( ! file_exists( $filename ) ) {
return false;
}
// use ttl param or global ttl
if ( null === $ttl ) {
$ttl = $this->ttl;
} elseif ( $this->ttl > 0 ) {
$ttl = min( (int) $ttl, $this->ttl );
} else {
$ttl = (int) $ttl;
}
//
if ( $ttl > 0 && ( filemtime( $filename ) + $ttl ) < time() ) {
if ( $this->ttl > 0 && $ttl >= $this->ttl ) {
unlink( $filename );
}
return false;
}
return $filename;
} | [
"public",
"function",
"has",
"(",
"$",
"key",
",",
"$",
"ttl",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"enabled",
")",
"{",
"return",
"false",
";",
"}",
"$",
"filename",
"=",
"$",
"this",
"->",
"filename",
"(",
"$",
"key",
")",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"filename",
")",
")",
"{",
"return",
"false",
";",
"}",
"// use ttl param or global ttl",
"if",
"(",
"null",
"===",
"$",
"ttl",
")",
"{",
"$",
"ttl",
"=",
"$",
"this",
"->",
"ttl",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"ttl",
">",
"0",
")",
"{",
"$",
"ttl",
"=",
"min",
"(",
"(",
"int",
")",
"$",
"ttl",
",",
"$",
"this",
"->",
"ttl",
")",
";",
"}",
"else",
"{",
"$",
"ttl",
"=",
"(",
"int",
")",
"$",
"ttl",
";",
"}",
"//",
"if",
"(",
"$",
"ttl",
">",
"0",
"&&",
"(",
"filemtime",
"(",
"$",
"filename",
")",
"+",
"$",
"ttl",
")",
"<",
"time",
"(",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"ttl",
">",
"0",
"&&",
"$",
"ttl",
">=",
"$",
"this",
"->",
"ttl",
")",
"{",
"unlink",
"(",
"$",
"filename",
")",
";",
"}",
"return",
"false",
";",
"}",
"return",
"$",
"filename",
";",
"}"
] | Check if a file is in cache and return its filename
@param string $key cache key
@param int $ttl time to live
@return bool|string filename or false | [
"Check",
"if",
"a",
"file",
"is",
"in",
"cache",
"and",
"return",
"its",
"filename"
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/FileCache.php#L89-L118 | train |
wp-cli/wp-cli | php/WP_CLI/FileCache.php | FileCache.read | public function read( $key, $ttl = null ) {
$filename = $this->has( $key, $ttl );
if ( $filename ) {
return file_get_contents( $filename );
}
return false;
} | php | public function read( $key, $ttl = null ) {
$filename = $this->has( $key, $ttl );
if ( $filename ) {
return file_get_contents( $filename );
}
return false;
} | [
"public",
"function",
"read",
"(",
"$",
"key",
",",
"$",
"ttl",
"=",
"null",
")",
"{",
"$",
"filename",
"=",
"$",
"this",
"->",
"has",
"(",
"$",
"key",
",",
"$",
"ttl",
")",
";",
"if",
"(",
"$",
"filename",
")",
"{",
"return",
"file_get_contents",
"(",
"$",
"filename",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Read from cache file
@param string $key cache key
@param int $ttl time to live
@return bool|string file contents or false | [
"Read",
"from",
"cache",
"file"
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/FileCache.php#L144-L152 | train |
wp-cli/wp-cli | php/WP_CLI/FileCache.php | FileCache.remove | public function remove( $key ) {
if ( ! $this->enabled ) {
return false;
}
$filename = $this->filename( $key );
if ( file_exists( $filename ) ) {
return unlink( $filename );
}
return false;
} | php | public function remove( $key ) {
if ( ! $this->enabled ) {
return false;
}
$filename = $this->filename( $key );
if ( file_exists( $filename ) ) {
return unlink( $filename );
}
return false;
} | [
"public",
"function",
"remove",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"enabled",
")",
"{",
"return",
"false",
";",
"}",
"$",
"filename",
"=",
"$",
"this",
"->",
"filename",
"(",
"$",
"key",
")",
";",
"if",
"(",
"file_exists",
"(",
"$",
"filename",
")",
")",
"{",
"return",
"unlink",
"(",
"$",
"filename",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Remove file from cache
@param string $key cache key
@return bool | [
"Remove",
"file",
"from",
"cache"
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/FileCache.php#L195-L207 | train |
wp-cli/wp-cli | php/WP_CLI/FileCache.php | FileCache.clean | public function clean() {
if ( ! $this->enabled ) {
return false;
}
$ttl = $this->ttl;
$max_size = $this->max_size;
// unlink expired files
if ( $ttl > 0 ) {
try {
$expire = new \DateTime();
} catch ( \Exception $e ) {
\WP_CLI::error( $e->getMessage() );
}
$expire->modify( '-' . $ttl . ' seconds' );
$finder = $this->get_finder()->date( 'until ' . $expire->format( 'Y-m-d H:i:s' ) );
foreach ( $finder as $file ) {
unlink( $file->getRealPath() );
}
}
// unlink older files if max cache size is exceeded
if ( $max_size > 0 ) {
$files = array_reverse( iterator_to_array( $this->get_finder()->sortByAccessedTime()->getIterator() ) );
$total = 0;
foreach ( $files as $file ) {
if ( ( $total + $file->getSize() ) <= $max_size ) {
$total += $file->getSize();
} else {
unlink( $file->getRealPath() );
}
}
}
return true;
} | php | public function clean() {
if ( ! $this->enabled ) {
return false;
}
$ttl = $this->ttl;
$max_size = $this->max_size;
// unlink expired files
if ( $ttl > 0 ) {
try {
$expire = new \DateTime();
} catch ( \Exception $e ) {
\WP_CLI::error( $e->getMessage() );
}
$expire->modify( '-' . $ttl . ' seconds' );
$finder = $this->get_finder()->date( 'until ' . $expire->format( 'Y-m-d H:i:s' ) );
foreach ( $finder as $file ) {
unlink( $file->getRealPath() );
}
}
// unlink older files if max cache size is exceeded
if ( $max_size > 0 ) {
$files = array_reverse( iterator_to_array( $this->get_finder()->sortByAccessedTime()->getIterator() ) );
$total = 0;
foreach ( $files as $file ) {
if ( ( $total + $file->getSize() ) <= $max_size ) {
$total += $file->getSize();
} else {
unlink( $file->getRealPath() );
}
}
}
return true;
} | [
"public",
"function",
"clean",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"enabled",
")",
"{",
"return",
"false",
";",
"}",
"$",
"ttl",
"=",
"$",
"this",
"->",
"ttl",
";",
"$",
"max_size",
"=",
"$",
"this",
"->",
"max_size",
";",
"// unlink expired files",
"if",
"(",
"$",
"ttl",
">",
"0",
")",
"{",
"try",
"{",
"$",
"expire",
"=",
"new",
"\\",
"DateTime",
"(",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"\\",
"WP_CLI",
"::",
"error",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"}",
"$",
"expire",
"->",
"modify",
"(",
"'-'",
".",
"$",
"ttl",
".",
"' seconds'",
")",
";",
"$",
"finder",
"=",
"$",
"this",
"->",
"get_finder",
"(",
")",
"->",
"date",
"(",
"'until '",
".",
"$",
"expire",
"->",
"format",
"(",
"'Y-m-d H:i:s'",
")",
")",
";",
"foreach",
"(",
"$",
"finder",
"as",
"$",
"file",
")",
"{",
"unlink",
"(",
"$",
"file",
"->",
"getRealPath",
"(",
")",
")",
";",
"}",
"}",
"// unlink older files if max cache size is exceeded",
"if",
"(",
"$",
"max_size",
">",
"0",
")",
"{",
"$",
"files",
"=",
"array_reverse",
"(",
"iterator_to_array",
"(",
"$",
"this",
"->",
"get_finder",
"(",
")",
"->",
"sortByAccessedTime",
"(",
")",
"->",
"getIterator",
"(",
")",
")",
")",
";",
"$",
"total",
"=",
"0",
";",
"foreach",
"(",
"$",
"files",
"as",
"$",
"file",
")",
"{",
"if",
"(",
"(",
"$",
"total",
"+",
"$",
"file",
"->",
"getSize",
"(",
")",
")",
"<=",
"$",
"max_size",
")",
"{",
"$",
"total",
"+=",
"$",
"file",
"->",
"getSize",
"(",
")",
";",
"}",
"else",
"{",
"unlink",
"(",
"$",
"file",
"->",
"getRealPath",
"(",
")",
")",
";",
"}",
"}",
"}",
"return",
"true",
";",
"}"
] | Clean cache based on time to live and max size
@return bool | [
"Clean",
"cache",
"based",
"on",
"time",
"to",
"live",
"and",
"max",
"size"
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/FileCache.php#L214-L252 | train |
wp-cli/wp-cli | php/WP_CLI/FileCache.php | FileCache.clear | public function clear() {
if ( ! $this->enabled ) {
return false;
}
$finder = $this->get_finder();
foreach ( $finder as $file ) {
unlink( $file->getRealPath() );
}
return true;
} | php | public function clear() {
if ( ! $this->enabled ) {
return false;
}
$finder = $this->get_finder();
foreach ( $finder as $file ) {
unlink( $file->getRealPath() );
}
return true;
} | [
"public",
"function",
"clear",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"enabled",
")",
"{",
"return",
"false",
";",
"}",
"$",
"finder",
"=",
"$",
"this",
"->",
"get_finder",
"(",
")",
";",
"foreach",
"(",
"$",
"finder",
"as",
"$",
"file",
")",
"{",
"unlink",
"(",
"$",
"file",
"->",
"getRealPath",
"(",
")",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Remove all cached files.
@return bool | [
"Remove",
"all",
"cached",
"files",
"."
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/FileCache.php#L259-L271 | train |
wp-cli/wp-cli | php/WP_CLI/FileCache.php | FileCache.prune | public function prune() {
if ( ! $this->enabled ) {
return false;
}
/** @var Finder $finder */
$finder = $this->get_finder()->sortByName();
$files_to_delete = array();
foreach ( $finder as $file ) {
$pieces = explode( '-', $file->getBasename( $file->getExtension() ) );
$timestamp = end( $pieces );
// No way to compare versions, do nothing.
if ( ! is_numeric( $timestamp ) ) {
continue;
}
$basename_without_timestamp = str_replace( '-' . $timestamp, '', $file->getBasename() );
// There's a file with an older timestamp, delete it.
if ( isset( $files_to_delete[ $basename_without_timestamp ] ) ) {
unlink( $files_to_delete[ $basename_without_timestamp ] );
}
$files_to_delete[ $basename_without_timestamp ] = $file->getRealPath();
}
return true;
} | php | public function prune() {
if ( ! $this->enabled ) {
return false;
}
/** @var Finder $finder */
$finder = $this->get_finder()->sortByName();
$files_to_delete = array();
foreach ( $finder as $file ) {
$pieces = explode( '-', $file->getBasename( $file->getExtension() ) );
$timestamp = end( $pieces );
// No way to compare versions, do nothing.
if ( ! is_numeric( $timestamp ) ) {
continue;
}
$basename_without_timestamp = str_replace( '-' . $timestamp, '', $file->getBasename() );
// There's a file with an older timestamp, delete it.
if ( isset( $files_to_delete[ $basename_without_timestamp ] ) ) {
unlink( $files_to_delete[ $basename_without_timestamp ] );
}
$files_to_delete[ $basename_without_timestamp ] = $file->getRealPath();
}
return true;
} | [
"public",
"function",
"prune",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"enabled",
")",
"{",
"return",
"false",
";",
"}",
"/** @var Finder $finder */",
"$",
"finder",
"=",
"$",
"this",
"->",
"get_finder",
"(",
")",
"->",
"sortByName",
"(",
")",
";",
"$",
"files_to_delete",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"finder",
"as",
"$",
"file",
")",
"{",
"$",
"pieces",
"=",
"explode",
"(",
"'-'",
",",
"$",
"file",
"->",
"getBasename",
"(",
"$",
"file",
"->",
"getExtension",
"(",
")",
")",
")",
";",
"$",
"timestamp",
"=",
"end",
"(",
"$",
"pieces",
")",
";",
"// No way to compare versions, do nothing.",
"if",
"(",
"!",
"is_numeric",
"(",
"$",
"timestamp",
")",
")",
"{",
"continue",
";",
"}",
"$",
"basename_without_timestamp",
"=",
"str_replace",
"(",
"'-'",
".",
"$",
"timestamp",
",",
"''",
",",
"$",
"file",
"->",
"getBasename",
"(",
")",
")",
";",
"// There's a file with an older timestamp, delete it.",
"if",
"(",
"isset",
"(",
"$",
"files_to_delete",
"[",
"$",
"basename_without_timestamp",
"]",
")",
")",
"{",
"unlink",
"(",
"$",
"files_to_delete",
"[",
"$",
"basename_without_timestamp",
"]",
")",
";",
"}",
"$",
"files_to_delete",
"[",
"$",
"basename_without_timestamp",
"]",
"=",
"$",
"file",
"->",
"getRealPath",
"(",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Remove all cached files except for the newest version of one.
@return bool | [
"Remove",
"all",
"cached",
"files",
"except",
"for",
"the",
"newest",
"version",
"of",
"one",
"."
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/FileCache.php#L278-L308 | train |
wp-cli/wp-cli | php/WP_CLI/FileCache.php | FileCache.ensure_dir_exists | protected function ensure_dir_exists( $dir ) {
if ( ! is_dir( $dir ) ) {
// Disable the cache if a null device like /dev/null is being used.
if ( preg_match( '{(^|[\\\\/])(\$null|nul|NUL|/dev/null)([\\\\/]|$)}', $dir ) ) {
return false;
}
if ( ! @mkdir( $dir, 0777, true ) ) {
$error = error_get_last();
\WP_CLI::warning( sprintf( "Failed to create directory '%s': %s.", $dir, $error['message'] ) );
return false;
}
}
return true;
} | php | protected function ensure_dir_exists( $dir ) {
if ( ! is_dir( $dir ) ) {
// Disable the cache if a null device like /dev/null is being used.
if ( preg_match( '{(^|[\\\\/])(\$null|nul|NUL|/dev/null)([\\\\/]|$)}', $dir ) ) {
return false;
}
if ( ! @mkdir( $dir, 0777, true ) ) {
$error = error_get_last();
\WP_CLI::warning( sprintf( "Failed to create directory '%s': %s.", $dir, $error['message'] ) );
return false;
}
}
return true;
} | [
"protected",
"function",
"ensure_dir_exists",
"(",
"$",
"dir",
")",
"{",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"dir",
")",
")",
"{",
"// Disable the cache if a null device like /dev/null is being used.",
"if",
"(",
"preg_match",
"(",
"'{(^|[\\\\\\\\/])(\\$null|nul|NUL|/dev/null)([\\\\\\\\/]|$)}'",
",",
"$",
"dir",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"@",
"mkdir",
"(",
"$",
"dir",
",",
"0777",
",",
"true",
")",
")",
"{",
"$",
"error",
"=",
"error_get_last",
"(",
")",
";",
"\\",
"WP_CLI",
"::",
"warning",
"(",
"sprintf",
"(",
"\"Failed to create directory '%s': %s.\"",
",",
"$",
"dir",
",",
"$",
"error",
"[",
"'message'",
"]",
")",
")",
";",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Ensure directory exists
@param string $dir directory
@return bool | [
"Ensure",
"directory",
"exists"
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/FileCache.php#L316-L331 | train |
wp-cli/wp-cli | php/WP_CLI/FileCache.php | FileCache.prepare_write | protected function prepare_write( $key ) {
if ( ! $this->enabled ) {
return false;
}
$filename = $this->filename( $key );
if ( ! $this->ensure_dir_exists( dirname( $filename ) ) ) {
return false;
}
return $filename;
} | php | protected function prepare_write( $key ) {
if ( ! $this->enabled ) {
return false;
}
$filename = $this->filename( $key );
if ( ! $this->ensure_dir_exists( dirname( $filename ) ) ) {
return false;
}
return $filename;
} | [
"protected",
"function",
"prepare_write",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"enabled",
")",
"{",
"return",
"false",
";",
"}",
"$",
"filename",
"=",
"$",
"this",
"->",
"filename",
"(",
"$",
"key",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"ensure_dir_exists",
"(",
"dirname",
"(",
"$",
"filename",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"filename",
";",
"}"
] | Prepare cache write
@param string $key cache key
@return bool|string filename or false | [
"Prepare",
"cache",
"write"
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/FileCache.php#L339-L351 | train |
wp-cli/wp-cli | php/WP_CLI/FileCache.php | FileCache.validate_key | protected function validate_key( $key ) {
$url_parts = Utils\parse_url( $key, -1, false );
if ( ! empty( $url_parts['scheme'] ) ) { // is url
$parts = array( 'misc' );
$parts[] = $url_parts['scheme'] . '-' . $url_parts['host'] .
( empty( $url_parts['port'] ) ? '' : '-' . $url_parts['port'] );
$parts[] = substr( $url_parts['path'], 1 ) .
( empty( $url_parts['query'] ) ? '' : '-' . $url_parts['query'] );
} else {
$key = str_replace( '\\', '/', $key );
$parts = explode( '/', ltrim( $key ) );
}
$parts = preg_replace( "#[^{$this->whitelist}]#i", '-', $parts );
return implode( '/', $parts );
} | php | protected function validate_key( $key ) {
$url_parts = Utils\parse_url( $key, -1, false );
if ( ! empty( $url_parts['scheme'] ) ) { // is url
$parts = array( 'misc' );
$parts[] = $url_parts['scheme'] . '-' . $url_parts['host'] .
( empty( $url_parts['port'] ) ? '' : '-' . $url_parts['port'] );
$parts[] = substr( $url_parts['path'], 1 ) .
( empty( $url_parts['query'] ) ? '' : '-' . $url_parts['query'] );
} else {
$key = str_replace( '\\', '/', $key );
$parts = explode( '/', ltrim( $key ) );
}
$parts = preg_replace( "#[^{$this->whitelist}]#i", '-', $parts );
return implode( '/', $parts );
} | [
"protected",
"function",
"validate_key",
"(",
"$",
"key",
")",
"{",
"$",
"url_parts",
"=",
"Utils",
"\\",
"parse_url",
"(",
"$",
"key",
",",
"-",
"1",
",",
"false",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"url_parts",
"[",
"'scheme'",
"]",
")",
")",
"{",
"// is url",
"$",
"parts",
"=",
"array",
"(",
"'misc'",
")",
";",
"$",
"parts",
"[",
"]",
"=",
"$",
"url_parts",
"[",
"'scheme'",
"]",
".",
"'-'",
".",
"$",
"url_parts",
"[",
"'host'",
"]",
".",
"(",
"empty",
"(",
"$",
"url_parts",
"[",
"'port'",
"]",
")",
"?",
"''",
":",
"'-'",
".",
"$",
"url_parts",
"[",
"'port'",
"]",
")",
";",
"$",
"parts",
"[",
"]",
"=",
"substr",
"(",
"$",
"url_parts",
"[",
"'path'",
"]",
",",
"1",
")",
".",
"(",
"empty",
"(",
"$",
"url_parts",
"[",
"'query'",
"]",
")",
"?",
"''",
":",
"'-'",
".",
"$",
"url_parts",
"[",
"'query'",
"]",
")",
";",
"}",
"else",
"{",
"$",
"key",
"=",
"str_replace",
"(",
"'\\\\'",
",",
"'/'",
",",
"$",
"key",
")",
";",
"$",
"parts",
"=",
"explode",
"(",
"'/'",
",",
"ltrim",
"(",
"$",
"key",
")",
")",
";",
"}",
"$",
"parts",
"=",
"preg_replace",
"(",
"\"#[^{$this->whitelist}]#i\"",
",",
"'-'",
",",
"$",
"parts",
")",
";",
"return",
"implode",
"(",
"'/'",
",",
"$",
"parts",
")",
";",
"}"
] | Validate cache key
@param string $key cache key
@return string relative filename | [
"Validate",
"cache",
"key"
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/FileCache.php#L359-L375 | train |
wp-cli/wp-cli | php/WP_CLI/Loggers/Execution.php | Execution.write | protected function write( $handle, $str ) {
switch ( $handle ) {
case STDOUT:
$this->stdout .= $str;
break;
case STDERR:
$this->stderr .= $str;
break;
}
} | php | protected function write( $handle, $str ) {
switch ( $handle ) {
case STDOUT:
$this->stdout .= $str;
break;
case STDERR:
$this->stderr .= $str;
break;
}
} | [
"protected",
"function",
"write",
"(",
"$",
"handle",
",",
"$",
"str",
")",
"{",
"switch",
"(",
"$",
"handle",
")",
"{",
"case",
"STDOUT",
":",
"$",
"this",
"->",
"stdout",
".=",
"$",
"str",
";",
"break",
";",
"case",
"STDERR",
":",
"$",
"this",
"->",
"stderr",
".=",
"$",
"str",
";",
"break",
";",
"}",
"}"
] | Write a string to a resource.
@param resource $handle Commonly STDOUT or STDERR.
@param string $str Message to write. | [
"Write",
"a",
"string",
"to",
"a",
"resource",
"."
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/Loggers/Execution.php#L45-L54 | train |
wp-cli/wp-cli | php/WP_CLI/Inflector.php | Inflector.ucwords | public static function ucwords( $string, $delimiters = " \n\t\r\0\x0B-" ) {
return preg_replace_callback(
'/[^' . preg_quote( $delimiters, '/' ) . ']+/',
function( $matches ) {
return ucfirst( $matches[0] );
},
$string
);
} | php | public static function ucwords( $string, $delimiters = " \n\t\r\0\x0B-" ) {
return preg_replace_callback(
'/[^' . preg_quote( $delimiters, '/' ) . ']+/',
function( $matches ) {
return ucfirst( $matches[0] );
},
$string
);
} | [
"public",
"static",
"function",
"ucwords",
"(",
"$",
"string",
",",
"$",
"delimiters",
"=",
"\" \\n\\t\\r\\0\\x0B-\"",
")",
"{",
"return",
"preg_replace_callback",
"(",
"'/[^'",
".",
"preg_quote",
"(",
"$",
"delimiters",
",",
"'/'",
")",
".",
"']+/'",
",",
"function",
"(",
"$",
"matches",
")",
"{",
"return",
"ucfirst",
"(",
"$",
"matches",
"[",
"0",
"]",
")",
";",
"}",
",",
"$",
"string",
")",
";",
"}"
] | Uppercases words with configurable delimeters between words.
Takes a string and capitalizes all of the words, like PHP's built-in
ucwords function. This extends that behavior, however, by allowing the
word delimeters to be configured, rather than only separating on
whitespace.
Here is an example:
<code>
<?php
$string = 'top-o-the-morning to all_of_you!';
echo \Doctrine\Common\Inflector\Inflector::ucwords($string);
// Top-O-The-Morning To All_of_you!
echo \Doctrine\Common\Inflector\Inflector::ucwords($string, '-_ ');
// Top-O-The-Morning To All_Of_You!
?>
</code>
@param string $string The string to operate on.
@param string $delimiters A list of word separators.
@return string The string with all delimeter-separated words capitalized. | [
"Uppercases",
"words",
"with",
"configurable",
"delimeters",
"between",
"words",
"."
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/Inflector.php#L368-L376 | train |
wp-cli/wp-cli | php/WP_CLI/Inflector.php | Inflector.pluralize | public static function pluralize( $word ) {
if ( isset( self::$cache['pluralize'][ $word ] ) ) {
return self::$cache['pluralize'][ $word ];
}
if ( ! isset( self::$plural['merged']['irregular'] ) ) {
self::$plural['merged']['irregular'] = self::$plural['irregular'];
}
if ( ! isset( self::$plural['merged']['uninflected'] ) ) {
self::$plural['merged']['uninflected'] = array_merge( self::$plural['uninflected'], self::$uninflected );
}
if ( ! isset( self::$plural['cacheUninflected'] ) || ! isset( self::$plural['cacheIrregular'] ) ) {
self::$plural['cacheUninflected'] = '(?:' . implode( '|', self::$plural['merged']['uninflected'] ) . ')';
self::$plural['cacheIrregular'] = '(?:' . implode( '|', array_keys( self::$plural['merged']['irregular'] ) ) . ')';
}
if ( preg_match( '/(.*)\\b(' . self::$plural['cacheIrregular'] . ')$/i', $word, $regs ) ) {
self::$cache['pluralize'][ $word ] = $regs[1] . substr( $word, 0, 1 ) . substr( self::$plural['merged']['irregular'][ strtolower( $regs[2] ) ], 1 );
return self::$cache['pluralize'][ $word ];
}
if ( preg_match( '/^(' . self::$plural['cacheUninflected'] . ')$/i', $word, $regs ) ) {
self::$cache['pluralize'][ $word ] = $word;
return $word;
}
foreach ( self::$plural['rules'] as $rule => $replacement ) {
if ( preg_match( $rule, $word ) ) {
self::$cache['pluralize'][ $word ] = preg_replace( $rule, $replacement, $word );
return self::$cache['pluralize'][ $word ];
}
}
} | php | public static function pluralize( $word ) {
if ( isset( self::$cache['pluralize'][ $word ] ) ) {
return self::$cache['pluralize'][ $word ];
}
if ( ! isset( self::$plural['merged']['irregular'] ) ) {
self::$plural['merged']['irregular'] = self::$plural['irregular'];
}
if ( ! isset( self::$plural['merged']['uninflected'] ) ) {
self::$plural['merged']['uninflected'] = array_merge( self::$plural['uninflected'], self::$uninflected );
}
if ( ! isset( self::$plural['cacheUninflected'] ) || ! isset( self::$plural['cacheIrregular'] ) ) {
self::$plural['cacheUninflected'] = '(?:' . implode( '|', self::$plural['merged']['uninflected'] ) . ')';
self::$plural['cacheIrregular'] = '(?:' . implode( '|', array_keys( self::$plural['merged']['irregular'] ) ) . ')';
}
if ( preg_match( '/(.*)\\b(' . self::$plural['cacheIrregular'] . ')$/i', $word, $regs ) ) {
self::$cache['pluralize'][ $word ] = $regs[1] . substr( $word, 0, 1 ) . substr( self::$plural['merged']['irregular'][ strtolower( $regs[2] ) ], 1 );
return self::$cache['pluralize'][ $word ];
}
if ( preg_match( '/^(' . self::$plural['cacheUninflected'] . ')$/i', $word, $regs ) ) {
self::$cache['pluralize'][ $word ] = $word;
return $word;
}
foreach ( self::$plural['rules'] as $rule => $replacement ) {
if ( preg_match( $rule, $word ) ) {
self::$cache['pluralize'][ $word ] = preg_replace( $rule, $replacement, $word );
return self::$cache['pluralize'][ $word ];
}
}
} | [
"public",
"static",
"function",
"pluralize",
"(",
"$",
"word",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"cache",
"[",
"'pluralize'",
"]",
"[",
"$",
"word",
"]",
")",
")",
"{",
"return",
"self",
"::",
"$",
"cache",
"[",
"'pluralize'",
"]",
"[",
"$",
"word",
"]",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"plural",
"[",
"'merged'",
"]",
"[",
"'irregular'",
"]",
")",
")",
"{",
"self",
"::",
"$",
"plural",
"[",
"'merged'",
"]",
"[",
"'irregular'",
"]",
"=",
"self",
"::",
"$",
"plural",
"[",
"'irregular'",
"]",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"plural",
"[",
"'merged'",
"]",
"[",
"'uninflected'",
"]",
")",
")",
"{",
"self",
"::",
"$",
"plural",
"[",
"'merged'",
"]",
"[",
"'uninflected'",
"]",
"=",
"array_merge",
"(",
"self",
"::",
"$",
"plural",
"[",
"'uninflected'",
"]",
",",
"self",
"::",
"$",
"uninflected",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"plural",
"[",
"'cacheUninflected'",
"]",
")",
"||",
"!",
"isset",
"(",
"self",
"::",
"$",
"plural",
"[",
"'cacheIrregular'",
"]",
")",
")",
"{",
"self",
"::",
"$",
"plural",
"[",
"'cacheUninflected'",
"]",
"=",
"'(?:'",
".",
"implode",
"(",
"'|'",
",",
"self",
"::",
"$",
"plural",
"[",
"'merged'",
"]",
"[",
"'uninflected'",
"]",
")",
".",
"')'",
";",
"self",
"::",
"$",
"plural",
"[",
"'cacheIrregular'",
"]",
"=",
"'(?:'",
".",
"implode",
"(",
"'|'",
",",
"array_keys",
"(",
"self",
"::",
"$",
"plural",
"[",
"'merged'",
"]",
"[",
"'irregular'",
"]",
")",
")",
".",
"')'",
";",
"}",
"if",
"(",
"preg_match",
"(",
"'/(.*)\\\\b('",
".",
"self",
"::",
"$",
"plural",
"[",
"'cacheIrregular'",
"]",
".",
"')$/i'",
",",
"$",
"word",
",",
"$",
"regs",
")",
")",
"{",
"self",
"::",
"$",
"cache",
"[",
"'pluralize'",
"]",
"[",
"$",
"word",
"]",
"=",
"$",
"regs",
"[",
"1",
"]",
".",
"substr",
"(",
"$",
"word",
",",
"0",
",",
"1",
")",
".",
"substr",
"(",
"self",
"::",
"$",
"plural",
"[",
"'merged'",
"]",
"[",
"'irregular'",
"]",
"[",
"strtolower",
"(",
"$",
"regs",
"[",
"2",
"]",
")",
"]",
",",
"1",
")",
";",
"return",
"self",
"::",
"$",
"cache",
"[",
"'pluralize'",
"]",
"[",
"$",
"word",
"]",
";",
"}",
"if",
"(",
"preg_match",
"(",
"'/^('",
".",
"self",
"::",
"$",
"plural",
"[",
"'cacheUninflected'",
"]",
".",
"')$/i'",
",",
"$",
"word",
",",
"$",
"regs",
")",
")",
"{",
"self",
"::",
"$",
"cache",
"[",
"'pluralize'",
"]",
"[",
"$",
"word",
"]",
"=",
"$",
"word",
";",
"return",
"$",
"word",
";",
"}",
"foreach",
"(",
"self",
"::",
"$",
"plural",
"[",
"'rules'",
"]",
"as",
"$",
"rule",
"=>",
"$",
"replacement",
")",
"{",
"if",
"(",
"preg_match",
"(",
"$",
"rule",
",",
"$",
"word",
")",
")",
"{",
"self",
"::",
"$",
"cache",
"[",
"'pluralize'",
"]",
"[",
"$",
"word",
"]",
"=",
"preg_replace",
"(",
"$",
"rule",
",",
"$",
"replacement",
",",
"$",
"word",
")",
";",
"return",
"self",
"::",
"$",
"cache",
"[",
"'pluralize'",
"]",
"[",
"$",
"word",
"]",
";",
"}",
"}",
"}"
] | Returns a word in plural form.
@param string $word The word in singular form.
@return string The word in plural form. | [
"Returns",
"a",
"word",
"in",
"plural",
"form",
"."
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/Inflector.php#L457-L494 | train |
wp-cli/wp-cli | php/WP_CLI/SynopsisValidator.php | SynopsisValidator.enough_positionals | public function enough_positionals( $args ) {
$positional = $this->query_spec(
array(
'type' => 'positional',
'optional' => false,
)
);
return count( $args ) >= count( $positional );
} | php | public function enough_positionals( $args ) {
$positional = $this->query_spec(
array(
'type' => 'positional',
'optional' => false,
)
);
return count( $args ) >= count( $positional );
} | [
"public",
"function",
"enough_positionals",
"(",
"$",
"args",
")",
"{",
"$",
"positional",
"=",
"$",
"this",
"->",
"query_spec",
"(",
"array",
"(",
"'type'",
"=>",
"'positional'",
",",
"'optional'",
"=>",
"false",
",",
")",
")",
";",
"return",
"count",
"(",
"$",
"args",
")",
">=",
"count",
"(",
"$",
"positional",
")",
";",
"}"
] | Check whether there are enough positional arguments.
@param array $args Positional arguments.
@return bool | [
"Check",
"whether",
"there",
"are",
"enough",
"positional",
"arguments",
"."
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/SynopsisValidator.php#L44-L53 | train |
wp-cli/wp-cli | php/WP_CLI/SynopsisValidator.php | SynopsisValidator.unknown_positionals | public function unknown_positionals( $args ) {
$positional_repeating = $this->query_spec(
array(
'type' => 'positional',
'repeating' => true,
)
);
// At least one positional supports as many as possible.
if ( ! empty( $positional_repeating ) ) {
return array();
}
$positional = $this->query_spec(
array(
'type' => 'positional',
'repeating' => false,
)
);
return array_slice( $args, count( $positional ) );
} | php | public function unknown_positionals( $args ) {
$positional_repeating = $this->query_spec(
array(
'type' => 'positional',
'repeating' => true,
)
);
// At least one positional supports as many as possible.
if ( ! empty( $positional_repeating ) ) {
return array();
}
$positional = $this->query_spec(
array(
'type' => 'positional',
'repeating' => false,
)
);
return array_slice( $args, count( $positional ) );
} | [
"public",
"function",
"unknown_positionals",
"(",
"$",
"args",
")",
"{",
"$",
"positional_repeating",
"=",
"$",
"this",
"->",
"query_spec",
"(",
"array",
"(",
"'type'",
"=>",
"'positional'",
",",
"'repeating'",
"=>",
"true",
",",
")",
")",
";",
"// At least one positional supports as many as possible.",
"if",
"(",
"!",
"empty",
"(",
"$",
"positional_repeating",
")",
")",
"{",
"return",
"array",
"(",
")",
";",
"}",
"$",
"positional",
"=",
"$",
"this",
"->",
"query_spec",
"(",
"array",
"(",
"'type'",
"=>",
"'positional'",
",",
"'repeating'",
"=>",
"false",
",",
")",
")",
";",
"return",
"array_slice",
"(",
"$",
"args",
",",
"count",
"(",
"$",
"positional",
")",
")",
";",
"}"
] | Check for any unknown positionals.
@param array $args Positional arguments.
@return array | [
"Check",
"for",
"any",
"unknown",
"positionals",
"."
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/SynopsisValidator.php#L61-L82 | train |
wp-cli/wp-cli | php/WP_CLI/SynopsisValidator.php | SynopsisValidator.validate_assoc | public function validate_assoc( $assoc_args ) {
$assoc_spec = $this->query_spec(
array(
'type' => 'assoc',
)
);
$errors = array(
'fatal' => array(),
'warning' => array(),
);
$to_unset = array();
foreach ( $assoc_spec as $param ) {
$key = $param['name'];
if ( ! isset( $assoc_args[ $key ] ) ) {
if ( ! $param['optional'] ) {
$errors['fatal'][ $key ] = "missing --$key parameter";
}
} else {
if ( true === $assoc_args[ $key ] && ! $param['value']['optional'] ) {
$error_type = ( ! $param['optional'] ) ? 'fatal' : 'warning';
$errors[ $error_type ][ $key ] = "--$key parameter needs a value";
$to_unset[] = $key;
}
}
}
return array( $errors, $to_unset );
} | php | public function validate_assoc( $assoc_args ) {
$assoc_spec = $this->query_spec(
array(
'type' => 'assoc',
)
);
$errors = array(
'fatal' => array(),
'warning' => array(),
);
$to_unset = array();
foreach ( $assoc_spec as $param ) {
$key = $param['name'];
if ( ! isset( $assoc_args[ $key ] ) ) {
if ( ! $param['optional'] ) {
$errors['fatal'][ $key ] = "missing --$key parameter";
}
} else {
if ( true === $assoc_args[ $key ] && ! $param['value']['optional'] ) {
$error_type = ( ! $param['optional'] ) ? 'fatal' : 'warning';
$errors[ $error_type ][ $key ] = "--$key parameter needs a value";
$to_unset[] = $key;
}
}
}
return array( $errors, $to_unset );
} | [
"public",
"function",
"validate_assoc",
"(",
"$",
"assoc_args",
")",
"{",
"$",
"assoc_spec",
"=",
"$",
"this",
"->",
"query_spec",
"(",
"array",
"(",
"'type'",
"=>",
"'assoc'",
",",
")",
")",
";",
"$",
"errors",
"=",
"array",
"(",
"'fatal'",
"=>",
"array",
"(",
")",
",",
"'warning'",
"=>",
"array",
"(",
")",
",",
")",
";",
"$",
"to_unset",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"assoc_spec",
"as",
"$",
"param",
")",
"{",
"$",
"key",
"=",
"$",
"param",
"[",
"'name'",
"]",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"assoc_args",
"[",
"$",
"key",
"]",
")",
")",
"{",
"if",
"(",
"!",
"$",
"param",
"[",
"'optional'",
"]",
")",
"{",
"$",
"errors",
"[",
"'fatal'",
"]",
"[",
"$",
"key",
"]",
"=",
"\"missing --$key parameter\"",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"true",
"===",
"$",
"assoc_args",
"[",
"$",
"key",
"]",
"&&",
"!",
"$",
"param",
"[",
"'value'",
"]",
"[",
"'optional'",
"]",
")",
"{",
"$",
"error_type",
"=",
"(",
"!",
"$",
"param",
"[",
"'optional'",
"]",
")",
"?",
"'fatal'",
":",
"'warning'",
";",
"$",
"errors",
"[",
"$",
"error_type",
"]",
"[",
"$",
"key",
"]",
"=",
"\"--$key parameter needs a value\"",
";",
"$",
"to_unset",
"[",
"]",
"=",
"$",
"key",
";",
"}",
"}",
"}",
"return",
"array",
"(",
"$",
"errors",
",",
"$",
"to_unset",
")",
";",
"}"
] | Check that all required keys are present and that they have values.
@param array $assoc_args Parameters passed to command.
@return array | [
"Check",
"that",
"all",
"required",
"keys",
"are",
"present",
"and",
"that",
"they",
"have",
"values",
"."
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/SynopsisValidator.php#L90-L122 | train |
wp-cli/wp-cli | php/WP_CLI/SynopsisValidator.php | SynopsisValidator.unknown_assoc | public function unknown_assoc( $assoc_args ) {
$generic = $this->query_spec(
array(
'type' => 'generic',
)
);
if ( count( $generic ) ) {
return array();
}
$known_assoc = array();
foreach ( $this->spec as $param ) {
if ( in_array( $param['type'], array( 'assoc', 'flag' ), true ) ) {
$known_assoc[] = $param['name'];
}
}
return array_diff( array_keys( $assoc_args ), $known_assoc );
} | php | public function unknown_assoc( $assoc_args ) {
$generic = $this->query_spec(
array(
'type' => 'generic',
)
);
if ( count( $generic ) ) {
return array();
}
$known_assoc = array();
foreach ( $this->spec as $param ) {
if ( in_array( $param['type'], array( 'assoc', 'flag' ), true ) ) {
$known_assoc[] = $param['name'];
}
}
return array_diff( array_keys( $assoc_args ), $known_assoc );
} | [
"public",
"function",
"unknown_assoc",
"(",
"$",
"assoc_args",
")",
"{",
"$",
"generic",
"=",
"$",
"this",
"->",
"query_spec",
"(",
"array",
"(",
"'type'",
"=>",
"'generic'",
",",
")",
")",
";",
"if",
"(",
"count",
"(",
"$",
"generic",
")",
")",
"{",
"return",
"array",
"(",
")",
";",
"}",
"$",
"known_assoc",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"spec",
"as",
"$",
"param",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"param",
"[",
"'type'",
"]",
",",
"array",
"(",
"'assoc'",
",",
"'flag'",
")",
",",
"true",
")",
")",
"{",
"$",
"known_assoc",
"[",
"]",
"=",
"$",
"param",
"[",
"'name'",
"]",
";",
"}",
"}",
"return",
"array_diff",
"(",
"array_keys",
"(",
"$",
"assoc_args",
")",
",",
"$",
"known_assoc",
")",
";",
"}"
] | Check whether there are unknown parameters supplied.
@param array $assoc_args Parameters passed to command.
@return array|false | [
"Check",
"whether",
"there",
"are",
"unknown",
"parameters",
"supplied",
"."
] | 564bf7b7cf1ac833071d1afed5d649d2a7198e15 | https://github.com/wp-cli/wp-cli/blob/564bf7b7cf1ac833071d1afed5d649d2a7198e15/php/WP_CLI/SynopsisValidator.php#L130-L150 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.