repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/ProxyReferenceRepository.php | ProxyReferenceRepository.getRealClass | protected function getRealClass($className)
{
if (Version::compare('2.2.0') <= 0) {
return ClassUtils::getRealClass($className);
}
if (substr($className, -5) === 'Proxy') {
return substr($className, 0, -5);
}
return $className;
} | php | protected function getRealClass($className)
{
if (Version::compare('2.2.0') <= 0) {
return ClassUtils::getRealClass($className);
}
if (substr($className, -5) === 'Proxy') {
return substr($className, 0, -5);
}
return $className;
} | [
"protected",
"function",
"getRealClass",
"(",
"$",
"className",
")",
"{",
"if",
"(",
"Version",
"::",
"compare",
"(",
"'2.2.0'",
")",
"<=",
"0",
")",
"{",
"return",
"ClassUtils",
"::",
"getRealClass",
"(",
"$",
"className",
")",
";",
"}",
"if",
"(",
"s... | Get real class name of a reference that could be a proxy
@param string $className Class name of reference object
@return string | [
"Get",
"real",
"class",
"name",
"of",
"a",
"reference",
"that",
"could",
"be",
"a",
"proxy"
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/ProxyReferenceRepository.php#L26-L37 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/ProxyReferenceRepository.php | ProxyReferenceRepository.serialize | public function serialize()
{
$unitOfWork = $this->getManager()->getUnitOfWork();
$simpleReferences = [];
foreach ($this->getReferences() as $name => $reference) {
$className = $this->getRealClass(get_class($reference));
$simpleReferences[$name] = [$className, $this->getIdentifier($reference, $unitOfWork)];
}
$serializedData = json_encode([
'references' => $simpleReferences,
'identities' => $this->getIdentities(),
]);
return $serializedData;
} | php | public function serialize()
{
$unitOfWork = $this->getManager()->getUnitOfWork();
$simpleReferences = [];
foreach ($this->getReferences() as $name => $reference) {
$className = $this->getRealClass(get_class($reference));
$simpleReferences[$name] = [$className, $this->getIdentifier($reference, $unitOfWork)];
}
$serializedData = json_encode([
'references' => $simpleReferences,
'identities' => $this->getIdentities(),
]);
return $serializedData;
} | [
"public",
"function",
"serialize",
"(",
")",
"{",
"$",
"unitOfWork",
"=",
"$",
"this",
"->",
"getManager",
"(",
")",
"->",
"getUnitOfWork",
"(",
")",
";",
"$",
"simpleReferences",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getReferences",
... | Serialize reference repository
@return string | [
"Serialize",
"reference",
"repository"
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/ProxyReferenceRepository.php#L44-L61 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/ProxyReferenceRepository.php | ProxyReferenceRepository.unserialize | public function unserialize($serializedData)
{
$repositoryData = json_decode($serializedData, true);
$references = $repositoryData['references'];
foreach ($references as $name => $proxyReference) {
$this->setReference(
$name,
$this->getManager()->getReference(
$proxyReference[0], // entity class name
$proxyReference[1] // identifiers
)
);
}
$identities = $repositoryData['identities'];
foreach ($identities as $name => $identity) {
$this->setReferenceIdentity($name, $identity);
}
} | php | public function unserialize($serializedData)
{
$repositoryData = json_decode($serializedData, true);
$references = $repositoryData['references'];
foreach ($references as $name => $proxyReference) {
$this->setReference(
$name,
$this->getManager()->getReference(
$proxyReference[0], // entity class name
$proxyReference[1] // identifiers
)
);
}
$identities = $repositoryData['identities'];
foreach ($identities as $name => $identity) {
$this->setReferenceIdentity($name, $identity);
}
} | [
"public",
"function",
"unserialize",
"(",
"$",
"serializedData",
")",
"{",
"$",
"repositoryData",
"=",
"json_decode",
"(",
"$",
"serializedData",
",",
"true",
")",
";",
"$",
"references",
"=",
"$",
"repositoryData",
"[",
"'references'",
"]",
";",
"foreach",
... | Unserialize reference repository
@param string $serializedData Serialized data | [
"Unserialize",
"reference",
"repository"
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/ProxyReferenceRepository.php#L68-L88 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/ProxyReferenceRepository.php | ProxyReferenceRepository.load | public function load($baseCacheName)
{
$filename = $baseCacheName . '.ser';
if ( ! file_exists($filename) || ($serializedData = file_get_contents($filename)) === false) {
return false;
}
$this->unserialize($serializedData);
return true;
} | php | public function load($baseCacheName)
{
$filename = $baseCacheName . '.ser';
if ( ! file_exists($filename) || ($serializedData = file_get_contents($filename)) === false) {
return false;
}
$this->unserialize($serializedData);
return true;
} | [
"public",
"function",
"load",
"(",
"$",
"baseCacheName",
")",
"{",
"$",
"filename",
"=",
"$",
"baseCacheName",
".",
"'.ser'",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"filename",
")",
"||",
"(",
"$",
"serializedData",
"=",
"file_get_contents",
"(",
... | Load data fixture reference repository
@param string $baseCacheName Base cache name
@return boolean | [
"Load",
"data",
"fixture",
"reference",
"repository"
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/ProxyReferenceRepository.php#L97-L108 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/Purger/ORMPurger.php | ORMPurger.getCommitOrder | private function getCommitOrder(EntityManagerInterface $em, array $classes)
{
$sorter = new TopologicalSorter();
foreach ($classes as $class) {
if ( ! $sorter->hasNode($class->name)) {
$sorter->addNode($class->name, $class);
}
// $class before its parents
foreach ($class->parentClasses as $parentClass) {
$parentClass = $em->getClassMetadata($parentClass);
$parentClassName = $parentClass->getName();
if ( ! $sorter->hasNode($parentClassName)) {
$sorter->addNode($parentClassName, $parentClass);
}
$sorter->addDependency($class->name, $parentClassName);
}
foreach ($class->associationMappings as $assoc) {
if ($assoc['isOwningSide']) {
/* @var $targetClass ClassMetadata */
$targetClass = $em->getClassMetadata($assoc['targetEntity']);
$targetClassName = $targetClass->getName();
if ( ! $sorter->hasNode($targetClassName)) {
$sorter->addNode($targetClassName, $targetClass);
}
// add dependency ($targetClass before $class)
$sorter->addDependency($targetClassName, $class->name);
// parents of $targetClass before $class, too
foreach ($targetClass->parentClasses as $parentClass) {
$parentClass = $em->getClassMetadata($parentClass);
$parentClassName = $parentClass->getName();
if ( ! $sorter->hasNode($parentClassName)) {
$sorter->addNode($parentClassName, $parentClass);
}
$sorter->addDependency($parentClassName, $class->name);
}
}
}
}
return array_reverse($sorter->sort());
} | php | private function getCommitOrder(EntityManagerInterface $em, array $classes)
{
$sorter = new TopologicalSorter();
foreach ($classes as $class) {
if ( ! $sorter->hasNode($class->name)) {
$sorter->addNode($class->name, $class);
}
// $class before its parents
foreach ($class->parentClasses as $parentClass) {
$parentClass = $em->getClassMetadata($parentClass);
$parentClassName = $parentClass->getName();
if ( ! $sorter->hasNode($parentClassName)) {
$sorter->addNode($parentClassName, $parentClass);
}
$sorter->addDependency($class->name, $parentClassName);
}
foreach ($class->associationMappings as $assoc) {
if ($assoc['isOwningSide']) {
/* @var $targetClass ClassMetadata */
$targetClass = $em->getClassMetadata($assoc['targetEntity']);
$targetClassName = $targetClass->getName();
if ( ! $sorter->hasNode($targetClassName)) {
$sorter->addNode($targetClassName, $targetClass);
}
// add dependency ($targetClass before $class)
$sorter->addDependency($targetClassName, $class->name);
// parents of $targetClass before $class, too
foreach ($targetClass->parentClasses as $parentClass) {
$parentClass = $em->getClassMetadata($parentClass);
$parentClassName = $parentClass->getName();
if ( ! $sorter->hasNode($parentClassName)) {
$sorter->addNode($parentClassName, $parentClass);
}
$sorter->addDependency($parentClassName, $class->name);
}
}
}
}
return array_reverse($sorter->sort());
} | [
"private",
"function",
"getCommitOrder",
"(",
"EntityManagerInterface",
"$",
"em",
",",
"array",
"$",
"classes",
")",
"{",
"$",
"sorter",
"=",
"new",
"TopologicalSorter",
"(",
")",
";",
"foreach",
"(",
"$",
"classes",
"as",
"$",
"class",
")",
"{",
"if",
... | @param EntityManagerInterface $em
@param ClassMetadata[] $classes
@return ClassMetadata[] | [
"@param",
"EntityManagerInterface",
"$em",
"@param",
"ClassMetadata",
"[]",
"$classes"
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/Purger/ORMPurger.php#L146-L196 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/Event/Listener/ORMReferenceListener.php | ORMReferenceListener.postPersist | public function postPersist(LifecycleEventArgs $args)
{
$object = $args->getEntity();
if (($names = $this->referenceRepository->getReferenceNames($object)) !== false) {
foreach ($names as $name) {
$identity = $args->getEntityManager()
->getUnitOfWork()
->getEntityIdentifier($object);
$this->referenceRepository->setReferenceIdentity($name, $identity);
}
}
} | php | public function postPersist(LifecycleEventArgs $args)
{
$object = $args->getEntity();
if (($names = $this->referenceRepository->getReferenceNames($object)) !== false) {
foreach ($names as $name) {
$identity = $args->getEntityManager()
->getUnitOfWork()
->getEntityIdentifier($object);
$this->referenceRepository->setReferenceIdentity($name, $identity);
}
}
} | [
"public",
"function",
"postPersist",
"(",
"LifecycleEventArgs",
"$",
"args",
")",
"{",
"$",
"object",
"=",
"$",
"args",
"->",
"getEntity",
"(",
")",
";",
"if",
"(",
"(",
"$",
"names",
"=",
"$",
"this",
"->",
"referenceRepository",
"->",
"getReferenceNames"... | Populates identities for stored references
@param LifecycleEventArgs $args | [
"Populates",
"identities",
"for",
"stored",
"references"
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/Event/Listener/ORMReferenceListener.php#L48-L61 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/Event/Listener/MongoDBReferenceListener.php | MongoDBReferenceListener.postPersist | public function postPersist(LifecycleEventArgs $args)
{
$object = $args->getDocument();
if (($names = $this->referenceRepository->getReferenceNames($object)) !== false) {
foreach ($names as $name) {
$identity = $args->getDocumentManager()
->getUnitOfWork()
->getDocumentIdentifier($object);
$this->referenceRepository->setReferenceIdentity($name, $identity);
}
}
} | php | public function postPersist(LifecycleEventArgs $args)
{
$object = $args->getDocument();
if (($names = $this->referenceRepository->getReferenceNames($object)) !== false) {
foreach ($names as $name) {
$identity = $args->getDocumentManager()
->getUnitOfWork()
->getDocumentIdentifier($object);
$this->referenceRepository->setReferenceIdentity($name, $identity);
}
}
} | [
"public",
"function",
"postPersist",
"(",
"LifecycleEventArgs",
"$",
"args",
")",
"{",
"$",
"object",
"=",
"$",
"args",
"->",
"getDocument",
"(",
")",
";",
"if",
"(",
"(",
"$",
"names",
"=",
"$",
"this",
"->",
"referenceRepository",
"->",
"getReferenceName... | Populates identities for stored references
@param LifecycleEventArgs $args | [
"Populates",
"identities",
"for",
"stored",
"references"
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/Event/Listener/MongoDBReferenceListener.php#L48-L61 |
symfony/polyfill-ctype | Ctype.php | Ctype.ctype_alnum | public static function ctype_alnum($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z0-9]/', $text);
} | php | public static function ctype_alnum($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z0-9]/', $text);
} | [
"public",
"static",
"function",
"ctype_alnum",
"(",
"$",
"text",
")",
"{",
"$",
"text",
"=",
"self",
"::",
"convert_int_to_char_for_ctype",
"(",
"$",
"text",
")",
";",
"return",
"\\",
"is_string",
"(",
"$",
"text",
")",
"&&",
"''",
"!==",
"$",
"text",
... | Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.
@see https://php.net/ctype-alnum
@param string|int $text
@return bool | [
"Returns",
"TRUE",
"if",
"every",
"character",
"in",
"text",
"is",
"either",
"a",
"letter",
"or",
"a",
"digit",
"FALSE",
"otherwise",
"."
] | train | https://github.com/symfony/polyfill-ctype/blob/82ebae02209c21113908c229e9883c419720738a/Ctype.php#L32-L37 |
symfony/polyfill-ctype | Ctype.php | Ctype.ctype_alpha | public static function ctype_alpha($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z]/', $text);
} | php | public static function ctype_alpha($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z]/', $text);
} | [
"public",
"static",
"function",
"ctype_alpha",
"(",
"$",
"text",
")",
"{",
"$",
"text",
"=",
"self",
"::",
"convert_int_to_char_for_ctype",
"(",
"$",
"text",
")",
";",
"return",
"\\",
"is_string",
"(",
"$",
"text",
")",
"&&",
"''",
"!==",
"$",
"text",
... | Returns TRUE if every character in text is a letter, FALSE otherwise.
@see https://php.net/ctype-alpha
@param string|int $text
@return bool | [
"Returns",
"TRUE",
"if",
"every",
"character",
"in",
"text",
"is",
"a",
"letter",
"FALSE",
"otherwise",
"."
] | train | https://github.com/symfony/polyfill-ctype/blob/82ebae02209c21113908c229e9883c419720738a/Ctype.php#L48-L53 |
symfony/polyfill-ctype | Ctype.php | Ctype.ctype_cntrl | public static function ctype_cntrl($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^\x00-\x1f\x7f]/', $text);
} | php | public static function ctype_cntrl($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^\x00-\x1f\x7f]/', $text);
} | [
"public",
"static",
"function",
"ctype_cntrl",
"(",
"$",
"text",
")",
"{",
"$",
"text",
"=",
"self",
"::",
"convert_int_to_char_for_ctype",
"(",
"$",
"text",
")",
";",
"return",
"\\",
"is_string",
"(",
"$",
"text",
")",
"&&",
"''",
"!==",
"$",
"text",
... | Returns TRUE if every character in text is a control character from the current locale, FALSE otherwise.
@see https://php.net/ctype-cntrl
@param string|int $text
@return bool | [
"Returns",
"TRUE",
"if",
"every",
"character",
"in",
"text",
"is",
"a",
"control",
"character",
"from",
"the",
"current",
"locale",
"FALSE",
"otherwise",
"."
] | train | https://github.com/symfony/polyfill-ctype/blob/82ebae02209c21113908c229e9883c419720738a/Ctype.php#L64-L69 |
symfony/polyfill-ctype | Ctype.php | Ctype.ctype_digit | public static function ctype_digit($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^0-9]/', $text);
} | php | public static function ctype_digit($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^0-9]/', $text);
} | [
"public",
"static",
"function",
"ctype_digit",
"(",
"$",
"text",
")",
"{",
"$",
"text",
"=",
"self",
"::",
"convert_int_to_char_for_ctype",
"(",
"$",
"text",
")",
";",
"return",
"\\",
"is_string",
"(",
"$",
"text",
")",
"&&",
"''",
"!==",
"$",
"text",
... | Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise.
@see https://php.net/ctype-digit
@param string|int $text
@return bool | [
"Returns",
"TRUE",
"if",
"every",
"character",
"in",
"the",
"string",
"text",
"is",
"a",
"decimal",
"digit",
"FALSE",
"otherwise",
"."
] | train | https://github.com/symfony/polyfill-ctype/blob/82ebae02209c21113908c229e9883c419720738a/Ctype.php#L80-L85 |
symfony/polyfill-ctype | Ctype.php | Ctype.ctype_graph | public static function ctype_graph($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^!-~]/', $text);
} | php | public static function ctype_graph($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^!-~]/', $text);
} | [
"public",
"static",
"function",
"ctype_graph",
"(",
"$",
"text",
")",
"{",
"$",
"text",
"=",
"self",
"::",
"convert_int_to_char_for_ctype",
"(",
"$",
"text",
")",
";",
"return",
"\\",
"is_string",
"(",
"$",
"text",
")",
"&&",
"''",
"!==",
"$",
"text",
... | Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise.
@see https://php.net/ctype-graph
@param string|int $text
@return bool | [
"Returns",
"TRUE",
"if",
"every",
"character",
"in",
"text",
"is",
"printable",
"and",
"actually",
"creates",
"visible",
"output",
"(",
"no",
"white",
"space",
")",
"FALSE",
"otherwise",
"."
] | train | https://github.com/symfony/polyfill-ctype/blob/82ebae02209c21113908c229e9883c419720738a/Ctype.php#L96-L101 |
symfony/polyfill-ctype | Ctype.php | Ctype.ctype_lower | public static function ctype_lower($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^a-z]/', $text);
} | php | public static function ctype_lower($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^a-z]/', $text);
} | [
"public",
"static",
"function",
"ctype_lower",
"(",
"$",
"text",
")",
"{",
"$",
"text",
"=",
"self",
"::",
"convert_int_to_char_for_ctype",
"(",
"$",
"text",
")",
";",
"return",
"\\",
"is_string",
"(",
"$",
"text",
")",
"&&",
"''",
"!==",
"$",
"text",
... | Returns TRUE if every character in text is a lowercase letter.
@see https://php.net/ctype-lower
@param string|int $text
@return bool | [
"Returns",
"TRUE",
"if",
"every",
"character",
"in",
"text",
"is",
"a",
"lowercase",
"letter",
"."
] | train | https://github.com/symfony/polyfill-ctype/blob/82ebae02209c21113908c229e9883c419720738a/Ctype.php#L112-L117 |
symfony/polyfill-ctype | Ctype.php | Ctype.ctype_print | public static function ctype_print($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^ -~]/', $text);
} | php | public static function ctype_print($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^ -~]/', $text);
} | [
"public",
"static",
"function",
"ctype_print",
"(",
"$",
"text",
")",
"{",
"$",
"text",
"=",
"self",
"::",
"convert_int_to_char_for_ctype",
"(",
"$",
"text",
")",
";",
"return",
"\\",
"is_string",
"(",
"$",
"text",
")",
"&&",
"''",
"!==",
"$",
"text",
... | Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all.
@see https://php.net/ctype-print
@param string|int $text
@return bool | [
"Returns",
"TRUE",
"if",
"every",
"character",
"in",
"text",
"will",
"actually",
"create",
"output",
"(",
"including",
"blanks",
")",
".",
"Returns",
"FALSE",
"if",
"text",
"contains",
"control",
"characters",
"or",
"characters",
"that",
"do",
"not",
"have",
... | train | https://github.com/symfony/polyfill-ctype/blob/82ebae02209c21113908c229e9883c419720738a/Ctype.php#L128-L133 |
symfony/polyfill-ctype | Ctype.php | Ctype.ctype_punct | public static function ctype_punct($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^!-\/\:-@\[-`\{-~]/', $text);
} | php | public static function ctype_punct($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^!-\/\:-@\[-`\{-~]/', $text);
} | [
"public",
"static",
"function",
"ctype_punct",
"(",
"$",
"text",
")",
"{",
"$",
"text",
"=",
"self",
"::",
"convert_int_to_char_for_ctype",
"(",
"$",
"text",
")",
";",
"return",
"\\",
"is_string",
"(",
"$",
"text",
")",
"&&",
"''",
"!==",
"$",
"text",
... | Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise.
@see https://php.net/ctype-punct
@param string|int $text
@return bool | [
"Returns",
"TRUE",
"if",
"every",
"character",
"in",
"text",
"is",
"printable",
"but",
"neither",
"letter",
"digit",
"or",
"blank",
"FALSE",
"otherwise",
"."
] | train | https://github.com/symfony/polyfill-ctype/blob/82ebae02209c21113908c229e9883c419720738a/Ctype.php#L144-L149 |
symfony/polyfill-ctype | Ctype.php | Ctype.ctype_space | public static function ctype_space($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^\s]/', $text);
} | php | public static function ctype_space($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^\s]/', $text);
} | [
"public",
"static",
"function",
"ctype_space",
"(",
"$",
"text",
")",
"{",
"$",
"text",
"=",
"self",
"::",
"convert_int_to_char_for_ctype",
"(",
"$",
"text",
")",
";",
"return",
"\\",
"is_string",
"(",
"$",
"text",
")",
"&&",
"''",
"!==",
"$",
"text",
... | Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters.
@see https://php.net/ctype-space
@param string|int $text
@return bool | [
"Returns",
"TRUE",
"if",
"every",
"character",
"in",
"text",
"creates",
"some",
"sort",
"of",
"white",
"space",
"FALSE",
"otherwise",
".",
"Besides",
"the",
"blank",
"character",
"this",
"also",
"includes",
"tab",
"vertical",
"tab",
"line",
"feed",
"carriage",... | train | https://github.com/symfony/polyfill-ctype/blob/82ebae02209c21113908c229e9883c419720738a/Ctype.php#L160-L165 |
symfony/polyfill-ctype | Ctype.php | Ctype.ctype_upper | public static function ctype_upper($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^A-Z]/', $text);
} | php | public static function ctype_upper($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^A-Z]/', $text);
} | [
"public",
"static",
"function",
"ctype_upper",
"(",
"$",
"text",
")",
"{",
"$",
"text",
"=",
"self",
"::",
"convert_int_to_char_for_ctype",
"(",
"$",
"text",
")",
";",
"return",
"\\",
"is_string",
"(",
"$",
"text",
")",
"&&",
"''",
"!==",
"$",
"text",
... | Returns TRUE if every character in text is an uppercase letter.
@see https://php.net/ctype-upper
@param string|int $text
@return bool | [
"Returns",
"TRUE",
"if",
"every",
"character",
"in",
"text",
"is",
"an",
"uppercase",
"letter",
"."
] | train | https://github.com/symfony/polyfill-ctype/blob/82ebae02209c21113908c229e9883c419720738a/Ctype.php#L176-L181 |
symfony/polyfill-ctype | Ctype.php | Ctype.ctype_xdigit | public static function ctype_xdigit($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^A-Fa-f0-9]/', $text);
} | php | public static function ctype_xdigit($text)
{
$text = self::convert_int_to_char_for_ctype($text);
return \is_string($text) && '' !== $text && !preg_match('/[^A-Fa-f0-9]/', $text);
} | [
"public",
"static",
"function",
"ctype_xdigit",
"(",
"$",
"text",
")",
"{",
"$",
"text",
"=",
"self",
"::",
"convert_int_to_char_for_ctype",
"(",
"$",
"text",
")",
";",
"return",
"\\",
"is_string",
"(",
"$",
"text",
")",
"&&",
"''",
"!==",
"$",
"text",
... | Returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise.
@see https://php.net/ctype-xdigit
@param string|int $text
@return bool | [
"Returns",
"TRUE",
"if",
"every",
"character",
"in",
"text",
"is",
"a",
"hexadecimal",
"digit",
"that",
"is",
"a",
"decimal",
"digit",
"or",
"a",
"character",
"from",
"[",
"A",
"-",
"Fa",
"-",
"f",
"]",
"FALSE",
"otherwise",
"."
] | train | https://github.com/symfony/polyfill-ctype/blob/82ebae02209c21113908c229e9883c419720738a/Ctype.php#L192-L197 |
symfony/polyfill-ctype | Ctype.php | Ctype.convert_int_to_char_for_ctype | private static function convert_int_to_char_for_ctype($int)
{
if (!\is_int($int)) {
return $int;
}
if ($int < -128 || $int > 255) {
return (string) $int;
}
if ($int < 0) {
$int += 256;
}
return \chr($int);
} | php | private static function convert_int_to_char_for_ctype($int)
{
if (!\is_int($int)) {
return $int;
}
if ($int < -128 || $int > 255) {
return (string) $int;
}
if ($int < 0) {
$int += 256;
}
return \chr($int);
} | [
"private",
"static",
"function",
"convert_int_to_char_for_ctype",
"(",
"$",
"int",
")",
"{",
"if",
"(",
"!",
"\\",
"is_int",
"(",
"$",
"int",
")",
")",
"{",
"return",
"$",
"int",
";",
"}",
"if",
"(",
"$",
"int",
"<",
"-",
"128",
"||",
"$",
"int",
... | Converts integers to their char versions according to normal ctype behaviour, if needed.
If an integer between -128 and 255 inclusive is provided,
it is interpreted as the ASCII value of a single character
(negative values have 256 added in order to allow characters in the Extended ASCII range).
Any other integer is interpreted as a string containing the decimal digits of the integer.
@param string|int $int
@return mixed | [
"Converts",
"integers",
"to",
"their",
"char",
"versions",
"according",
"to",
"normal",
"ctype",
"behaviour",
"if",
"needed",
"."
] | train | https://github.com/symfony/polyfill-ctype/blob/82ebae02209c21113908c229e9883c419720738a/Ctype.php#L211-L226 |
rogeriopvl/php-lrucache | src/LRUCache/LRUCache.php | LRUCache.get | public function get($key) {
if (!isset($this->hashmap[$key])) { return null; }
$node = $this->hashmap[$key];
if (count($this->hashmap) == 1) { return $node->getData(); }
// refresh the access
$this->detach($node);
$this->attach($this->head, $node);
return $node->getData();
} | php | public function get($key) {
if (!isset($this->hashmap[$key])) { return null; }
$node = $this->hashmap[$key];
if (count($this->hashmap) == 1) { return $node->getData(); }
// refresh the access
$this->detach($node);
$this->attach($this->head, $node);
return $node->getData();
} | [
"public",
"function",
"get",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"hashmap",
"[",
"$",
"key",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"node",
"=",
"$",
"this",
"->",
"hashmap",
"[",
"$",
"ke... | Get an element with the given key
@param string $key the key of the element to be retrieved
@return mixed the content of the element to be retrieved | [
"Get",
"an",
"element",
"with",
"the",
"given",
"key"
] | train | https://github.com/rogeriopvl/php-lrucache/blob/0a1d303f50894900fd847d8e6131b8f7bf728d39/src/LRUCache/LRUCache.php#L45-L57 |
rogeriopvl/php-lrucache | src/LRUCache/LRUCache.php | LRUCache.put | public function put($key, $data) {
if ($this->capacity <= 0) { return false; }
if (isset($this->hashmap[$key]) && !empty($this->hashmap[$key])) {
$node = $this->hashmap[$key];
// update data
$this->detach($node);
$this->attach($this->head, $node);
$node->setData($data);
}
else {
$node = new Node($key, $data);
$this->hashmap[$key] = $node;
$this->attach($this->head, $node);
// check if cache is full
if (count($this->hashmap) > $this->capacity) {
// we're full, remove the tail
$nodeToRemove = $this->tail->getPrevious();
$this->detach($nodeToRemove);
unset($this->hashmap[$nodeToRemove->getKey()]);
}
}
return true;
} | php | public function put($key, $data) {
if ($this->capacity <= 0) { return false; }
if (isset($this->hashmap[$key]) && !empty($this->hashmap[$key])) {
$node = $this->hashmap[$key];
// update data
$this->detach($node);
$this->attach($this->head, $node);
$node->setData($data);
}
else {
$node = new Node($key, $data);
$this->hashmap[$key] = $node;
$this->attach($this->head, $node);
// check if cache is full
if (count($this->hashmap) > $this->capacity) {
// we're full, remove the tail
$nodeToRemove = $this->tail->getPrevious();
$this->detach($nodeToRemove);
unset($this->hashmap[$nodeToRemove->getKey()]);
}
}
return true;
} | [
"public",
"function",
"put",
"(",
"$",
"key",
",",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"capacity",
"<=",
"0",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"hashmap",
"[",
"$",
"key",
"]",
... | Inserts a new element into the cache
@param string $key the key of the new element
@param string $data the content of the new element
@return boolean true on success, false if cache has zero capacity | [
"Inserts",
"a",
"new",
"element",
"into",
"the",
"cache"
] | train | https://github.com/rogeriopvl/php-lrucache/blob/0a1d303f50894900fd847d8e6131b8f7bf728d39/src/LRUCache/LRUCache.php#L65-L88 |
rogeriopvl/php-lrucache | src/LRUCache/LRUCache.php | LRUCache.remove | public function remove($key) {
if (!isset($this->hashmap[$key])) { return false; }
$nodeToRemove = $this->hashmap[$key];
$this->detach($nodeToRemove);
unset($this->hashmap[$nodeToRemove->getKey()]);
return true;
} | php | public function remove($key) {
if (!isset($this->hashmap[$key])) { return false; }
$nodeToRemove = $this->hashmap[$key];
$this->detach($nodeToRemove);
unset($this->hashmap[$nodeToRemove->getKey()]);
return true;
} | [
"public",
"function",
"remove",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"hashmap",
"[",
"$",
"key",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"nodeToRemove",
"=",
"$",
"this",
"->",
"hashmap",
"[",
... | Removes a key from the cache
@param string $key key to remove
@return bool true if removed, false if not found | [
"Removes",
"a",
"key",
"from",
"the",
"cache"
] | train | https://github.com/rogeriopvl/php-lrucache/blob/0a1d303f50894900fd847d8e6131b8f7bf728d39/src/LRUCache/LRUCache.php#L95-L101 |
rogeriopvl/php-lrucache | src/LRUCache/LRUCache.php | LRUCache.attach | private function attach($head, $node) {
$node->setPrevious($head);
$node->setNext($head->getNext());
$node->getNext()->setPrevious($node);
$node->getPrevious()->setNext($node);
} | php | private function attach($head, $node) {
$node->setPrevious($head);
$node->setNext($head->getNext());
$node->getNext()->setPrevious($node);
$node->getPrevious()->setNext($node);
} | [
"private",
"function",
"attach",
"(",
"$",
"head",
",",
"$",
"node",
")",
"{",
"$",
"node",
"->",
"setPrevious",
"(",
"$",
"head",
")",
";",
"$",
"node",
"->",
"setNext",
"(",
"$",
"head",
"->",
"getNext",
"(",
")",
")",
";",
"$",
"node",
"->",
... | Adds a node to the head of the list
@param Node $head the node object that represents the head of the list
@param Node $node the node to move to the head of the list | [
"Adds",
"a",
"node",
"to",
"the",
"head",
"of",
"the",
"list"
] | train | https://github.com/rogeriopvl/php-lrucache/blob/0a1d303f50894900fd847d8e6131b8f7bf728d39/src/LRUCache/LRUCache.php#L108-L113 |
rogeriopvl/php-lrucache | src/LRUCache/LRUCache.php | LRUCache.detach | private function detach($node) {
$node->getPrevious()->setNext($node->getNext());
$node->getNext()->setPrevious($node->getPrevious());
} | php | private function detach($node) {
$node->getPrevious()->setNext($node->getNext());
$node->getNext()->setPrevious($node->getPrevious());
} | [
"private",
"function",
"detach",
"(",
"$",
"node",
")",
"{",
"$",
"node",
"->",
"getPrevious",
"(",
")",
"->",
"setNext",
"(",
"$",
"node",
"->",
"getNext",
"(",
")",
")",
";",
"$",
"node",
"->",
"getNext",
"(",
")",
"->",
"setPrevious",
"(",
"$",
... | Removes a node from the list
@param Node $node the node to remove from the list | [
"Removes",
"a",
"node",
"from",
"the",
"list"
] | train | https://github.com/rogeriopvl/php-lrucache/blob/0a1d303f50894900fd847d8e6131b8f7bf728d39/src/LRUCache/LRUCache.php#L119-L122 |
doctrine/DoctrineFixturesBundle | Command/LoadDataFixturesDoctrineCommand.php | LoadDataFixturesDoctrineCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$ui = new SymfonyStyle($input, $output);
/** @var ManagerRegistry $doctrine */
$doctrine = $this->getContainer()->get('doctrine');
$em = $doctrine->getManager($input->getOption('em'));
if (! $input->getOption('append')) {
if (! $ui->confirm(sprintf('Careful, database "%s" will be purged. Do you want to continue?', $em->getConnection()->getDatabase()), ! $input->isInteractive())) {
return;
}
}
if ($input->getOption('shard')) {
if (! $em->getConnection() instanceof PoolingShardConnection) {
throw new LogicException(sprintf(
'Connection of EntityManager "%s" must implement shards configuration.',
$input->getOption('em')
));
}
$em->getConnection()->connect($input->getOption('shard'));
}
$groups = $input->getOption('group');
$fixtures = $this->fixturesLoader->getFixtures($groups);
if (! $fixtures) {
$message = 'Could not find any fixture services to load';
if (! empty($groups)) {
$message .= sprintf(' in the groups (%s)', implode(', ', $groups));
}
$ui->error($message . '.');
return 1;
}
$purger = new ORMPurger($em);
$purger->setPurgeMode($input->getOption('purge-with-truncate') ? ORMPurger::PURGE_MODE_TRUNCATE : ORMPurger::PURGE_MODE_DELETE);
$executor = new ORMExecutor($em, $purger);
$executor->setLogger(static function ($message) use ($ui) : void {
$ui->text(sprintf(' <comment>></comment> <info>%s</info>', $message));
});
$executor->execute($fixtures, $input->getOption('append'));
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$ui = new SymfonyStyle($input, $output);
/** @var ManagerRegistry $doctrine */
$doctrine = $this->getContainer()->get('doctrine');
$em = $doctrine->getManager($input->getOption('em'));
if (! $input->getOption('append')) {
if (! $ui->confirm(sprintf('Careful, database "%s" will be purged. Do you want to continue?', $em->getConnection()->getDatabase()), ! $input->isInteractive())) {
return;
}
}
if ($input->getOption('shard')) {
if (! $em->getConnection() instanceof PoolingShardConnection) {
throw new LogicException(sprintf(
'Connection of EntityManager "%s" must implement shards configuration.',
$input->getOption('em')
));
}
$em->getConnection()->connect($input->getOption('shard'));
}
$groups = $input->getOption('group');
$fixtures = $this->fixturesLoader->getFixtures($groups);
if (! $fixtures) {
$message = 'Could not find any fixture services to load';
if (! empty($groups)) {
$message .= sprintf(' in the groups (%s)', implode(', ', $groups));
}
$ui->error($message . '.');
return 1;
}
$purger = new ORMPurger($em);
$purger->setPurgeMode($input->getOption('purge-with-truncate') ? ORMPurger::PURGE_MODE_TRUNCATE : ORMPurger::PURGE_MODE_DELETE);
$executor = new ORMExecutor($em, $purger);
$executor->setLogger(static function ($message) use ($ui) : void {
$ui->text(sprintf(' <comment>></comment> <info>%s</info>', $message));
});
$executor->execute($fixtures, $input->getOption('append'));
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"ui",
"=",
"new",
"SymfonyStyle",
"(",
"$",
"input",
",",
"$",
"output",
")",
";",
"/** @var ManagerRegistry $doctrine */",
"$",
"doc... | phpcs:ignore SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingReturnTypeHint | [
"phpcs",
":",
"ignore",
"SlevomatCodingStandard",
".",
"TypeHints",
".",
"TypeHintDeclaration",
".",
"MissingReturnTypeHint"
] | train | https://github.com/doctrine/DoctrineFixturesBundle/blob/22c1e38fa0ca32218eff2cd7fc5646c5ec6d11e6/Command/LoadDataFixturesDoctrineCommand.php#L72-L117 |
doctrine/DoctrineFixturesBundle | DependencyInjection/DoctrineFixturesExtension.php | DoctrineFixturesExtension.load | public function load(array $configs, ContainerBuilder $container)
{
$loader = new XmlFileLoader($container, new FileLocator(dirname(__DIR__) . '/Resources/config'));
$loader->load('services.xml');
$container->registerForAutoconfiguration(ORMFixtureInterface::class)
->addTag(FixturesCompilerPass::FIXTURE_TAG);
} | php | public function load(array $configs, ContainerBuilder $container)
{
$loader = new XmlFileLoader($container, new FileLocator(dirname(__DIR__) . '/Resources/config'));
$loader->load('services.xml');
$container->registerForAutoconfiguration(ORMFixtureInterface::class)
->addTag(FixturesCompilerPass::FIXTURE_TAG);
} | [
"public",
"function",
"load",
"(",
"array",
"$",
"configs",
",",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"loader",
"=",
"new",
"XmlFileLoader",
"(",
"$",
"container",
",",
"new",
"FileLocator",
"(",
"dirname",
"(",
"__DIR__",
")",
".",
"'/Reso... | {@inheritdoc} | [
"{"
] | train | https://github.com/doctrine/DoctrineFixturesBundle/blob/22c1e38fa0ca32218eff2cd7fc5646c5ec6d11e6/DependencyInjection/DoctrineFixturesExtension.php#L20-L28 |
doctrine/DoctrineFixturesBundle | Loader/SymfonyFixturesLoader.php | SymfonyFixturesLoader.createFixture | protected function createFixture($class) : FixtureInterface
{
/*
* We don't actually need to create the fixture. We just
* return the one that already exists.
*/
if (! isset($this->loadedFixtures[$class])) {
throw new LogicException(sprintf(
'The "%s" fixture class is trying to be loaded, but is not available. Make sure this class is defined as a service and tagged with "%s".',
$class,
FixturesCompilerPass::FIXTURE_TAG
));
}
return $this->loadedFixtures[$class];
} | php | protected function createFixture($class) : FixtureInterface
{
/*
* We don't actually need to create the fixture. We just
* return the one that already exists.
*/
if (! isset($this->loadedFixtures[$class])) {
throw new LogicException(sprintf(
'The "%s" fixture class is trying to be loaded, but is not available. Make sure this class is defined as a service and tagged with "%s".',
$class,
FixturesCompilerPass::FIXTURE_TAG
));
}
return $this->loadedFixtures[$class];
} | [
"protected",
"function",
"createFixture",
"(",
"$",
"class",
")",
":",
"FixtureInterface",
"{",
"/*\n * We don't actually need to create the fixture. We just\n * return the one that already exists.\n */",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
... | Overridden to not allow new fixture classes to be instantiated.
@param string $class | [
"Overridden",
"to",
"not",
"allow",
"new",
"fixture",
"classes",
"to",
"be",
"instantiated",
"."
] | train | https://github.com/doctrine/DoctrineFixturesBundle/blob/22c1e38fa0ca32218eff2cd7fc5646c5ec6d11e6/Loader/SymfonyFixturesLoader.php#L68-L84 |
doctrine/DoctrineFixturesBundle | Loader/SymfonyFixturesLoader.php | SymfonyFixturesLoader.getFixtures | public function getFixtures(array $groups = []) : array
{
$fixtures = parent::getFixtures();
if (empty($groups)) {
return $fixtures;
}
$filteredFixtures = [];
foreach ($fixtures as $fixture) {
foreach ($groups as $group) {
$fixtureClass = get_class($fixture);
if (isset($this->groupsFixtureMapping[$group][$fixtureClass])) {
$filteredFixtures[$fixtureClass] = $fixture;
continue 2;
}
}
}
foreach ($filteredFixtures as $fixture) {
$this->validateDependencies($filteredFixtures, $fixture);
}
return array_values($filteredFixtures);
} | php | public function getFixtures(array $groups = []) : array
{
$fixtures = parent::getFixtures();
if (empty($groups)) {
return $fixtures;
}
$filteredFixtures = [];
foreach ($fixtures as $fixture) {
foreach ($groups as $group) {
$fixtureClass = get_class($fixture);
if (isset($this->groupsFixtureMapping[$group][$fixtureClass])) {
$filteredFixtures[$fixtureClass] = $fixture;
continue 2;
}
}
}
foreach ($filteredFixtures as $fixture) {
$this->validateDependencies($filteredFixtures, $fixture);
}
return array_values($filteredFixtures);
} | [
"public",
"function",
"getFixtures",
"(",
"array",
"$",
"groups",
"=",
"[",
"]",
")",
":",
"array",
"{",
"$",
"fixtures",
"=",
"parent",
"::",
"getFixtures",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"groups",
")",
")",
"{",
"return",
"$",
"fixt... | Returns the array of data fixtures to execute.
@param string[] $groups
@return FixtureInterface[] | [
"Returns",
"the",
"array",
"of",
"data",
"fixtures",
"to",
"execute",
"."
] | train | https://github.com/doctrine/DoctrineFixturesBundle/blob/22c1e38fa0ca32218eff2cd7fc5646c5ec6d11e6/Loader/SymfonyFixturesLoader.php#L93-L117 |
doctrine/DoctrineFixturesBundle | Loader/SymfonyFixturesLoader.php | SymfonyFixturesLoader.addGroupsFixtureMapping | private function addGroupsFixtureMapping(string $className, array $groups) : void
{
foreach ($groups as $group) {
$this->groupsFixtureMapping[$group][$className] = true;
}
} | php | private function addGroupsFixtureMapping(string $className, array $groups) : void
{
foreach ($groups as $group) {
$this->groupsFixtureMapping[$group][$className] = true;
}
} | [
"private",
"function",
"addGroupsFixtureMapping",
"(",
"string",
"$",
"className",
",",
"array",
"$",
"groups",
")",
":",
"void",
"{",
"foreach",
"(",
"$",
"groups",
"as",
"$",
"group",
")",
"{",
"$",
"this",
"->",
"groupsFixtureMapping",
"[",
"$",
"group"... | Generates an array of the groups and their fixtures
@param string[] $groups | [
"Generates",
"an",
"array",
"of",
"the",
"groups",
"and",
"their",
"fixtures"
] | train | https://github.com/doctrine/DoctrineFixturesBundle/blob/22c1e38fa0ca32218eff2cd7fc5646c5ec6d11e6/Loader/SymfonyFixturesLoader.php#L124-L129 |
doctrine/DoctrineFixturesBundle | Loader/SymfonyFixturesLoader.php | SymfonyFixturesLoader.validateDependencies | private function validateDependencies(array $fixtures, FixtureInterface $fixture) : void
{
if (! $fixture instanceof DependentFixtureInterface) {
return;
}
$dependenciesClasses = $fixture->getDependencies();
foreach ($dependenciesClasses as $class) {
if (! array_key_exists($class, $fixtures)) {
throw new RuntimeException(sprintf('Fixture "%s" was declared as a dependency for fixture "%s", but it was not included in any of the loaded fixture groups.', $class, get_class($fixture)));
}
}
} | php | private function validateDependencies(array $fixtures, FixtureInterface $fixture) : void
{
if (! $fixture instanceof DependentFixtureInterface) {
return;
}
$dependenciesClasses = $fixture->getDependencies();
foreach ($dependenciesClasses as $class) {
if (! array_key_exists($class, $fixtures)) {
throw new RuntimeException(sprintf('Fixture "%s" was declared as a dependency for fixture "%s", but it was not included in any of the loaded fixture groups.', $class, get_class($fixture)));
}
}
} | [
"private",
"function",
"validateDependencies",
"(",
"array",
"$",
"fixtures",
",",
"FixtureInterface",
"$",
"fixture",
")",
":",
"void",
"{",
"if",
"(",
"!",
"$",
"fixture",
"instanceof",
"DependentFixtureInterface",
")",
"{",
"return",
";",
"}",
"$",
"depende... | @param string[] $fixtures An array of fixtures with class names as keys
@throws RuntimeException | [
"@param",
"string",
"[]",
"$fixtures",
"An",
"array",
"of",
"fixtures",
"with",
"class",
"names",
"as",
"keys"
] | train | https://github.com/doctrine/DoctrineFixturesBundle/blob/22c1e38fa0ca32218eff2cd7fc5646c5ec6d11e6/Loader/SymfonyFixturesLoader.php#L136-L149 |
opis/closure | src/SerializableClosure.php | SerializableClosure.getReflector | public function getReflector()
{
if ($this->reflector === null) {
$this->reflector = new ReflectionClosure($this->closure, $this->code);
$this->code = null;
}
return $this->reflector;
} | php | public function getReflector()
{
if ($this->reflector === null) {
$this->reflector = new ReflectionClosure($this->closure, $this->code);
$this->code = null;
}
return $this->reflector;
} | [
"public",
"function",
"getReflector",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"reflector",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"reflector",
"=",
"new",
"ReflectionClosure",
"(",
"$",
"this",
"->",
"closure",
",",
"$",
"this",
"->",
"code",... | Get the reflector for closure
@return ReflectionClosure | [
"Get",
"the",
"reflector",
"for",
"closure"
] | train | https://github.com/opis/closure/blob/ccb8e3928c5c8181c76cdd0ed9366c5bcaafd91b/src/SerializableClosure.php#L94-L102 |
opis/closure | src/SerializableClosure.php | SerializableClosure.serialize | public function serialize()
{
if ($this->scope === null) {
$this->scope = new ClosureScope();
$this->scope->toserialize++;
}
$this->scope->serializations++;
$scope = $object = null;
$reflector = $this->getReflector();
if($reflector->isBindingRequired()){
$object = $reflector->getClosureThis();
static::wrapClosures($object, $this->scope);
if($scope = $reflector->getClosureScopeClass()){
$scope = $scope->name;
}
} elseif($reflector->isScopeRequired()) {
if($scope = $reflector->getClosureScopeClass()){
$scope = $scope->name;
}
}
$this->reference = spl_object_hash($this->closure);
$this->scope[$this->closure] = $this;
$use = $this->transformUseVariables($reflector->getUseVariables());
$code = $reflector->getCode();
$this->mapByReference($use);
$ret = \serialize(array(
'use' => $use,
'function' => $code,
'scope' => $scope,
'this' => $object,
'self' => $this->reference,
));
if(static::$securityProvider !== null){
$ret = '@' . json_encode(static::$securityProvider->sign($ret));
}
if (!--$this->scope->serializations && !--$this->scope->toserialize) {
$this->scope = null;
}
return $ret;
} | php | public function serialize()
{
if ($this->scope === null) {
$this->scope = new ClosureScope();
$this->scope->toserialize++;
}
$this->scope->serializations++;
$scope = $object = null;
$reflector = $this->getReflector();
if($reflector->isBindingRequired()){
$object = $reflector->getClosureThis();
static::wrapClosures($object, $this->scope);
if($scope = $reflector->getClosureScopeClass()){
$scope = $scope->name;
}
} elseif($reflector->isScopeRequired()) {
if($scope = $reflector->getClosureScopeClass()){
$scope = $scope->name;
}
}
$this->reference = spl_object_hash($this->closure);
$this->scope[$this->closure] = $this;
$use = $this->transformUseVariables($reflector->getUseVariables());
$code = $reflector->getCode();
$this->mapByReference($use);
$ret = \serialize(array(
'use' => $use,
'function' => $code,
'scope' => $scope,
'this' => $object,
'self' => $this->reference,
));
if(static::$securityProvider !== null){
$ret = '@' . json_encode(static::$securityProvider->sign($ret));
}
if (!--$this->scope->serializations && !--$this->scope->toserialize) {
$this->scope = null;
}
return $ret;
} | [
"public",
"function",
"serialize",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"scope",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"scope",
"=",
"new",
"ClosureScope",
"(",
")",
";",
"$",
"this",
"->",
"scope",
"->",
"toserialize",
"++",
";",
"}"... | Implementation of Serializable::serialize()
@return string The serialized closure | [
"Implementation",
"of",
"Serializable",
"::",
"serialize",
"()"
] | train | https://github.com/opis/closure/blob/ccb8e3928c5c8181c76cdd0ed9366c5bcaafd91b/src/SerializableClosure.php#L117-L167 |
opis/closure | src/SerializableClosure.php | SerializableClosure.unserialize | public function unserialize($data)
{
ClosureStream::register();
if (static::$securityProvider !== null) {
if ($data[0] !== '@') {
throw new SecurityException("The serialized closure is not signed. ".
"Make sure you use a security provider for both serialization and unserialization.");
}
$data = json_decode(substr($data, 1), true);
if (!is_array($data) || !static::$securityProvider->verify($data)) {
throw new SecurityException("Your serialized closure might have been modified and it's unsafe to be unserialized. " .
"Make sure you use the same security provider, with the same settings, " .
"both for serialization and unserialization.");
}
$data = $data['closure'];
} elseif ($data[0] === '@') {
throw new SecurityException("The serialized closure is signed. ".
"Make sure you use a security provider for both serialization and unserialization.");
}
$this->code = \unserialize($data);
// unset data
unset($data);
$this->code['objects'] = array();
if ($this->code['use']) {
$this->scope = new ClosureScope();
$this->code['use'] = $this->resolveUseVariables($this->code['use']);
$this->mapPointers($this->code['use']);
extract($this->code['use'], EXTR_OVERWRITE | EXTR_REFS);
$this->scope = null;
}
$this->closure = include(ClosureStream::STREAM_PROTO . '://' . $this->code['function']);
if($this->code['this'] === $this){
$this->code['this'] = null;
}
if ($this->code['scope'] !== null || $this->code['this'] !== null) {
$this->closure = $this->closure->bindTo($this->code['this'], $this->code['scope']);
}
if(!empty($this->code['objects'])){
foreach ($this->code['objects'] as $item){
$item['property']->setValue($item['instance'], $item['object']->getClosure());
}
}
$this->code = $this->code['function'];
} | php | public function unserialize($data)
{
ClosureStream::register();
if (static::$securityProvider !== null) {
if ($data[0] !== '@') {
throw new SecurityException("The serialized closure is not signed. ".
"Make sure you use a security provider for both serialization and unserialization.");
}
$data = json_decode(substr($data, 1), true);
if (!is_array($data) || !static::$securityProvider->verify($data)) {
throw new SecurityException("Your serialized closure might have been modified and it's unsafe to be unserialized. " .
"Make sure you use the same security provider, with the same settings, " .
"both for serialization and unserialization.");
}
$data = $data['closure'];
} elseif ($data[0] === '@') {
throw new SecurityException("The serialized closure is signed. ".
"Make sure you use a security provider for both serialization and unserialization.");
}
$this->code = \unserialize($data);
// unset data
unset($data);
$this->code['objects'] = array();
if ($this->code['use']) {
$this->scope = new ClosureScope();
$this->code['use'] = $this->resolveUseVariables($this->code['use']);
$this->mapPointers($this->code['use']);
extract($this->code['use'], EXTR_OVERWRITE | EXTR_REFS);
$this->scope = null;
}
$this->closure = include(ClosureStream::STREAM_PROTO . '://' . $this->code['function']);
if($this->code['this'] === $this){
$this->code['this'] = null;
}
if ($this->code['scope'] !== null || $this->code['this'] !== null) {
$this->closure = $this->closure->bindTo($this->code['this'], $this->code['scope']);
}
if(!empty($this->code['objects'])){
foreach ($this->code['objects'] as $item){
$item['property']->setValue($item['instance'], $item['object']->getClosure());
}
}
$this->code = $this->code['function'];
} | [
"public",
"function",
"unserialize",
"(",
"$",
"data",
")",
"{",
"ClosureStream",
"::",
"register",
"(",
")",
";",
"if",
"(",
"static",
"::",
"$",
"securityProvider",
"!==",
"null",
")",
"{",
"if",
"(",
"$",
"data",
"[",
"0",
"]",
"!==",
"'@'",
")",
... | Implementation of Serializable::unserialize()
@param string $data Serialized data
@throws SecurityException | [
"Implementation",
"of",
"Serializable",
"::",
"unserialize",
"()"
] | train | https://github.com/opis/closure/blob/ccb8e3928c5c8181c76cdd0ed9366c5bcaafd91b/src/SerializableClosure.php#L186-L242 |
opis/closure | src/SerializableClosure.php | SerializableClosure.from | public static function from(Closure $closure)
{
if (static::$context === null) {
$instance = new static($closure);
} elseif (isset(static::$context->scope[$closure])) {
$instance = static::$context->scope[$closure];
} else {
$instance = new static($closure);
static::$context->scope[$closure] = $instance;
}
return $instance;
} | php | public static function from(Closure $closure)
{
if (static::$context === null) {
$instance = new static($closure);
} elseif (isset(static::$context->scope[$closure])) {
$instance = static::$context->scope[$closure];
} else {
$instance = new static($closure);
static::$context->scope[$closure] = $instance;
}
return $instance;
} | [
"public",
"static",
"function",
"from",
"(",
"Closure",
"$",
"closure",
")",
"{",
"if",
"(",
"static",
"::",
"$",
"context",
"===",
"null",
")",
"{",
"$",
"instance",
"=",
"new",
"static",
"(",
"$",
"closure",
")",
";",
"}",
"elseif",
"(",
"isset",
... | Wraps a closure and sets the serialization context (if any)
@param Closure $closure Closure to be wrapped
@return self The wrapped closure | [
"Wraps",
"a",
"closure",
"and",
"sets",
"the",
"serialization",
"context",
"(",
"if",
"any",
")"
] | train | https://github.com/opis/closure/blob/ccb8e3928c5c8181c76cdd0ed9366c5bcaafd91b/src/SerializableClosure.php#L262-L274 |
opis/closure | src/SerializableClosure.php | SerializableClosure.wrapClosures | public static function wrapClosures(&$data, SplObjectStorage $storage = null)
{
static::enterContext();
if($storage === null){
$storage = static::$context->scope;
}
if($data instanceof Closure){
$data = static::from($data);
} elseif (is_array($data)){
if(isset($data[self::ARRAY_RECURSIVE_KEY])){
return;
}
$data[self::ARRAY_RECURSIVE_KEY] = true;
foreach ($data as $key => &$value){
if($key === self::ARRAY_RECURSIVE_KEY){
continue;
}
static::wrapClosures($value, $storage);
}
unset($value);
unset($data[self::ARRAY_RECURSIVE_KEY]);
} elseif($data instanceof \stdClass){
if(isset($storage[$data])){
$data = $storage[$data];
return;
}
$data = $storage[$data] = clone($data);
foreach ($data as &$value){
static::wrapClosures($value, $storage);
}
unset($value);
} elseif (is_object($data) && ! $data instanceof static){
if(isset($storage[$data])){
$data = $storage[$data];
return;
}
$instance = $data;
$reflection = new ReflectionObject($instance);
if(!$reflection->isUserDefined()){
$storage[$instance] = $data;
return;
}
$storage[$instance] = $data = $reflection->newInstanceWithoutConstructor();
do{
if(!$reflection->isUserDefined()){
break;
}
foreach ($reflection->getProperties() as $property){
if($property->isStatic() || !$property->getDeclaringClass()->isUserDefined()){
continue;
}
$property->setAccessible(true);
$value = $property->getValue($instance);
if(is_array($value) || is_object($value)){
static::wrapClosures($value, $storage);
}
$property->setValue($data, $value);
};
} while($reflection = $reflection->getParentClass());
}
static::exitContext();
} | php | public static function wrapClosures(&$data, SplObjectStorage $storage = null)
{
static::enterContext();
if($storage === null){
$storage = static::$context->scope;
}
if($data instanceof Closure){
$data = static::from($data);
} elseif (is_array($data)){
if(isset($data[self::ARRAY_RECURSIVE_KEY])){
return;
}
$data[self::ARRAY_RECURSIVE_KEY] = true;
foreach ($data as $key => &$value){
if($key === self::ARRAY_RECURSIVE_KEY){
continue;
}
static::wrapClosures($value, $storage);
}
unset($value);
unset($data[self::ARRAY_RECURSIVE_KEY]);
} elseif($data instanceof \stdClass){
if(isset($storage[$data])){
$data = $storage[$data];
return;
}
$data = $storage[$data] = clone($data);
foreach ($data as &$value){
static::wrapClosures($value, $storage);
}
unset($value);
} elseif (is_object($data) && ! $data instanceof static){
if(isset($storage[$data])){
$data = $storage[$data];
return;
}
$instance = $data;
$reflection = new ReflectionObject($instance);
if(!$reflection->isUserDefined()){
$storage[$instance] = $data;
return;
}
$storage[$instance] = $data = $reflection->newInstanceWithoutConstructor();
do{
if(!$reflection->isUserDefined()){
break;
}
foreach ($reflection->getProperties() as $property){
if($property->isStatic() || !$property->getDeclaringClass()->isUserDefined()){
continue;
}
$property->setAccessible(true);
$value = $property->getValue($instance);
if(is_array($value) || is_object($value)){
static::wrapClosures($value, $storage);
}
$property->setValue($data, $value);
};
} while($reflection = $reflection->getParentClass());
}
static::exitContext();
} | [
"public",
"static",
"function",
"wrapClosures",
"(",
"&",
"$",
"data",
",",
"SplObjectStorage",
"$",
"storage",
"=",
"null",
")",
"{",
"static",
"::",
"enterContext",
"(",
")",
";",
"if",
"(",
"$",
"storage",
"===",
"null",
")",
"{",
"$",
"storage",
"=... | Wrap closures
@internal
@param $data
@param ClosureScope|SplObjectStorage|null $storage | [
"Wrap",
"closures"
] | train | https://github.com/opis/closure/blob/ccb8e3928c5c8181c76cdd0ed9366c5bcaafd91b/src/SerializableClosure.php#L339-L404 |
opis/closure | src/SerializableClosure.php | SerializableClosure.unwrapClosures | public static function unwrapClosures(&$data, SplObjectStorage $storage = null)
{
if($storage === null){
$storage = static::$context->scope;
}
if($data instanceof static){
$data = $data->getClosure();
} elseif (is_array($data)){
if(isset($data[self::ARRAY_RECURSIVE_KEY])){
return;
}
$data[self::ARRAY_RECURSIVE_KEY] = true;
foreach ($data as $key => &$value){
if($key === self::ARRAY_RECURSIVE_KEY){
continue;
}
static::unwrapClosures($value, $storage);
}
unset($data[self::ARRAY_RECURSIVE_KEY]);
}elseif ($data instanceof \stdClass){
if(isset($storage[$data])){
return;
}
$storage[$data] = true;
foreach ($data as &$property){
static::unwrapClosures($property, $storage);
}
} elseif (is_object($data) && !($data instanceof Closure)){
if(isset($storage[$data])){
return;
}
$storage[$data] = true;
$reflection = new ReflectionObject($data);
do{
if(!$reflection->isUserDefined()){
break;
}
foreach ($reflection->getProperties() as $property){
if($property->isStatic() || !$property->getDeclaringClass()->isUserDefined()){
continue;
}
$property->setAccessible(true);
$value = $property->getValue($data);
if(is_array($value) || is_object($value)){
static::unwrapClosures($value, $storage);
$property->setValue($data, $value);
}
};
} while($reflection = $reflection->getParentClass());
}
} | php | public static function unwrapClosures(&$data, SplObjectStorage $storage = null)
{
if($storage === null){
$storage = static::$context->scope;
}
if($data instanceof static){
$data = $data->getClosure();
} elseif (is_array($data)){
if(isset($data[self::ARRAY_RECURSIVE_KEY])){
return;
}
$data[self::ARRAY_RECURSIVE_KEY] = true;
foreach ($data as $key => &$value){
if($key === self::ARRAY_RECURSIVE_KEY){
continue;
}
static::unwrapClosures($value, $storage);
}
unset($data[self::ARRAY_RECURSIVE_KEY]);
}elseif ($data instanceof \stdClass){
if(isset($storage[$data])){
return;
}
$storage[$data] = true;
foreach ($data as &$property){
static::unwrapClosures($property, $storage);
}
} elseif (is_object($data) && !($data instanceof Closure)){
if(isset($storage[$data])){
return;
}
$storage[$data] = true;
$reflection = new ReflectionObject($data);
do{
if(!$reflection->isUserDefined()){
break;
}
foreach ($reflection->getProperties() as $property){
if($property->isStatic() || !$property->getDeclaringClass()->isUserDefined()){
continue;
}
$property->setAccessible(true);
$value = $property->getValue($data);
if(is_array($value) || is_object($value)){
static::unwrapClosures($value, $storage);
$property->setValue($data, $value);
}
};
} while($reflection = $reflection->getParentClass());
}
} | [
"public",
"static",
"function",
"unwrapClosures",
"(",
"&",
"$",
"data",
",",
"SplObjectStorage",
"$",
"storage",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"storage",
"===",
"null",
")",
"{",
"$",
"storage",
"=",
"static",
"::",
"$",
"context",
"->",
"sco... | Unwrap closures
@internal
@param $data
@param SplObjectStorage|null $storage | [
"Unwrap",
"closures"
] | train | https://github.com/opis/closure/blob/ccb8e3928c5c8181c76cdd0ed9366c5bcaafd91b/src/SerializableClosure.php#L413-L465 |
opis/closure | src/SerializableClosure.php | SerializableClosure.mapPointers | protected function mapPointers(&$data)
{
$scope = $this->scope;
if ($data instanceof static) {
$data = &$data->closure;
} elseif (is_array($data)) {
if(isset($data[self::ARRAY_RECURSIVE_KEY])){
return;
}
$data[self::ARRAY_RECURSIVE_KEY] = true;
foreach ($data as $key => &$value){
if($key === self::ARRAY_RECURSIVE_KEY){
continue;
} elseif ($value instanceof static) {
$data[$key] = &$value->closure;
} elseif ($value instanceof SelfReference && $value->hash === $this->code['self']){
$data[$key] = &$this->closure;
} else {
$this->mapPointers($value);
}
}
unset($value);
unset($data[self::ARRAY_RECURSIVE_KEY]);
} elseif ($data instanceof \stdClass) {
if(isset($scope[$data])){
return;
}
$scope[$data] = true;
foreach ($data as $key => &$value){
if ($value instanceof SelfReference && $value->hash === $this->code['self']){
$data->{$key} = &$this->closure;
} elseif(is_array($value) || is_object($value)) {
$this->mapPointers($value);
}
}
unset($value);
} elseif (is_object($data) && !($data instanceof Closure)){
if(isset($scope[$data])){
return;
}
$scope[$data] = true;
$reflection = new ReflectionObject($data);
do{
if(!$reflection->isUserDefined()){
break;
}
foreach ($reflection->getProperties() as $property){
if($property->isStatic() || !$property->getDeclaringClass()->isUserDefined()){
continue;
}
$property->setAccessible(true);
$item = $property->getValue($data);
if ($item instanceof SerializableClosure || ($item instanceof SelfReference && $item->hash === $this->code['self'])) {
$this->code['objects'][] = array(
'instance' => $data,
'property' => $property,
'object' => $item instanceof SelfReference ? $this : $item,
);
} elseif (is_array($item) || is_object($item)) {
$this->mapPointers($item);
$property->setValue($data, $item);
}
}
} while($reflection = $reflection->getParentClass());
}
} | php | protected function mapPointers(&$data)
{
$scope = $this->scope;
if ($data instanceof static) {
$data = &$data->closure;
} elseif (is_array($data)) {
if(isset($data[self::ARRAY_RECURSIVE_KEY])){
return;
}
$data[self::ARRAY_RECURSIVE_KEY] = true;
foreach ($data as $key => &$value){
if($key === self::ARRAY_RECURSIVE_KEY){
continue;
} elseif ($value instanceof static) {
$data[$key] = &$value->closure;
} elseif ($value instanceof SelfReference && $value->hash === $this->code['self']){
$data[$key] = &$this->closure;
} else {
$this->mapPointers($value);
}
}
unset($value);
unset($data[self::ARRAY_RECURSIVE_KEY]);
} elseif ($data instanceof \stdClass) {
if(isset($scope[$data])){
return;
}
$scope[$data] = true;
foreach ($data as $key => &$value){
if ($value instanceof SelfReference && $value->hash === $this->code['self']){
$data->{$key} = &$this->closure;
} elseif(is_array($value) || is_object($value)) {
$this->mapPointers($value);
}
}
unset($value);
} elseif (is_object($data) && !($data instanceof Closure)){
if(isset($scope[$data])){
return;
}
$scope[$data] = true;
$reflection = new ReflectionObject($data);
do{
if(!$reflection->isUserDefined()){
break;
}
foreach ($reflection->getProperties() as $property){
if($property->isStatic() || !$property->getDeclaringClass()->isUserDefined()){
continue;
}
$property->setAccessible(true);
$item = $property->getValue($data);
if ($item instanceof SerializableClosure || ($item instanceof SelfReference && $item->hash === $this->code['self'])) {
$this->code['objects'][] = array(
'instance' => $data,
'property' => $property,
'object' => $item instanceof SelfReference ? $this : $item,
);
} elseif (is_array($item) || is_object($item)) {
$this->mapPointers($item);
$property->setValue($data, $item);
}
}
} while($reflection = $reflection->getParentClass());
}
} | [
"protected",
"function",
"mapPointers",
"(",
"&",
"$",
"data",
")",
"{",
"$",
"scope",
"=",
"$",
"this",
"->",
"scope",
";",
"if",
"(",
"$",
"data",
"instanceof",
"static",
")",
"{",
"$",
"data",
"=",
"&",
"$",
"data",
"->",
"closure",
";",
"}",
... | Internal method used to map closure pointers
@internal
@param $data | [
"Internal",
"method",
"used",
"to",
"map",
"closure",
"pointers"
] | train | https://github.com/opis/closure/blob/ccb8e3928c5c8181c76cdd0ed9366c5bcaafd91b/src/SerializableClosure.php#L472-L538 |
opis/closure | src/SerializableClosure.php | SerializableClosure.mapByReference | protected function mapByReference(&$data)
{
if ($data instanceof Closure) {
if($data === $this->closure){
$data = new SelfReference($this->reference);
return;
}
if (isset($this->scope[$data])) {
$data = $this->scope[$data];
return;
}
$instance = new static($data);
if (static::$context !== null) {
static::$context->scope->toserialize--;
} else {
$instance->scope = $this->scope;
}
$data = $this->scope[$data] = $instance;
} elseif (is_array($data)) {
if(isset($data[self::ARRAY_RECURSIVE_KEY])){
return;
}
$data[self::ARRAY_RECURSIVE_KEY] = true;
foreach ($data as $key => &$value){
if($key === self::ARRAY_RECURSIVE_KEY){
continue;
}
$this->mapByReference($value);
}
unset($value);
unset($data[self::ARRAY_RECURSIVE_KEY]);
} elseif ($data instanceof \stdClass) {
if(isset($this->scope[$data])){
$data = $this->scope[$data];
return;
}
$instance = $data;
$this->scope[$instance] = $data = clone($data);
foreach ($data as &$value){
$this->mapByReference($value);
}
unset($value);
} elseif (is_object($data) && !$data instanceof SerializableClosure){
if(isset($this->scope[$data])){
$data = $this->scope[$data];
return;
}
$instance = $data;
$reflection = new ReflectionObject($data);
if(!$reflection->isUserDefined()){
$this->scope[$instance] = $data;
return;
}
$this->scope[$instance] = $data = $reflection->newInstanceWithoutConstructor();
do{
if(!$reflection->isUserDefined()){
break;
}
foreach ($reflection->getProperties() as $property){
if($property->isStatic() || !$property->getDeclaringClass()->isUserDefined()){
continue;
}
$property->setAccessible(true);
$value = $property->getValue($instance);
if(is_array($value) || is_object($value)){
$this->mapByReference($value);
}
$property->setValue($data, $value);
}
} while($reflection = $reflection->getParentClass());
}
} | php | protected function mapByReference(&$data)
{
if ($data instanceof Closure) {
if($data === $this->closure){
$data = new SelfReference($this->reference);
return;
}
if (isset($this->scope[$data])) {
$data = $this->scope[$data];
return;
}
$instance = new static($data);
if (static::$context !== null) {
static::$context->scope->toserialize--;
} else {
$instance->scope = $this->scope;
}
$data = $this->scope[$data] = $instance;
} elseif (is_array($data)) {
if(isset($data[self::ARRAY_RECURSIVE_KEY])){
return;
}
$data[self::ARRAY_RECURSIVE_KEY] = true;
foreach ($data as $key => &$value){
if($key === self::ARRAY_RECURSIVE_KEY){
continue;
}
$this->mapByReference($value);
}
unset($value);
unset($data[self::ARRAY_RECURSIVE_KEY]);
} elseif ($data instanceof \stdClass) {
if(isset($this->scope[$data])){
$data = $this->scope[$data];
return;
}
$instance = $data;
$this->scope[$instance] = $data = clone($data);
foreach ($data as &$value){
$this->mapByReference($value);
}
unset($value);
} elseif (is_object($data) && !$data instanceof SerializableClosure){
if(isset($this->scope[$data])){
$data = $this->scope[$data];
return;
}
$instance = $data;
$reflection = new ReflectionObject($data);
if(!$reflection->isUserDefined()){
$this->scope[$instance] = $data;
return;
}
$this->scope[$instance] = $data = $reflection->newInstanceWithoutConstructor();
do{
if(!$reflection->isUserDefined()){
break;
}
foreach ($reflection->getProperties() as $property){
if($property->isStatic() || !$property->getDeclaringClass()->isUserDefined()){
continue;
}
$property->setAccessible(true);
$value = $property->getValue($instance);
if(is_array($value) || is_object($value)){
$this->mapByReference($value);
}
$property->setValue($data, $value);
}
} while($reflection = $reflection->getParentClass());
}
} | [
"protected",
"function",
"mapByReference",
"(",
"&",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"data",
"instanceof",
"Closure",
")",
"{",
"if",
"(",
"$",
"data",
"===",
"$",
"this",
"->",
"closure",
")",
"{",
"$",
"data",
"=",
"new",
"SelfReference",
"(... | Internal method used to map closures by reference
@internal
@param mixed &$data | [
"Internal",
"method",
"used",
"to",
"map",
"closures",
"by",
"reference"
] | train | https://github.com/opis/closure/blob/ccb8e3928c5c8181c76cdd0ed9366c5bcaafd91b/src/SerializableClosure.php#L546-L624 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.get_slug | function get_slug( $name = null ) {
// If no name set use the post type name.
if ( ! isset( $name ) ) {
$name = $this->post_type_name;
}
// Name to lower case.
$name = strtolower( $name );
// Replace spaces with hyphen.
$name = str_replace( " ", "-", $name );
// Replace underscore with hyphen.
$name = str_replace( "_", "-", $name );
return $name;
} | php | function get_slug( $name = null ) {
// If no name set use the post type name.
if ( ! isset( $name ) ) {
$name = $this->post_type_name;
}
// Name to lower case.
$name = strtolower( $name );
// Replace spaces with hyphen.
$name = str_replace( " ", "-", $name );
// Replace underscore with hyphen.
$name = str_replace( "_", "-", $name );
return $name;
} | [
"function",
"get_slug",
"(",
"$",
"name",
"=",
"null",
")",
"{",
"// If no name set use the post type name.",
"if",
"(",
"!",
"isset",
"(",
"$",
"name",
")",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"post_type_name",
";",
"}",
"// Name to lower case.",... | Get slug
Creates an url friendly slug.
@param string $name Name to slugify.
@return string $name Returns the slug. | [
"Get",
"slug"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L292-L310 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.get_plural | function get_plural( $name = null ) {
// If no name is passed the post_type_name is used.
if ( ! isset( $name ) ) {
$name = $this->post_type_name;
}
// Return the plural name. Add 's' to the end.
return $this->get_human_friendly( $name ) . 's';
} | php | function get_plural( $name = null ) {
// If no name is passed the post_type_name is used.
if ( ! isset( $name ) ) {
$name = $this->post_type_name;
}
// Return the plural name. Add 's' to the end.
return $this->get_human_friendly( $name ) . 's';
} | [
"function",
"get_plural",
"(",
"$",
"name",
"=",
"null",
")",
"{",
"// If no name is passed the post_type_name is used.",
"if",
"(",
"!",
"isset",
"(",
"$",
"name",
")",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"post_type_name",
";",
"}",
"// Return th... | Get plural
Returns the friendly plural name.
ucwords capitalize words
strtolower makes string lowercase before capitalizing
str_replace replace all instances of _ to space
@param string $name The slug name you want to pluralize.
@return string the friendly pluralized name. | [
"Get",
"plural"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L324-L334 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.get_singular | function get_singular( $name = null ) {
// If no name is passed the post_type_name is used.
if ( ! isset( $name ) ) {
$name = $this->post_type_name;
}
// Return the string.
return $this->get_human_friendly( $name );
} | php | function get_singular( $name = null ) {
// If no name is passed the post_type_name is used.
if ( ! isset( $name ) ) {
$name = $this->post_type_name;
}
// Return the string.
return $this->get_human_friendly( $name );
} | [
"function",
"get_singular",
"(",
"$",
"name",
"=",
"null",
")",
"{",
"// If no name is passed the post_type_name is used.",
"if",
"(",
"!",
"isset",
"(",
"$",
"name",
")",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"post_type_name",
";",
"}",
"// Return ... | Get singular
Returns the friendly singular name.
ucwords capitalize words
strtolower makes string lowercase before capitalizing
str_replace replace all instances of _ to space
@param string $name The slug name you want to unpluralize.
@return string The friendly singular name. | [
"Get",
"singular"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L348-L359 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.get_human_friendly | function get_human_friendly( $name = null ) {
// If no name is passed the post_type_name is used.
if ( ! isset( $name ) ) {
$name = $this->post_type_name;
}
// Return human friendly name.
return ucwords( strtolower( str_replace( "-", " ", str_replace( "_", " ", $name ) ) ) );
} | php | function get_human_friendly( $name = null ) {
// If no name is passed the post_type_name is used.
if ( ! isset( $name ) ) {
$name = $this->post_type_name;
}
// Return human friendly name.
return ucwords( strtolower( str_replace( "-", " ", str_replace( "_", " ", $name ) ) ) );
} | [
"function",
"get_human_friendly",
"(",
"$",
"name",
"=",
"null",
")",
"{",
"// If no name is passed the post_type_name is used.",
"if",
"(",
"!",
"isset",
"(",
"$",
"name",
")",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"post_type_name",
";",
"}",
"// R... | Get human friendly
Returns the human friendly name.
ucwords capitalize words
strtolower makes string lowercase before capitalizing
str_replace replace all instances of hyphens and underscores to spaces
@param string $name The name you want to make friendly.
@return string The human friendly name. | [
"Get",
"human",
"friendly"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L373-L383 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.register_post_type | function register_post_type() {
// Friendly post type names.
$plural = $this->plural;
$singular = $this->singular;
$slug = $this->slug;
// Default labels.
$labels = array(
'name' => sprintf( __( '%s', $this->textdomain ), $plural ),
'singular_name' => sprintf( __( '%s', $this->textdomain ), $singular ),
'menu_name' => sprintf( __( '%s', $this->textdomain ), $plural ),
'all_items' => sprintf( __( '%s', $this->textdomain ), $plural ),
'add_new' => __( 'Add New', $this->textdomain ),
'add_new_item' => sprintf( __( 'Add New %s', $this->textdomain ), $singular ),
'edit_item' => sprintf( __( 'Edit %s', $this->textdomain ), $singular ),
'new_item' => sprintf( __( 'New %s', $this->textdomain ), $singular ),
'view_item' => sprintf( __( 'View %s', $this->textdomain ), $singular ),
'search_items' => sprintf( __( 'Search %s', $this->textdomain ), $plural ),
'not_found' => sprintf( __( 'No %s found', $this->textdomain ), $plural ),
'not_found_in_trash' => sprintf( __( 'No %s found in Trash', $this->textdomain ), $plural ),
'parent_item_colon' => sprintf( __( 'Parent %s:', $this->textdomain ), $singular )
);
// Default options.
$defaults = array(
'labels' => $labels,
'public' => true,
'rewrite' => array(
'slug' => $slug,
)
);
// Merge user submitted options with defaults.
$options = array_replace_recursive( $defaults, $this->options );
// Set the object options as full options passed.
$this->options = $options;
// Check that the post type doesn't already exist.
if ( ! post_type_exists( $this->post_type_name ) ) {
// Register the post type.
register_post_type( $this->post_type_name, $options );
}
} | php | function register_post_type() {
// Friendly post type names.
$plural = $this->plural;
$singular = $this->singular;
$slug = $this->slug;
// Default labels.
$labels = array(
'name' => sprintf( __( '%s', $this->textdomain ), $plural ),
'singular_name' => sprintf( __( '%s', $this->textdomain ), $singular ),
'menu_name' => sprintf( __( '%s', $this->textdomain ), $plural ),
'all_items' => sprintf( __( '%s', $this->textdomain ), $plural ),
'add_new' => __( 'Add New', $this->textdomain ),
'add_new_item' => sprintf( __( 'Add New %s', $this->textdomain ), $singular ),
'edit_item' => sprintf( __( 'Edit %s', $this->textdomain ), $singular ),
'new_item' => sprintf( __( 'New %s', $this->textdomain ), $singular ),
'view_item' => sprintf( __( 'View %s', $this->textdomain ), $singular ),
'search_items' => sprintf( __( 'Search %s', $this->textdomain ), $plural ),
'not_found' => sprintf( __( 'No %s found', $this->textdomain ), $plural ),
'not_found_in_trash' => sprintf( __( 'No %s found in Trash', $this->textdomain ), $plural ),
'parent_item_colon' => sprintf( __( 'Parent %s:', $this->textdomain ), $singular )
);
// Default options.
$defaults = array(
'labels' => $labels,
'public' => true,
'rewrite' => array(
'slug' => $slug,
)
);
// Merge user submitted options with defaults.
$options = array_replace_recursive( $defaults, $this->options );
// Set the object options as full options passed.
$this->options = $options;
// Check that the post type doesn't already exist.
if ( ! post_type_exists( $this->post_type_name ) ) {
// Register the post type.
register_post_type( $this->post_type_name, $options );
}
} | [
"function",
"register_post_type",
"(",
")",
"{",
"// Friendly post type names.",
"$",
"plural",
"=",
"$",
"this",
"->",
"plural",
";",
"$",
"singular",
"=",
"$",
"this",
"->",
"singular",
";",
"$",
"slug",
"=",
"$",
"this",
"->",
"slug",
";",
"// Default l... | Register Post Type
@see http://codex.wordpress.org/Function_Reference/register_post_type | [
"Register",
"Post",
"Type"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L390-L435 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.register_taxonomy | function register_taxonomy($taxonomy_names, $options = array()) {
// Post type defaults to $this post type if unspecified.
$post_type = $this->post_type_name;
// An array of the names required excluding taxonomy_name.
$names = array(
'singular',
'plural',
'slug'
);
// if an array of names are passed
if ( is_array( $taxonomy_names ) ) {
// Set the taxonomy name
$taxonomy_name = $taxonomy_names['taxonomy_name'];
// Cycle through possible names.
foreach ( $names as $name ) {
// If the user has set the name.
if ( isset( $taxonomy_names[ $name ] ) ) {
// Use user submitted name.
$$name = $taxonomy_names[ $name ];
// Else generate the name.
} else {
// Define the function to be used.
$method = 'get_' . $name;
// Generate the name
$$name = $this->$method( $taxonomy_name );
}
}
// Else if only the taxonomy_name has been supplied.
} else {
// Create user friendly names.
$taxonomy_name = $taxonomy_names;
$singular = $this->get_singular( $taxonomy_name );
$plural = $this->get_plural( $taxonomy_name );
$slug = $this->get_slug( $taxonomy_name );
}
// Default labels.
$labels = array(
'name' => sprintf( __( '%s', $this->textdomain ), $plural ),
'singular_name' => sprintf( __( '%s', $this->textdomain ), $singular ),
'menu_name' => sprintf( __( '%s', $this->textdomain ), $plural ),
'all_items' => sprintf( __( 'All %s', $this->textdomain ), $plural ),
'edit_item' => sprintf( __( 'Edit %s', $this->textdomain ), $singular ),
'view_item' => sprintf( __( 'View %s', $this->textdomain ), $singular ),
'update_item' => sprintf( __( 'Update %s', $this->textdomain ), $singular ),
'add_new_item' => sprintf( __( 'Add New %s', $this->textdomain ), $singular ),
'new_item_name' => sprintf( __( 'New %s Name', $this->textdomain ), $singular ),
'parent_item' => sprintf( __( 'Parent %s', $this->textdomain ), $plural ),
'parent_item_colon' => sprintf( __( 'Parent %s:', $this->textdomain ), $plural ),
'search_items' => sprintf( __( 'Search %s', $this->textdomain ), $plural ),
'popular_items' => sprintf( __( 'Popular %s', $this->textdomain ), $plural ),
'separate_items_with_commas' => sprintf( __( 'Seperate %s with commas', $this->textdomain ), $plural ),
'add_or_remove_items' => sprintf( __( 'Add or remove %s', $this->textdomain ), $plural ),
'choose_from_most_used' => sprintf( __( 'Choose from most used %s', $this->textdomain ), $plural ),
'not_found' => sprintf( __( 'No %s found', $this->textdomain ), $plural ),
);
// Default options.
$defaults = array(
'labels' => $labels,
'hierarchical' => true,
'rewrite' => array(
'slug' => $slug
)
);
// Merge default options with user submitted options.
$options = array_replace_recursive( $defaults, $options );
// Add the taxonomy to the object array, this is used to add columns and filters to admin panel.
$this->taxonomies[] = $taxonomy_name;
// Create array used when registering taxonomies.
$this->taxonomy_settings[ $taxonomy_name ] = $options;
} | php | function register_taxonomy($taxonomy_names, $options = array()) {
// Post type defaults to $this post type if unspecified.
$post_type = $this->post_type_name;
// An array of the names required excluding taxonomy_name.
$names = array(
'singular',
'plural',
'slug'
);
// if an array of names are passed
if ( is_array( $taxonomy_names ) ) {
// Set the taxonomy name
$taxonomy_name = $taxonomy_names['taxonomy_name'];
// Cycle through possible names.
foreach ( $names as $name ) {
// If the user has set the name.
if ( isset( $taxonomy_names[ $name ] ) ) {
// Use user submitted name.
$$name = $taxonomy_names[ $name ];
// Else generate the name.
} else {
// Define the function to be used.
$method = 'get_' . $name;
// Generate the name
$$name = $this->$method( $taxonomy_name );
}
}
// Else if only the taxonomy_name has been supplied.
} else {
// Create user friendly names.
$taxonomy_name = $taxonomy_names;
$singular = $this->get_singular( $taxonomy_name );
$plural = $this->get_plural( $taxonomy_name );
$slug = $this->get_slug( $taxonomy_name );
}
// Default labels.
$labels = array(
'name' => sprintf( __( '%s', $this->textdomain ), $plural ),
'singular_name' => sprintf( __( '%s', $this->textdomain ), $singular ),
'menu_name' => sprintf( __( '%s', $this->textdomain ), $plural ),
'all_items' => sprintf( __( 'All %s', $this->textdomain ), $plural ),
'edit_item' => sprintf( __( 'Edit %s', $this->textdomain ), $singular ),
'view_item' => sprintf( __( 'View %s', $this->textdomain ), $singular ),
'update_item' => sprintf( __( 'Update %s', $this->textdomain ), $singular ),
'add_new_item' => sprintf( __( 'Add New %s', $this->textdomain ), $singular ),
'new_item_name' => sprintf( __( 'New %s Name', $this->textdomain ), $singular ),
'parent_item' => sprintf( __( 'Parent %s', $this->textdomain ), $plural ),
'parent_item_colon' => sprintf( __( 'Parent %s:', $this->textdomain ), $plural ),
'search_items' => sprintf( __( 'Search %s', $this->textdomain ), $plural ),
'popular_items' => sprintf( __( 'Popular %s', $this->textdomain ), $plural ),
'separate_items_with_commas' => sprintf( __( 'Seperate %s with commas', $this->textdomain ), $plural ),
'add_or_remove_items' => sprintf( __( 'Add or remove %s', $this->textdomain ), $plural ),
'choose_from_most_used' => sprintf( __( 'Choose from most used %s', $this->textdomain ), $plural ),
'not_found' => sprintf( __( 'No %s found', $this->textdomain ), $plural ),
);
// Default options.
$defaults = array(
'labels' => $labels,
'hierarchical' => true,
'rewrite' => array(
'slug' => $slug
)
);
// Merge default options with user submitted options.
$options = array_replace_recursive( $defaults, $options );
// Add the taxonomy to the object array, this is used to add columns and filters to admin panel.
$this->taxonomies[] = $taxonomy_name;
// Create array used when registering taxonomies.
$this->taxonomy_settings[ $taxonomy_name ] = $options;
} | [
"function",
"register_taxonomy",
"(",
"$",
"taxonomy_names",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"// Post type defaults to $this post type if unspecified.",
"$",
"post_type",
"=",
"$",
"this",
"->",
"post_type_name",
";",
"// An array of the names req... | Register taxonomy
@see http://codex.wordpress.org/Function_Reference/register_taxonomy
@param string $taxonomy_name The slug for the taxonomy.
@param array $options Taxonomy options. | [
"Register",
"taxonomy"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L445-L534 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.register_taxonomies | function register_taxonomies() {
if ( is_array( $this->taxonomy_settings ) ) {
// Foreach taxonomy registered with the post type.
foreach ( $this->taxonomy_settings as $taxonomy_name => $options ) {
// Register the taxonomy if it doesn't exist.
if ( ! taxonomy_exists( $taxonomy_name ) ) {
// Register the taxonomy with Wordpress
register_taxonomy( $taxonomy_name, $this->post_type_name, $options );
} else {
// If taxonomy exists, register it later with register_exisiting_taxonomies
$this->exisiting_taxonomies[] = $taxonomy_name;
}
}
}
} | php | function register_taxonomies() {
if ( is_array( $this->taxonomy_settings ) ) {
// Foreach taxonomy registered with the post type.
foreach ( $this->taxonomy_settings as $taxonomy_name => $options ) {
// Register the taxonomy if it doesn't exist.
if ( ! taxonomy_exists( $taxonomy_name ) ) {
// Register the taxonomy with Wordpress
register_taxonomy( $taxonomy_name, $this->post_type_name, $options );
} else {
// If taxonomy exists, register it later with register_exisiting_taxonomies
$this->exisiting_taxonomies[] = $taxonomy_name;
}
}
}
} | [
"function",
"register_taxonomies",
"(",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"taxonomy_settings",
")",
")",
"{",
"// Foreach taxonomy registered with the post type.",
"foreach",
"(",
"$",
"this",
"->",
"taxonomy_settings",
"as",
"$",
"taxonomy_na... | Register taxonomies
Cycles through taxonomies added with the class and registers them. | [
"Register",
"taxonomies"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L543-L563 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.register_exisiting_taxonomies | function register_exisiting_taxonomies() {
if( is_array( $this->exisiting_taxonomies ) ) {
foreach( $this->exisiting_taxonomies as $taxonomy_name ) {
register_taxonomy_for_object_type( $taxonomy_name, $this->post_type_name );
}
}
} | php | function register_exisiting_taxonomies() {
if( is_array( $this->exisiting_taxonomies ) ) {
foreach( $this->exisiting_taxonomies as $taxonomy_name ) {
register_taxonomy_for_object_type( $taxonomy_name, $this->post_type_name );
}
}
} | [
"function",
"register_exisiting_taxonomies",
"(",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"exisiting_taxonomies",
")",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"exisiting_taxonomies",
"as",
"$",
"taxonomy_name",
")",
"{",
"register_taxonomy_... | Register Exisiting Taxonomies
Cycles through exisiting taxonomies and registers them after the post type has been registered | [
"Register",
"Exisiting",
"Taxonomies"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L570-L577 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.add_admin_columns | function add_admin_columns( $columns ) {
// If no user columns have been specified, add taxonomies
if ( ! isset( $this->columns ) ) {
$new_columns = array();
// determine which column to add custom taxonomies after
if ( is_array( $this->taxonomies ) && in_array( 'post_tag', $this->taxonomies ) || $this->post_type_name === 'post' ) {
$after = 'tags';
} elseif( is_array( $this->taxonomies ) && in_array( 'category', $this->taxonomies ) || $this->post_type_name === 'post' ) {
$after = 'categories';
} elseif( post_type_supports( $this->post_type_name, 'author' ) ) {
$after = 'author';
} else {
$after = 'title';
}
// foreach exisiting columns
foreach( $columns as $key => $title ) {
// add exisiting column to the new column array
$new_columns[$key] = $title;
// we want to add taxonomy columns after a specific column
if( $key === $after ) {
// If there are taxonomies registered to the post type.
if ( is_array( $this->taxonomies ) ) {
// Create a column for each taxonomy.
foreach( $this->taxonomies as $tax ) {
// WordPress adds Categories and Tags automatically, ignore these
if( $tax !== 'category' && $tax !== 'post_tag' ) {
// Get the taxonomy object for labels.
$taxonomy_object = get_taxonomy( $tax );
// Column key is the slug, value is friendly name.
$new_columns[ $tax ] = sprintf( __( '%s', $this->textdomain ), $taxonomy_object->labels->name );
}
}
}
}
}
// overide with new columns
$columns = $new_columns;
} else {
// Use user submitted columns, these are defined using the object columns() method.
$columns = $this->columns;
}
return $columns;
} | php | function add_admin_columns( $columns ) {
// If no user columns have been specified, add taxonomies
if ( ! isset( $this->columns ) ) {
$new_columns = array();
// determine which column to add custom taxonomies after
if ( is_array( $this->taxonomies ) && in_array( 'post_tag', $this->taxonomies ) || $this->post_type_name === 'post' ) {
$after = 'tags';
} elseif( is_array( $this->taxonomies ) && in_array( 'category', $this->taxonomies ) || $this->post_type_name === 'post' ) {
$after = 'categories';
} elseif( post_type_supports( $this->post_type_name, 'author' ) ) {
$after = 'author';
} else {
$after = 'title';
}
// foreach exisiting columns
foreach( $columns as $key => $title ) {
// add exisiting column to the new column array
$new_columns[$key] = $title;
// we want to add taxonomy columns after a specific column
if( $key === $after ) {
// If there are taxonomies registered to the post type.
if ( is_array( $this->taxonomies ) ) {
// Create a column for each taxonomy.
foreach( $this->taxonomies as $tax ) {
// WordPress adds Categories and Tags automatically, ignore these
if( $tax !== 'category' && $tax !== 'post_tag' ) {
// Get the taxonomy object for labels.
$taxonomy_object = get_taxonomy( $tax );
// Column key is the slug, value is friendly name.
$new_columns[ $tax ] = sprintf( __( '%s', $this->textdomain ), $taxonomy_object->labels->name );
}
}
}
}
}
// overide with new columns
$columns = $new_columns;
} else {
// Use user submitted columns, these are defined using the object columns() method.
$columns = $this->columns;
}
return $columns;
} | [
"function",
"add_admin_columns",
"(",
"$",
"columns",
")",
"{",
"// If no user columns have been specified, add taxonomies",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"columns",
")",
")",
"{",
"$",
"new_columns",
"=",
"array",
"(",
")",
";",
"// determine... | Add admin columns
Adds columns to the admin edit screen. Function is used with add_action
@param array $columns Columns to be added to the admin edit screen.
@return array | [
"Add",
"admin",
"columns"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L587-L643 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.populate_admin_columns | function populate_admin_columns( $column, $post_id ) {
// Get wordpress $post object.
global $post;
// determine the column
switch( $column ) {
// If column is a taxonomy associated with the post type.
case ( taxonomy_exists( $column ) ) :
// Get the taxonomy for the post
$terms = get_the_terms( $post_id, $column );
// If we have terms.
if ( ! empty( $terms ) ) {
$output = array();
// Loop through each term, linking to the 'edit posts' page for the specific term.
foreach( $terms as $term ) {
// Output is an array of terms associated with the post.
$output[] = sprintf(
// Define link.
'<a href="%s">%s</a>',
// Create filter url.
esc_url( add_query_arg( array( 'post_type' => $post->post_type, $column => $term->slug ), 'edit.php' ) ),
// Create friendly term name.
esc_html( sanitize_term_field( 'name', $term->name, $term->term_id, $column, 'display' ) )
);
}
// Join the terms, separating them with a comma.
echo join( ', ', $output );
// If no terms found.
} else {
// Get the taxonomy object for labels
$taxonomy_object = get_taxonomy( $column );
// Echo no terms.
printf( __( 'No %s', $this->textdomain ), $taxonomy_object->labels->name );
}
break;
// If column is for the post ID.
case 'post_id' :
echo $post->ID;
break;
// if the column is prepended with 'meta_', this will automagically retrieve the meta values and display them.
case ( preg_match( '/^meta_/', $column ) ? true : false ) :
// meta_book_author (meta key = book_author)
$x = substr( $column, 5 );
$meta = get_post_meta( $post->ID, $x );
echo join( ", ", $meta );
break;
// If the column is post thumbnail.
case 'icon' :
// Create the edit link.
$link = esc_url( add_query_arg( array( 'post' => $post->ID, 'action' => 'edit' ), 'post.php' ) );
// If it post has a featured image.
if ( has_post_thumbnail() ) {
// Display post featured image with edit link.
echo '<a href="' . $link . '">';
the_post_thumbnail( array(60, 60) );
echo '</a>';
} else {
// Display default media image with link.
echo '<a href="' . $link . '"><img src="'. site_url( '/wp-includes/images/crystal/default.png' ) .'" alt="' . $post->post_title . '" /></a>';
}
break;
// Default case checks if the column has a user function, this is most commonly used for custom fields.
default :
// If there are user custom columns to populate.
if ( isset( $this->custom_populate_columns ) && is_array( $this->custom_populate_columns ) ) {
// If this column has a user submitted function to run.
if ( isset( $this->custom_populate_columns[ $column ] ) && is_callable( $this->custom_populate_columns[ $column ] ) ) {
// Run the function.
call_user_func_array( $this->custom_populate_columns[ $column ], array( $column, $post ) );
}
}
break;
} // end switch( $column )
} | php | function populate_admin_columns( $column, $post_id ) {
// Get wordpress $post object.
global $post;
// determine the column
switch( $column ) {
// If column is a taxonomy associated with the post type.
case ( taxonomy_exists( $column ) ) :
// Get the taxonomy for the post
$terms = get_the_terms( $post_id, $column );
// If we have terms.
if ( ! empty( $terms ) ) {
$output = array();
// Loop through each term, linking to the 'edit posts' page for the specific term.
foreach( $terms as $term ) {
// Output is an array of terms associated with the post.
$output[] = sprintf(
// Define link.
'<a href="%s">%s</a>',
// Create filter url.
esc_url( add_query_arg( array( 'post_type' => $post->post_type, $column => $term->slug ), 'edit.php' ) ),
// Create friendly term name.
esc_html( sanitize_term_field( 'name', $term->name, $term->term_id, $column, 'display' ) )
);
}
// Join the terms, separating them with a comma.
echo join( ', ', $output );
// If no terms found.
} else {
// Get the taxonomy object for labels
$taxonomy_object = get_taxonomy( $column );
// Echo no terms.
printf( __( 'No %s', $this->textdomain ), $taxonomy_object->labels->name );
}
break;
// If column is for the post ID.
case 'post_id' :
echo $post->ID;
break;
// if the column is prepended with 'meta_', this will automagically retrieve the meta values and display them.
case ( preg_match( '/^meta_/', $column ) ? true : false ) :
// meta_book_author (meta key = book_author)
$x = substr( $column, 5 );
$meta = get_post_meta( $post->ID, $x );
echo join( ", ", $meta );
break;
// If the column is post thumbnail.
case 'icon' :
// Create the edit link.
$link = esc_url( add_query_arg( array( 'post' => $post->ID, 'action' => 'edit' ), 'post.php' ) );
// If it post has a featured image.
if ( has_post_thumbnail() ) {
// Display post featured image with edit link.
echo '<a href="' . $link . '">';
the_post_thumbnail( array(60, 60) );
echo '</a>';
} else {
// Display default media image with link.
echo '<a href="' . $link . '"><img src="'. site_url( '/wp-includes/images/crystal/default.png' ) .'" alt="' . $post->post_title . '" /></a>';
}
break;
// Default case checks if the column has a user function, this is most commonly used for custom fields.
default :
// If there are user custom columns to populate.
if ( isset( $this->custom_populate_columns ) && is_array( $this->custom_populate_columns ) ) {
// If this column has a user submitted function to run.
if ( isset( $this->custom_populate_columns[ $column ] ) && is_callable( $this->custom_populate_columns[ $column ] ) ) {
// Run the function.
call_user_func_array( $this->custom_populate_columns[ $column ], array( $column, $post ) );
}
}
break;
} // end switch( $column )
} | [
"function",
"populate_admin_columns",
"(",
"$",
"column",
",",
"$",
"post_id",
")",
"{",
"// Get wordpress $post object.",
"global",
"$",
"post",
";",
"// determine the column",
"switch",
"(",
"$",
"column",
")",
"{",
"// If column is a taxonomy associated with the post t... | Populate admin columns
Populate custom columns on the admin edit screen.
@param string $column The name of the column.
@param integer $post_id The post ID. | [
"Populate",
"admin",
"columns"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L653-L764 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.add_taxonomy_filters | function add_taxonomy_filters() {
global $typenow;
global $wp_query;
// Must set this to the post type you want the filter(s) displayed on.
if ( $typenow == $this->post_type_name ) {
// if custom filters are defined use those
if ( is_array( $this->filters ) ) {
$filters = $this->filters;
// else default to use all taxonomies associated with the post
} else {
$filters = $this->taxonomies;
}
if ( ! empty( $filters ) ) {
// Foreach of the taxonomies we want to create filters for...
foreach ( $filters as $tax_slug ) {
// ...object for taxonomy, doesn't contain the terms.
$tax = get_taxonomy( $tax_slug );
// Get taxonomy terms and order by name.
$args = array(
'orderby' => 'name',
'hide_empty' => false
);
// Get taxonomy terms.
$terms = get_terms( $tax_slug, $args );
// If we have terms.
if ( $terms ) {
// Set up select box.
printf( ' <select name="%s" class="postform">', $tax_slug );
// Default show all.
printf( '<option value="0">%s</option>', sprintf( __( 'Show all %s', $this->textdomain ), $tax->label ) );
// Foreach term create an option field...
foreach ( $terms as $term ) {
// ...if filtered by this term make it selected.
if ( isset( $_GET[ $tax_slug ] ) && $_GET[ $tax_slug ] === $term->slug ) {
printf( '<option value="%s" selected="selected">%s (%s)</option>', $term->slug, $term->name, $term->count );
// ...create option for taxonomy.
} else {
printf( '<option value="%s">%s (%s)</option>', $term->slug, $term->name, $term->count );
}
}
// End the select field.
print( '</select> ' );
}
}
}
}
} | php | function add_taxonomy_filters() {
global $typenow;
global $wp_query;
// Must set this to the post type you want the filter(s) displayed on.
if ( $typenow == $this->post_type_name ) {
// if custom filters are defined use those
if ( is_array( $this->filters ) ) {
$filters = $this->filters;
// else default to use all taxonomies associated with the post
} else {
$filters = $this->taxonomies;
}
if ( ! empty( $filters ) ) {
// Foreach of the taxonomies we want to create filters for...
foreach ( $filters as $tax_slug ) {
// ...object for taxonomy, doesn't contain the terms.
$tax = get_taxonomy( $tax_slug );
// Get taxonomy terms and order by name.
$args = array(
'orderby' => 'name',
'hide_empty' => false
);
// Get taxonomy terms.
$terms = get_terms( $tax_slug, $args );
// If we have terms.
if ( $terms ) {
// Set up select box.
printf( ' <select name="%s" class="postform">', $tax_slug );
// Default show all.
printf( '<option value="0">%s</option>', sprintf( __( 'Show all %s', $this->textdomain ), $tax->label ) );
// Foreach term create an option field...
foreach ( $terms as $term ) {
// ...if filtered by this term make it selected.
if ( isset( $_GET[ $tax_slug ] ) && $_GET[ $tax_slug ] === $term->slug ) {
printf( '<option value="%s" selected="selected">%s (%s)</option>', $term->slug, $term->name, $term->count );
// ...create option for taxonomy.
} else {
printf( '<option value="%s">%s (%s)</option>', $term->slug, $term->name, $term->count );
}
}
// End the select field.
print( '</select> ' );
}
}
}
}
} | [
"function",
"add_taxonomy_filters",
"(",
")",
"{",
"global",
"$",
"typenow",
";",
"global",
"$",
"wp_query",
";",
"// Must set this to the post type you want the filter(s) displayed on.",
"if",
"(",
"$",
"typenow",
"==",
"$",
"this",
"->",
"post_type_name",
")",
"{",
... | Add taxtonomy filters
Creates select fields for filtering posts by taxonomies on admin edit screen. | [
"Add",
"taxtonomy",
"filters"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L783-L848 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.sortable | function sortable( $columns = array() ) {
// Assign user defined sortable columns to object variable.
$this->sortable = $columns;
// Run filter to make columns sortable.
$this->add_filter( 'manage_edit-' . $this->post_type_name . '_sortable_columns', array( &$this, 'make_columns_sortable' ) );
// Run action that sorts columns on request.
$this->add_action( 'load-edit.php', array( &$this, 'load_edit' ) );
} | php | function sortable( $columns = array() ) {
// Assign user defined sortable columns to object variable.
$this->sortable = $columns;
// Run filter to make columns sortable.
$this->add_filter( 'manage_edit-' . $this->post_type_name . '_sortable_columns', array( &$this, 'make_columns_sortable' ) );
// Run action that sorts columns on request.
$this->add_action( 'load-edit.php', array( &$this, 'load_edit' ) );
} | [
"function",
"sortable",
"(",
"$",
"columns",
"=",
"array",
"(",
")",
")",
"{",
"// Assign user defined sortable columns to object variable.",
"$",
"this",
"->",
"sortable",
"=",
"$",
"columns",
";",
"// Run filter to make columns sortable.",
"$",
"this",
"->",
"add_fi... | Sortable
Define what columns are sortable in the admin edit screen.
@param array $columns An array of columns that are sortable. | [
"Sortable"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L889-L899 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.make_columns_sortable | function make_columns_sortable( $columns ) {
// For each sortable column.
foreach ( $this->sortable as $column => $values ) {
// Make an array to merge into wordpress sortable columns.
$sortable_columns[ $column ] = $values[0];
}
// Merge sortable columns array into wordpress sortable columns.
$columns = array_merge( $sortable_columns, $columns );
return $columns;
} | php | function make_columns_sortable( $columns ) {
// For each sortable column.
foreach ( $this->sortable as $column => $values ) {
// Make an array to merge into wordpress sortable columns.
$sortable_columns[ $column ] = $values[0];
}
// Merge sortable columns array into wordpress sortable columns.
$columns = array_merge( $sortable_columns, $columns );
return $columns;
} | [
"function",
"make_columns_sortable",
"(",
"$",
"columns",
")",
"{",
"// For each sortable column.",
"foreach",
"(",
"$",
"this",
"->",
"sortable",
"as",
"$",
"column",
"=>",
"$",
"values",
")",
"{",
"// Make an array to merge into wordpress sortable columns.",
"$",
"s... | Make columns sortable
Internal function that adds user defined sortable columns to WordPress default columns.
@param array $columns Columns to be sortable. | [
"Make",
"columns",
"sortable"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L909-L922 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.sort_columns | function sort_columns( $vars ) {
// Cycle through all sortable columns submitted by the user
foreach ( $this->sortable as $column => $values ) {
// Retrieve the meta key from the user submitted array of sortable columns
$meta_key = $values[0];
// If the meta_key is a taxonomy
if( taxonomy_exists( $meta_key ) ) {
// Sort by taxonomy.
$key = "taxonomy";
} else {
// else by meta key.
$key = "meta_key";
}
// If the optional parameter is set and is set to true
if ( isset( $values[1] ) && true === $values[1] ) {
// Vaules needed to be ordered by integer value
$orderby = 'meta_value_num';
} else {
// Values are to be order by string value
$orderby = 'meta_value';
}
// Check if we're viewing this post type
if ( isset( $vars['post_type'] ) && $this->post_type_name == $vars['post_type'] ) {
// find the meta key we want to order posts by
if ( isset( $vars['orderby'] ) && $meta_key == $vars['orderby'] ) {
// Merge the query vars with our custom variables
$vars = array_merge(
$vars,
array(
'meta_key' => $meta_key,
'orderby' => $orderby
)
);
}
}
}
return $vars;
} | php | function sort_columns( $vars ) {
// Cycle through all sortable columns submitted by the user
foreach ( $this->sortable as $column => $values ) {
// Retrieve the meta key from the user submitted array of sortable columns
$meta_key = $values[0];
// If the meta_key is a taxonomy
if( taxonomy_exists( $meta_key ) ) {
// Sort by taxonomy.
$key = "taxonomy";
} else {
// else by meta key.
$key = "meta_key";
}
// If the optional parameter is set and is set to true
if ( isset( $values[1] ) && true === $values[1] ) {
// Vaules needed to be ordered by integer value
$orderby = 'meta_value_num';
} else {
// Values are to be order by string value
$orderby = 'meta_value';
}
// Check if we're viewing this post type
if ( isset( $vars['post_type'] ) && $this->post_type_name == $vars['post_type'] ) {
// find the meta key we want to order posts by
if ( isset( $vars['orderby'] ) && $meta_key == $vars['orderby'] ) {
// Merge the query vars with our custom variables
$vars = array_merge(
$vars,
array(
'meta_key' => $meta_key,
'orderby' => $orderby
)
);
}
}
}
return $vars;
} | [
"function",
"sort_columns",
"(",
"$",
"vars",
")",
"{",
"// Cycle through all sortable columns submitted by the user",
"foreach",
"(",
"$",
"this",
"->",
"sortable",
"as",
"$",
"column",
"=>",
"$",
"values",
")",
"{",
"// Retrieve the meta key from the user submitted arra... | Sort columns
Internal function that sorts columns on request.
@see load_edit()
@param array $vars The query vars submitted by user.
@return array A sorted array. | [
"Sort",
"columns"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L948-L998 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.menu_icon | function menu_icon( $icon = "dashicons-admin-page" ) {
if ( is_string( $icon ) && stripos( $icon, "dashicons" ) !== false ) {
$this->options["menu_icon"] = $icon;
} else {
// Set a default menu icon
$this->options["menu_icon"] = "dashicons-admin-page";
}
} | php | function menu_icon( $icon = "dashicons-admin-page" ) {
if ( is_string( $icon ) && stripos( $icon, "dashicons" ) !== false ) {
$this->options["menu_icon"] = $icon;
} else {
// Set a default menu icon
$this->options["menu_icon"] = "dashicons-admin-page";
}
} | [
"function",
"menu_icon",
"(",
"$",
"icon",
"=",
"\"dashicons-admin-page\"",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"icon",
")",
"&&",
"stripos",
"(",
"$",
"icon",
",",
"\"dashicons\"",
")",
"!==",
"false",
")",
"{",
"$",
"this",
"->",
"options",
"... | Set menu icon
Use this function to set the menu icon in the admin dashboard. Since WordPress v3.8
dashicons are used. For more information see @link http://melchoyce.github.io/dashicons/
@param string $icon dashicon name | [
"Set",
"menu",
"icon"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L1008-L1019 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.updated_messages | function updated_messages( $messages ) {
$post = get_post();
$singular = $this->singular;
$messages[$this->post_type_name] = array(
0 => '',
1 => sprintf( __( '%s updated.', $this->textdomain ), $singular ),
2 => __( 'Custom field updated.', $this->textdomain ),
3 => __( 'Custom field deleted.', $this->textdomain ),
4 => sprintf( __( '%s updated.', $this->textdomain ), $singular ),
5 => isset( $_GET['revision'] ) ? sprintf( __( '%2$s restored to revision from %1$s', $this->textdomain ), wp_post_revision_title( (int) $_GET['revision'], false ), $singular ) : false,
6 => sprintf( __( '%s updated.', $this->textdomain ), $singular ),
7 => sprintf( __( '%s saved.', $this->textdomain ), $singular ),
8 => sprintf( __( '%s submitted.', $this->textdomain ), $singular ),
9 => sprintf(
__( '%2$s scheduled for: <strong>%1$s</strong>.', $this->textdomain ),
date_i18n( __( 'M j, Y @ G:i', $this->textdomain ), strtotime( $post->post_date ) ),
$singular
),
10 => sprintf( __( '%s draft updated.', $this->textdomain ), $singular ),
);
return $messages;
} | php | function updated_messages( $messages ) {
$post = get_post();
$singular = $this->singular;
$messages[$this->post_type_name] = array(
0 => '',
1 => sprintf( __( '%s updated.', $this->textdomain ), $singular ),
2 => __( 'Custom field updated.', $this->textdomain ),
3 => __( 'Custom field deleted.', $this->textdomain ),
4 => sprintf( __( '%s updated.', $this->textdomain ), $singular ),
5 => isset( $_GET['revision'] ) ? sprintf( __( '%2$s restored to revision from %1$s', $this->textdomain ), wp_post_revision_title( (int) $_GET['revision'], false ), $singular ) : false,
6 => sprintf( __( '%s updated.', $this->textdomain ), $singular ),
7 => sprintf( __( '%s saved.', $this->textdomain ), $singular ),
8 => sprintf( __( '%s submitted.', $this->textdomain ), $singular ),
9 => sprintf(
__( '%2$s scheduled for: <strong>%1$s</strong>.', $this->textdomain ),
date_i18n( __( 'M j, Y @ G:i', $this->textdomain ), strtotime( $post->post_date ) ),
$singular
),
10 => sprintf( __( '%s draft updated.', $this->textdomain ), $singular ),
);
return $messages;
} | [
"function",
"updated_messages",
"(",
"$",
"messages",
")",
"{",
"$",
"post",
"=",
"get_post",
"(",
")",
";",
"$",
"singular",
"=",
"$",
"this",
"->",
"singular",
";",
"$",
"messages",
"[",
"$",
"this",
"->",
"post_type_name",
"]",
"=",
"array",
"(",
... | Updated messages
Internal function that modifies the post type names in updated messages
@param array $messages an array of post updated messages | [
"Updated",
"messages"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L1037-L1061 |
jjgrainger/wp-custom-post-type-class | src/CPT.php | CPT.bulk_updated_messages | function bulk_updated_messages( $bulk_messages, $bulk_counts ) {
$singular = $this->singular;
$plural = $this->plural;
$bulk_messages[ $this->post_type_name ] = array(
'updated' => _n( '%s '.$singular.' updated.', '%s '.$plural.' updated.', $bulk_counts['updated'] ),
'locked' => _n( '%s '.$singular.' not updated, somebody is editing it.', '%s '.$plural.' not updated, somebody is editing them.', $bulk_counts['locked'] ),
'deleted' => _n( '%s '.$singular.' permanently deleted.', '%s '.$plural.' permanently deleted.', $bulk_counts['deleted'] ),
'trashed' => _n( '%s '.$singular.' moved to the Trash.', '%s '.$plural.' moved to the Trash.', $bulk_counts['trashed'] ),
'untrashed' => _n( '%s '.$singular.' restored from the Trash.', '%s '.$plural.' restored from the Trash.', $bulk_counts['untrashed'] ),
);
return $bulk_messages;
} | php | function bulk_updated_messages( $bulk_messages, $bulk_counts ) {
$singular = $this->singular;
$plural = $this->plural;
$bulk_messages[ $this->post_type_name ] = array(
'updated' => _n( '%s '.$singular.' updated.', '%s '.$plural.' updated.', $bulk_counts['updated'] ),
'locked' => _n( '%s '.$singular.' not updated, somebody is editing it.', '%s '.$plural.' not updated, somebody is editing them.', $bulk_counts['locked'] ),
'deleted' => _n( '%s '.$singular.' permanently deleted.', '%s '.$plural.' permanently deleted.', $bulk_counts['deleted'] ),
'trashed' => _n( '%s '.$singular.' moved to the Trash.', '%s '.$plural.' moved to the Trash.', $bulk_counts['trashed'] ),
'untrashed' => _n( '%s '.$singular.' restored from the Trash.', '%s '.$plural.' restored from the Trash.', $bulk_counts['untrashed'] ),
);
return $bulk_messages;
} | [
"function",
"bulk_updated_messages",
"(",
"$",
"bulk_messages",
",",
"$",
"bulk_counts",
")",
"{",
"$",
"singular",
"=",
"$",
"this",
"->",
"singular",
";",
"$",
"plural",
"=",
"$",
"this",
"->",
"plural",
";",
"$",
"bulk_messages",
"[",
"$",
"this",
"->... | Bulk updated messages
Internal function that modifies the post type names in bulk updated messages
@param array $messages an array of bulk updated messages | [
"Bulk",
"updated",
"messages"
] | train | https://github.com/jjgrainger/wp-custom-post-type-class/blob/f866c3a35ec8041f8ccded863d064778e2080edb/src/CPT.php#L1070-L1084 |
doctrine/event-manager | lib/Doctrine/Common/EventManager.php | EventManager.dispatchEvent | public function dispatchEvent($eventName, ?EventArgs $eventArgs = null)
{
if (! isset($this->_listeners[$eventName])) {
return;
}
$eventArgs = $eventArgs ?? EventArgs::getEmptyInstance();
foreach ($this->_listeners[$eventName] as $listener) {
$listener->$eventName($eventArgs);
}
} | php | public function dispatchEvent($eventName, ?EventArgs $eventArgs = null)
{
if (! isset($this->_listeners[$eventName])) {
return;
}
$eventArgs = $eventArgs ?? EventArgs::getEmptyInstance();
foreach ($this->_listeners[$eventName] as $listener) {
$listener->$eventName($eventArgs);
}
} | [
"public",
"function",
"dispatchEvent",
"(",
"$",
"eventName",
",",
"?",
"EventArgs",
"$",
"eventArgs",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"_listeners",
"[",
"$",
"eventName",
"]",
")",
")",
"{",
"return",
";",
"}"... | Dispatches an event to all registered listeners.
@param string $eventName The name of the event to dispatch. The name of the event is
the name of the method that is invoked on listeners.
@param EventArgs|null $eventArgs The event arguments to pass to the event handlers/listeners.
If not supplied, the single empty EventArgs instance is used.
@return void | [
"Dispatches",
"an",
"event",
"to",
"all",
"registered",
"listeners",
"."
] | train | https://github.com/doctrine/event-manager/blob/45e6c7bc79b5f46e601236ebd6e69623e528d312/lib/Doctrine/Common/EventManager.php#L32-L43 |
doctrine/event-manager | lib/Doctrine/Common/EventManager.php | EventManager.addEventListener | public function addEventListener($events, $listener)
{
// Picks the hash code related to that listener
$hash = spl_object_hash($listener);
foreach ((array) $events as $event) {
// Overrides listener if a previous one was associated already
// Prevents duplicate listeners on same event (same instance only)
$this->_listeners[$event][$hash] = $listener;
}
} | php | public function addEventListener($events, $listener)
{
// Picks the hash code related to that listener
$hash = spl_object_hash($listener);
foreach ((array) $events as $event) {
// Overrides listener if a previous one was associated already
// Prevents duplicate listeners on same event (same instance only)
$this->_listeners[$event][$hash] = $listener;
}
} | [
"public",
"function",
"addEventListener",
"(",
"$",
"events",
",",
"$",
"listener",
")",
"{",
"// Picks the hash code related to that listener",
"$",
"hash",
"=",
"spl_object_hash",
"(",
"$",
"listener",
")",
";",
"foreach",
"(",
"(",
"array",
")",
"$",
"events"... | Adds an event listener that listens on the specified events.
@param string|string[] $events The event(s) to listen on.
@param object $listener The listener object.
@return void | [
"Adds",
"an",
"event",
"listener",
"that",
"listens",
"on",
"the",
"specified",
"events",
"."
] | train | https://github.com/doctrine/event-manager/blob/45e6c7bc79b5f46e601236ebd6e69623e528d312/lib/Doctrine/Common/EventManager.php#L77-L87 |
phpDocumentor/TypeResolver | src/Types/ContextFactory.php | ContextFactory.createFromReflector | public function createFromReflector(\Reflector $reflector): Context
{
if ($reflector instanceof \ReflectionClass) {
return $this->createFromReflectionClass($reflector);
}
if ($reflector instanceof \ReflectionParameter) {
return $this->createFromReflectionParameter($reflector);
}
if ($reflector instanceof \ReflectionMethod) {
return $this->createFromReflectionMethod($reflector);
}
if ($reflector instanceof \ReflectionProperty) {
return $this->createFromReflectionProperty($reflector);
}
if ($reflector instanceof \ReflectionClassConstant) {
return $this->createFromReflectionClassConstant($reflector);
}
throw new UnexpectedValueException('Unhandled \Reflector instance given: ' . get_class($reflector));
} | php | public function createFromReflector(\Reflector $reflector): Context
{
if ($reflector instanceof \ReflectionClass) {
return $this->createFromReflectionClass($reflector);
}
if ($reflector instanceof \ReflectionParameter) {
return $this->createFromReflectionParameter($reflector);
}
if ($reflector instanceof \ReflectionMethod) {
return $this->createFromReflectionMethod($reflector);
}
if ($reflector instanceof \ReflectionProperty) {
return $this->createFromReflectionProperty($reflector);
}
if ($reflector instanceof \ReflectionClassConstant) {
return $this->createFromReflectionClassConstant($reflector);
}
throw new UnexpectedValueException('Unhandled \Reflector instance given: ' . get_class($reflector));
} | [
"public",
"function",
"createFromReflector",
"(",
"\\",
"Reflector",
"$",
"reflector",
")",
":",
"Context",
"{",
"if",
"(",
"$",
"reflector",
"instanceof",
"\\",
"ReflectionClass",
")",
"{",
"return",
"$",
"this",
"->",
"createFromReflectionClass",
"(",
"$",
"... | Build a Context given a Class Reflection.
@see Context for more information on Contexts. | [
"Build",
"a",
"Context",
"given",
"a",
"Class",
"Reflection",
"."
] | train | https://github.com/phpDocumentor/TypeResolver/blob/864039eafacb5907af109eaf739d77d1e7ee7e7b/src/Types/ContextFactory.php#L39-L62 |
phpDocumentor/TypeResolver | src/Types/ContextFactory.php | ContextFactory.createForNamespace | public function createForNamespace($namespace, $fileContents)
{
$namespace = trim($namespace, '\\');
$useStatements = [];
$currentNamespace = '';
$tokens = new \ArrayIterator(token_get_all($fileContents));
while ($tokens->valid()) {
switch ($tokens->current()[0]) {
case T_NAMESPACE:
$currentNamespace = $this->parseNamespace($tokens);
break;
case T_CLASS:
// Fast-forward the iterator through the class so that any
// T_USE tokens found within are skipped - these are not
// valid namespace use statements so should be ignored.
$braceLevel = 0;
$firstBraceFound = false;
while ($tokens->valid() && ($braceLevel > 0 || !$firstBraceFound)) {
if ($tokens->current() === '{'
|| $tokens->current()[0] === T_CURLY_OPEN
|| $tokens->current()[0] === T_DOLLAR_OPEN_CURLY_BRACES) {
if (!$firstBraceFound) {
$firstBraceFound = true;
}
++$braceLevel;
}
if ($tokens->current() === '}') {
--$braceLevel;
}
$tokens->next();
}
break;
case T_USE:
if ($currentNamespace === $namespace) {
$useStatements = array_merge($useStatements, $this->parseUseStatement($tokens));
}
break;
}
$tokens->next();
}
return new Context($namespace, $useStatements);
} | php | public function createForNamespace($namespace, $fileContents)
{
$namespace = trim($namespace, '\\');
$useStatements = [];
$currentNamespace = '';
$tokens = new \ArrayIterator(token_get_all($fileContents));
while ($tokens->valid()) {
switch ($tokens->current()[0]) {
case T_NAMESPACE:
$currentNamespace = $this->parseNamespace($tokens);
break;
case T_CLASS:
// Fast-forward the iterator through the class so that any
// T_USE tokens found within are skipped - these are not
// valid namespace use statements so should be ignored.
$braceLevel = 0;
$firstBraceFound = false;
while ($tokens->valid() && ($braceLevel > 0 || !$firstBraceFound)) {
if ($tokens->current() === '{'
|| $tokens->current()[0] === T_CURLY_OPEN
|| $tokens->current()[0] === T_DOLLAR_OPEN_CURLY_BRACES) {
if (!$firstBraceFound) {
$firstBraceFound = true;
}
++$braceLevel;
}
if ($tokens->current() === '}') {
--$braceLevel;
}
$tokens->next();
}
break;
case T_USE:
if ($currentNamespace === $namespace) {
$useStatements = array_merge($useStatements, $this->parseUseStatement($tokens));
}
break;
}
$tokens->next();
}
return new Context($namespace, $useStatements);
} | [
"public",
"function",
"createForNamespace",
"(",
"$",
"namespace",
",",
"$",
"fileContents",
")",
"{",
"$",
"namespace",
"=",
"trim",
"(",
"$",
"namespace",
",",
"'\\\\'",
")",
";",
"$",
"useStatements",
"=",
"[",
"]",
";",
"$",
"currentNamespace",
"=",
... | Build a Context for a namespace in the provided file contents.
@param string $namespace It does not matter if a `\` precedes the namespace name, this method first normalizes.
@param string $fileContents the file's contents to retrieve the aliases from with the given namespace.
@see Context for more information on Contexts.
@return Context | [
"Build",
"a",
"Context",
"for",
"a",
"namespace",
"in",
"the",
"provided",
"file",
"contents",
"."
] | train | https://github.com/phpDocumentor/TypeResolver/blob/864039eafacb5907af109eaf739d77d1e7ee7e7b/src/Types/ContextFactory.php#L114-L161 |
phpDocumentor/TypeResolver | src/Types/ContextFactory.php | ContextFactory.parseNamespace | private function parseNamespace(\ArrayIterator $tokens)
{
// skip to the first string or namespace separator
$this->skipToNextStringOrNamespaceSeparator($tokens);
$name = '';
while ($tokens->valid() && ($tokens->current()[0] === T_STRING || $tokens->current()[0] === T_NS_SEPARATOR)
) {
$name .= $tokens->current()[1];
$tokens->next();
}
return $name;
} | php | private function parseNamespace(\ArrayIterator $tokens)
{
// skip to the first string or namespace separator
$this->skipToNextStringOrNamespaceSeparator($tokens);
$name = '';
while ($tokens->valid() && ($tokens->current()[0] === T_STRING || $tokens->current()[0] === T_NS_SEPARATOR)
) {
$name .= $tokens->current()[1];
$tokens->next();
}
return $name;
} | [
"private",
"function",
"parseNamespace",
"(",
"\\",
"ArrayIterator",
"$",
"tokens",
")",
"{",
"// skip to the first string or namespace separator",
"$",
"this",
"->",
"skipToNextStringOrNamespaceSeparator",
"(",
"$",
"tokens",
")",
";",
"$",
"name",
"=",
"''",
";",
... | Deduce the name from tokens when we are at the T_NAMESPACE token.
@return string | [
"Deduce",
"the",
"name",
"from",
"tokens",
"when",
"we",
"are",
"at",
"the",
"T_NAMESPACE",
"token",
"."
] | train | https://github.com/phpDocumentor/TypeResolver/blob/864039eafacb5907af109eaf739d77d1e7ee7e7b/src/Types/ContextFactory.php#L168-L181 |
phpDocumentor/TypeResolver | src/Types/ContextFactory.php | ContextFactory.parseUseStatement | private function parseUseStatement(\ArrayIterator $tokens)
{
$uses = [];
$continue = true;
while ($continue) {
$this->skipToNextStringOrNamespaceSeparator($tokens);
$uses = array_merge($uses, $this->extractUseStatements($tokens));
if ($tokens->current()[0] === self::T_LITERAL_END_OF_USE) {
$continue = false;
}
}
return $uses;
} | php | private function parseUseStatement(\ArrayIterator $tokens)
{
$uses = [];
$continue = true;
while ($continue) {
$this->skipToNextStringOrNamespaceSeparator($tokens);
$uses = array_merge($uses, $this->extractUseStatements($tokens));
if ($tokens->current()[0] === self::T_LITERAL_END_OF_USE) {
$continue = false;
}
}
return $uses;
} | [
"private",
"function",
"parseUseStatement",
"(",
"\\",
"ArrayIterator",
"$",
"tokens",
")",
"{",
"$",
"uses",
"=",
"[",
"]",
";",
"$",
"continue",
"=",
"true",
";",
"while",
"(",
"$",
"continue",
")",
"{",
"$",
"this",
"->",
"skipToNextStringOrNamespaceSep... | Deduce the names of all imports when we are at the T_USE token.
@return string[] | [
"Deduce",
"the",
"names",
"of",
"all",
"imports",
"when",
"we",
"are",
"at",
"the",
"T_USE",
"token",
"."
] | train | https://github.com/phpDocumentor/TypeResolver/blob/864039eafacb5907af109eaf739d77d1e7ee7e7b/src/Types/ContextFactory.php#L188-L203 |
phpDocumentor/TypeResolver | src/Types/ContextFactory.php | ContextFactory.extractUseStatements | private function extractUseStatements(\ArrayIterator $tokens)
{
$extractedUseStatements = [];
$groupedNs = '';
$currentNs = '';
$currentAlias = null;
$state = 'start';
$i = 0;
while ($tokens->valid()) {
$i += 1;
$currentToken = $tokens->current();
$tokenId = is_string($currentToken) ? $currentToken : $currentToken[0];
$tokenValue = is_string($currentToken) ? null : $currentToken[1];
switch ($state) {
case 'start':
switch ($tokenId) {
case T_STRING:
case T_NS_SEPARATOR:
$currentNs .= $tokenValue;
break;
case T_CURLY_OPEN:
case '{':
$state = 'grouped';
$groupedNs = $currentNs;
break;
case T_AS:
$state = 'start-alias';
break;
case self::T_LITERAL_USE_SEPARATOR:
case self::T_LITERAL_END_OF_USE:
$state = 'end';
break;
default:
break;
}
break;
case 'start-alias':
switch ($tokenId) {
case T_STRING:
$currentAlias .= $tokenValue;
break;
case self::T_LITERAL_USE_SEPARATOR:
case self::T_LITERAL_END_OF_USE:
$state = 'end';
break;
default:
break;
}
break;
case 'grouped':
switch ($tokenId) {
case T_STRING:
case T_NS_SEPARATOR:
$currentNs .= $tokenValue;
break;
case T_AS:
$state = 'grouped-alias';
break;
case self::T_LITERAL_USE_SEPARATOR:
$state = 'grouped';
$extractedUseStatements[$currentAlias ?: $currentNs] = $currentNs;
$currentNs = $groupedNs;
$currentAlias = null;
break;
case self::T_LITERAL_END_OF_USE:
$state = 'end';
break;
default:
break;
}
break;
case 'grouped-alias':
switch ($tokenId) {
case T_STRING:
$currentAlias .= $tokenValue;
break;
case self::T_LITERAL_USE_SEPARATOR:
$state = 'grouped';
$extractedUseStatements[$currentAlias ?: $currentNs] = $currentNs;
$currentNs = $groupedNs;
$currentAlias = null;
break;
case self::T_LITERAL_END_OF_USE:
$state = 'end';
break;
default:
break;
}
}
if ($state === 'end') {
break;
}
$tokens->next();
}
if ($groupedNs !== $currentNs) {
$extractedUseStatements[$currentAlias ?: $currentNs] = $currentNs;
}
return $extractedUseStatements;
} | php | private function extractUseStatements(\ArrayIterator $tokens)
{
$extractedUseStatements = [];
$groupedNs = '';
$currentNs = '';
$currentAlias = null;
$state = 'start';
$i = 0;
while ($tokens->valid()) {
$i += 1;
$currentToken = $tokens->current();
$tokenId = is_string($currentToken) ? $currentToken : $currentToken[0];
$tokenValue = is_string($currentToken) ? null : $currentToken[1];
switch ($state) {
case 'start':
switch ($tokenId) {
case T_STRING:
case T_NS_SEPARATOR:
$currentNs .= $tokenValue;
break;
case T_CURLY_OPEN:
case '{':
$state = 'grouped';
$groupedNs = $currentNs;
break;
case T_AS:
$state = 'start-alias';
break;
case self::T_LITERAL_USE_SEPARATOR:
case self::T_LITERAL_END_OF_USE:
$state = 'end';
break;
default:
break;
}
break;
case 'start-alias':
switch ($tokenId) {
case T_STRING:
$currentAlias .= $tokenValue;
break;
case self::T_LITERAL_USE_SEPARATOR:
case self::T_LITERAL_END_OF_USE:
$state = 'end';
break;
default:
break;
}
break;
case 'grouped':
switch ($tokenId) {
case T_STRING:
case T_NS_SEPARATOR:
$currentNs .= $tokenValue;
break;
case T_AS:
$state = 'grouped-alias';
break;
case self::T_LITERAL_USE_SEPARATOR:
$state = 'grouped';
$extractedUseStatements[$currentAlias ?: $currentNs] = $currentNs;
$currentNs = $groupedNs;
$currentAlias = null;
break;
case self::T_LITERAL_END_OF_USE:
$state = 'end';
break;
default:
break;
}
break;
case 'grouped-alias':
switch ($tokenId) {
case T_STRING:
$currentAlias .= $tokenValue;
break;
case self::T_LITERAL_USE_SEPARATOR:
$state = 'grouped';
$extractedUseStatements[$currentAlias ?: $currentNs] = $currentNs;
$currentNs = $groupedNs;
$currentAlias = null;
break;
case self::T_LITERAL_END_OF_USE:
$state = 'end';
break;
default:
break;
}
}
if ($state === 'end') {
break;
}
$tokens->next();
}
if ($groupedNs !== $currentNs) {
$extractedUseStatements[$currentAlias ?: $currentNs] = $currentNs;
}
return $extractedUseStatements;
} | [
"private",
"function",
"extractUseStatements",
"(",
"\\",
"ArrayIterator",
"$",
"tokens",
")",
"{",
"$",
"extractedUseStatements",
"=",
"[",
"]",
";",
"$",
"groupedNs",
"=",
"''",
";",
"$",
"currentNs",
"=",
"''",
";",
"$",
"currentAlias",
"=",
"null",
";"... | Deduce the namespace name and alias of an import when we are at the T_USE token or have not reached the end of
a USE statement yet. This will return a key/value array of the alias => namespace.
@return array | [
"Deduce",
"the",
"namespace",
"name",
"and",
"alias",
"of",
"an",
"import",
"when",
"we",
"are",
"at",
"the",
"T_USE",
"token",
"or",
"have",
"not",
"reached",
"the",
"end",
"of",
"a",
"USE",
"statement",
"yet",
".",
"This",
"will",
"return",
"a",
"key... | train | https://github.com/phpDocumentor/TypeResolver/blob/864039eafacb5907af109eaf739d77d1e7ee7e7b/src/Types/ContextFactory.php#L221-L324 |
phpDocumentor/TypeResolver | src/FqsenResolver.php | FqsenResolver.resolvePartialStructuralElementName | private function resolvePartialStructuralElementName($type, Context $context): Fqsen
{
$typeParts = explode(self::OPERATOR_NAMESPACE, $type, 2);
$namespaceAliases = $context->getNamespaceAliases();
// if the first segment is not an alias; prepend namespace name and return
if (!isset($namespaceAliases[$typeParts[0]])) {
$namespace = $context->getNamespace();
if ('' !== $namespace) {
$namespace .= self::OPERATOR_NAMESPACE;
}
return new Fqsen(self::OPERATOR_NAMESPACE . $namespace . $type);
}
$typeParts[0] = $namespaceAliases[$typeParts[0]];
return new Fqsen(self::OPERATOR_NAMESPACE . implode(self::OPERATOR_NAMESPACE, $typeParts));
} | php | private function resolvePartialStructuralElementName($type, Context $context): Fqsen
{
$typeParts = explode(self::OPERATOR_NAMESPACE, $type, 2);
$namespaceAliases = $context->getNamespaceAliases();
// if the first segment is not an alias; prepend namespace name and return
if (!isset($namespaceAliases[$typeParts[0]])) {
$namespace = $context->getNamespace();
if ('' !== $namespace) {
$namespace .= self::OPERATOR_NAMESPACE;
}
return new Fqsen(self::OPERATOR_NAMESPACE . $namespace . $type);
}
$typeParts[0] = $namespaceAliases[$typeParts[0]];
return new Fqsen(self::OPERATOR_NAMESPACE . implode(self::OPERATOR_NAMESPACE, $typeParts));
} | [
"private",
"function",
"resolvePartialStructuralElementName",
"(",
"$",
"type",
",",
"Context",
"$",
"context",
")",
":",
"Fqsen",
"{",
"$",
"typeParts",
"=",
"explode",
"(",
"self",
"::",
"OPERATOR_NAMESPACE",
",",
"$",
"type",
",",
"2",
")",
";",
"$",
"n... | Resolves a partial Structural Element Name (i.e. `Reflection\DocBlock`) to its FQSEN representation
(i.e. `\phpDocumentor\Reflection\DocBlock`) based on the Namespace and aliases mentioned in the Context.
@param string $type
@return Fqsen
@throws \InvalidArgumentException when type is not a valid FQSEN. | [
"Resolves",
"a",
"partial",
"Structural",
"Element",
"Name",
"(",
"i",
".",
"e",
".",
"Reflection",
"\\",
"DocBlock",
")",
"to",
"its",
"FQSEN",
"representation",
"(",
"i",
".",
"e",
".",
"\\",
"phpDocumentor",
"\\",
"Reflection",
"\\",
"DocBlock",
")",
... | train | https://github.com/phpDocumentor/TypeResolver/blob/864039eafacb5907af109eaf739d77d1e7ee7e7b/src/FqsenResolver.php#L55-L74 |
phpDocumentor/TypeResolver | src/TypeResolver.php | TypeResolver.resolve | public function resolve(string $type, Context $context = null): Type
{
$type = trim($type);
if (!$type) {
throw new \InvalidArgumentException('Attempted to resolve "' . $type . '" but it appears to be empty');
}
if ($context === null) {
$context = new Context('');
}
// split the type string into tokens `|`, `?`, `<`, `>`, `,`, `(`, `)[]`, '<', '>' and type names
$tokens = preg_split(
'/(\\||\\?|<|>|, ?|\\(|\\)(?:\\[\\])+)/',
$type,
-1,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
);
if (false === $tokens) {
throw new \InvalidArgumentException('Unable to split the type string "' . $type . '" into tokens');
}
$tokenIterator = new \ArrayIterator($tokens);
return $this->parseTypes($tokenIterator, $context, self::PARSER_IN_COMPOUND);
} | php | public function resolve(string $type, Context $context = null): Type
{
$type = trim($type);
if (!$type) {
throw new \InvalidArgumentException('Attempted to resolve "' . $type . '" but it appears to be empty');
}
if ($context === null) {
$context = new Context('');
}
// split the type string into tokens `|`, `?`, `<`, `>`, `,`, `(`, `)[]`, '<', '>' and type names
$tokens = preg_split(
'/(\\||\\?|<|>|, ?|\\(|\\)(?:\\[\\])+)/',
$type,
-1,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
);
if (false === $tokens) {
throw new \InvalidArgumentException('Unable to split the type string "' . $type . '" into tokens');
}
$tokenIterator = new \ArrayIterator($tokens);
return $this->parseTypes($tokenIterator, $context, self::PARSER_IN_COMPOUND);
} | [
"public",
"function",
"resolve",
"(",
"string",
"$",
"type",
",",
"Context",
"$",
"context",
"=",
"null",
")",
":",
"Type",
"{",
"$",
"type",
"=",
"trim",
"(",
"$",
"type",
")",
";",
"if",
"(",
"!",
"$",
"type",
")",
"{",
"throw",
"new",
"\\",
... | Analyzes the given type and returns the FQCN variant.
When a type is provided this method checks whether it is not a keyword or
Fully Qualified Class Name. If so it will use the given namespace and
aliases to expand the type to a FQCN representation.
This method only works as expected if the namespace and aliases are set;
no dynamic reflection is being performed here.
@param string $type The relative or absolute type.
@uses Context::getNamespace() to determine with what to prefix the type name.
@uses Context::getNamespaceAliases() to check whether the first part of the relative type name should not be
replaced with another namespace.
@return Type | [
"Analyzes",
"the",
"given",
"type",
"and",
"returns",
"the",
"FQCN",
"variant",
"."
] | train | https://github.com/phpDocumentor/TypeResolver/blob/864039eafacb5907af109eaf739d77d1e7ee7e7b/src/TypeResolver.php#L100-L126 |
phpDocumentor/TypeResolver | src/TypeResolver.php | TypeResolver.parseTypes | private function parseTypes(\ArrayIterator $tokens, Context $context, $parserContext)
{
$types = [];
$token = '';
while ($tokens->valid()) {
$token = $tokens->current();
if ($token === '|') {
if (count($types) === 0) {
throw new \RuntimeException(
'A type is missing before a type separator'
);
}
if ($parserContext !== self::PARSER_IN_COMPOUND
&& $parserContext !== self::PARSER_IN_ARRAY_EXPRESSION
&& $parserContext !== self::PARSER_IN_COLLECTION_EXPRESSION
) {
throw new \RuntimeException(
'Unexpected type separator'
);
}
$tokens->next();
} elseif ($token === '?') {
if ($parserContext !== self::PARSER_IN_COMPOUND
&& $parserContext !== self::PARSER_IN_ARRAY_EXPRESSION
&& $parserContext !== self::PARSER_IN_COLLECTION_EXPRESSION
) {
throw new \RuntimeException(
'Unexpected nullable character'
);
}
$tokens->next();
$type = $this->parseTypes($tokens, $context, self::PARSER_IN_NULLABLE);
$types[] = new Nullable($type);
} elseif ($token === '(') {
$tokens->next();
$type = $this->parseTypes($tokens, $context, self::PARSER_IN_ARRAY_EXPRESSION);
$resolvedType = new Array_($type);
$token = $tokens->current();
// Someone did not properly close their array expression ..
if ($token === null) {
break;
}
// we generate arrays corresponding to the number of '[]' after the ')'
$numberOfArrays = (strlen($token) - 1) / 2;
for ($i = 0; $i < $numberOfArrays - 1; ++$i) {
$resolvedType = new Array_($resolvedType);
}
$types[] = $resolvedType;
$tokens->next();
} elseif ($parserContext === self::PARSER_IN_ARRAY_EXPRESSION && $token[0] === ')') {
break;
} elseif ($token === '<') {
if (count($types) === 0) {
throw new \RuntimeException(
'Unexpected collection operator "<", class name is missing'
);
}
$classType = array_pop($types);
if ($classType !== null) {
$types[] = $this->resolveCollection($tokens, $classType, $context);
}
$tokens->next();
} elseif ($parserContext === self::PARSER_IN_COLLECTION_EXPRESSION
&& ($token === '>' || trim($token) === ',')
) {
break;
} else {
$type = $this->resolveSingleType($token, $context);
$tokens->next();
if ($parserContext === self::PARSER_IN_NULLABLE) {
return $type;
}
$types[] = $type;
}
}
if ($token === '|') {
throw new \RuntimeException(
'A type is missing after a type separator'
);
}
if (count($types) === 0) {
if ($parserContext === self::PARSER_IN_NULLABLE) {
throw new \RuntimeException(
'A type is missing after a nullable character'
);
}
if ($parserContext === self::PARSER_IN_ARRAY_EXPRESSION) {
throw new \RuntimeException(
'A type is missing in an array expression'
);
}
if ($parserContext === self::PARSER_IN_COLLECTION_EXPRESSION) {
throw new \RuntimeException(
'A type is missing in a collection expression'
);
}
} elseif (count($types) === 1) {
return $types[0];
}
return new Compound($types);
} | php | private function parseTypes(\ArrayIterator $tokens, Context $context, $parserContext)
{
$types = [];
$token = '';
while ($tokens->valid()) {
$token = $tokens->current();
if ($token === '|') {
if (count($types) === 0) {
throw new \RuntimeException(
'A type is missing before a type separator'
);
}
if ($parserContext !== self::PARSER_IN_COMPOUND
&& $parserContext !== self::PARSER_IN_ARRAY_EXPRESSION
&& $parserContext !== self::PARSER_IN_COLLECTION_EXPRESSION
) {
throw new \RuntimeException(
'Unexpected type separator'
);
}
$tokens->next();
} elseif ($token === '?') {
if ($parserContext !== self::PARSER_IN_COMPOUND
&& $parserContext !== self::PARSER_IN_ARRAY_EXPRESSION
&& $parserContext !== self::PARSER_IN_COLLECTION_EXPRESSION
) {
throw new \RuntimeException(
'Unexpected nullable character'
);
}
$tokens->next();
$type = $this->parseTypes($tokens, $context, self::PARSER_IN_NULLABLE);
$types[] = new Nullable($type);
} elseif ($token === '(') {
$tokens->next();
$type = $this->parseTypes($tokens, $context, self::PARSER_IN_ARRAY_EXPRESSION);
$resolvedType = new Array_($type);
$token = $tokens->current();
// Someone did not properly close their array expression ..
if ($token === null) {
break;
}
// we generate arrays corresponding to the number of '[]' after the ')'
$numberOfArrays = (strlen($token) - 1) / 2;
for ($i = 0; $i < $numberOfArrays - 1; ++$i) {
$resolvedType = new Array_($resolvedType);
}
$types[] = $resolvedType;
$tokens->next();
} elseif ($parserContext === self::PARSER_IN_ARRAY_EXPRESSION && $token[0] === ')') {
break;
} elseif ($token === '<') {
if (count($types) === 0) {
throw new \RuntimeException(
'Unexpected collection operator "<", class name is missing'
);
}
$classType = array_pop($types);
if ($classType !== null) {
$types[] = $this->resolveCollection($tokens, $classType, $context);
}
$tokens->next();
} elseif ($parserContext === self::PARSER_IN_COLLECTION_EXPRESSION
&& ($token === '>' || trim($token) === ',')
) {
break;
} else {
$type = $this->resolveSingleType($token, $context);
$tokens->next();
if ($parserContext === self::PARSER_IN_NULLABLE) {
return $type;
}
$types[] = $type;
}
}
if ($token === '|') {
throw new \RuntimeException(
'A type is missing after a type separator'
);
}
if (count($types) === 0) {
if ($parserContext === self::PARSER_IN_NULLABLE) {
throw new \RuntimeException(
'A type is missing after a nullable character'
);
}
if ($parserContext === self::PARSER_IN_ARRAY_EXPRESSION) {
throw new \RuntimeException(
'A type is missing in an array expression'
);
}
if ($parserContext === self::PARSER_IN_COLLECTION_EXPRESSION) {
throw new \RuntimeException(
'A type is missing in a collection expression'
);
}
} elseif (count($types) === 1) {
return $types[0];
}
return new Compound($types);
} | [
"private",
"function",
"parseTypes",
"(",
"\\",
"ArrayIterator",
"$",
"tokens",
",",
"Context",
"$",
"context",
",",
"$",
"parserContext",
")",
"{",
"$",
"types",
"=",
"[",
"]",
";",
"$",
"token",
"=",
"''",
";",
"while",
"(",
"$",
"tokens",
"->",
"v... | Analyse each tokens and creates types
@param \ArrayIterator $tokens the iterator on tokens
@param int $parserContext on of self::PARSER_* constants, indicating
the context where we are in the parsing
@return Type | [
"Analyse",
"each",
"tokens",
"and",
"creates",
"types"
] | train | https://github.com/phpDocumentor/TypeResolver/blob/864039eafacb5907af109eaf739d77d1e7ee7e7b/src/TypeResolver.php#L136-L252 |
phpDocumentor/TypeResolver | src/TypeResolver.php | TypeResolver.resolveSingleType | private function resolveSingleType($type, Context $context)
{
switch (true) {
case $this->isKeyword($type):
return $this->resolveKeyword($type);
case $this->isTypedArray($type):
return $this->resolveTypedArray($type, $context);
case $this->isFqsen($type):
return $this->resolveTypedObject($type);
case $this->isPartialStructuralElementName($type):
return $this->resolveTypedObject($type, $context);
// @codeCoverageIgnoreStart
default:
// I haven't got the foggiest how the logic would come here but added this as a defense.
throw new \RuntimeException(
'Unable to resolve type "' . $type . '", there is no known method to resolve it'
);
}
// @codeCoverageIgnoreEnd
} | php | private function resolveSingleType($type, Context $context)
{
switch (true) {
case $this->isKeyword($type):
return $this->resolveKeyword($type);
case $this->isTypedArray($type):
return $this->resolveTypedArray($type, $context);
case $this->isFqsen($type):
return $this->resolveTypedObject($type);
case $this->isPartialStructuralElementName($type):
return $this->resolveTypedObject($type, $context);
// @codeCoverageIgnoreStart
default:
// I haven't got the foggiest how the logic would come here but added this as a defense.
throw new \RuntimeException(
'Unable to resolve type "' . $type . '", there is no known method to resolve it'
);
}
// @codeCoverageIgnoreEnd
} | [
"private",
"function",
"resolveSingleType",
"(",
"$",
"type",
",",
"Context",
"$",
"context",
")",
"{",
"switch",
"(",
"true",
")",
"{",
"case",
"$",
"this",
"->",
"isKeyword",
"(",
"$",
"type",
")",
":",
"return",
"$",
"this",
"->",
"resolveKeyword",
... | resolve the given type into a type object
@param string $type the type string, representing a single type
@return Type|Array_|Object_ | [
"resolve",
"the",
"given",
"type",
"into",
"a",
"type",
"object"
] | train | https://github.com/phpDocumentor/TypeResolver/blob/864039eafacb5907af109eaf739d77d1e7ee7e7b/src/TypeResolver.php#L260-L280 |
phpDocumentor/TypeResolver | src/TypeResolver.php | TypeResolver.addKeyword | public function addKeyword($keyword, $typeClassName)
{
if (!class_exists($typeClassName)) {
throw new \InvalidArgumentException(
'The Value Object that needs to be created with a keyword "' . $keyword . '" must be an existing class'
. ' but we could not find the class ' . $typeClassName
);
}
if (!in_array(Type::class, class_implements($typeClassName), true)) {
throw new \InvalidArgumentException(
'The class "' . $typeClassName . '" must implement the interface "phpDocumentor\Reflection\Type"'
);
}
$this->keywords[$keyword] = $typeClassName;
} | php | public function addKeyword($keyword, $typeClassName)
{
if (!class_exists($typeClassName)) {
throw new \InvalidArgumentException(
'The Value Object that needs to be created with a keyword "' . $keyword . '" must be an existing class'
. ' but we could not find the class ' . $typeClassName
);
}
if (!in_array(Type::class, class_implements($typeClassName), true)) {
throw new \InvalidArgumentException(
'The class "' . $typeClassName . '" must implement the interface "phpDocumentor\Reflection\Type"'
);
}
$this->keywords[$keyword] = $typeClassName;
} | [
"public",
"function",
"addKeyword",
"(",
"$",
"keyword",
",",
"$",
"typeClassName",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"typeClassName",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'The Value Object that needs to be creat... | Adds a keyword to the list of Keywords and associates it with a specific Value Object.
@param string $keyword
@param string $typeClassName | [
"Adds",
"a",
"keyword",
"to",
"the",
"list",
"of",
"Keywords",
"and",
"associates",
"it",
"with",
"a",
"specific",
"Value",
"Object",
"."
] | train | https://github.com/phpDocumentor/TypeResolver/blob/864039eafacb5907af109eaf739d77d1e7ee7e7b/src/TypeResolver.php#L288-L304 |
phpDocumentor/TypeResolver | src/TypeResolver.php | TypeResolver.resolveTypedArray | private function resolveTypedArray($type, Context $context)
{
return new Array_($this->resolveSingleType(substr($type, 0, -2), $context));
} | php | private function resolveTypedArray($type, Context $context)
{
return new Array_($this->resolveSingleType(substr($type, 0, -2), $context));
} | [
"private",
"function",
"resolveTypedArray",
"(",
"$",
"type",
",",
"Context",
"$",
"context",
")",
"{",
"return",
"new",
"Array_",
"(",
"$",
"this",
"->",
"resolveSingleType",
"(",
"substr",
"(",
"$",
"type",
",",
"0",
",",
"-",
"2",
")",
",",
"$",
"... | Resolves the given typed array string (i.e. `string[]`) into an Array object with the right types set.
@param string $type
@return Array_ | [
"Resolves",
"the",
"given",
"typed",
"array",
"string",
"(",
"i",
".",
"e",
".",
"string",
"[]",
")",
"into",
"an",
"Array",
"object",
"with",
"the",
"right",
"types",
"set",
"."
] | train | https://github.com/phpDocumentor/TypeResolver/blob/864039eafacb5907af109eaf739d77d1e7ee7e7b/src/TypeResolver.php#L360-L363 |
phpDocumentor/TypeResolver | src/TypeResolver.php | TypeResolver.resolveTypedObject | private function resolveTypedObject($type, Context $context = null)
{
return new Object_($this->fqsenResolver->resolve($type, $context));
} | php | private function resolveTypedObject($type, Context $context = null)
{
return new Object_($this->fqsenResolver->resolve($type, $context));
} | [
"private",
"function",
"resolveTypedObject",
"(",
"$",
"type",
",",
"Context",
"$",
"context",
"=",
"null",
")",
"{",
"return",
"new",
"Object_",
"(",
"$",
"this",
"->",
"fqsenResolver",
"->",
"resolve",
"(",
"$",
"type",
",",
"$",
"context",
")",
")",
... | Resolves the given FQSEN string into an FQSEN object.
@param string $type
@param Context|null $context
@return Object_ | [
"Resolves",
"the",
"given",
"FQSEN",
"string",
"into",
"an",
"FQSEN",
"object",
"."
] | train | https://github.com/phpDocumentor/TypeResolver/blob/864039eafacb5907af109eaf739d77d1e7ee7e7b/src/TypeResolver.php#L387-L390 |
phpDocumentor/TypeResolver | src/TypeResolver.php | TypeResolver.resolveCollection | private function resolveCollection(\ArrayIterator $tokens, Type $classType, Context $context)
{
$isArray = ('array' === (string) $classType);
// allow only "array" or class name before "<"
if (!$isArray
&& (! $classType instanceof Object_ || $classType->getFqsen() === null)) {
throw new \RuntimeException(
$classType . ' is not a collection'
);
}
$tokens->next();
$valueType = $this->parseTypes($tokens, $context, self::PARSER_IN_COLLECTION_EXPRESSION);
$keyType = null;
if ($tokens->current() !== null && trim($tokens->current()) === ',') {
// if we have a comma, then we just parsed the key type, not the value type
$keyType = $valueType;
if ($isArray) {
// check the key type for an "array" collection. We allow only
// strings or integers.
if (! $keyType instanceof String_ &&
! $keyType instanceof Integer &&
! $keyType instanceof Compound
) {
throw new \RuntimeException(
'An array can have only integers or strings as keys'
);
}
if ($keyType instanceof Compound) {
foreach ($keyType->getIterator() as $item) {
if (! $item instanceof String_ &&
! $item instanceof Integer
) {
throw new \RuntimeException(
'An array can have only integers or strings as keys'
);
}
}
}
}
$tokens->next();
// now let's parse the value type
$valueType = $this->parseTypes($tokens, $context, self::PARSER_IN_COLLECTION_EXPRESSION);
}
if ($tokens->current() !== '>') {
if (empty($tokens->current())) {
throw new \RuntimeException(
'Collection: ">" is missing'
);
}
throw new \RuntimeException(
'Unexpected character "' . $tokens->current() . '", ">" is missing'
);
}
if ($isArray) {
return new Array_($valueType, $keyType);
}
if ($classType instanceof Object_) {
return $this->makeCollectionFromObject($classType, $valueType, $keyType);
}
} | php | private function resolveCollection(\ArrayIterator $tokens, Type $classType, Context $context)
{
$isArray = ('array' === (string) $classType);
// allow only "array" or class name before "<"
if (!$isArray
&& (! $classType instanceof Object_ || $classType->getFqsen() === null)) {
throw new \RuntimeException(
$classType . ' is not a collection'
);
}
$tokens->next();
$valueType = $this->parseTypes($tokens, $context, self::PARSER_IN_COLLECTION_EXPRESSION);
$keyType = null;
if ($tokens->current() !== null && trim($tokens->current()) === ',') {
// if we have a comma, then we just parsed the key type, not the value type
$keyType = $valueType;
if ($isArray) {
// check the key type for an "array" collection. We allow only
// strings or integers.
if (! $keyType instanceof String_ &&
! $keyType instanceof Integer &&
! $keyType instanceof Compound
) {
throw new \RuntimeException(
'An array can have only integers or strings as keys'
);
}
if ($keyType instanceof Compound) {
foreach ($keyType->getIterator() as $item) {
if (! $item instanceof String_ &&
! $item instanceof Integer
) {
throw new \RuntimeException(
'An array can have only integers or strings as keys'
);
}
}
}
}
$tokens->next();
// now let's parse the value type
$valueType = $this->parseTypes($tokens, $context, self::PARSER_IN_COLLECTION_EXPRESSION);
}
if ($tokens->current() !== '>') {
if (empty($tokens->current())) {
throw new \RuntimeException(
'Collection: ">" is missing'
);
}
throw new \RuntimeException(
'Unexpected character "' . $tokens->current() . '", ">" is missing'
);
}
if ($isArray) {
return new Array_($valueType, $keyType);
}
if ($classType instanceof Object_) {
return $this->makeCollectionFromObject($classType, $valueType, $keyType);
}
} | [
"private",
"function",
"resolveCollection",
"(",
"\\",
"ArrayIterator",
"$",
"tokens",
",",
"Type",
"$",
"classType",
",",
"Context",
"$",
"context",
")",
"{",
"$",
"isArray",
"=",
"(",
"'array'",
"===",
"(",
"string",
")",
"$",
"classType",
")",
";",
"/... | Resolves the collection values and keys
@return Array_|Collection | [
"Resolves",
"the",
"collection",
"values",
"and",
"keys"
] | train | https://github.com/phpDocumentor/TypeResolver/blob/864039eafacb5907af109eaf739d77d1e7ee7e7b/src/TypeResolver.php#L397-L466 |
schmittjoh/php-option | src/PhpOption/Option.php | Option.fromValue | public static function fromValue($value, $noneValue = null)
{
if ($value === $noneValue) {
return None::create();
}
return new Some($value);
} | php | public static function fromValue($value, $noneValue = null)
{
if ($value === $noneValue) {
return None::create();
}
return new Some($value);
} | [
"public",
"static",
"function",
"fromValue",
"(",
"$",
"value",
",",
"$",
"noneValue",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"$",
"noneValue",
")",
"{",
"return",
"None",
"::",
"create",
"(",
")",
";",
"}",
"return",
"new",
"Some",
... | Creates an option given a return value.
This is intended for consuming existing APIs and allows you to easily
convert them to an option. By default, we treat ``null`` as the None case,
and everything else as Some.
@param mixed $value The actual return value.
@param mixed $noneValue The value which should be considered "None"; null
by default.
@return Option | [
"Creates",
"an",
"option",
"given",
"a",
"return",
"value",
"."
] | train | https://github.com/schmittjoh/php-option/blob/94e644f7d2051a5f0fcf77d81605f152eecff0ed/src/PhpOption/Option.php#L43-L50 |
schmittjoh/php-option | src/PhpOption/Option.php | Option.fromReturn | public static function fromReturn($callback, array $arguments = array(), $noneValue = null)
{
return new LazyOption(function() use ($callback, $arguments, $noneValue) {
$return = call_user_func_array($callback, $arguments);
if ($return === $noneValue) {
return None::create();
}
return new Some($return);
});
} | php | public static function fromReturn($callback, array $arguments = array(), $noneValue = null)
{
return new LazyOption(function() use ($callback, $arguments, $noneValue) {
$return = call_user_func_array($callback, $arguments);
if ($return === $noneValue) {
return None::create();
}
return new Some($return);
});
} | [
"public",
"static",
"function",
"fromReturn",
"(",
"$",
"callback",
",",
"array",
"$",
"arguments",
"=",
"array",
"(",
")",
",",
"$",
"noneValue",
"=",
"null",
")",
"{",
"return",
"new",
"LazyOption",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"callba... | Creates a lazy-option with the given callback.
This is also a helper constructor for lazy-consuming existing APIs where
the return value is not yet an option. By default, we treat ``null`` as
None case, and everything else as Some.
@param callable $callback The callback to evaluate.
@param array $arguments
@param mixed $noneValue The value which should be considered "None"; null
by default.
@return Option | [
"Creates",
"a",
"lazy",
"-",
"option",
"with",
"the",
"given",
"callback",
"."
] | train | https://github.com/schmittjoh/php-option/blob/94e644f7d2051a5f0fcf77d81605f152eecff0ed/src/PhpOption/Option.php#L88-L99 |
schmittjoh/php-option | src/PhpOption/Option.php | Option.ensure | public static function ensure($value, $noneValue = null)
{
if ($value instanceof Option) {
return $value;
} elseif ($value instanceof \Closure) {
return new LazyOption(function() use ($value, $noneValue) {
$return = $value();
if ($return instanceof Option) {
return $return;
} else {
return Option::fromValue($return, $noneValue);
}
});
} else {
return Option::fromValue($value, $noneValue);
}
} | php | public static function ensure($value, $noneValue = null)
{
if ($value instanceof Option) {
return $value;
} elseif ($value instanceof \Closure) {
return new LazyOption(function() use ($value, $noneValue) {
$return = $value();
if ($return instanceof Option) {
return $return;
} else {
return Option::fromValue($return, $noneValue);
}
});
} else {
return Option::fromValue($value, $noneValue);
}
} | [
"public",
"static",
"function",
"ensure",
"(",
"$",
"value",
",",
"$",
"noneValue",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"value",
"instanceof",
"Option",
")",
"{",
"return",
"$",
"value",
";",
"}",
"elseif",
"(",
"$",
"value",
"instanceof",
"\\",
"... | Option factory, which creates new option based on passed value.
If value is already an option, it simply returns
If value is a \Closure, LazyOption with passed callback created and returned. If Option returned from callback,
it returns directly (flatMap-like behaviour)
On other case value passed to Option::fromValue() method
@param Option|\Closure|mixed $value
@param null $noneValue used when $value is mixed or Closure, for None-check
@return Option | [
"Option",
"factory",
"which",
"creates",
"new",
"option",
"based",
"on",
"passed",
"value",
".",
"If",
"value",
"is",
"already",
"an",
"option",
"it",
"simply",
"returns",
"If",
"value",
"is",
"a",
"\\",
"Closure",
"LazyOption",
"with",
"passed",
"callback",... | train | https://github.com/schmittjoh/php-option/blob/94e644f7d2051a5f0fcf77d81605f152eecff0ed/src/PhpOption/Option.php#L113-L130 |
laravel/nexmo-notification-channel | src/NexmoChannelServiceProvider.php | NexmoChannelServiceProvider.register | public function register()
{
Notification::resolved(function (ChannelManager $service) {
$service->extend('nexmo', function ($app) {
return new Channels\NexmoSmsChannel(
new NexmoClient(new NexmoCredentials(
$this->app['config']['services.nexmo.key'],
$this->app['config']['services.nexmo.secret']
)),
$this->app['config']['services.nexmo.sms_from']
);
});
});
} | php | public function register()
{
Notification::resolved(function (ChannelManager $service) {
$service->extend('nexmo', function ($app) {
return new Channels\NexmoSmsChannel(
new NexmoClient(new NexmoCredentials(
$this->app['config']['services.nexmo.key'],
$this->app['config']['services.nexmo.secret']
)),
$this->app['config']['services.nexmo.sms_from']
);
});
});
} | [
"public",
"function",
"register",
"(",
")",
"{",
"Notification",
"::",
"resolved",
"(",
"function",
"(",
"ChannelManager",
"$",
"service",
")",
"{",
"$",
"service",
"->",
"extend",
"(",
"'nexmo'",
",",
"function",
"(",
"$",
"app",
")",
"{",
"return",
"ne... | Register the service provider.
@return void | [
"Register",
"the",
"service",
"provider",
"."
] | train | https://github.com/laravel/nexmo-notification-channel/blob/8c2157d35a73e45e52c3aae7323df04728615d19/src/NexmoChannelServiceProvider.php#L17-L30 |
namshi/jose | src/Namshi/JOSE/SimpleJWS.php | SimpleJWS.isValid | public function isValid($key, $algo = null)
{
return $this->verify($key, $algo) && !$this->isExpired();
} | php | public function isValid($key, $algo = null)
{
return $this->verify($key, $algo) && !$this->isExpired();
} | [
"public",
"function",
"isValid",
"(",
"$",
"key",
",",
"$",
"algo",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"verify",
"(",
"$",
"key",
",",
"$",
"algo",
")",
"&&",
"!",
"$",
"this",
"->",
"isExpired",
"(",
")",
";",
"}"
] | Checks that the JWS has been signed with a valid private key by verifying it with a public $key
and the token is not expired.
@param resource|string $key
@param string $algo The algorithms this JWS should be signed with. Use it if you want to restrict which algorithms you want to allow to be validated.
@return bool | [
"Checks",
"that",
"the",
"JWS",
"has",
"been",
"signed",
"with",
"a",
"valid",
"private",
"key",
"by",
"verifying",
"it",
"with",
"a",
"public",
"$key",
"and",
"the",
"token",
"is",
"not",
"expired",
"."
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/SimpleJWS.php#L53-L56 |
namshi/jose | src/Namshi/JOSE/SimpleJWS.php | SimpleJWS.isExpired | public function isExpired()
{
$payload = $this->getPayload();
if (isset($payload['exp'])) {
$now = new \DateTime('now');
if (is_int($payload['exp'])) {
return ($now->getTimestamp() - $payload['exp']) > 0;
}
if (is_numeric($payload['exp'])) {
return ($now->format('U') - $payload['exp']) > 0;
}
}
return false;
} | php | public function isExpired()
{
$payload = $this->getPayload();
if (isset($payload['exp'])) {
$now = new \DateTime('now');
if (is_int($payload['exp'])) {
return ($now->getTimestamp() - $payload['exp']) > 0;
}
if (is_numeric($payload['exp'])) {
return ($now->format('U') - $payload['exp']) > 0;
}
}
return false;
} | [
"public",
"function",
"isExpired",
"(",
")",
"{",
"$",
"payload",
"=",
"$",
"this",
"->",
"getPayload",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"payload",
"[",
"'exp'",
"]",
")",
")",
"{",
"$",
"now",
"=",
"new",
"\\",
"DateTime",
"(",
"'now... | Checks whether the token is expired based on the 'exp' value.
it.
@return bool | [
"Checks",
"whether",
"the",
"token",
"is",
"expired",
"based",
"on",
"the",
"exp",
"value",
".",
"it",
"."
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/SimpleJWS.php#L64-L81 |
namshi/jose | src/Namshi/JOSE/Signer/OpenSSL/ECDSA.php | ECDSA.supportsKey | protected function supportsKey($key)
{
if (false === parent::supportsKey($key)) {
return false;
}
// openssl_sign with EC keys was introduced in this PHP release
$minVersions = array(
'5.4' => '5.4.26',
'5.5' => '5.5.10',
'5.6' => '5.6.0',
);
if (isset($minVersions[PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION]) &&
version_compare(PHP_VERSION, $minVersions[PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION], '<')) {
return false;
}
$keyDetails = openssl_pkey_get_details($key);
if (0 === preg_match('/-----BEGIN PUBLIC KEY-----([^-]+)-----END PUBLIC KEY-----/', $keyDetails['key'], $matches)) {
return false;
}
$publicKey = trim($matches[1]);
$asn1 = new ASN1();
/*
* http://tools.ietf.org/html/rfc3279#section-2.2.3
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL
* }
* For ECDSA Signature Algorithm:
* algorithm: ansi-X9-62 => 1.2.840.10045.2.1
* parameters: id-ecSigType => 1.2.840.10045.x.y.z
*
*/
$asnAlgorithmIdentifier = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'ansi-X9-62' => array(
'type' => ASN1::TYPE_OBJECT_IDENTIFIER,
),
'id-ecSigType' => array(
'type' => ASN1::TYPE_OBJECT_IDENTIFIER,
),
),
);
/*
* http://tools.ietf.org/html/rfc5280#section-4.1
* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING
* }
*/
$asnSubjectPublicKeyInfo = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'algorithm' => $asnAlgorithmIdentifier,
'subjectPublicKey' => array(
'type' => ASN1::TYPE_BIT_STRING,
),
),
);
$decoded = $asn1->decodeBER(base64_decode($publicKey));
$mappedDetails = $asn1->asn1map($decoded[0], $asnSubjectPublicKeyInfo);
return isset($mappedDetails['algorithm']['id-ecSigType']) ? $this->getSupportedECDSACurve() === $mappedDetails['algorithm']['id-ecSigType'] : false;
} | php | protected function supportsKey($key)
{
if (false === parent::supportsKey($key)) {
return false;
}
// openssl_sign with EC keys was introduced in this PHP release
$minVersions = array(
'5.4' => '5.4.26',
'5.5' => '5.5.10',
'5.6' => '5.6.0',
);
if (isset($minVersions[PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION]) &&
version_compare(PHP_VERSION, $minVersions[PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION], '<')) {
return false;
}
$keyDetails = openssl_pkey_get_details($key);
if (0 === preg_match('/-----BEGIN PUBLIC KEY-----([^-]+)-----END PUBLIC KEY-----/', $keyDetails['key'], $matches)) {
return false;
}
$publicKey = trim($matches[1]);
$asn1 = new ASN1();
/*
* http://tools.ietf.org/html/rfc3279#section-2.2.3
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL
* }
* For ECDSA Signature Algorithm:
* algorithm: ansi-X9-62 => 1.2.840.10045.2.1
* parameters: id-ecSigType => 1.2.840.10045.x.y.z
*
*/
$asnAlgorithmIdentifier = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'ansi-X9-62' => array(
'type' => ASN1::TYPE_OBJECT_IDENTIFIER,
),
'id-ecSigType' => array(
'type' => ASN1::TYPE_OBJECT_IDENTIFIER,
),
),
);
/*
* http://tools.ietf.org/html/rfc5280#section-4.1
* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING
* }
*/
$asnSubjectPublicKeyInfo = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'algorithm' => $asnAlgorithmIdentifier,
'subjectPublicKey' => array(
'type' => ASN1::TYPE_BIT_STRING,
),
),
);
$decoded = $asn1->decodeBER(base64_decode($publicKey));
$mappedDetails = $asn1->asn1map($decoded[0], $asnSubjectPublicKeyInfo);
return isset($mappedDetails['algorithm']['id-ecSigType']) ? $this->getSupportedECDSACurve() === $mappedDetails['algorithm']['id-ecSigType'] : false;
} | [
"protected",
"function",
"supportsKey",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"false",
"===",
"parent",
"::",
"supportsKey",
"(",
"$",
"key",
")",
")",
"{",
"return",
"false",
";",
"}",
"// openssl_sign with EC keys was introduced in this PHP release",
"$",
"min... | {@inheritdoc} | [
"{"
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/Signer/OpenSSL/ECDSA.php#L22-L92 |
namshi/jose | src/Namshi/JOSE/JWS.php | JWS.sign | public function sign($key, $password = null)
{
$this->signature = $this->getSigner()->sign($this->generateSigninInput(), $key, $password);
$this->isSigned = true;
return $this->signature;
} | php | public function sign($key, $password = null)
{
$this->signature = $this->getSigner()->sign($this->generateSigninInput(), $key, $password);
$this->isSigned = true;
return $this->signature;
} | [
"public",
"function",
"sign",
"(",
"$",
"key",
",",
"$",
"password",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"signature",
"=",
"$",
"this",
"->",
"getSigner",
"(",
")",
"->",
"sign",
"(",
"$",
"this",
"->",
"generateSigninInput",
"(",
")",
",",
"... | Signs the JWS signininput.
@param resource|string $key
@param optional string $password
@return string | [
"Signs",
"the",
"JWS",
"signininput",
"."
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/JWS.php#L58-L64 |
namshi/jose | src/Namshi/JOSE/JWS.php | JWS.getTokenString | public function getTokenString()
{
$signinInput = $this->generateSigninInput();
return sprintf('%s.%s', $signinInput, $this->encoder->encode($this->getSignature()));
} | php | public function getTokenString()
{
$signinInput = $this->generateSigninInput();
return sprintf('%s.%s', $signinInput, $this->encoder->encode($this->getSignature()));
} | [
"public",
"function",
"getTokenString",
"(",
")",
"{",
"$",
"signinInput",
"=",
"$",
"this",
"->",
"generateSigninInput",
"(",
")",
";",
"return",
"sprintf",
"(",
"'%s.%s'",
",",
"$",
"signinInput",
",",
"$",
"this",
"->",
"encoder",
"->",
"encode",
"(",
... | Returns the string representing the JWT.
@return string | [
"Returns",
"the",
"string",
"representing",
"the",
"JWT",
"."
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/JWS.php#L95-L100 |
namshi/jose | src/Namshi/JOSE/JWS.php | JWS.load | public static function load($jwsTokenString, $allowUnsecure = false, Encoder $encoder = null, $encryptionEngine = 'OpenSSL')
{
if ($encoder === null) {
$encoder = strpbrk($jwsTokenString, '+/=') ? new Base64Encoder() : new Base64UrlSafeEncoder();
}
$parts = explode('.', $jwsTokenString);
if (count($parts) === 3) {
$header = json_decode($encoder->decode($parts[0]), true);
$payload = json_decode($encoder->decode($parts[1]), true);
if (is_array($header) && is_array($payload)) {
if (strtolower($header['alg']) === 'none' && !$allowUnsecure) {
throw new InvalidArgumentException(sprintf('The token "%s" cannot be validated in a secure context, as it uses the unallowed "none" algorithm', $jwsTokenString));
}
$jws = new static($header, $encryptionEngine);
$jws->setEncoder($encoder)
->setHeader($header)
->setPayload($payload)
->setOriginalToken($jwsTokenString)
->setEncodedSignature($parts[2]);
return $jws;
}
}
throw new InvalidArgumentException(sprintf('The token "%s" is an invalid JWS', $jwsTokenString));
} | php | public static function load($jwsTokenString, $allowUnsecure = false, Encoder $encoder = null, $encryptionEngine = 'OpenSSL')
{
if ($encoder === null) {
$encoder = strpbrk($jwsTokenString, '+/=') ? new Base64Encoder() : new Base64UrlSafeEncoder();
}
$parts = explode('.', $jwsTokenString);
if (count($parts) === 3) {
$header = json_decode($encoder->decode($parts[0]), true);
$payload = json_decode($encoder->decode($parts[1]), true);
if (is_array($header) && is_array($payload)) {
if (strtolower($header['alg']) === 'none' && !$allowUnsecure) {
throw new InvalidArgumentException(sprintf('The token "%s" cannot be validated in a secure context, as it uses the unallowed "none" algorithm', $jwsTokenString));
}
$jws = new static($header, $encryptionEngine);
$jws->setEncoder($encoder)
->setHeader($header)
->setPayload($payload)
->setOriginalToken($jwsTokenString)
->setEncodedSignature($parts[2]);
return $jws;
}
}
throw new InvalidArgumentException(sprintf('The token "%s" is an invalid JWS', $jwsTokenString));
} | [
"public",
"static",
"function",
"load",
"(",
"$",
"jwsTokenString",
",",
"$",
"allowUnsecure",
"=",
"false",
",",
"Encoder",
"$",
"encoder",
"=",
"null",
",",
"$",
"encryptionEngine",
"=",
"'OpenSSL'",
")",
"{",
"if",
"(",
"$",
"encoder",
"===",
"null",
... | Creates an instance of a JWS from a JWT.
@param string $jwsTokenString
@param bool $allowUnsecure
@param Encoder $encoder
@param string $encryptionEngine
@return JWS
@throws \InvalidArgumentException | [
"Creates",
"an",
"instance",
"of",
"a",
"JWS",
"from",
"a",
"JWT",
"."
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/JWS.php#L114-L144 |
namshi/jose | src/Namshi/JOSE/JWS.php | JWS.verify | public function verify($key, $algo = null)
{
if (empty($key) || ($algo && $this->header['alg'] !== $algo)) {
return false;
}
$decodedSignature = $this->encoder->decode($this->getEncodedSignature());
$signinInput = $this->getSigninInput();
return $this->getSigner()->verify($key, $decodedSignature, $signinInput);
} | php | public function verify($key, $algo = null)
{
if (empty($key) || ($algo && $this->header['alg'] !== $algo)) {
return false;
}
$decodedSignature = $this->encoder->decode($this->getEncodedSignature());
$signinInput = $this->getSigninInput();
return $this->getSigner()->verify($key, $decodedSignature, $signinInput);
} | [
"public",
"function",
"verify",
"(",
"$",
"key",
",",
"$",
"algo",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"key",
")",
"||",
"(",
"$",
"algo",
"&&",
"$",
"this",
"->",
"header",
"[",
"'alg'",
"]",
"!==",
"$",
"algo",
")",
")",
"{... | Verifies that the internal signin input corresponds to the encoded
signature previously stored (@see JWS::load).
@param resource|string $key
@param string $algo The algorithms this JWS should be signed with. Use it if you want to restrict which algorithms you want to allow to be validated.
@return bool | [
"Verifies",
"that",
"the",
"internal",
"signin",
"input",
"corresponds",
"to",
"the",
"encoded",
"signature",
"previously",
"stored",
"(",
"@see",
"JWS",
"::",
"load",
")",
"."
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/JWS.php#L155-L165 |
namshi/jose | src/Namshi/JOSE/JWS.php | JWS.getSigninInput | private function getSigninInput()
{
$parts = explode('.', $this->originalToken);
if (count($parts) >= 2) {
return sprintf('%s.%s', $parts[0], $parts[1]);
}
return $this->generateSigninInput();
} | php | private function getSigninInput()
{
$parts = explode('.', $this->originalToken);
if (count($parts) >= 2) {
return sprintf('%s.%s', $parts[0], $parts[1]);
}
return $this->generateSigninInput();
} | [
"private",
"function",
"getSigninInput",
"(",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"'.'",
",",
"$",
"this",
"->",
"originalToken",
")",
";",
"if",
"(",
"count",
"(",
"$",
"parts",
")",
">=",
"2",
")",
"{",
"return",
"sprintf",
"(",
"'%s.%s'",... | Get the original token signin input if it exists, otherwise generate the
signin input for the current JWS
@return string | [
"Get",
"the",
"original",
"token",
"signin",
"input",
"if",
"it",
"exists",
"otherwise",
"generate",
"the",
"signin",
"input",
"for",
"the",
"current",
"JWS"
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/JWS.php#L173-L182 |
namshi/jose | src/Namshi/JOSE/JWS.php | JWS.getSigner | protected function getSigner()
{
$signerClass = sprintf('Namshi\\JOSE\\Signer\\%s\\%s', $this->encryptionEngine, $this->header['alg']);
if (class_exists($signerClass)) {
return new $signerClass();
}
throw new InvalidArgumentException(
sprintf("The algorithm '%s' is not supported for %s", $this->header['alg'], $this->encryptionEngine));
} | php | protected function getSigner()
{
$signerClass = sprintf('Namshi\\JOSE\\Signer\\%s\\%s', $this->encryptionEngine, $this->header['alg']);
if (class_exists($signerClass)) {
return new $signerClass();
}
throw new InvalidArgumentException(
sprintf("The algorithm '%s' is not supported for %s", $this->header['alg'], $this->encryptionEngine));
} | [
"protected",
"function",
"getSigner",
"(",
")",
"{",
"$",
"signerClass",
"=",
"sprintf",
"(",
"'Namshi\\\\JOSE\\\\Signer\\\\%s\\\\%s'",
",",
"$",
"this",
"->",
"encryptionEngine",
",",
"$",
"this",
"->",
"header",
"[",
"'alg'",
"]",
")",
";",
"if",
"(",
"cla... | Returns the signer responsible to encrypting / decrypting this JWS.
@return SignerInterface
@throws \InvalidArgumentException | [
"Returns",
"the",
"signer",
"responsible",
"to",
"encrypting",
"/",
"decrypting",
"this",
"JWS",
"."
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/JWS.php#L229-L239 |
namshi/jose | src/Namshi/JOSE/JWT.php | JWT.generateSigninInput | public function generateSigninInput()
{
$base64payload = $this->encoder->encode(json_encode($this->getPayload(), JSON_UNESCAPED_SLASHES));
$base64header = $this->encoder->encode(json_encode($this->getHeader(), JSON_UNESCAPED_SLASHES));
return sprintf('%s.%s', $base64header, $base64payload);
} | php | public function generateSigninInput()
{
$base64payload = $this->encoder->encode(json_encode($this->getPayload(), JSON_UNESCAPED_SLASHES));
$base64header = $this->encoder->encode(json_encode($this->getHeader(), JSON_UNESCAPED_SLASHES));
return sprintf('%s.%s', $base64header, $base64payload);
} | [
"public",
"function",
"generateSigninInput",
"(",
")",
"{",
"$",
"base64payload",
"=",
"$",
"this",
"->",
"encoder",
"->",
"encode",
"(",
"json_encode",
"(",
"$",
"this",
"->",
"getPayload",
"(",
")",
",",
"JSON_UNESCAPED_SLASHES",
")",
")",
";",
"$",
"bas... | Generates the signininput for the current JWT.
@return string | [
"Generates",
"the",
"signininput",
"for",
"the",
"current",
"JWT",
"."
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/JWT.php#L56-L62 |
namshi/jose | src/Namshi/JOSE/Signer/SecLib/PublicKey.php | PublicKey.sign | public function sign($input, $key, $password = null)
{
if ($password) {
$this->encryptionAlgorithm->setPassword($password);
}
if (!$this->encryptionAlgorithm->loadKey($key)) {
throw new InvalidArgumentException('Invalid key supplied.');
}
return $this->encryptionAlgorithm->sign($input);
} | php | public function sign($input, $key, $password = null)
{
if ($password) {
$this->encryptionAlgorithm->setPassword($password);
}
if (!$this->encryptionAlgorithm->loadKey($key)) {
throw new InvalidArgumentException('Invalid key supplied.');
}
return $this->encryptionAlgorithm->sign($input);
} | [
"public",
"function",
"sign",
"(",
"$",
"input",
",",
"$",
"key",
",",
"$",
"password",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"password",
")",
"{",
"$",
"this",
"->",
"encryptionAlgorithm",
"->",
"setPassword",
"(",
"$",
"password",
")",
";",
"}",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/Signer/SecLib/PublicKey.php#L15-L26 |
namshi/jose | src/Namshi/JOSE/Signer/SecLib/PublicKey.php | PublicKey.verify | public function verify($key, $signature, $input)
{
if (!$this->encryptionAlgorithm->loadKey($key)) {
throw new InvalidArgumentException('Invalid key supplied.');
}
return $this->encryptionAlgorithm->verify($input, $signature);
} | php | public function verify($key, $signature, $input)
{
if (!$this->encryptionAlgorithm->loadKey($key)) {
throw new InvalidArgumentException('Invalid key supplied.');
}
return $this->encryptionAlgorithm->verify($input, $signature);
} | [
"public",
"function",
"verify",
"(",
"$",
"key",
",",
"$",
"signature",
",",
"$",
"input",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"encryptionAlgorithm",
"->",
"loadKey",
"(",
"$",
"key",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/Signer/SecLib/PublicKey.php#L31-L38 |
namshi/jose | src/Namshi/JOSE/Signer/OpenSSL/HMAC.php | HMAC.sign | public function sign($input, $key)
{
return hash_hmac($this->getHashingAlgorithm(), $input, (string) $key, true);
} | php | public function sign($input, $key)
{
return hash_hmac($this->getHashingAlgorithm(), $input, (string) $key, true);
} | [
"public",
"function",
"sign",
"(",
"$",
"input",
",",
"$",
"key",
")",
"{",
"return",
"hash_hmac",
"(",
"$",
"this",
"->",
"getHashingAlgorithm",
"(",
")",
",",
"$",
"input",
",",
"(",
"string",
")",
"$",
"key",
",",
"true",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/Signer/OpenSSL/HMAC.php#L15-L18 |
namshi/jose | src/Namshi/JOSE/Signer/OpenSSL/HMAC.php | HMAC.verify | public function verify($key, $signature, $input)
{
$signedInput = $this->sign($input, $key);
return $this->timingSafeEquals($signedInput, $signature);
} | php | public function verify($key, $signature, $input)
{
$signedInput = $this->sign($input, $key);
return $this->timingSafeEquals($signedInput, $signature);
} | [
"public",
"function",
"verify",
"(",
"$",
"key",
",",
"$",
"signature",
",",
"$",
"input",
")",
"{",
"$",
"signedInput",
"=",
"$",
"this",
"->",
"sign",
"(",
"$",
"input",
",",
"$",
"key",
")",
";",
"return",
"$",
"this",
"->",
"timingSafeEquals",
... | To prevent timing attacks we are using PHP 5.6 native function hash_equals,
in case of PHP < 5.6 a timing safe equals comparison function.
more info here:
http://blog.ircmaxell.com/2014/11/its-all-about-time.html
{@inheritdoc} | [
"To",
"prevent",
"timing",
"attacks",
"we",
"are",
"using",
"PHP",
"5",
".",
"6",
"native",
"function",
"hash_equals",
"in",
"case",
"of",
"PHP",
"<",
"5",
".",
"6",
"a",
"timing",
"safe",
"equals",
"comparison",
"function",
"."
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/Signer/OpenSSL/HMAC.php#L30-L35 |
namshi/jose | src/Namshi/JOSE/Signer/OpenSSL/PublicKey.php | PublicKey.sign | public function sign($input, $key, $password = null)
{
$keyResource = $this->getKeyResource($key, $password);
if (!$this->supportsKey($keyResource)) {
throw new InvalidArgumentException('Invalid key supplied.');
}
$signature = null;
openssl_sign($input, $signature, $keyResource, $this->getHashingAlgorithm());
return $signature;
} | php | public function sign($input, $key, $password = null)
{
$keyResource = $this->getKeyResource($key, $password);
if (!$this->supportsKey($keyResource)) {
throw new InvalidArgumentException('Invalid key supplied.');
}
$signature = null;
openssl_sign($input, $signature, $keyResource, $this->getHashingAlgorithm());
return $signature;
} | [
"public",
"function",
"sign",
"(",
"$",
"input",
",",
"$",
"key",
",",
"$",
"password",
"=",
"null",
")",
"{",
"$",
"keyResource",
"=",
"$",
"this",
"->",
"getKeyResource",
"(",
"$",
"key",
",",
"$",
"password",
")",
";",
"if",
"(",
"!",
"$",
"th... | {@inheritdoc} | [
"{"
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/Signer/OpenSSL/PublicKey.php#L17-L28 |
namshi/jose | src/Namshi/JOSE/Signer/OpenSSL/PublicKey.php | PublicKey.verify | public function verify($key, $signature, $input)
{
$keyResource = $this->getKeyResource($key);
if (!$this->supportsKey($keyResource)) {
throw new InvalidArgumentException('Invalid key supplied.');
}
$result = openssl_verify($input, $signature, $keyResource, $this->getHashingAlgorithm());
if ($result === -1) {
throw new RuntimeException('Unknown error during verification.');
}
return (bool) $result;
} | php | public function verify($key, $signature, $input)
{
$keyResource = $this->getKeyResource($key);
if (!$this->supportsKey($keyResource)) {
throw new InvalidArgumentException('Invalid key supplied.');
}
$result = openssl_verify($input, $signature, $keyResource, $this->getHashingAlgorithm());
if ($result === -1) {
throw new RuntimeException('Unknown error during verification.');
}
return (bool) $result;
} | [
"public",
"function",
"verify",
"(",
"$",
"key",
",",
"$",
"signature",
",",
"$",
"input",
")",
"{",
"$",
"keyResource",
"=",
"$",
"this",
"->",
"getKeyResource",
"(",
"$",
"key",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"supportsKey",
"(",
"$"... | {@inheritdoc} | [
"{"
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/Signer/OpenSSL/PublicKey.php#L33-L47 |
namshi/jose | src/Namshi/JOSE/Signer/OpenSSL/PublicKey.php | PublicKey.getKeyResource | protected function getKeyResource($key, $password = null)
{
if (is_resource($key)) {
return $key;
}
$resource = openssl_pkey_get_public($key) ?: openssl_pkey_get_private($key, $password);
if ($resource === false) {
throw new RuntimeException('Could not read key resource: ' . openssl_error_string());
}
return $resource;
} | php | protected function getKeyResource($key, $password = null)
{
if (is_resource($key)) {
return $key;
}
$resource = openssl_pkey_get_public($key) ?: openssl_pkey_get_private($key, $password);
if ($resource === false) {
throw new RuntimeException('Could not read key resource: ' . openssl_error_string());
}
return $resource;
} | [
"protected",
"function",
"getKeyResource",
"(",
"$",
"key",
",",
"$",
"password",
"=",
"null",
")",
"{",
"if",
"(",
"is_resource",
"(",
"$",
"key",
")",
")",
"{",
"return",
"$",
"key",
";",
"}",
"$",
"resource",
"=",
"openssl_pkey_get_public",
"(",
"$"... | Converts a string representation of a key into an OpenSSL resource.
@param string|resource $key
@param string $password
@return resource OpenSSL key resource | [
"Converts",
"a",
"string",
"representation",
"of",
"a",
"key",
"into",
"an",
"OpenSSL",
"resource",
"."
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/Signer/OpenSSL/PublicKey.php#L57-L68 |
namshi/jose | src/Namshi/JOSE/Signer/OpenSSL/PublicKey.php | PublicKey.supportsKey | protected function supportsKey($key)
{
// OpenSSL 0.9.8+
$keyDetails = openssl_pkey_get_details($key);
return isset($keyDetails['type']) ? $this->getSupportedPrivateKeyType() === $keyDetails['type'] : false;
} | php | protected function supportsKey($key)
{
// OpenSSL 0.9.8+
$keyDetails = openssl_pkey_get_details($key);
return isset($keyDetails['type']) ? $this->getSupportedPrivateKeyType() === $keyDetails['type'] : false;
} | [
"protected",
"function",
"supportsKey",
"(",
"$",
"key",
")",
"{",
"// OpenSSL 0.9.8+",
"$",
"keyDetails",
"=",
"openssl_pkey_get_details",
"(",
"$",
"key",
")",
";",
"return",
"isset",
"(",
"$",
"keyDetails",
"[",
"'type'",
"]",
")",
"?",
"$",
"this",
"->... | Check if the key is supported by this signer.
@param resource $key Public or private key
@return bool | [
"Check",
"if",
"the",
"key",
"is",
"supported",
"by",
"this",
"signer",
"."
] | train | https://github.com/namshi/jose/blob/188f6e0361436a6afc3d077741820ff86a7eb204/src/Namshi/JOSE/Signer/OpenSSL/PublicKey.php#L77-L83 |
jmespath/jmespath.php | src/Utils.php | Utils.isTruthy | public static function isTruthy($value)
{
if (!$value) {
return $value === 0 || $value === '0';
} elseif ($value instanceof \stdClass) {
return (bool) get_object_vars($value);
} else {
return true;
}
} | php | public static function isTruthy($value)
{
if (!$value) {
return $value === 0 || $value === '0';
} elseif ($value instanceof \stdClass) {
return (bool) get_object_vars($value);
} else {
return true;
}
} | [
"public",
"static",
"function",
"isTruthy",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"$",
"value",
")",
"{",
"return",
"$",
"value",
"===",
"0",
"||",
"$",
"value",
"===",
"'0'",
";",
"}",
"elseif",
"(",
"$",
"value",
"instanceof",
"\\",
"stdCl... | Returns true if the value is truthy
@param mixed $value Value to check
@return bool | [
"Returns",
"true",
"if",
"the",
"value",
"is",
"truthy"
] | train | https://github.com/jmespath/jmespath.php/blob/adcc9531682cf87dfda21e1fd5d0e7a41d292fac/src/Utils.php#L22-L31 |
jmespath/jmespath.php | src/Utils.php | Utils.isArray | public static function isArray($value)
{
if (is_array($value)) {
return !$value || array_keys($value)[0] === 0;
}
// Handle array-like values. Must be empty or offset 0 exists.
return $value instanceof \Countable && $value instanceof \ArrayAccess
? count($value) == 0 || $value->offsetExists(0)
: false;
} | php | public static function isArray($value)
{
if (is_array($value)) {
return !$value || array_keys($value)[0] === 0;
}
// Handle array-like values. Must be empty or offset 0 exists.
return $value instanceof \Countable && $value instanceof \ArrayAccess
? count($value) == 0 || $value->offsetExists(0)
: false;
} | [
"public",
"static",
"function",
"isArray",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"return",
"!",
"$",
"value",
"||",
"array_keys",
"(",
"$",
"value",
")",
"[",
"0",
"]",
"===",
"0",
";",
"}",
"// Han... | Determine if the provided value is a JMESPath compatible array.
@param mixed $value
@return bool | [
"Determine",
"if",
"the",
"provided",
"value",
"is",
"a",
"JMESPath",
"compatible",
"array",
"."
] | train | https://github.com/jmespath/jmespath.php/blob/adcc9531682cf87dfda21e1fd5d0e7a41d292fac/src/Utils.php#L96-L106 |
jmespath/jmespath.php | src/Utils.php | Utils.isEqual | public static function isEqual($a, $b)
{
if ($a === $b) {
return true;
} elseif ($a instanceof \stdClass) {
return self::isEqual((array) $a, $b);
} elseif ($b instanceof \stdClass) {
return self::isEqual($a, (array) $b);
} else {
return false;
}
} | php | public static function isEqual($a, $b)
{
if ($a === $b) {
return true;
} elseif ($a instanceof \stdClass) {
return self::isEqual((array) $a, $b);
} elseif ($b instanceof \stdClass) {
return self::isEqual($a, (array) $b);
} else {
return false;
}
} | [
"public",
"static",
"function",
"isEqual",
"(",
"$",
"a",
",",
"$",
"b",
")",
"{",
"if",
"(",
"$",
"a",
"===",
"$",
"b",
")",
"{",
"return",
"true",
";",
"}",
"elseif",
"(",
"$",
"a",
"instanceof",
"\\",
"stdClass",
")",
"{",
"return",
"self",
... | JSON aware value comparison function.
@param mixed $a First value to compare
@param mixed $b Second value to compare
@return bool | [
"JSON",
"aware",
"value",
"comparison",
"function",
"."
] | train | https://github.com/jmespath/jmespath.php/blob/adcc9531682cf87dfda21e1fd5d0e7a41d292fac/src/Utils.php#L116-L127 |
jmespath/jmespath.php | src/Utils.php | Utils.slice | public static function slice($value, $start = null, $stop = null, $step = 1)
{
if (!is_array($value) && !is_string($value)) {
throw new \InvalidArgumentException('Expects string or array');
}
return self::sliceIndices($value, $start, $stop, $step);
} | php | public static function slice($value, $start = null, $stop = null, $step = 1)
{
if (!is_array($value) && !is_string($value)) {
throw new \InvalidArgumentException('Expects string or array');
}
return self::sliceIndices($value, $start, $stop, $step);
} | [
"public",
"static",
"function",
"slice",
"(",
"$",
"value",
",",
"$",
"start",
"=",
"null",
",",
"$",
"stop",
"=",
"null",
",",
"$",
"step",
"=",
"1",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"value",
")",
"&&",
"!",
"is_string",
"(",
"$... | Creates a Python-style slice of a string or array.
@param array|string $value Value to slice
@param int|null $start Starting position
@param int|null $stop Stop position
@param int $step Step (1, 2, -1, -2, etc.)
@return array|string
@throws \InvalidArgumentException | [
"Creates",
"a",
"Python",
"-",
"style",
"slice",
"of",
"a",
"string",
"or",
"array",
"."
] | train | https://github.com/jmespath/jmespath.php/blob/adcc9531682cf87dfda21e1fd5d0e7a41d292fac/src/Utils.php#L164-L171 |
jmespath/jmespath.php | src/TreeInterpreter.php | TreeInterpreter.dispatch | private function dispatch(array $node, $value)
{
$dispatcher = $this->fnDispatcher;
switch ($node['type']) {
case 'field':
if (is_array($value) || $value instanceof \ArrayAccess) {
return isset($value[$node['value']]) ? $value[$node['value']] : null;
} elseif ($value instanceof \stdClass) {
return isset($value->{$node['value']}) ? $value->{$node['value']} : null;
}
return null;
case 'subexpression':
return $this->dispatch(
$node['children'][1],
$this->dispatch($node['children'][0], $value)
);
case 'index':
if (!Utils::isArray($value)) {
return null;
}
$idx = $node['value'] >= 0
? $node['value']
: $node['value'] + count($value);
return isset($value[$idx]) ? $value[$idx] : null;
case 'projection':
$left = $this->dispatch($node['children'][0], $value);
switch ($node['from']) {
case 'object':
if (!Utils::isObject($left)) {
return null;
}
break;
case 'array':
if (!Utils::isArray($left)) {
return null;
}
break;
default:
if (!is_array($left) || !($left instanceof \stdClass)) {
return null;
}
}
$collected = [];
foreach ((array) $left as $val) {
$result = $this->dispatch($node['children'][1], $val);
if ($result !== null) {
$collected[] = $result;
}
}
return $collected;
case 'flatten':
static $skipElement = [];
$value = $this->dispatch($node['children'][0], $value);
if (!Utils::isArray($value)) {
return null;
}
$merged = [];
foreach ($value as $values) {
// Only merge up arrays lists and not hashes
if (is_array($values) && isset($values[0])) {
$merged = array_merge($merged, $values);
} elseif ($values !== $skipElement) {
$merged[] = $values;
}
}
return $merged;
case 'literal':
return $node['value'];
case 'current':
return $value;
case 'or':
$result = $this->dispatch($node['children'][0], $value);
return Utils::isTruthy($result)
? $result
: $this->dispatch($node['children'][1], $value);
case 'and':
$result = $this->dispatch($node['children'][0], $value);
return Utils::isTruthy($result)
? $this->dispatch($node['children'][1], $value)
: $result;
case 'not':
return !Utils::isTruthy(
$this->dispatch($node['children'][0], $value)
);
case 'pipe':
return $this->dispatch(
$node['children'][1],
$this->dispatch($node['children'][0], $value)
);
case 'multi_select_list':
if ($value === null) {
return null;
}
$collected = [];
foreach ($node['children'] as $node) {
$collected[] = $this->dispatch($node, $value);
}
return $collected;
case 'multi_select_hash':
if ($value === null) {
return null;
}
$collected = [];
foreach ($node['children'] as $node) {
$collected[$node['value']] = $this->dispatch(
$node['children'][0],
$value
);
}
return $collected;
case 'comparator':
$left = $this->dispatch($node['children'][0], $value);
$right = $this->dispatch($node['children'][1], $value);
if ($node['value'] == '==') {
return Utils::isEqual($left, $right);
} elseif ($node['value'] == '!=') {
return !Utils::isEqual($left, $right);
} else {
return self::relativeCmp($left, $right, $node['value']);
}
case 'condition':
return Utils::isTruthy($this->dispatch($node['children'][0], $value))
? $this->dispatch($node['children'][1], $value)
: null;
case 'function':
$args = [];
foreach ($node['children'] as $arg) {
$args[] = $this->dispatch($arg, $value);
}
return $dispatcher($node['value'], $args);
case 'slice':
return is_string($value) || Utils::isArray($value)
? Utils::slice(
$value,
$node['value'][0],
$node['value'][1],
$node['value'][2]
) : null;
case 'expref':
$apply = $node['children'][0];
return function ($value) use ($apply) {
return $this->visit($apply, $value);
};
default:
throw new \RuntimeException("Unknown node type: {$node['type']}");
}
} | php | private function dispatch(array $node, $value)
{
$dispatcher = $this->fnDispatcher;
switch ($node['type']) {
case 'field':
if (is_array($value) || $value instanceof \ArrayAccess) {
return isset($value[$node['value']]) ? $value[$node['value']] : null;
} elseif ($value instanceof \stdClass) {
return isset($value->{$node['value']}) ? $value->{$node['value']} : null;
}
return null;
case 'subexpression':
return $this->dispatch(
$node['children'][1],
$this->dispatch($node['children'][0], $value)
);
case 'index':
if (!Utils::isArray($value)) {
return null;
}
$idx = $node['value'] >= 0
? $node['value']
: $node['value'] + count($value);
return isset($value[$idx]) ? $value[$idx] : null;
case 'projection':
$left = $this->dispatch($node['children'][0], $value);
switch ($node['from']) {
case 'object':
if (!Utils::isObject($left)) {
return null;
}
break;
case 'array':
if (!Utils::isArray($left)) {
return null;
}
break;
default:
if (!is_array($left) || !($left instanceof \stdClass)) {
return null;
}
}
$collected = [];
foreach ((array) $left as $val) {
$result = $this->dispatch($node['children'][1], $val);
if ($result !== null) {
$collected[] = $result;
}
}
return $collected;
case 'flatten':
static $skipElement = [];
$value = $this->dispatch($node['children'][0], $value);
if (!Utils::isArray($value)) {
return null;
}
$merged = [];
foreach ($value as $values) {
// Only merge up arrays lists and not hashes
if (is_array($values) && isset($values[0])) {
$merged = array_merge($merged, $values);
} elseif ($values !== $skipElement) {
$merged[] = $values;
}
}
return $merged;
case 'literal':
return $node['value'];
case 'current':
return $value;
case 'or':
$result = $this->dispatch($node['children'][0], $value);
return Utils::isTruthy($result)
? $result
: $this->dispatch($node['children'][1], $value);
case 'and':
$result = $this->dispatch($node['children'][0], $value);
return Utils::isTruthy($result)
? $this->dispatch($node['children'][1], $value)
: $result;
case 'not':
return !Utils::isTruthy(
$this->dispatch($node['children'][0], $value)
);
case 'pipe':
return $this->dispatch(
$node['children'][1],
$this->dispatch($node['children'][0], $value)
);
case 'multi_select_list':
if ($value === null) {
return null;
}
$collected = [];
foreach ($node['children'] as $node) {
$collected[] = $this->dispatch($node, $value);
}
return $collected;
case 'multi_select_hash':
if ($value === null) {
return null;
}
$collected = [];
foreach ($node['children'] as $node) {
$collected[$node['value']] = $this->dispatch(
$node['children'][0],
$value
);
}
return $collected;
case 'comparator':
$left = $this->dispatch($node['children'][0], $value);
$right = $this->dispatch($node['children'][1], $value);
if ($node['value'] == '==') {
return Utils::isEqual($left, $right);
} elseif ($node['value'] == '!=') {
return !Utils::isEqual($left, $right);
} else {
return self::relativeCmp($left, $right, $node['value']);
}
case 'condition':
return Utils::isTruthy($this->dispatch($node['children'][0], $value))
? $this->dispatch($node['children'][1], $value)
: null;
case 'function':
$args = [];
foreach ($node['children'] as $arg) {
$args[] = $this->dispatch($arg, $value);
}
return $dispatcher($node['value'], $args);
case 'slice':
return is_string($value) || Utils::isArray($value)
? Utils::slice(
$value,
$node['value'][0],
$node['value'][1],
$node['value'][2]
) : null;
case 'expref':
$apply = $node['children'][0];
return function ($value) use ($apply) {
return $this->visit($apply, $value);
};
default:
throw new \RuntimeException("Unknown node type: {$node['type']}");
}
} | [
"private",
"function",
"dispatch",
"(",
"array",
"$",
"node",
",",
"$",
"value",
")",
"{",
"$",
"dispatcher",
"=",
"$",
"this",
"->",
"fnDispatcher",
";",
"switch",
"(",
"$",
"node",
"[",
"'type'",
"]",
")",
"{",
"case",
"'field'",
":",
"if",
"(",
... | Recursively traverses an AST using depth-first, pre-order traversal.
The evaluation logic for each node type is embedded into a large switch
statement to avoid the cost of "double dispatch".
@return mixed | [
"Recursively",
"traverses",
"an",
"AST",
"using",
"depth",
"-",
"first",
"pre",
"-",
"order",
"traversal",
".",
"The",
"evaluation",
"logic",
"for",
"each",
"node",
"type",
"is",
"embedded",
"into",
"a",
"large",
"switch",
"statement",
"to",
"avoid",
"the",
... | train | https://github.com/jmespath/jmespath.php/blob/adcc9531682cf87dfda21e1fd5d0e7a41d292fac/src/TreeInterpreter.php#L41-L216 |
MarkBaker/PHPComplex | classes/src/Complex.php | Complex.parseComplex | private static function parseComplex($complexNumber)
{
// Test for real number, with no imaginary part
if (is_numeric($complexNumber)) {
return [$complexNumber, 0, null];
}
// Fix silly human errors
$complexNumber = str_replace(
['+-', '-+', '++', '--'],
['-', '-', '+', '+'],
$complexNumber
);
// Basic validation of string, to parse out real and imaginary parts, and any suffix
$validComplex = preg_match(
self::NUMBER_SPLIT_REGEXP,
$complexNumber,
$complexParts
);
if (!$validComplex) {
// Neither real nor imaginary part, so test to see if we actually have a suffix
$validComplex = preg_match('/^([\-\+]?)([ij])$/ui', $complexNumber, $complexParts);
if (!$validComplex) {
throw new Exception('Invalid complex number');
}
// We have a suffix, so set the real to 0, the imaginary to either 1 or -1 (as defined by the sign)
$imaginary = 1;
if ($complexParts[1] === '-') {
$imaginary = 0 - $imaginary;
}
return [0, $imaginary, $complexParts[2]];
}
// If we don't have an imaginary part, identify whether it should be +1 or -1...
if (($complexParts[4] === '') && ($complexParts[9] !== '')) {
if ($complexParts[7] !== $complexParts[9]) {
$complexParts[4] = 1;
if ($complexParts[8] === '-') {
$complexParts[4] = -1;
}
} else {
// ... or if we have only the real and no imaginary part
// (in which case our real should be the imaginary)
$complexParts[4] = $complexParts[1];
$complexParts[1] = 0;
}
}
// Return real and imaginary parts and suffix as an array, and set a default suffix if user input lazily
return [
$complexParts[1],
$complexParts[4],
!empty($complexParts[9]) ? $complexParts[9] : 'i'
];
} | php | private static function parseComplex($complexNumber)
{
// Test for real number, with no imaginary part
if (is_numeric($complexNumber)) {
return [$complexNumber, 0, null];
}
// Fix silly human errors
$complexNumber = str_replace(
['+-', '-+', '++', '--'],
['-', '-', '+', '+'],
$complexNumber
);
// Basic validation of string, to parse out real and imaginary parts, and any suffix
$validComplex = preg_match(
self::NUMBER_SPLIT_REGEXP,
$complexNumber,
$complexParts
);
if (!$validComplex) {
// Neither real nor imaginary part, so test to see if we actually have a suffix
$validComplex = preg_match('/^([\-\+]?)([ij])$/ui', $complexNumber, $complexParts);
if (!$validComplex) {
throw new Exception('Invalid complex number');
}
// We have a suffix, so set the real to 0, the imaginary to either 1 or -1 (as defined by the sign)
$imaginary = 1;
if ($complexParts[1] === '-') {
$imaginary = 0 - $imaginary;
}
return [0, $imaginary, $complexParts[2]];
}
// If we don't have an imaginary part, identify whether it should be +1 or -1...
if (($complexParts[4] === '') && ($complexParts[9] !== '')) {
if ($complexParts[7] !== $complexParts[9]) {
$complexParts[4] = 1;
if ($complexParts[8] === '-') {
$complexParts[4] = -1;
}
} else {
// ... or if we have only the real and no imaginary part
// (in which case our real should be the imaginary)
$complexParts[4] = $complexParts[1];
$complexParts[1] = 0;
}
}
// Return real and imaginary parts and suffix as an array, and set a default suffix if user input lazily
return [
$complexParts[1],
$complexParts[4],
!empty($complexParts[9]) ? $complexParts[9] : 'i'
];
} | [
"private",
"static",
"function",
"parseComplex",
"(",
"$",
"complexNumber",
")",
"{",
"// Test for real number, with no imaginary part",
"if",
"(",
"is_numeric",
"(",
"$",
"complexNumber",
")",
")",
"{",
"return",
"[",
"$",
"complexNumber",
",",
"0",
",",
"null",
... | Validates whether the argument is a valid complex number, converting scalar or array values if possible
@param mixed $complexNumber The value to parse
@return array
@throws Exception If the argument isn't a Complex number or cannot be converted to one | [
"Validates",
"whether",
"the",
"argument",
"is",
"a",
"valid",
"complex",
"number",
"converting",
"scalar",
"or",
"array",
"values",
"if",
"possible"
] | train | https://github.com/MarkBaker/PHPComplex/blob/4e20202cd759a3afe0b2f9318d697484fa10ad68/classes/src/Complex.php#L109-L165 |
MarkBaker/PHPComplex | classes/src/Complex.php | Complex.validateComplexArgument | public static function validateComplexArgument($complex)
{
if (is_scalar($complex) || is_array($complex)) {
$complex = new Complex($complex);
} elseif (!is_object($complex) || !($complex instanceof Complex)) {
throw new Exception('Value is not a valid complex number');
}
return $complex;
} | php | public static function validateComplexArgument($complex)
{
if (is_scalar($complex) || is_array($complex)) {
$complex = new Complex($complex);
} elseif (!is_object($complex) || !($complex instanceof Complex)) {
throw new Exception('Value is not a valid complex number');
}
return $complex;
} | [
"public",
"static",
"function",
"validateComplexArgument",
"(",
"$",
"complex",
")",
"{",
"if",
"(",
"is_scalar",
"(",
"$",
"complex",
")",
"||",
"is_array",
"(",
"$",
"complex",
")",
")",
"{",
"$",
"complex",
"=",
"new",
"Complex",
"(",
"$",
"complex",
... | Validates whether the argument is a valid complex number, converting scalar or array values if possible
@param mixed $complex The value to validate
@return Complex
@throws Exception If the argument isn't a Complex number or cannot be converted to one | [
"Validates",
"whether",
"the",
"argument",
"is",
"a",
"valid",
"complex",
"number",
"converting",
"scalar",
"or",
"array",
"values",
"if",
"possible"
] | train | https://github.com/MarkBaker/PHPComplex/blob/4e20202cd759a3afe0b2f9318d697484fa10ad68/classes/src/Complex.php#L274-L283 |
MarkBaker/PHPComplex | classes/src/Complex.php | Complex.reverse | public function reverse()
{
return new Complex(
$this->imaginaryPart,
$this->realPart,
($this->realPart == 0.0) ? null : $this->suffix
);
} | php | public function reverse()
{
return new Complex(
$this->imaginaryPart,
$this->realPart,
($this->realPart == 0.0) ? null : $this->suffix
);
} | [
"public",
"function",
"reverse",
"(",
")",
"{",
"return",
"new",
"Complex",
"(",
"$",
"this",
"->",
"imaginaryPart",
",",
"$",
"this",
"->",
"realPart",
",",
"(",
"$",
"this",
"->",
"realPart",
"==",
"0.0",
")",
"?",
"null",
":",
"$",
"this",
"->",
... | Returns the reverse of this complex number
@return Complex | [
"Returns",
"the",
"reverse",
"of",
"this",
"complex",
"number"
] | train | https://github.com/MarkBaker/PHPComplex/blob/4e20202cd759a3afe0b2f9318d697484fa10ad68/classes/src/Complex.php#L290-L297 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.