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
ko-ko-ko/php-assert
src/Assert.php
Assert.match
public function match($pattern) { if (!is_string($pattern)) { throw new InvalidStringException('pattern', $pattern); } elseif (empty($pattern)) { throw new InvalidNotEmptyException('pattern'); } if (!is_string($this->value)) { throw new InvalidStringException($this->name, $this->value); } // God please sorry for this @ $checkResult = @preg_match($pattern, $this->value); if ((preg_last_error() !== PREG_NO_ERROR) || ($checkResult === false)) { throw new InvalidRegExpPatternException('pattern', $pattern); } if ($checkResult === 0) { throw new StringNotMatchRegExpException($this->name, $this->value, $pattern); } return $this; }
php
public function match($pattern) { if (!is_string($pattern)) { throw new InvalidStringException('pattern', $pattern); } elseif (empty($pattern)) { throw new InvalidNotEmptyException('pattern'); } if (!is_string($this->value)) { throw new InvalidStringException($this->name, $this->value); } // God please sorry for this @ $checkResult = @preg_match($pattern, $this->value); if ((preg_last_error() !== PREG_NO_ERROR) || ($checkResult === false)) { throw new InvalidRegExpPatternException('pattern', $pattern); } if ($checkResult === 0) { throw new StringNotMatchRegExpException($this->name, $this->value, $pattern); } return $this; }
[ "public", "function", "match", "(", "$", "pattern", ")", "{", "if", "(", "!", "is_string", "(", "$", "pattern", ")", ")", "{", "throw", "new", "InvalidStringException", "(", "'pattern'", ",", "$", "pattern", ")", ";", "}", "elseif", "(", "empty", "(", ...
Check if value match regexp pattern @param string $pattern @return $this @throws InvalidNotEmptyException @throws InvalidRegexpPatternException @throws InvalidStringException @throws StringNotMatchRegExpException
[ "Check", "if", "value", "match", "regexp", "pattern" ]
train
https://github.com/ko-ko-ko/php-assert/blob/e4968588fd3f42c95a763ca3c36cfb846b24ab81/src/Assert.php#L621-L645
ko-ko-ko/php-assert
src/Assert.php
Assert.glob
public function glob($pattern) { if (!is_string($pattern)) { throw new InvalidStringException('pattern', $pattern); } elseif (empty($pattern)) { throw new InvalidNotEmptyException('pattern'); } if (!is_string($this->value)) { throw new InvalidStringException($this->name, $this->value); } elseif (!fnmatch($pattern, $this->value)) { throw new StringNotMatchGlobException($this->name, $this->value, $pattern); } return $this; }
php
public function glob($pattern) { if (!is_string($pattern)) { throw new InvalidStringException('pattern', $pattern); } elseif (empty($pattern)) { throw new InvalidNotEmptyException('pattern'); } if (!is_string($this->value)) { throw new InvalidStringException($this->name, $this->value); } elseif (!fnmatch($pattern, $this->value)) { throw new StringNotMatchGlobException($this->name, $this->value, $pattern); } return $this; }
[ "public", "function", "glob", "(", "$", "pattern", ")", "{", "if", "(", "!", "is_string", "(", "$", "pattern", ")", ")", "{", "throw", "new", "InvalidStringException", "(", "'pattern'", ",", "$", "pattern", ")", ";", "}", "elseif", "(", "empty", "(", ...
Check if value match glob pattern @param string $pattern @return $this @throws InvalidNotEmptyException @throws InvalidStringException @throws StringNotMatchGlobException
[ "Check", "if", "value", "match", "glob", "pattern" ]
train
https://github.com/ko-ko-ko/php-assert/blob/e4968588fd3f42c95a763ca3c36cfb846b24ab81/src/Assert.php#L656-L671
ko-ko-ko/php-assert
src/Assert.php
Assert.negative
public function negative() { if (!is_int($this->value) && !is_float($this->value)) { throw new InvalidIntOrFloatException($this->name, $this->value); } elseif ($this->value >= 0) { throw new NumberNotNegativeException($this->name, $this->value); } return $this; }
php
public function negative() { if (!is_int($this->value) && !is_float($this->value)) { throw new InvalidIntOrFloatException($this->name, $this->value); } elseif ($this->value >= 0) { throw new NumberNotNegativeException($this->name, $this->value); } return $this; }
[ "public", "function", "negative", "(", ")", "{", "if", "(", "!", "is_int", "(", "$", "this", "->", "value", ")", "&&", "!", "is_float", "(", "$", "this", "->", "value", ")", ")", "{", "throw", "new", "InvalidIntOrFloatException", "(", "$", "this", "-...
Check if value < 0 @return $this @throws InvalidIntOrFloatException @throws NumberNotNegativeException
[ "Check", "if", "value", "<", "0" ]
train
https://github.com/ko-ko-ko/php-assert/blob/e4968588fd3f42c95a763ca3c36cfb846b24ab81/src/Assert.php#L680-L689
ko-ko-ko/php-assert
src/Assert.php
Assert.positive
public function positive() { if (!is_int($this->value) && !is_float($this->value)) { throw new InvalidIntOrFloatException($this->name, $this->value); } elseif ($this->value <= 0) { throw new NumberNotPositiveException($this->name, $this->value); } return $this; }
php
public function positive() { if (!is_int($this->value) && !is_float($this->value)) { throw new InvalidIntOrFloatException($this->name, $this->value); } elseif ($this->value <= 0) { throw new NumberNotPositiveException($this->name, $this->value); } return $this; }
[ "public", "function", "positive", "(", ")", "{", "if", "(", "!", "is_int", "(", "$", "this", "->", "value", ")", "&&", "!", "is_float", "(", "$", "this", "->", "value", ")", ")", "{", "throw", "new", "InvalidIntOrFloatException", "(", "$", "this", "-...
Check if value > 0 @return $this @throws InvalidIntOrFloatException @throws NumberNotPositiveException
[ "Check", "if", "value", ">", "0" ]
train
https://github.com/ko-ko-ko/php-assert/blob/e4968588fd3f42c95a763ca3c36cfb846b24ab81/src/Assert.php#L698-L707
ko-ko-ko/php-assert
src/Assert.php
Assert.isSame
public function isSame($anotherValue) { if (is_object($anotherValue)) { throw new InvalidNotObjectException('anotherValue'); } if ($this->value !== $anotherValue) { throw new InvalidSameValueException($this->name, $this->value, $anotherValue); } return $this; }
php
public function isSame($anotherValue) { if (is_object($anotherValue)) { throw new InvalidNotObjectException('anotherValue'); } if ($this->value !== $anotherValue) { throw new InvalidSameValueException($this->name, $this->value, $anotherValue); } return $this; }
[ "public", "function", "isSame", "(", "$", "anotherValue", ")", "{", "if", "(", "is_object", "(", "$", "anotherValue", ")", ")", "{", "throw", "new", "InvalidNotObjectException", "(", "'anotherValue'", ")", ";", "}", "if", "(", "$", "this", "->", "value", ...
Check if value is same as $anotherValue @param int|float|bool|string|resource|array|null $anotherValue @return $this @throws InvalidNotObjectException @throws InvalidSameValueException
[ "Check", "if", "value", "is", "same", "as", "$anotherValue" ]
train
https://github.com/ko-ko-ko/php-assert/blob/e4968588fd3f42c95a763ca3c36cfb846b24ab81/src/Assert.php#L717-L728
ko-ko-ko/php-assert
src/Assert.php
Assert.notSame
public function notSame($anotherValue) { if (is_object($anotherValue)) { throw new InvalidNotObjectException('anotherValue'); } if ($this->value === $anotherValue) { throw new InvalidNotSameValueException($this->name, $this->value); } return $this; }
php
public function notSame($anotherValue) { if (is_object($anotherValue)) { throw new InvalidNotObjectException('anotherValue'); } if ($this->value === $anotherValue) { throw new InvalidNotSameValueException($this->name, $this->value); } return $this; }
[ "public", "function", "notSame", "(", "$", "anotherValue", ")", "{", "if", "(", "is_object", "(", "$", "anotherValue", ")", ")", "{", "throw", "new", "InvalidNotObjectException", "(", "'anotherValue'", ")", ";", "}", "if", "(", "$", "this", "->", "value", ...
Check if value is not same as $anotherValue @param int|float|bool|string|resource|array|null $anotherValue @return $this @throws InvalidNotObjectException @throws InvalidNotSameValueException
[ "Check", "if", "value", "is", "not", "same", "as", "$anotherValue" ]
train
https://github.com/ko-ko-ko/php-assert/blob/e4968588fd3f42c95a763ca3c36cfb846b24ab81/src/Assert.php#L738-L749
ko-ko-ko/php-assert
src/Assert.php
Assert.isNull
public function isNull() { if (!is_null($this->value)) { throw new InvalidNullException($this->name, $this->value); } return $this; }
php
public function isNull() { if (!is_null($this->value)) { throw new InvalidNullException($this->name, $this->value); } return $this; }
[ "public", "function", "isNull", "(", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "value", ")", ")", "{", "throw", "new", "InvalidNullException", "(", "$", "this", "->", "name", ",", "$", "this", "->", "value", ")", ";", "}", "retur...
Check if value is null @return $this @throws InvalidNullException
[ "Check", "if", "value", "is", "null" ]
train
https://github.com/ko-ko-ko/php-assert/blob/e4968588fd3f42c95a763ca3c36cfb846b24ab81/src/Assert.php#L757-L764
ko-ko-ko/php-assert
src/Assert.php
Assert.numeric
public function numeric() { if (!is_int($this->value) && !is_float($this->value) && !is_string($this->value)) { throw new InvalidIntOrFloatOrStringException($this->name, $this->value); } elseif (!is_numeric($this->value)) { throw new InvalidNumericException($this->name, $this->value); } return $this; }
php
public function numeric() { if (!is_int($this->value) && !is_float($this->value) && !is_string($this->value)) { throw new InvalidIntOrFloatOrStringException($this->name, $this->value); } elseif (!is_numeric($this->value)) { throw new InvalidNumericException($this->name, $this->value); } return $this; }
[ "public", "function", "numeric", "(", ")", "{", "if", "(", "!", "is_int", "(", "$", "this", "->", "value", ")", "&&", "!", "is_float", "(", "$", "this", "->", "value", ")", "&&", "!", "is_string", "(", "$", "this", "->", "value", ")", ")", "{", ...
Check if value is numeric (is_numeric) @return $this @throws InvalidIntOrFloatOrStringException @throws InvalidNumericException
[ "Check", "if", "value", "is", "numeric", "(", "is_numeric", ")" ]
train
https://github.com/ko-ko-ko/php-assert/blob/e4968588fd3f42c95a763ca3c36cfb846b24ab81/src/Assert.php#L788-L797
ko-ko-ko/php-assert
src/Assert.php
Assert.resource
public function resource() { if (!is_resource($this->value)) { throw new InvalidResourceException($this->name, $this->value); } return $this; }
php
public function resource() { if (!is_resource($this->value)) { throw new InvalidResourceException($this->name, $this->value); } return $this; }
[ "public", "function", "resource", "(", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "value", ")", ")", "{", "throw", "new", "InvalidResourceException", "(", "$", "this", "->", "name", ",", "$", "this", "->", "value", ")", ";", "}"...
Check if value is resource (is_resource) @return $this @throws InvalidResourceException
[ "Check", "if", "value", "is", "resource", "(", "is_resource", ")" ]
train
https://github.com/ko-ko-ko/php-assert/blob/e4968588fd3f42c95a763ca3c36cfb846b24ab81/src/Assert.php#L805-L812
ko-ko-ko/php-assert
src/Assert.php
Assert.string
public function string() { if (!is_string($this->value)) { throw new InvalidStringException($this->name, $this->value); } return $this; }
php
public function string() { if (!is_string($this->value)) { throw new InvalidStringException($this->name, $this->value); } return $this; }
[ "public", "function", "string", "(", ")", "{", "if", "(", "!", "is_string", "(", "$", "this", "->", "value", ")", ")", "{", "throw", "new", "InvalidStringException", "(", "$", "this", "->", "name", ",", "$", "this", "->", "value", ")", ";", "}", "r...
Check if value is string (is_string) @return $this @throws InvalidStringException
[ "Check", "if", "value", "is", "string", "(", "is_string", ")" ]
train
https://github.com/ko-ko-ko/php-assert/blob/e4968588fd3f42c95a763ca3c36cfb846b24ab81/src/Assert.php#L820-L827
ko-ko-ko/php-assert
src/Assert.php
Assert.toFloat
public function toFloat() { if (is_array($this->value)) { throw new InvalidNotArrayException($this->name); } elseif (!empty($this->value) && !is_numeric($this->value)) { throw new InvalidNumericException($this->name, $this->value); } $this->value = (float) $this->value; return $this; }
php
public function toFloat() { if (is_array($this->value)) { throw new InvalidNotArrayException($this->name); } elseif (!empty($this->value) && !is_numeric($this->value)) { throw new InvalidNumericException($this->name, $this->value); } $this->value = (float) $this->value; return $this; }
[ "public", "function", "toFloat", "(", ")", "{", "if", "(", "is_array", "(", "$", "this", "->", "value", ")", ")", "{", "throw", "new", "InvalidNotArrayException", "(", "$", "this", "->", "name", ")", ";", "}", "elseif", "(", "!", "empty", "(", "$", ...
Cast value to float. If it's not numeric - there will be fail cast @return $this @throws InvalidNotArrayException @throws InvalidNumericException
[ "Cast", "value", "to", "float", ".", "If", "it", "s", "not", "numeric", "-", "there", "will", "be", "fail", "cast" ]
train
https://github.com/ko-ko-ko/php-assert/blob/e4968588fd3f42c95a763ca3c36cfb846b24ab81/src/Assert.php#L848-L859
ko-ko-ko/php-assert
src/Assert.php
Assert.toInt
public function toInt() { if (is_array($this->value)) { throw new InvalidNotArrayException($this->name); } elseif (!empty($this->value) && !is_numeric($this->value)) { throw new InvalidNumericException($this->name, $this->value); } $this->value = (int) $this->value; return $this; }
php
public function toInt() { if (is_array($this->value)) { throw new InvalidNotArrayException($this->name); } elseif (!empty($this->value) && !is_numeric($this->value)) { throw new InvalidNumericException($this->name, $this->value); } $this->value = (int) $this->value; return $this; }
[ "public", "function", "toInt", "(", ")", "{", "if", "(", "is_array", "(", "$", "this", "->", "value", ")", ")", "{", "throw", "new", "InvalidNotArrayException", "(", "$", "this", "->", "name", ")", ";", "}", "elseif", "(", "!", "empty", "(", "$", "...
Cast value to int. If it's not numeric - there will be fail cast @return $this @throws InvalidNotArrayException @throws InvalidNumericException
[ "Cast", "value", "to", "int", ".", "If", "it", "s", "not", "numeric", "-", "there", "will", "be", "fail", "cast" ]
train
https://github.com/ko-ko-ko/php-assert/blob/e4968588fd3f42c95a763ca3c36cfb846b24ab81/src/Assert.php#L868-L879
ko-ko-ko/php-assert
src/Assert.php
Assert.toString
public function toString() { if (is_array($this->value)) { throw new InvalidNotArrayException($this->name); } $this->value = (string) $this->value; return $this; }
php
public function toString() { if (is_array($this->value)) { throw new InvalidNotArrayException($this->name); } $this->value = (string) $this->value; return $this; }
[ "public", "function", "toString", "(", ")", "{", "if", "(", "is_array", "(", "$", "this", "->", "value", ")", ")", "{", "throw", "new", "InvalidNotArrayException", "(", "$", "this", "->", "name", ")", ";", "}", "$", "this", "->", "value", "=", "(", ...
Cast value to string. If it's array - there will be fail cast @return $this @throws InvalidNotArrayException
[ "Cast", "value", "to", "string", ".", "If", "it", "s", "array", "-", "there", "will", "be", "fail", "cast" ]
train
https://github.com/ko-ko-ko/php-assert/blob/e4968588fd3f42c95a763ca3c36cfb846b24ab81/src/Assert.php#L887-L896
dave-redfern/laravel-doctrine-tenancy
src/Repositories/TenantAwareRepository.php
TenantAwareRepository.createQueryBuilder
public function createQueryBuilder($alias, $indexBy = null) { $qb = $this->repository->createQueryBuilder($alias, $indexBy); $this->applySecurityModel($qb, $alias); return $qb; }
php
public function createQueryBuilder($alias, $indexBy = null) { $qb = $this->repository->createQueryBuilder($alias, $indexBy); $this->applySecurityModel($qb, $alias); return $qb; }
[ "public", "function", "createQueryBuilder", "(", "$", "alias", ",", "$", "indexBy", "=", "null", ")", "{", "$", "qb", "=", "$", "this", "->", "repository", "->", "createQueryBuilder", "(", "$", "alias", ",", "$", "indexBy", ")", ";", "$", "this", "->",...
Creates a new QueryBuilder instance that is prepopulated for this entity name. @param string $alias @param string $indexBy The index for the from. @return QueryBuilder
[ "Creates", "a", "new", "QueryBuilder", "instance", "that", "is", "prepopulated", "for", "this", "entity", "name", "." ]
train
https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Repositories/TenantAwareRepository.php#L119-L126
dave-redfern/laravel-doctrine-tenancy
src/Repositories/TenantAwareRepository.php
TenantAwareRepository.applySecurityModel
protected function applySecurityModel(QueryBuilder $qb, $alias) { $model = $this->tenant->getTenantSecurityModel(); $method = 'apply' . ucfirst($model) . 'SecurityModel'; if ( method_exists($this, $method) ) { $this->$method($qb, $alias); } else { throw new \RuntimeException( sprintf('Security model "%s" has not been implemented by "%s"', $model, $method) ); } }
php
protected function applySecurityModel(QueryBuilder $qb, $alias) { $model = $this->tenant->getTenantSecurityModel(); $method = 'apply' . ucfirst($model) . 'SecurityModel'; if ( method_exists($this, $method) ) { $this->$method($qb, $alias); } else { throw new \RuntimeException( sprintf('Security model "%s" has not been implemented by "%s"', $model, $method) ); } }
[ "protected", "function", "applySecurityModel", "(", "QueryBuilder", "$", "qb", ",", "$", "alias", ")", "{", "$", "model", "=", "$", "this", "->", "tenant", "->", "getTenantSecurityModel", "(", ")", ";", "$", "method", "=", "'apply'", ".", "ucfirst", "(", ...
Applies the rules for the selected Security Model The security model name is capitalised, and then turned into a method prefixed with apply and suffixed with SecurityModel e.g.: shared -> applySharedSecurityModel. @param QueryBuilder $qb @param string $alias
[ "Applies", "the", "rules", "for", "the", "selected", "Security", "Model" ]
train
https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Repositories/TenantAwareRepository.php#L137-L149
dave-redfern/laravel-doctrine-tenancy
src/Repositories/TenantAwareRepository.php
TenantAwareRepository.find
public function find($id) { $qb = $this->createQueryBuilder('o'); $meta = $this->em->getClassMetadata($this->repository->getClassName()); $qb->andWhere("o.{$meta->getSingleIdentifierFieldName()} = :id")->setParameter(':id', $id); return $qb->getQuery()->getOneOrNullResult(); }
php
public function find($id) { $qb = $this->createQueryBuilder('o'); $meta = $this->em->getClassMetadata($this->repository->getClassName()); $qb->andWhere("o.{$meta->getSingleIdentifierFieldName()} = :id")->setParameter(':id', $id); return $qb->getQuery()->getOneOrNullResult(); }
[ "public", "function", "find", "(", "$", "id", ")", "{", "$", "qb", "=", "$", "this", "->", "createQueryBuilder", "(", "'o'", ")", ";", "$", "meta", "=", "$", "this", "->", "em", "->", "getClassMetadata", "(", "$", "this", "->", "repository", "->", ...
Finds an object by its primary key / identifier. @todo Might have performance issues since we are accessing EM to get class meta data to reference the correct primary identifier. @todo Allow composite primary key look up? @param mixed $id The identifier. @return object|null The object.
[ "Finds", "an", "object", "by", "its", "primary", "key", "/", "identifier", "." ]
train
https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Repositories/TenantAwareRepository.php#L216-L224
dave-redfern/laravel-doctrine-tenancy
src/Repositories/TenantAwareRepository.php
TenantAwareRepository.findBy
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) { $qb = $this->createQueryBuilder('o'); if (null !== $offset) $qb->setFirstResult($offset); if (null !== $limit) $qb->setMaxResults($limit); $this->applyCriteriaAndOrderByToQueryBuilder($qb, $criteria, $orderBy); return $qb->getQuery()->getResult(); }
php
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) { $qb = $this->createQueryBuilder('o'); if (null !== $offset) $qb->setFirstResult($offset); if (null !== $limit) $qb->setMaxResults($limit); $this->applyCriteriaAndOrderByToQueryBuilder($qb, $criteria, $orderBy); return $qb->getQuery()->getResult(); }
[ "public", "function", "findBy", "(", "array", "$", "criteria", ",", "array", "$", "orderBy", "=", "null", ",", "$", "limit", "=", "null", ",", "$", "offset", "=", "null", ")", "{", "$", "qb", "=", "$", "this", "->", "createQueryBuilder", "(", "'o'", ...
Finds objects by a set of criteria. Optionally sorting and limiting details can be passed. An implementation may throw an UnexpectedValueException if certain values of the sorting or limiting details are not supported. @param array $criteria @param array|null $orderBy ['field' => 'ASC|DESC'] @param int|null $limit @param int|null $offset @return array The objects. @throws \UnexpectedValueException
[ "Finds", "objects", "by", "a", "set", "of", "criteria", "." ]
train
https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Repositories/TenantAwareRepository.php#L252-L261
dave-redfern/laravel-doctrine-tenancy
src/Repositories/TenantAwareRepository.php
TenantAwareRepository.findOneBy
public function findOneBy(array $criteria, array $orderBy = null) { $qb = $this->createQueryBuilder('o'); $this->applyCriteriaAndOrderByToQueryBuilder($qb, $criteria, $orderBy); return $qb->getQuery()->getOneOrNullResult(); }
php
public function findOneBy(array $criteria, array $orderBy = null) { $qb = $this->createQueryBuilder('o'); $this->applyCriteriaAndOrderByToQueryBuilder($qb, $criteria, $orderBy); return $qb->getQuery()->getOneOrNullResult(); }
[ "public", "function", "findOneBy", "(", "array", "$", "criteria", ",", "array", "$", "orderBy", "=", "null", ")", "{", "$", "qb", "=", "$", "this", "->", "createQueryBuilder", "(", "'o'", ")", ";", "$", "this", "->", "applyCriteriaAndOrderByToQueryBuilder", ...
Finds a single entity by a set of criteria. @param array $criteria @param array|null $orderBy ['field' => 'ASC|DESC'] @return object|null The entity instance or NULL if the entity can not be found.
[ "Finds", "a", "single", "entity", "by", "a", "set", "of", "criteria", "." ]
train
https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Repositories/TenantAwareRepository.php#L271-L278
awurth/SlimHelpers
Controller/Controller.php
Controller.render
protected function render(Response $response, $template, array $params = []) { return $this->container['twig']->render($response, $template, $params); }
php
protected function render(Response $response, $template, array $params = []) { return $this->container['twig']->render($response, $template, $params); }
[ "protected", "function", "render", "(", "Response", "$", "response", ",", "$", "template", ",", "array", "$", "params", "=", "[", "]", ")", "{", "return", "$", "this", "->", "container", "[", "'twig'", "]", "->", "render", "(", "$", "response", ",", ...
@param Response $response @param string $template @param array $params @return Response
[ "@param", "Response", "$response", "@param", "string", "$template", "@param", "array", "$params" ]
train
https://github.com/awurth/SlimHelpers/blob/abaa0e16e285148f4e4c6b2fd0bb176bce6dac36/Controller/Controller.php#L31-L34
txj123/zilf
src/Zilf/Cache/CacheManager.php
CacheManager.get
protected function get($name) { return isset($this->stores[$name]) ? $this->stores[$name] : $this->resolve($name); }
php
protected function get($name) { return isset($this->stores[$name]) ? $this->stores[$name] : $this->resolve($name); }
[ "protected", "function", "get", "(", "$", "name", ")", "{", "return", "isset", "(", "$", "this", "->", "stores", "[", "$", "name", "]", ")", "?", "$", "this", "->", "stores", "[", "$", "name", "]", ":", "$", "this", "->", "resolve", "(", "$", "...
Attempt to get the store from the local cache. @param string $name @return \Zilf\Cache\Repository
[ "Attempt", "to", "get", "the", "store", "from", "the", "local", "cache", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Cache/CacheManager.php#L76-L79
txj123/zilf
src/Zilf/Cache/CacheManager.php
CacheManager.createDatabaseDriver
protected function createDatabaseDriver(array $config) { $connection = $this->app['db']->connection(Arr::get($config, 'connection')); return $this->repository( new DatabaseStore( $connection, $config['table'], $this->getPrefix($config) ) ); }
php
protected function createDatabaseDriver(array $config) { $connection = $this->app['db']->connection(Arr::get($config, 'connection')); return $this->repository( new DatabaseStore( $connection, $config['table'], $this->getPrefix($config) ) ); }
[ "protected", "function", "createDatabaseDriver", "(", "array", "$", "config", ")", "{", "$", "connection", "=", "$", "this", "->", "app", "[", "'db'", "]", "->", "connection", "(", "Arr", "::", "get", "(", "$", "config", ",", "'connection'", ")", ")", ...
Create an instance of the database cache driver. @param array $config @return \Zilf\Cache\DatabaseStore
[ "Create", "an", "instance", "of", "the", "database", "cache", "driver", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Cache/CacheManager.php#L206-L215
txj123/zilf
src/Zilf/DataCrawler/PhpQuery/phpQuery/DOMDocumentWrapper.php
DOMDocumentWrapper.charsetFixHTML
protected function charsetFixHTML($markup) { $matches = array(); // find meta tag preg_match( '@\s*<meta[^>]+http-equiv\\s*=\\s*(["|\'])Content-Type\\1([^>]+?)>@i', $markup, $matches, PREG_OFFSET_CAPTURE ); if (! isset($matches[0])) { return; } $metaContentType = $matches[0][0]; $markup = substr($markup, 0, $matches[0][1]) .substr($markup, $matches[0][1]+strlen($metaContentType)); $headStart = stripos($markup, '<head>'); $markup = substr($markup, 0, $headStart+6).$metaContentType .substr($markup, $headStart+6); return $markup; }
php
protected function charsetFixHTML($markup) { $matches = array(); // find meta tag preg_match( '@\s*<meta[^>]+http-equiv\\s*=\\s*(["|\'])Content-Type\\1([^>]+?)>@i', $markup, $matches, PREG_OFFSET_CAPTURE ); if (! isset($matches[0])) { return; } $metaContentType = $matches[0][0]; $markup = substr($markup, 0, $matches[0][1]) .substr($markup, $matches[0][1]+strlen($metaContentType)); $headStart = stripos($markup, '<head>'); $markup = substr($markup, 0, $headStart+6).$metaContentType .substr($markup, $headStart+6); return $markup; }
[ "protected", "function", "charsetFixHTML", "(", "$", "markup", ")", "{", "$", "matches", "=", "array", "(", ")", ";", "// find meta tag", "preg_match", "(", "'@\\s*<meta[^>]+http-equiv\\\\s*=\\\\s*([\"|\\'])Content-Type\\\\1([^>]+?)>@i'", ",", "$", "markup", ",", "$", ...
Repositions meta[type=charset] at the start of head. Bypasses DOMDocument bug. @link http://code.google.com/p/phpquery/issues/detail?id=80 @param $html
[ "Repositions", "meta", "[", "type", "=", "charset", "]", "at", "the", "start", "of", "head", ".", "Bypasses", "DOMDocument", "bug", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/DOMDocumentWrapper.php#L404-L422
txj123/zilf
src/Zilf/DataCrawler/PhpQuery/phpQuery/DOMDocumentWrapper.php
DOMDocumentWrapper.markup
public function markup($nodes = null, $innerMarkup = false) { if (isset($nodes) && count($nodes) == 1 && $nodes[0] instanceof DOMDOCUMENT) { $nodes = null; } if (isset($nodes)) { $markup = ''; if (!is_array($nodes) && !($nodes instanceof DOMNODELIST) ) { $nodes = array($nodes); } if ($this->isDocumentFragment && ! $innerMarkup) { foreach($nodes as $i => $node) { if ($node->isSameNode($this->root)) { // var_dump($node); $nodes = array_slice($nodes, 0, $i) + phpQuery::DOMNodeListToArray($node->childNodes) + array_slice($nodes, $i+1); } } } if ($this->isXML && ! $innerMarkup) { self::debug("Getting outerXML with charset '{$this->charset}'"); // we need outerXML, so we can benefit from // $node param support in saveXML() foreach($nodes as $node) { $markup .= $this->document->saveXML($node); } } else { $loop = array(); if ($innerMarkup) { foreach($nodes as $node) { if ($node->childNodes) { foreach($node->childNodes as $child) { $loop[] = $child; } } else { $loop[] = $node; } } } else { $loop = $nodes; } self::debug("Getting markup, moving selected nodes (".count($loop).") to new DocumentFragment"); $fake = $this->documentFragmentCreate($loop); $markup = $this->documentFragmentToMarkup($fake); } if ($this->isXHTML) { self::debug("Fixing XHTML"); $markup = self::markupFixXHTML($markup); } self::debug("Markup: ".substr($markup, 0, 250)); return $markup; } else { if ($this->isDocumentFragment) { // documentFragment, html only... self::debug("Getting markup, DocumentFragment detected"); // return $this->markup( //// $this->document->getElementsByTagName('body')->item(0) // $this->document->root, true // ); $markup = $this->documentFragmentToMarkup($this); // no need for markupFixXHTML, as it's done thought markup($nodes) method return $markup; } else { self::debug("Getting markup (".($this->isXML?'XML':'HTML')."), final with charset '{$this->charset}'"); $markup = $this->isXML ? $this->document->saveXML() : $this->document->saveHTML(); if ($this->isXHTML) { self::debug("Fixing XHTML"); $markup = self::markupFixXHTML($markup); } self::debug("Markup: ".substr($markup, 0, 250)); return $markup; } } }
php
public function markup($nodes = null, $innerMarkup = false) { if (isset($nodes) && count($nodes) == 1 && $nodes[0] instanceof DOMDOCUMENT) { $nodes = null; } if (isset($nodes)) { $markup = ''; if (!is_array($nodes) && !($nodes instanceof DOMNODELIST) ) { $nodes = array($nodes); } if ($this->isDocumentFragment && ! $innerMarkup) { foreach($nodes as $i => $node) { if ($node->isSameNode($this->root)) { // var_dump($node); $nodes = array_slice($nodes, 0, $i) + phpQuery::DOMNodeListToArray($node->childNodes) + array_slice($nodes, $i+1); } } } if ($this->isXML && ! $innerMarkup) { self::debug("Getting outerXML with charset '{$this->charset}'"); // we need outerXML, so we can benefit from // $node param support in saveXML() foreach($nodes as $node) { $markup .= $this->document->saveXML($node); } } else { $loop = array(); if ($innerMarkup) { foreach($nodes as $node) { if ($node->childNodes) { foreach($node->childNodes as $child) { $loop[] = $child; } } else { $loop[] = $node; } } } else { $loop = $nodes; } self::debug("Getting markup, moving selected nodes (".count($loop).") to new DocumentFragment"); $fake = $this->documentFragmentCreate($loop); $markup = $this->documentFragmentToMarkup($fake); } if ($this->isXHTML) { self::debug("Fixing XHTML"); $markup = self::markupFixXHTML($markup); } self::debug("Markup: ".substr($markup, 0, 250)); return $markup; } else { if ($this->isDocumentFragment) { // documentFragment, html only... self::debug("Getting markup, DocumentFragment detected"); // return $this->markup( //// $this->document->getElementsByTagName('body')->item(0) // $this->document->root, true // ); $markup = $this->documentFragmentToMarkup($this); // no need for markupFixXHTML, as it's done thought markup($nodes) method return $markup; } else { self::debug("Getting markup (".($this->isXML?'XML':'HTML')."), final with charset '{$this->charset}'"); $markup = $this->isXML ? $this->document->saveXML() : $this->document->saveHTML(); if ($this->isXHTML) { self::debug("Fixing XHTML"); $markup = self::markupFixXHTML($markup); } self::debug("Markup: ".substr($markup, 0, 250)); return $markup; } } }
[ "public", "function", "markup", "(", "$", "nodes", "=", "null", ",", "$", "innerMarkup", "=", "false", ")", "{", "if", "(", "isset", "(", "$", "nodes", ")", "&&", "count", "(", "$", "nodes", ")", "==", "1", "&&", "$", "nodes", "[", "0", "]", "i...
Return document markup, starting with optional $nodes as root. @param $nodes DOMNode|DOMNodeList @return string
[ "Return", "document", "markup", "starting", "with", "optional", "$nodes", "as", "root", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/DOMDocumentWrapper.php#L641-L717
txj123/zilf
src/Zilf/DataCrawler/PhpQuery/phpQuery/DOMDocumentWrapper.php
DOMDocumentWrapper.expandEmptyTag
public static function expandEmptyTag($tag, $xml) { $indice = 0; while ($indice< strlen($xml)){ $pos = strpos($xml, "<$tag ", $indice); if ($pos) { $posCierre = strpos($xml, ">", $pos); if ($xml[$posCierre-1] == "/") { $xml = substr_replace($xml, "></$tag>", $posCierre-1, 2); } $indice = $posCierre; } else { break; } } return $xml; }
php
public static function expandEmptyTag($tag, $xml) { $indice = 0; while ($indice< strlen($xml)){ $pos = strpos($xml, "<$tag ", $indice); if ($pos) { $posCierre = strpos($xml, ">", $pos); if ($xml[$posCierre-1] == "/") { $xml = substr_replace($xml, "></$tag>", $posCierre-1, 2); } $indice = $posCierre; } else { break; } } return $xml; }
[ "public", "static", "function", "expandEmptyTag", "(", "$", "tag", ",", "$", "xml", ")", "{", "$", "indice", "=", "0", ";", "while", "(", "$", "indice", "<", "strlen", "(", "$", "xml", ")", ")", "{", "$", "pos", "=", "strpos", "(", "$", "xml", ...
expandEmptyTag @param $tag @param $xml @return string @author mjaque at ilkebenson dot com @link http://php.net/manual/en/domdocument.savehtml.php#81256
[ "expandEmptyTag" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/DOMDocumentWrapper.php#L738-L754
txj123/zilf
src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/File/Count.php
Zend_Validate_File_Count.isValid
public function isValid($value, $file = null) { if (is_string($value)) { $value = array($value); } foreach ($value as $file) { if (!isset($this->_files[$file])) { $this->_files[$file] = $file; } } if (($this->_max !== null) && (count($this->_files) > $this->_max)) { $this->_value = $this->_max; $this->_error(self::TOO_MUCH); return false; } if (($this->_min !== null) && (count($this->_files) < $this->_min)) { $this->_value = $this->_min; $this->_error(self::TOO_LESS); return false; } return true; }
php
public function isValid($value, $file = null) { if (is_string($value)) { $value = array($value); } foreach ($value as $file) { if (!isset($this->_files[$file])) { $this->_files[$file] = $file; } } if (($this->_max !== null) && (count($this->_files) > $this->_max)) { $this->_value = $this->_max; $this->_error(self::TOO_MUCH); return false; } if (($this->_min !== null) && (count($this->_files) < $this->_min)) { $this->_value = $this->_min; $this->_error(self::TOO_LESS); return false; } return true; }
[ "public", "function", "isValid", "(", "$", "value", ",", "$", "file", "=", "null", ")", "{", "if", "(", "is_string", "(", "$", "value", ")", ")", "{", "$", "value", "=", "array", "(", "$", "value", ")", ";", "}", "foreach", "(", "$", "value", "...
Defined by Zend_Validate_Interface Returns true if and only if the file count of all checked files is at least min and not bigger than max (when max is not null). Attention: When checking with set min you must give all files with the first call, otherwise you will get an false. @param string|array $value Filenames to check for count @param array $file File data from Zend_File_Transfer @return boolean
[ "Defined", "by", "Zend_Validate_Interface" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/File/Count.php#L212-L237
oxygen-cms/core
src/Console/Command.php
Command.heading
public function heading($text) { $this->info(''); $this->info('==================='); $this->info($text); $this->info('==================='); $this->info(''); }
php
public function heading($text) { $this->info(''); $this->info('==================='); $this->info($text); $this->info('==================='); $this->info(''); }
[ "public", "function", "heading", "(", "$", "text", ")", "{", "$", "this", "->", "info", "(", "''", ")", ";", "$", "this", "->", "info", "(", "'==================='", ")", ";", "$", "this", "->", "info", "(", "$", "text", ")", ";", "$", "this", "-...
Prints a heading. @param string $text
[ "Prints", "a", "heading", "." ]
train
https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Console/Command.php#L14-L20
hfcorriez/pagon
app/src/Api/Api.php
Api.dump
protected function dump(array $data, $code = 200) { $this->output->status($code); switch ($this->_format) { case 'xml': $this->output->xml($data, $this->_xml_option); break; case 'jsonp': $this->output->jsonp($data, $this->_jsonp_callback); break; default: $this->output->json($data); } $this->output->end(); }
php
protected function dump(array $data, $code = 200) { $this->output->status($code); switch ($this->_format) { case 'xml': $this->output->xml($data, $this->_xml_option); break; case 'jsonp': $this->output->jsonp($data, $this->_jsonp_callback); break; default: $this->output->json($data); } $this->output->end(); }
[ "protected", "function", "dump", "(", "array", "$", "data", ",", "$", "code", "=", "200", ")", "{", "$", "this", "->", "output", "->", "status", "(", "$", "code", ")", ";", "switch", "(", "$", "this", "->", "_format", ")", "{", "case", "'xml'", "...
Dump API data @param array $data @param int $code
[ "Dump", "API", "data" ]
train
https://github.com/hfcorriez/pagon/blob/c847a59c4ce4876887c65d35880ded8bb559cc48/app/src/Api/Api.php#L64-L80
txj123/zilf
src/Zilf/HttpFoundation/Session/Storage/MockFileSessionStorage.php
MockFileSessionStorage.save
public function save() { if (!$this->started) { throw new \RuntimeException('Trying to save a session that was not started yet or was already closed'); } file_put_contents($this->getFilePath(), serialize($this->data)); // this is needed for Silex, where the session object is re-used across requests // in functional tests. In Symfony, the container is rebooted, so we don't have // this issue $this->started = false; }
php
public function save() { if (!$this->started) { throw new \RuntimeException('Trying to save a session that was not started yet or was already closed'); } file_put_contents($this->getFilePath(), serialize($this->data)); // this is needed for Silex, where the session object is re-used across requests // in functional tests. In Symfony, the container is rebooted, so we don't have // this issue $this->started = false; }
[ "public", "function", "save", "(", ")", "{", "if", "(", "!", "$", "this", "->", "started", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Trying to save a session that was not started yet or was already closed'", ")", ";", "}", "file_put_contents", "(", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Session/Storage/MockFileSessionStorage.php#L93-L105
kharanenka/oc-pagination
src/Kharanenka/Helper/Pagination.php
Pagination.getProperties
public static function getProperties($sPluginName) { return [ 'count_per_page' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.count_per_page', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['count_per_page'], ], 'pagination_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.pagination_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['pagination_limit'], ], 'active_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.active_class', 'type' => 'string', 'default' => self::$arSettings['active_class'], ], 'button_list' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_list', 'description' => 'lovata.'.$sPluginName.'::lang.settings.button_list_description', 'type' => 'string', ], //First button 'first_button_name' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_name', 'type' => 'string', 'default' => self::$arSettings['first_button_name'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.first_button', ], 'first_button_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['first_button_limit'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.first_button', ], 'first_button_number' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_number', 'type' => 'checkbox', 'default' => self::$arSettings['first_button_number'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.first_button', ], 'first_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['first_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.first_button', ], //First-more button 'first-more_button_name' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_name', 'type' => 'string', 'default' => self::$arSettings['first-more_button_name'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.first-more_button', ], 'first-more_button_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['first-more_button_limit'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.first-more_button', ], 'first-more_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['first-more_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.first-more_button', ], //Prev button 'prev_button_name' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_name', 'type' => 'string', 'default' => self::$arSettings['prev_button_name'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.prev_button', ], 'prev_button_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['prev_button_limit'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.prev_button', ], 'prev_button_number' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_number', 'type' => 'checkbox', 'default' => self::$arSettings['prev_button_number'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.prev_button', ], 'prev_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['prev_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.prev_button', ], //Prev-more button 'prev-more_button_name' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_name', 'type' => 'string', 'default' => self::$arSettings['prev-more_button_name'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.prev-more_button', ], 'prev-more_button_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['prev-more_button_limit'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.prev-more_button', ], 'prev-more_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['prev-more_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.prev-more_button', ], //Main number buttons 'main_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['main_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.main_button', ], //Next-more button 'next-more_button_name' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_name', 'type' => 'string', 'default' => self::$arSettings['next-more_button_name'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.next-more_button', ], 'next-more_button_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['next-more_button_limit'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.next-more_button', ], 'next-more_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['next-more_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.next-more_button', ], //Next button 'next_button_name' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_name', 'type' => 'string', 'default' => self::$arSettings['next_button_name'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.next_button', ], 'next_button_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['next_button_limit'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.next_button', ], 'next_button_number' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_number', 'type' => 'checkbox', 'default' => self::$arSettings['next_button_number'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.next_button', ], 'next_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['next_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.next_button', ], //Last-more button 'last-more_button_name' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_name', 'type' => 'string', 'default' => self::$arSettings['last-more_button_name'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.last-more_button', ], 'last-more_button_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['last-more_button_limit'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.last-more_button', ], 'last-more_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['last-more_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.last-more_button', ], //Last button 'last_button_name' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_name', 'type' => 'string', 'default' => self::$arSettings['last_button_name'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.last_button', ], 'last_button_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['last_button_limit'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.last_button', ], 'last_button_number' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_number', 'type' => 'checkbox', 'default' => self::$arSettings['last_button_number'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.last_button', ], 'last_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['last_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.last_button', ], ]; }
php
public static function getProperties($sPluginName) { return [ 'count_per_page' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.count_per_page', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['count_per_page'], ], 'pagination_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.pagination_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['pagination_limit'], ], 'active_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.active_class', 'type' => 'string', 'default' => self::$arSettings['active_class'], ], 'button_list' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_list', 'description' => 'lovata.'.$sPluginName.'::lang.settings.button_list_description', 'type' => 'string', ], //First button 'first_button_name' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_name', 'type' => 'string', 'default' => self::$arSettings['first_button_name'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.first_button', ], 'first_button_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['first_button_limit'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.first_button', ], 'first_button_number' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_number', 'type' => 'checkbox', 'default' => self::$arSettings['first_button_number'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.first_button', ], 'first_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['first_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.first_button', ], //First-more button 'first-more_button_name' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_name', 'type' => 'string', 'default' => self::$arSettings['first-more_button_name'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.first-more_button', ], 'first-more_button_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['first-more_button_limit'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.first-more_button', ], 'first-more_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['first-more_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.first-more_button', ], //Prev button 'prev_button_name' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_name', 'type' => 'string', 'default' => self::$arSettings['prev_button_name'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.prev_button', ], 'prev_button_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['prev_button_limit'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.prev_button', ], 'prev_button_number' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_number', 'type' => 'checkbox', 'default' => self::$arSettings['prev_button_number'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.prev_button', ], 'prev_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['prev_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.prev_button', ], //Prev-more button 'prev-more_button_name' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_name', 'type' => 'string', 'default' => self::$arSettings['prev-more_button_name'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.prev-more_button', ], 'prev-more_button_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['prev-more_button_limit'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.prev-more_button', ], 'prev-more_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['prev-more_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.prev-more_button', ], //Main number buttons 'main_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['main_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.main_button', ], //Next-more button 'next-more_button_name' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_name', 'type' => 'string', 'default' => self::$arSettings['next-more_button_name'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.next-more_button', ], 'next-more_button_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['next-more_button_limit'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.next-more_button', ], 'next-more_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['next-more_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.next-more_button', ], //Next button 'next_button_name' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_name', 'type' => 'string', 'default' => self::$arSettings['next_button_name'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.next_button', ], 'next_button_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['next_button_limit'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.next_button', ], 'next_button_number' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_number', 'type' => 'checkbox', 'default' => self::$arSettings['next_button_number'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.next_button', ], 'next_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['next_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.next_button', ], //Last-more button 'last-more_button_name' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_name', 'type' => 'string', 'default' => self::$arSettings['last-more_button_name'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.last-more_button', ], 'last-more_button_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['last-more_button_limit'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.last-more_button', ], 'last-more_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['last-more_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.last-more_button', ], //Last button 'last_button_name' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_name', 'type' => 'string', 'default' => self::$arSettings['last_button_name'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.last_button', ], 'last_button_limit' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_limit', 'type' => 'string', 'validationPattern' => '^[0-9]+$', 'validationMessage' => Lang::get('lovata.'.$sPluginName.'::lang.settings.number_validation'), 'default' => self::$arSettings['last_button_limit'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.last_button', ], 'last_button_number' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_number', 'type' => 'checkbox', 'default' => self::$arSettings['last_button_number'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.last_button', ], 'last_button_class' => [ 'title' => 'lovata.'.$sPluginName.'::lang.settings.button_class', 'type' => 'string', 'default' => self::$arSettings['last_button_class'], 'group' => 'lovata.'.$sPluginName.'::lang.settings.last_button', ], ]; }
[ "public", "static", "function", "getProperties", "(", "$", "sPluginName", ")", "{", "return", "[", "'count_per_page'", "=>", "[", "'title'", "=>", "'lovata.'", ".", "$", "sPluginName", ".", "'::lang.settings.count_per_page'", ",", "'type'", "=>", "'string'", ",", ...
Get pagination properties @param string $sPluginName @return array
[ "Get", "pagination", "properties" ]
train
https://github.com/kharanenka/oc-pagination/blob/0a26015df60c7a3194dbdabe1f882efa287affd3/src/Kharanenka/Helper/Pagination.php#L17-L252
kharanenka/oc-pagination
src/Kharanenka/Helper/Pagination.php
Pagination.get
public static function get($iCurrentPage, $iTotalCount, $arSettings = []) { if(!empty($arSettings) && isset($arSettings['button_list']) && !empty($arSettings['button_list'])) { $arSettings['button_list'] = explode(',', $arSettings['button_list']); } return parent::get($iCurrentPage, $iTotalCount, $arSettings); }
php
public static function get($iCurrentPage, $iTotalCount, $arSettings = []) { if(!empty($arSettings) && isset($arSettings['button_list']) && !empty($arSettings['button_list'])) { $arSettings['button_list'] = explode(',', $arSettings['button_list']); } return parent::get($iCurrentPage, $iTotalCount, $arSettings); }
[ "public", "static", "function", "get", "(", "$", "iCurrentPage", ",", "$", "iTotalCount", ",", "$", "arSettings", "=", "[", "]", ")", "{", "if", "(", "!", "empty", "(", "$", "arSettings", ")", "&&", "isset", "(", "$", "arSettings", "[", "'button_list'"...
Get pagination elements @param int $iCurrentPage - current page number @param int $iTotalCount - total count elements @param array $arSettings - settings array @return array
[ "Get", "pagination", "elements" ]
train
https://github.com/kharanenka/oc-pagination/blob/0a26015df60c7a3194dbdabe1f882efa287affd3/src/Kharanenka/Helper/Pagination.php#L261-L269
oxygen-cms/core
src/Html/Toolbar/Factory/VoidButtonToolbarItemFactory.php
VoidButtonToolbarItemFactory.create
public function create(array $parameters) { $toolbarItem = new VoidButtonToolbarItem($parameters['label'], $parameters['action']); unset($parameters['label'], $parameters['action']); foreach($parameters as $key => $value) { $toolbarItem->$key = $value; } return $toolbarItem; }
php
public function create(array $parameters) { $toolbarItem = new VoidButtonToolbarItem($parameters['label'], $parameters['action']); unset($parameters['label'], $parameters['action']); foreach($parameters as $key => $value) { $toolbarItem->$key = $value; } return $toolbarItem; }
[ "public", "function", "create", "(", "array", "$", "parameters", ")", "{", "$", "toolbarItem", "=", "new", "VoidButtonToolbarItem", "(", "$", "parameters", "[", "'label'", "]", ",", "$", "parameters", "[", "'action'", "]", ")", ";", "unset", "(", "$", "p...
Creates a new toolbar item using the passed parameters. @param array $parameters Passed parameters @return VoidButtonToolbarItem
[ "Creates", "a", "new", "toolbar", "item", "using", "the", "passed", "parameters", "." ]
train
https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Toolbar/Factory/VoidButtonToolbarItemFactory.php#L16-L23
txj123/zilf
src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Barcode/UpcA.php
Zend_Validate_Barcode_UpcA.isValid
public function isValid($value) { $valueString = (string) $value; $this->_setValue($valueString); if (strlen($valueString) !== 12) { $this->_error(self::INVALID_LENGTH); return false; } $barcode = substr($valueString, 0, -1); $oddSum = 0; $evenSum = 0; for ($i = 0; $i < 11; $i++) { if ($i % 2 === 0) { $oddSum += $barcode[$i] * 3; } elseif ($i % 2 === 1) { $evenSum += $barcode[$i]; } } $calculation = ($oddSum + $evenSum) % 10; $checksum = ($calculation === 0) ? 0 : 10 - $calculation; if ($valueString[11] != $checksum) { $this->_error(self::INVALID); return false; } return true; }
php
public function isValid($value) { $valueString = (string) $value; $this->_setValue($valueString); if (strlen($valueString) !== 12) { $this->_error(self::INVALID_LENGTH); return false; } $barcode = substr($valueString, 0, -1); $oddSum = 0; $evenSum = 0; for ($i = 0; $i < 11; $i++) { if ($i % 2 === 0) { $oddSum += $barcode[$i] * 3; } elseif ($i % 2 === 1) { $evenSum += $barcode[$i]; } } $calculation = ($oddSum + $evenSum) % 10; $checksum = ($calculation === 0) ? 0 : 10 - $calculation; if ($valueString[11] != $checksum) { $this->_error(self::INVALID); return false; } return true; }
[ "public", "function", "isValid", "(", "$", "value", ")", "{", "$", "valueString", "=", "(", "string", ")", "$", "value", ";", "$", "this", "->", "_setValue", "(", "$", "valueString", ")", ";", "if", "(", "strlen", "(", "$", "valueString", ")", "!==",...
Defined by Zend_Validate_Interface Returns true if and only if $value contains a valid barcode @param string $value @return boolean
[ "Defined", "by", "Zend_Validate_Interface" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Barcode/UpcA.php#L68-L99
mikelgoig/laravel-spotify-wrapper
src/SpotifyWrapper.php
SpotifyWrapper.requestAccessToken
public function requestAccessToken() { try { $this->session->requestAccessToken($_GET['code']); return $this; } catch (Exception $e) { $this->redirectToSpotifyAuthorizeUrl(); } }
php
public function requestAccessToken() { try { $this->session->requestAccessToken($_GET['code']); return $this; } catch (Exception $e) { $this->redirectToSpotifyAuthorizeUrl(); } }
[ "public", "function", "requestAccessToken", "(", ")", "{", "try", "{", "$", "this", "->", "session", "->", "requestAccessToken", "(", "$", "_GET", "[", "'code'", "]", ")", ";", "return", "$", "this", ";", "}", "catch", "(", "Exception", "$", "e", ")", ...
Request an access token. @return void
[ "Request", "an", "access", "token", "." ]
train
https://github.com/mikelgoig/laravel-spotify-wrapper/blob/0f93b561ec1a590c3568c47f901f5f7ac4e61cf1/src/SpotifyWrapper.php#L68-L76
txj123/zilf
src/Zilf/Queue/InteractsWithQueue.php
InteractsWithQueue.fail
public function fail($exception = null) { if ($this->job) { FailingJob::handle($this->job->getConnectionName(), $this->job, $exception); } }
php
public function fail($exception = null) { if ($this->job) { FailingJob::handle($this->job->getConnectionName(), $this->job, $exception); } }
[ "public", "function", "fail", "(", "$", "exception", "=", "null", ")", "{", "if", "(", "$", "this", "->", "job", ")", "{", "FailingJob", "::", "handle", "(", "$", "this", "->", "job", "->", "getConnectionName", "(", ")", ",", "$", "this", "->", "jo...
Fail the job from the queue. @param \Throwable $exception @return void
[ "Fail", "the", "job", "from", "the", "queue", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/InteractsWithQueue.php#L42-L47
dave-redfern/laravel-doctrine-tenancy
src/Http/Controller/TenantController.php
TenantController.tenantTypeNotSupportedAction
public function tenantTypeNotSupportedAction(Request $request) { return view($this->getTenantTypeNotSupportedView(), [ 'user' => auth()->user(), 'type' => $request->get('type', 'Not Defined'), ]); }
php
public function tenantTypeNotSupportedAction(Request $request) { return view($this->getTenantTypeNotSupportedView(), [ 'user' => auth()->user(), 'type' => $request->get('type', 'Not Defined'), ]); }
[ "public", "function", "tenantTypeNotSupportedAction", "(", "Request", "$", "request", ")", "{", "return", "view", "(", "$", "this", "->", "getTenantTypeNotSupportedView", "(", ")", ",", "[", "'user'", "=>", "auth", "(", ")", "->", "user", "(", ")", ",", "'...
Route: tenant.tenant_type_not_supported @param Request $request @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
[ "Route", ":", "tenant", ".", "tenant_type_not_supported" ]
train
https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Http/Controller/TenantController.php#L93-L99
kiwiz/esquery
src/Util.php
Util.escapeString
public static function escapeString($str, $allow_wildcards=false) { $needles = [ '\\', '+', '-', '=', '&&', '||', '>', '<', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', ':', '/', ' ' ]; $replacements = [ '\\\\', '\\+', '\\-', '\\=', '\\&&', '\\||', '\\>', '\\<', '\\!', '\\(', '\\)', '\\{', '\\}', '\\[', '\\]', '\\^', '\\"', '\\~', '\\:', '\\/', '\\ ' ]; if(!$allow_wildcards) { $needles = array_merge($needles, ['*', '?']); $replacements = array_merge($replacements, ['\\*', '\\?']); } return str_replace($needles, $replacements, $str); }
php
public static function escapeString($str, $allow_wildcards=false) { $needles = [ '\\', '+', '-', '=', '&&', '||', '>', '<', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', ':', '/', ' ' ]; $replacements = [ '\\\\', '\\+', '\\-', '\\=', '\\&&', '\\||', '\\>', '\\<', '\\!', '\\(', '\\)', '\\{', '\\}', '\\[', '\\]', '\\^', '\\"', '\\~', '\\:', '\\/', '\\ ' ]; if(!$allow_wildcards) { $needles = array_merge($needles, ['*', '?']); $replacements = array_merge($replacements, ['\\*', '\\?']); } return str_replace($needles, $replacements, $str); }
[ "public", "static", "function", "escapeString", "(", "$", "str", ",", "$", "allow_wildcards", "=", "false", ")", "{", "$", "needles", "=", "[", "'\\\\'", ",", "'+'", ",", "'-'", ",", "'='", ",", "'&&'", ",", "'||'", ",", "'>'", ",", "'<'", ",", "'!...
Escape special characters in a query.
[ "Escape", "special", "characters", "in", "a", "query", "." ]
train
https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Util.php#L15-L29
kiwiz/esquery
src/Util.php
Util.escapeGroup
public static function escapeGroup($arr, $wildcard=false) { return implode('', array_map(function($x) use ($wildcard) { if(is_string($x)) { if($wildcard) { return Util::escapeString($x); } else { return '"' . str_replace('"', '\\"', $x) . '"'; } } else if($x == Token::W_STAR) { return '*'; } else if ($x == Token::W_QMARK) { return '?'; } }, $arr)); }
php
public static function escapeGroup($arr, $wildcard=false) { return implode('', array_map(function($x) use ($wildcard) { if(is_string($x)) { if($wildcard) { return Util::escapeString($x); } else { return '"' . str_replace('"', '\\"', $x) . '"'; } } else if($x == Token::W_STAR) { return '*'; } else if ($x == Token::W_QMARK) { return '?'; } }, $arr)); }
[ "public", "static", "function", "escapeGroup", "(", "$", "arr", ",", "$", "wildcard", "=", "false", ")", "{", "return", "implode", "(", "''", ",", "array_map", "(", "function", "(", "$", "x", ")", "use", "(", "$", "wildcard", ")", "{", "if", "(", "...
Escape special characters in an array of query chunks.
[ "Escape", "special", "characters", "in", "an", "array", "of", "query", "chunks", "." ]
train
https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Util.php#L32-L46
kiwiz/esquery
src/Util.php
Util.combine
public static function combine($first, $rest, $idx) { $ret = []; $ret[] = $first; foreach($rest as $val) { $ret[] = $val[$idx]; } return $ret; }
php
public static function combine($first, $rest, $idx) { $ret = []; $ret[] = $first; foreach($rest as $val) { $ret[] = $val[$idx]; } return $ret; }
[ "public", "static", "function", "combine", "(", "$", "first", ",", "$", "rest", ",", "$", "idx", ")", "{", "$", "ret", "=", "[", "]", ";", "$", "ret", "[", "]", "=", "$", "first", ";", "foreach", "(", "$", "rest", "as", "$", "val", ")", "{", ...
Parser helper. Flatten results into an array.
[ "Parser", "helper", ".", "Flatten", "results", "into", "an", "array", "." ]
train
https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Util.php#L49-L57
kiwiz/esquery
src/Util.php
Util.assoc
public static function assoc($first, $rest, $idx) { $ret = []; $ret[$first[0]] = $first[1]; foreach($rest as $val) { $ret[$val[$idx][0]] = $val[$idx][1]; } return $ret; }
php
public static function assoc($first, $rest, $idx) { $ret = []; $ret[$first[0]] = $first[1]; foreach($rest as $val) { $ret[$val[$idx][0]] = $val[$idx][1]; } return $ret; }
[ "public", "static", "function", "assoc", "(", "$", "first", ",", "$", "rest", ",", "$", "idx", ")", "{", "$", "ret", "=", "[", "]", ";", "$", "ret", "[", "$", "first", "[", "0", "]", "]", "=", "$", "first", "[", "1", "]", ";", "foreach", "(...
Parser helper. Turn results into an associative array.
[ "Parser", "helper", ".", "Turn", "results", "into", "an", "associative", "array", "." ]
train
https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Util.php#L60-L68
kiwiz/esquery
src/Util.php
Util.generateDateIndices
public static function generateDateIndices($format, $interval, $from_ts, $to_ts) { $fmt_arr = []; $escaped = false; foreach(str_split($format) as $chr) { switch($chr) { case '[': $escaped = true; break; case ']': $escaped = false; break; default: $fmt_arr[] = $escaped ? "\\$chr":$chr; break; } } $fmt_str = implode('', $fmt_arr); $ret = []; $current = new \DateTime("@$from_ts"); $to = new \DateTime("@$to_ts"); $interval_map = [ 'y' => 'year', 'm' => 'month', 'w' => 'week', 'd' => 'day', 'h' => 'hour', ]; $interval_str = Util::get($interval_map, $interval, 'day'); // Zero out the time component. $current->setTime($interval == 'h' ? $current->format('H'):0, 0); while ($current <= $to) { $ret[] = $current->format($fmt_str); $current = $current->modify("+1$interval_str"); } return $ret; }
php
public static function generateDateIndices($format, $interval, $from_ts, $to_ts) { $fmt_arr = []; $escaped = false; foreach(str_split($format) as $chr) { switch($chr) { case '[': $escaped = true; break; case ']': $escaped = false; break; default: $fmt_arr[] = $escaped ? "\\$chr":$chr; break; } } $fmt_str = implode('', $fmt_arr); $ret = []; $current = new \DateTime("@$from_ts"); $to = new \DateTime("@$to_ts"); $interval_map = [ 'y' => 'year', 'm' => 'month', 'w' => 'week', 'd' => 'day', 'h' => 'hour', ]; $interval_str = Util::get($interval_map, $interval, 'day'); // Zero out the time component. $current->setTime($interval == 'h' ? $current->format('H'):0, 0); while ($current <= $to) { $ret[] = $current->format($fmt_str); $current = $current->modify("+1$interval_str"); } return $ret; }
[ "public", "static", "function", "generateDateIndices", "(", "$", "format", ",", "$", "interval", ",", "$", "from_ts", ",", "$", "to_ts", ")", "{", "$", "fmt_arr", "=", "[", "]", ";", "$", "escaped", "=", "false", ";", "foreach", "(", "str_split", "(", ...
Generate a list of date-based indices. @param string $format The index format. @param string $interval The interval size (h,d,w,m,y). @param int $from_ts Start timestamp. @param int $to_ts End timestamp. @return string[] List of indices.
[ "Generate", "a", "list", "of", "date", "-", "based", "indices", "." ]
train
https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Util.php#L78-L119
oxygen-cms/core
src/Console/PackageMigrateCommand.php
PackageMigrateCommand.fire
public function fire() { if(!$this->confirmToProceed()) { return; } $this->prepareDatabase(); // The pretend option can be used for "simulating" the migration and grabbing // the SQL queries that would fire if the migration were to be run against // a database for real, which is helpful for double checking migrations. $pretend = $this->input->getOption('pretend'); // migrate each path foreach($this->paths->getPaths() as $package => $path) { $this->info('Running migrations for ' . $package); $this->migrator->run($path, $pretend); // Once the migrator has run we will grab the note output and send it out to // the console screen, since the migrator itself functions without having // any instances of the OutputInterface contract passed into the class. foreach($this->migrator->getNotes() as $note) { $this->output->writeln($note); } } }
php
public function fire() { if(!$this->confirmToProceed()) { return; } $this->prepareDatabase(); // The pretend option can be used for "simulating" the migration and grabbing // the SQL queries that would fire if the migration were to be run against // a database for real, which is helpful for double checking migrations. $pretend = $this->input->getOption('pretend'); // migrate each path foreach($this->paths->getPaths() as $package => $path) { $this->info('Running migrations for ' . $package); $this->migrator->run($path, $pretend); // Once the migrator has run we will grab the note output and send it out to // the console screen, since the migrator itself functions without having // any instances of the OutputInterface contract passed into the class. foreach($this->migrator->getNotes() as $note) { $this->output->writeln($note); } } }
[ "public", "function", "fire", "(", ")", "{", "if", "(", "!", "$", "this", "->", "confirmToProceed", "(", ")", ")", "{", "return", ";", "}", "$", "this", "->", "prepareDatabase", "(", ")", ";", "// The pretend option can be used for \"simulating\" the migration a...
Execute the console command. @return void
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Console/PackageMigrateCommand.php#L60-L85
oxygen-cms/core
src/Console/PackageMigrateCommand.php
PackageMigrateCommand.prepareDatabase
protected function prepareDatabase() { $this->migrator->setConnection($this->input->getOption('database')); if(!$this->migrator->repositoryExists()) { $options = ['--database' => $this->input->getOption('database')]; $this->call('migrate:install', $options); } }
php
protected function prepareDatabase() { $this->migrator->setConnection($this->input->getOption('database')); if(!$this->migrator->repositoryExists()) { $options = ['--database' => $this->input->getOption('database')]; $this->call('migrate:install', $options); } }
[ "protected", "function", "prepareDatabase", "(", ")", "{", "$", "this", "->", "migrator", "->", "setConnection", "(", "$", "this", "->", "input", "->", "getOption", "(", "'database'", ")", ")", ";", "if", "(", "!", "$", "this", "->", "migrator", "->", ...
Prepare the migration database for running. @return void
[ "Prepare", "the", "migration", "database", "for", "running", "." ]
train
https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Console/PackageMigrateCommand.php#L92-L100
krafthaus/bauhaus
src/KraftHaus/Bauhaus/Export/Builder.php
Builder.export
public function export($type) { $format = sprintf('\\KraftHaus\\Bauhaus\\Export\\Format\\%sFormat', ucfirst($type)); return (new $format) ->setListBuilder($this->getListBuilder()) ->export(); }
php
public function export($type) { $format = sprintf('\\KraftHaus\\Bauhaus\\Export\\Format\\%sFormat', ucfirst($type)); return (new $format) ->setListBuilder($this->getListBuilder()) ->export(); }
[ "public", "function", "export", "(", "$", "type", ")", "{", "$", "format", "=", "sprintf", "(", "'\\\\KraftHaus\\\\Bauhaus\\\\Export\\\\Format\\\\%sFormat'", ",", "ucfirst", "(", "$", "type", ")", ")", ";", "return", "(", "new", "$", "format", ")", "->", "se...
Create a new export based on the ListBuilder output. @param string $type @access public @return mixed
[ "Create", "a", "new", "export", "based", "on", "the", "ListBuilder", "output", "." ]
train
https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/KraftHaus/Bauhaus/Export/Builder.php#L60-L66
txj123/zilf
src/Zilf/Cache/DatabaseStore.php
DatabaseStore.get
public function get($key) { $prefixed = $this->prefix.$key; $cache = $this->table()->where('key', '=', $prefixed)->first(); // If we have a cache record we will check the expiration time against current // time on the system and see if the record has expired. If it has, we will // remove the records from the database table so it isn't returned again. if (is_null($cache)) { return; } $cache = is_array($cache) ? (object) $cache : $cache; // If this cache expiration date is past the current time, we will remove this // item from the cache. Then we will return a null value since the cache is // expired. We will use "Carbon" to make this comparison with the column. if (Carbon::now()->getTimestamp() >= $cache->expiration) { $this->forget($key); return; } return unserialize($cache->value); }
php
public function get($key) { $prefixed = $this->prefix.$key; $cache = $this->table()->where('key', '=', $prefixed)->first(); // If we have a cache record we will check the expiration time against current // time on the system and see if the record has expired. If it has, we will // remove the records from the database table so it isn't returned again. if (is_null($cache)) { return; } $cache = is_array($cache) ? (object) $cache : $cache; // If this cache expiration date is past the current time, we will remove this // item from the cache. Then we will return a null value since the cache is // expired. We will use "Carbon" to make this comparison with the column. if (Carbon::now()->getTimestamp() >= $cache->expiration) { $this->forget($key); return; } return unserialize($cache->value); }
[ "public", "function", "get", "(", "$", "key", ")", "{", "$", "prefixed", "=", "$", "this", "->", "prefix", ".", "$", "key", ";", "$", "cache", "=", "$", "this", "->", "table", "(", ")", "->", "where", "(", "'key'", ",", "'='", ",", "$", "prefix...
Retrieve an item from the cache by key. @param string|array $key @return mixed
[ "Retrieve", "an", "item", "from", "the", "cache", "by", "key", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Cache/DatabaseStore.php#L57-L82
txj123/zilf
src/Zilf/Cache/DatabaseStore.php
DatabaseStore.put
public function put($key, $value, $minutes) { $key = $this->prefix.$key; $value = serialize($value); $expiration = $this->getTime() + (int) ($minutes * 60); try { $this->table()->insert(compact('key', 'value', 'expiration')); } catch (Exception $e) { $this->table()->where('key', $key)->update(compact('value', 'expiration')); } }
php
public function put($key, $value, $minutes) { $key = $this->prefix.$key; $value = serialize($value); $expiration = $this->getTime() + (int) ($minutes * 60); try { $this->table()->insert(compact('key', 'value', 'expiration')); } catch (Exception $e) { $this->table()->where('key', $key)->update(compact('value', 'expiration')); } }
[ "public", "function", "put", "(", "$", "key", ",", "$", "value", ",", "$", "minutes", ")", "{", "$", "key", "=", "$", "this", "->", "prefix", ".", "$", "key", ";", "$", "value", "=", "serialize", "(", "$", "value", ")", ";", "$", "expiration", ...
Store an item in the cache for a given number of minutes. @param string $key @param mixed $value @param float|int $minutes @return void
[ "Store", "an", "item", "in", "the", "cache", "for", "a", "given", "number", "of", "minutes", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Cache/DatabaseStore.php#L92-L105
netzmacht/contao-icon-wizard
src/IconWidget.php
IconWidget.validator
protected function validator($value) { $value = parent::validator($value); if ($this->hasErrors()) { return null; } elseif ($value == '') { if ($this->mandatory) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['mandatory'], $this->strLabel)); } } elseif (!$this->iconExists($value)) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['iconNotFound'], $this->strLabel)); } return $value; }
php
protected function validator($value) { $value = parent::validator($value); if ($this->hasErrors()) { return null; } elseif ($value == '') { if ($this->mandatory) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['mandatory'], $this->strLabel)); } } elseif (!$this->iconExists($value)) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['iconNotFound'], $this->strLabel)); } return $value; }
[ "protected", "function", "validator", "(", "$", "value", ")", "{", "$", "value", "=", "parent", "::", "validator", "(", "$", "value", ")", ";", "if", "(", "$", "this", "->", "hasErrors", "(", ")", ")", "{", "return", "null", ";", "}", "elseif", "("...
Call the validator. @param mixed $value The value. @return mixed @SuppressWarnings(PHPMD.Superglobals)
[ "Call", "the", "validator", "." ]
train
https://github.com/netzmacht/contao-icon-wizard/blob/d0b5dba08d8167740f5828d0ee49b11f3eb0b946/src/IconWidget.php#L121-L136
netzmacht/contao-icon-wizard
src/IconWidget.php
IconWidget.generate
public function generate() { $url = sprintf( 'system/modules/icon-wizard/public/popup.php?table=%s&amp;field=%s&amp;name=ctrl_%s&amp;id=%s', $this->strTable, $this->strField, $this->name, \Input::get('id') ); $template = <<<HTML <div class="iconWizard"><input type="hidden" name="%s" id="ctrl_%s" value="%s"%s <span class="icon">%s</span> <span class="title">%s</span><a href="%s" onclick="Backend.getScrollOffset();Backend.openModalIframe({url:'%s', width: %s, title: '%s'});return false" title="%s" class="tl_submit">%s</a></div> HTML; return sprintf( $template, $this->name, $this->name, $this->icon, $this->strTagEnding, $this->icon ? sprintf($this->iconTemplate, $this->icon) : '', $this->icon ? $this->icon : '-', $url, $url, 790, $GLOBALS['TL_LANG']['MSC']['iconWizard'][0], $GLOBALS['TL_LANG']['MSC']['iconWizardlink'][1], $GLOBALS['TL_LANG']['MSC']['iconWizardlink'][0] ); }
php
public function generate() { $url = sprintf( 'system/modules/icon-wizard/public/popup.php?table=%s&amp;field=%s&amp;name=ctrl_%s&amp;id=%s', $this->strTable, $this->strField, $this->name, \Input::get('id') ); $template = <<<HTML <div class="iconWizard"><input type="hidden" name="%s" id="ctrl_%s" value="%s"%s <span class="icon">%s</span> <span class="title">%s</span><a href="%s" onclick="Backend.getScrollOffset();Backend.openModalIframe({url:'%s', width: %s, title: '%s'});return false" title="%s" class="tl_submit">%s</a></div> HTML; return sprintf( $template, $this->name, $this->name, $this->icon, $this->strTagEnding, $this->icon ? sprintf($this->iconTemplate, $this->icon) : '', $this->icon ? $this->icon : '-', $url, $url, 790, $GLOBALS['TL_LANG']['MSC']['iconWizard'][0], $GLOBALS['TL_LANG']['MSC']['iconWizardlink'][1], $GLOBALS['TL_LANG']['MSC']['iconWizardlink'][0] ); }
[ "public", "function", "generate", "(", ")", "{", "$", "url", "=", "sprintf", "(", "'system/modules/icon-wizard/public/popup.php?table=%s&amp;field=%s&amp;name=ctrl_%s&amp;id=%s'", ",", "$", "this", "->", "strTable", ",", "$", "this", "->", "strField", ",", "$", "this"...
Generate the widget. @return string @SuppressWarnings(PHPMD.Superglobals)
[ "Generate", "the", "widget", "." ]
train
https://github.com/netzmacht/contao-icon-wizard/blob/d0b5dba08d8167740f5828d0ee49b11f3eb0b946/src/IconWidget.php#L145-L177
netzmacht/contao-icon-wizard
src/IconWidget.php
IconWidget.iconExists
protected function iconExists($icon) { foreach ($this->icons as $group) { foreach ($group as $entry) { if (!is_array($entry)) { continue; } if ($entry['value'] === $icon) { return true; } } } return false; }
php
protected function iconExists($icon) { foreach ($this->icons as $group) { foreach ($group as $entry) { if (!is_array($entry)) { continue; } if ($entry['value'] === $icon) { return true; } } } return false; }
[ "protected", "function", "iconExists", "(", "$", "icon", ")", "{", "foreach", "(", "$", "this", "->", "icons", "as", "$", "group", ")", "{", "foreach", "(", "$", "group", "as", "$", "entry", ")", "{", "if", "(", "!", "is_array", "(", "$", "entry", ...
Check if icon exists. @param string $icon The icon name. @return bool
[ "Check", "if", "icon", "exists", "." ]
train
https://github.com/netzmacht/contao-icon-wizard/blob/d0b5dba08d8167740f5828d0ee49b11f3eb0b946/src/IconWidget.php#L186-L201
dave-redfern/laravel-doctrine-tenancy
src/Http/TenantRedirectorService.php
TenantRedirectorService.resolve
public function resolve($user) { if ($user instanceof ParticipantContract) { return redirect()->route('tenant.index', [ 'tenant_owner_id' => $user->getTenantParticipant()->getTenantOwner()->getId(), 'tenant_creator_id' => $user->getTenantParticipant()->getId() ]); } if ($user instanceof ParticipantsContract) { switch ($user->getTenantParticipants()->count()) { case 0: $response = redirect()->route('tenant.no_tenants'); break; case 1: $response = redirect()->route('tenant.index', [ 'tenant_owner_id' => $user->getTenantParticipants()->first()->getTenantOwner()->getId(), 'tenant_creator_id' => $user->getTenantParticipants()->first()->getId() ]); break; default: $response = redirect()->route('tenant.select_tenant'); } return $response; } throw new \InvalidArgumentException( sprintf('Supplied Authenticatable User instance does not implement tenancy') ); }
php
public function resolve($user) { if ($user instanceof ParticipantContract) { return redirect()->route('tenant.index', [ 'tenant_owner_id' => $user->getTenantParticipant()->getTenantOwner()->getId(), 'tenant_creator_id' => $user->getTenantParticipant()->getId() ]); } if ($user instanceof ParticipantsContract) { switch ($user->getTenantParticipants()->count()) { case 0: $response = redirect()->route('tenant.no_tenants'); break; case 1: $response = redirect()->route('tenant.index', [ 'tenant_owner_id' => $user->getTenantParticipants()->first()->getTenantOwner()->getId(), 'tenant_creator_id' => $user->getTenantParticipants()->first()->getId() ]); break; default: $response = redirect()->route('tenant.select_tenant'); } return $response; } throw new \InvalidArgumentException( sprintf('Supplied Authenticatable User instance does not implement tenancy') ); }
[ "public", "function", "resolve", "(", "$", "user", ")", "{", "if", "(", "$", "user", "instanceof", "ParticipantContract", ")", "{", "return", "redirect", "(", ")", "->", "route", "(", "'tenant.index'", ",", "[", "'tenant_owner_id'", "=>", "$", "user", "->"...
@param ParticipantContract|ParticipantsContract $user @return \Illuminate\Http\RedirectResponse
[ "@param", "ParticipantContract|ParticipantsContract", "$user" ]
train
https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Http/TenantRedirectorService.php#L43-L73
ivopetkov/lock
src/Lock.php
Lock.acquire
static public function acquire($key, $options = []) { $keyMD5 = md5(self::$keyPrefix . serialize($key)); $timeout = isset($options['timeout']) ? (float) $options['timeout'] : self::$defaultLockTimeout; $retryInterval = 0.5; $maxRetriesCount = floor($timeout / $retryInterval); $lock = function() use ($keyMD5) { if (!isset(self::$data[$keyMD5])) { set_error_handler(function($errno, $errstr) { throw new \Exception($errstr); }); $dir = self::getLocksDir(); if (!is_dir($dir)) { try { mkdir($dir, 0777, true); } catch (\Exception $e) { if ($e->getMessage() !== 'mkdir(): File exists') { // The directory may be just created in other process. restore_error_handler(); return false; } } } $filename = $dir . $keyMD5 . '.lock'; try { $filePointer = fopen($filename, "w"); if ($filePointer !== false && flock($filePointer, LOCK_EX | LOCK_NB) !== false) { self::$data[$keyMD5] = $filePointer; restore_error_handler(); return true; } } catch (\Exception $e) { } restore_error_handler(); return false; } return false; }; $startTime = microtime(true); for ($i = 0; $i < $maxRetriesCount + 1; $i++) { if ($lock()) { return; } if (microtime(true) - $startTime > $timeout) { break; } usleep($retryInterval * 1000000); } throw new \Exception('Cannot acquire lock for "' . $key . '"'); }
php
static public function acquire($key, $options = []) { $keyMD5 = md5(self::$keyPrefix . serialize($key)); $timeout = isset($options['timeout']) ? (float) $options['timeout'] : self::$defaultLockTimeout; $retryInterval = 0.5; $maxRetriesCount = floor($timeout / $retryInterval); $lock = function() use ($keyMD5) { if (!isset(self::$data[$keyMD5])) { set_error_handler(function($errno, $errstr) { throw new \Exception($errstr); }); $dir = self::getLocksDir(); if (!is_dir($dir)) { try { mkdir($dir, 0777, true); } catch (\Exception $e) { if ($e->getMessage() !== 'mkdir(): File exists') { // The directory may be just created in other process. restore_error_handler(); return false; } } } $filename = $dir . $keyMD5 . '.lock'; try { $filePointer = fopen($filename, "w"); if ($filePointer !== false && flock($filePointer, LOCK_EX | LOCK_NB) !== false) { self::$data[$keyMD5] = $filePointer; restore_error_handler(); return true; } } catch (\Exception $e) { } restore_error_handler(); return false; } return false; }; $startTime = microtime(true); for ($i = 0; $i < $maxRetriesCount + 1; $i++) { if ($lock()) { return; } if (microtime(true) - $startTime > $timeout) { break; } usleep($retryInterval * 1000000); } throw new \Exception('Cannot acquire lock for "' . $key . '"'); }
[ "static", "public", "function", "acquire", "(", "$", "key", ",", "$", "options", "=", "[", "]", ")", "{", "$", "keyMD5", "=", "md5", "(", "self", "::", "$", "keyPrefix", ".", "serialize", "(", "$", "key", ")", ")", ";", "$", "timeout", "=", "isse...
Acquires a new lock for the key specified. @param mixed $key The key of the lock. @param array $options Lock options. Available values: - timeout - A time (in seconds) to retry acquiring the lock. @throws \Exception
[ "Acquires", "a", "new", "lock", "for", "the", "key", "specified", "." ]
train
https://github.com/ivopetkov/lock/blob/8b2a5f6dd3f1431c643d4eda2f647141a8811b50/src/Lock.php#L91-L140
ivopetkov/lock
src/Lock.php
Lock.exists
static public function exists($key) { $keyMD5 = md5(self::$keyPrefix . serialize($key)); $dir = self::getLocksDir(); if (!is_dir($dir)) { return false; } $filename = $dir . $keyMD5 . '.lock'; set_error_handler(function($errno, $errstr) { throw new \Exception($errstr); }); try { $filePointer = fopen($filename, "w"); if ($filePointer !== false) { $wouldBlock = null; if (flock($filePointer, LOCK_EX | LOCK_NB, $wouldBlock)) { restore_error_handler(); return false; } else { restore_error_handler(); return $wouldBlock === 1; } } } catch (\Exception $e) { } restore_error_handler(); throw new \Exception('Cannot check if lock named "' . $key . '" exists.'); }
php
static public function exists($key) { $keyMD5 = md5(self::$keyPrefix . serialize($key)); $dir = self::getLocksDir(); if (!is_dir($dir)) { return false; } $filename = $dir . $keyMD5 . '.lock'; set_error_handler(function($errno, $errstr) { throw new \Exception($errstr); }); try { $filePointer = fopen($filename, "w"); if ($filePointer !== false) { $wouldBlock = null; if (flock($filePointer, LOCK_EX | LOCK_NB, $wouldBlock)) { restore_error_handler(); return false; } else { restore_error_handler(); return $wouldBlock === 1; } } } catch (\Exception $e) { } restore_error_handler(); throw new \Exception('Cannot check if lock named "' . $key . '" exists.'); }
[ "static", "public", "function", "exists", "(", "$", "key", ")", "{", "$", "keyMD5", "=", "md5", "(", "self", "::", "$", "keyPrefix", ".", "serialize", "(", "$", "key", ")", ")", ";", "$", "dir", "=", "self", "::", "getLocksDir", "(", ")", ";", "i...
Checks if a lock exists. @param mixed $key The key of the lock. @throws \Exception @return boolean Returns TRUE if the lock exists, FALSE otherwise.
[ "Checks", "if", "a", "lock", "exists", "." ]
train
https://github.com/ivopetkov/lock/blob/8b2a5f6dd3f1431c643d4eda2f647141a8811b50/src/Lock.php#L149-L177
ivopetkov/lock
src/Lock.php
Lock.release
static public function release($key) { $keyMD5 = md5(self::$keyPrefix . serialize($key)); if (!isset(self::$data[$keyMD5])) { throw new \Exception('A lock name "' . $key . '" does not exists in current process!'); } $dir = self::getLocksDir(); if (!is_dir($dir)) { return; } set_error_handler(function($errno, $errstr) { throw new \Exception($errstr); }); try { if (flock(self::$data[$keyMD5], LOCK_UN) && fclose(self::$data[$keyMD5])) { try { $filename = $dir . $keyMD5 . '.lock'; $tempFilename = $filename . '.' . md5(uniqid() . rand(0, 999999)); $renameResult = rename($filename, $tempFilename); if ($renameResult) { unlink($tempFilename); } } catch (\Exception $e) { // Don't care whether the rename is successful } unset(self::$data[$keyMD5]); restore_error_handler(); return; } } catch (\Exception $e) { restore_error_handler(); throw new \Exception('Cannot release the lock named "' . $key . '". Reason: ' . $e->getMessage()); } restore_error_handler(); throw new \Exception('Cannot release the lock named "' . $key . '"'); }
php
static public function release($key) { $keyMD5 = md5(self::$keyPrefix . serialize($key)); if (!isset(self::$data[$keyMD5])) { throw new \Exception('A lock name "' . $key . '" does not exists in current process!'); } $dir = self::getLocksDir(); if (!is_dir($dir)) { return; } set_error_handler(function($errno, $errstr) { throw new \Exception($errstr); }); try { if (flock(self::$data[$keyMD5], LOCK_UN) && fclose(self::$data[$keyMD5])) { try { $filename = $dir . $keyMD5 . '.lock'; $tempFilename = $filename . '.' . md5(uniqid() . rand(0, 999999)); $renameResult = rename($filename, $tempFilename); if ($renameResult) { unlink($tempFilename); } } catch (\Exception $e) { // Don't care whether the rename is successful } unset(self::$data[$keyMD5]); restore_error_handler(); return; } } catch (\Exception $e) { restore_error_handler(); throw new \Exception('Cannot release the lock named "' . $key . '". Reason: ' . $e->getMessage()); } restore_error_handler(); throw new \Exception('Cannot release the lock named "' . $key . '"'); }
[ "static", "public", "function", "release", "(", "$", "key", ")", "{", "$", "keyMD5", "=", "md5", "(", "self", "::", "$", "keyPrefix", ".", "serialize", "(", "$", "key", ")", ")", ";", "if", "(", "!", "isset", "(", "self", "::", "$", "data", "[", ...
Releases a lock. @param mixed $key The key of the lock. @throws \Exception
[ "Releases", "a", "lock", "." ]
train
https://github.com/ivopetkov/lock/blob/8b2a5f6dd3f1431c643d4eda2f647141a8811b50/src/Lock.php#L185-L220
czukowski/markdown-toc
classes/TOCTrait.php
TOCTrait.findHeadlines
protected function findHeadlines($markdown, $fromLevel = 1, $toLevel = 6) { $headlines = []; foreach ($this->parseBlocks($this->splitLines($markdown)) as $block) { if ($this->isItemOfType($block, 'headline') && isset($block['level']) && $block['level'] >= $fromLevel && $block['level'] <= $toLevel ) { $headlines[] = $block; } } return $headlines; }
php
protected function findHeadlines($markdown, $fromLevel = 1, $toLevel = 6) { $headlines = []; foreach ($this->parseBlocks($this->splitLines($markdown)) as $block) { if ($this->isItemOfType($block, 'headline') && isset($block['level']) && $block['level'] >= $fromLevel && $block['level'] <= $toLevel ) { $headlines[] = $block; } } return $headlines; }
[ "protected", "function", "findHeadlines", "(", "$", "markdown", ",", "$", "fromLevel", "=", "1", ",", "$", "toLevel", "=", "6", ")", "{", "$", "headlines", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "parseBlocks", "(", "$", "this", "->", ...
Finds headlines in a markdown content. @param string $markdown source markdown. @param integer $fromLevel find headlines starting with this level @param integer $toLevel find headlines up to this level @return array
[ "Finds", "headlines", "in", "a", "markdown", "content", "." ]
train
https://github.com/czukowski/markdown-toc/blob/eb1682acf9515afa19ee710666011937dcb4a2fc/classes/TOCTrait.php#L58-L68
czukowski/markdown-toc
classes/TOCTrait.php
TOCTrait.toAscii
protected static function toAscii($s) { static $transliterator = NULL; if ($transliterator === NULL && class_exists('Transliterator', FALSE)) { $transliterator = \Transliterator::create('Any-Latin; Latin-ASCII'); } $s = preg_replace('#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{2FF}\x{370}-\x{10FFFF}]#u', '', $s); $s = strtr($s, '`\'"^~?', "\x01\x02\x03\x04\x05\x06"); $s = str_replace( ["\xE2\x80\x9E", "\xE2\x80\x9C", "\xE2\x80\x9D", "\xE2\x80\x9A", "\xE2\x80\x98", "\xE2\x80\x99", "\xC2\xB0"], ["\x03", "\x03", "\x03", "\x02", "\x02", "\x02", "\x04"], $s ); if ($transliterator !== NULL) { $s = $transliterator->transliterate($s); } if (ICONV_IMPL === 'glibc') { $s = str_replace( ["\xC2\xBB", "\xC2\xAB", "\xE2\x80\xA6", "\xE2\x84\xA2", "\xC2\xA9", "\xC2\xAE"], ['>>', '<<', '...', 'TM', '(c)', '(R)'], $s ); $s = @iconv('UTF-8', 'WINDOWS-1250//TRANSLIT//IGNORE', $s); // intentionally @ $s = strtr($s, "\xa5\xa3\xbc\x8c\xa7\x8a\xaa\x8d\x8f\x8e\xaf\xb9\xb3\xbe\x9c\x9a\xba\x9d\x9f\x9e" ."\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3" ."\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8" ."\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe" ."\x96\xa0\x8b\x97\x9b\xa6\xad\xb7", 'ALLSSSSTZZZallssstzzzRAAAALCCCEEEEIIDDNNOOOOxRUUUUYTsraaaalccceeeeiiddnnooooruuuuyt- <->|-.'); $s = preg_replace('#[^\x00-\x7F]++#', '', $s); } else { $s = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s); // intentionally @ } $s = str_replace(['`', "'", '"', '^', '~', '?'], '', $s); return strtr($s, "\x01\x02\x03\x04\x05\x06", '`\'"^~?'); }
php
protected static function toAscii($s) { static $transliterator = NULL; if ($transliterator === NULL && class_exists('Transliterator', FALSE)) { $transliterator = \Transliterator::create('Any-Latin; Latin-ASCII'); } $s = preg_replace('#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{2FF}\x{370}-\x{10FFFF}]#u', '', $s); $s = strtr($s, '`\'"^~?', "\x01\x02\x03\x04\x05\x06"); $s = str_replace( ["\xE2\x80\x9E", "\xE2\x80\x9C", "\xE2\x80\x9D", "\xE2\x80\x9A", "\xE2\x80\x98", "\xE2\x80\x99", "\xC2\xB0"], ["\x03", "\x03", "\x03", "\x02", "\x02", "\x02", "\x04"], $s ); if ($transliterator !== NULL) { $s = $transliterator->transliterate($s); } if (ICONV_IMPL === 'glibc') { $s = str_replace( ["\xC2\xBB", "\xC2\xAB", "\xE2\x80\xA6", "\xE2\x84\xA2", "\xC2\xA9", "\xC2\xAE"], ['>>', '<<', '...', 'TM', '(c)', '(R)'], $s ); $s = @iconv('UTF-8', 'WINDOWS-1250//TRANSLIT//IGNORE', $s); // intentionally @ $s = strtr($s, "\xa5\xa3\xbc\x8c\xa7\x8a\xaa\x8d\x8f\x8e\xaf\xb9\xb3\xbe\x9c\x9a\xba\x9d\x9f\x9e" ."\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3" ."\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8" ."\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe" ."\x96\xa0\x8b\x97\x9b\xa6\xad\xb7", 'ALLSSSSTZZZallssstzzzRAAAALCCCEEEEIIDDNNOOOOxRUUUUYTsraaaalccceeeeiiddnnooooruuuuyt- <->|-.'); $s = preg_replace('#[^\x00-\x7F]++#', '', $s); } else { $s = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s); // intentionally @ } $s = str_replace(['`', "'", '"', '^', '~', '?'], '', $s); return strtr($s, "\x01\x02\x03\x04\x05\x06", '`\'"^~?'); }
[ "protected", "static", "function", "toAscii", "(", "$", "s", ")", "{", "static", "$", "transliterator", "=", "NULL", ";", "if", "(", "$", "transliterator", "===", "NULL", "&&", "class_exists", "(", "'Transliterator'", ",", "FALSE", ")", ")", "{", "$", "t...
Converts string to ASCII. This function is taken from `nette/utils` package. @author David Grudl <https://davidgrudl.com> @see https://github.com/nette/utils @license https://github.com/nette/utils/blob/master/license.md @param string $s UTF-8 encoding @return string ASCII
[ "Converts", "string", "to", "ASCII", "." ]
train
https://github.com/czukowski/markdown-toc/blob/eb1682acf9515afa19ee710666011937dcb4a2fc/classes/TOCTrait.php#L229-L262
czukowski/markdown-toc
classes/TOCTrait.php
TOCTrait.webalize
protected static function webalize($s, $charlist = NULL, $lower = TRUE) { $s = self::toAscii($s); if ($lower) { $s = strtolower($s); } $s = preg_replace('#[^a-z0-9'.preg_quote($charlist, '#').']+#i', '-', $s); $s = trim($s, '-'); return $s; }
php
protected static function webalize($s, $charlist = NULL, $lower = TRUE) { $s = self::toAscii($s); if ($lower) { $s = strtolower($s); } $s = preg_replace('#[^a-z0-9'.preg_quote($charlist, '#').']+#i', '-', $s); $s = trim($s, '-'); return $s; }
[ "protected", "static", "function", "webalize", "(", "$", "s", ",", "$", "charlist", "=", "NULL", ",", "$", "lower", "=", "TRUE", ")", "{", "$", "s", "=", "self", "::", "toAscii", "(", "$", "s", ")", ";", "if", "(", "$", "lower", ")", "{", "$", ...
Converts to web safe characters [a-z0-9-] text. This function is taken from `nette/utils` package. @author David Grudl <https://davidgrudl.com> @see https://github.com/nette/utils @license https://github.com/nette/utils/blob/master/license.md @param string $s UTF-8 encoding @param string $charlist allowed characters @param boolean $lower convert to lower case? @return string
[ "Converts", "to", "web", "safe", "characters", "[", "a", "-", "z0", "-", "9", "-", "]", "text", "." ]
train
https://github.com/czukowski/markdown-toc/blob/eb1682acf9515afa19ee710666011937dcb4a2fc/classes/TOCTrait.php#L278-L286
xutl/qcloud-cmq
src/Requests/BatchPublishMessageRequest.php
BatchPublishMessageRequest.setMsgBodys
public function setMsgBodys($msgBodys) { if (is_array($msgBodys) && !empty($msgBodys)) { $n = 1; foreach ($msgBodys as $msgBody) { $key = 'msgBody.' . $n; $this->setParameter($key, $msgBody); $n += 1; } } return $this; }
php
public function setMsgBodys($msgBodys) { if (is_array($msgBodys) && !empty($msgBodys)) { $n = 1; foreach ($msgBodys as $msgBody) { $key = 'msgBody.' . $n; $this->setParameter($key, $msgBody); $n += 1; } } return $this; }
[ "public", "function", "setMsgBodys", "(", "$", "msgBodys", ")", "{", "if", "(", "is_array", "(", "$", "msgBodys", ")", "&&", "!", "empty", "(", "$", "msgBodys", ")", ")", "{", "$", "n", "=", "1", ";", "foreach", "(", "$", "msgBodys", "as", "$", "...
为方便用户使用,n 从 0 开始或者从 1 开始都可以,但必须连续,例如发送两条消息,可以是(msgBody.0, msgBody.1),或者(msgBody.1, msgBody.2)。 注意:由于目前限制所有消息大小总和(不包含消息头和其他参数,仅msgBody)不超过 64k,所以建议提前规划好批量发送的数量。 @param array $msgBodys @return BaseRequest
[ "为方便用户使用,n", "从", "0", "开始或者从", "1", "开始都可以,但必须连续,例如发送两条消息,可以是", "(", "msgBody", ".", "0", "msgBody", ".", "1", ")", ",或者", "(", "msgBody", ".", "1", "msgBody", ".", "2", ")", "。", "注意:由于目前限制所有消息大小总和(不包含消息头和其他参数,仅msgBody)不超过", "64k,所以建议提前规划好批量发送的数量。" ]
train
https://github.com/xutl/qcloud-cmq/blob/f48b905c2d4001817126f0c25a0433acda79ea6a/src/Requests/BatchPublishMessageRequest.php#L40-L51
xutl/qcloud-cmq
src/Requests/BatchPublishMessageRequest.php
BatchPublishMessageRequest.setFilterTags
public function setFilterTags($tags) { if (is_array($tags) && !empty($tags)) { $n = 1; foreach ($tags as $tag) { $key = 'filterTag.' . $n; $this->setParameter($key, $tag); $n += 1; } } return $this; }
php
public function setFilterTags($tags) { if (is_array($tags) && !empty($tags)) { $n = 1; foreach ($tags as $tag) { $key = 'filterTag.' . $n; $this->setParameter($key, $tag); $n += 1; } } return $this; }
[ "public", "function", "setFilterTags", "(", "$", "tags", ")", "{", "if", "(", "is_array", "(", "$", "tags", ")", "&&", "!", "empty", "(", "$", "tags", ")", ")", "{", "$", "n", "=", "1", ";", "foreach", "(", "$", "tags", "as", "$", "tag", ")", ...
消息正文。消息标签(用于消息过滤)。标签数量不能超过5个,每个标签不超过16个字符。与 (Batch)PublishMessage 的 msgTag 参数配合使用,规则:1)如果 filterTag 没有设置, 则无论 msgTag 是否有设置,订阅接收所有发布到 Topic 的消息;2)如果 filterTag 数组有值,则只有数组中至少有一个值在 msgTag 数组中也存在时(即 filterTag 和 msgTag 有交集),订阅才接收该发布到 Topic 的消息;3) 如果 filterTag 数组有值,但 msgTag 没设置,则不接收任何发布到 Topic 的消息,可以认为是2)的一种特例,此时 filterTag 和 msgTag 没有交集。规则整体的设计思想是以订阅者的意愿为主。 @param array $tags @return BaseRequest
[ "消息正文。消息标签(用于消息过滤", ")", "。标签数量不能超过5个,每个标签不超过16个字符。与", "(", "Batch", ")", "PublishMessage", "的", "msgTag", "参数配合使用,规则:1)如果", "filterTag", "没有设置,", "则无论", "msgTag", "是否有设置,订阅接收所有发布到", "Topic", "的消息;2)如果", "filterTag", "数组有值,则只有数组中至少有一个值在", "msgTag", "数组中也存在时(即", "filterTag",...
train
https://github.com/xutl/qcloud-cmq/blob/f48b905c2d4001817126f0c25a0433acda79ea6a/src/Requests/BatchPublishMessageRequest.php#L74-L85
webbuilders-group/silverstripe-frontendgridfield
code/forms/FrontEndGridFieldDetailForm.php
FrontEndGridFieldDetailForm_ItemRequest.ItemEditForm
public function ItemEditForm() { $list=$this->gridField->getList(); if(empty($this->record)) { $controller=$this->getToplevelController(); $noActionURL=$controller->removeAction($_REQUEST['url']); $controller->getResponse()->removeHeader('Location'); //clear the existing redirect return $controller->redirect($noActionURL, 302); } $canView=$this->record->canView(); $canEdit=$this->record->canEdit(); $canDelete=$this->record->canDelete(); $canCreate=$this->record->canCreate(); if(!$canView) { return $this->getToplevelController()->httpError(403); } $actions=new FieldList(); if($this->record->ID!==0) { if($canEdit) { $actions->push(FormAction::create('doSave', _t('GridFieldDetailForm.Save', 'Save')) ->setUseButtonTag(true) ->addExtraClass('ss-ui-action-constructive') ->setAttribute('data-icon', 'accept')); } if($canDelete) { $actions->push(FormAction::create('doDelete', _t('GridFieldDetailForm.Delete', 'Delete')) ->setUseButtonTag(true) ->addExtraClass('ss-ui-action-destructive action-delete')); } }else { // adding new record //Change the Save label to 'Create' $actions->push(FormAction::create('doSave', _t('GridFieldDetailForm.Create', 'Create')) ->setUseButtonTag(true) ->addExtraClass('ss-ui-action-constructive') ->setAttribute('data-icon', 'add')); // Add a Cancel link which is a button-like link and link back to one level up. $curmbs = $this->Breadcrumbs(); if($curmbs && $curmbs->count()>=2){ $one_level_up = $curmbs->offsetGet($curmbs->count()-2); $text=sprintf( "<a class=\"%s\" href=\"%s\">%s</a>", "crumb ss-ui-button ss-ui-action-destructive cms-panel-link ui-corner-all", // CSS classes $one_level_up->Link, // url _t('GridFieldDetailForm.CancelBtn', 'Cancel') // label ); $actions->push(new LiteralField('cancelbutton', $text)); } } // If we are creating a new record in a has-many list, then // pre-populate the record's foreign key. if($list instanceof HasManyList && !$this->record->isInDB()) { $key=$list->getForeignKey(); $id=$list->getForeignID(); $this->record->$key=$id; } $fields=$this->component->getFields(); if(!$fields) { $fields=($this->record->hasMethod('getFrontEndFields') ? $this->record->getFrontEndFields():$this->record->getCMSFields()); } // If we are creating a new record in a has-many list, then // Disable the form field as it has no effect. if($list instanceof HasManyList) { $key=$list->getForeignKey(); if($field=$fields->dataFieldByName($key)) { $fields->makeFieldReadonly($field); } } // this pushes the current page ID in as a hidden field // this means the request will have the current page ID in it // rather than relying on session which can have been rewritten // by the user having another tab open // see LeftAndMain::currentPageID if($this->controller->hasMethod('currentPageID') && $this->controller->currentPageID()) { $fields->push(new HiddenField('CMSMainCurrentPageID', null, $this->controller->currentPageID())); } // Caution: API violation. Form expects a Controller, but we are giving it a RequestHandler instead. // Thanks to this however, we are able to nest GridFields, and also access the initial Controller by // dereferencing GridFieldDetailForm_ItemRequest->getController() multiple times. See getToplevelController // below. $form=new Form( $this, 'ItemEditForm', $fields, $actions, $this->component->getValidator() ); $form->loadDataFrom($this->record, ($this->record->ID==0 ? Form::MERGE_IGNORE_FALSEISH:Form::MERGE_DEFAULT)); if($this->record->ID && !$canEdit) { // Restrict editing of existing records $form->makeReadonly(); // Hack to re-enable delete button if user can delete if($canDelete) { $form->Actions()->fieldByName('action_doDelete')->setReadonly(false); } }else if(!$this->record->ID && !$canCreate) { // Restrict creation of new records $form->makeReadonly(); } // Load many_many extraData for record. // Fields with the correct 'ManyMany' namespace need to be added manually through getCMSFields(). if($list instanceof ManyManyList) { $extraData=$list->getExtraData('', $this->record->ID); $form->loadDataFrom(array('ManyMany' => $extraData)); } $cb=$this->component->getItemEditFormCallback(); if($cb) { $cb($form, $this); } $this->extend("updateItemEditForm", $form); return $form; }
php
public function ItemEditForm() { $list=$this->gridField->getList(); if(empty($this->record)) { $controller=$this->getToplevelController(); $noActionURL=$controller->removeAction($_REQUEST['url']); $controller->getResponse()->removeHeader('Location'); //clear the existing redirect return $controller->redirect($noActionURL, 302); } $canView=$this->record->canView(); $canEdit=$this->record->canEdit(); $canDelete=$this->record->canDelete(); $canCreate=$this->record->canCreate(); if(!$canView) { return $this->getToplevelController()->httpError(403); } $actions=new FieldList(); if($this->record->ID!==0) { if($canEdit) { $actions->push(FormAction::create('doSave', _t('GridFieldDetailForm.Save', 'Save')) ->setUseButtonTag(true) ->addExtraClass('ss-ui-action-constructive') ->setAttribute('data-icon', 'accept')); } if($canDelete) { $actions->push(FormAction::create('doDelete', _t('GridFieldDetailForm.Delete', 'Delete')) ->setUseButtonTag(true) ->addExtraClass('ss-ui-action-destructive action-delete')); } }else { // adding new record //Change the Save label to 'Create' $actions->push(FormAction::create('doSave', _t('GridFieldDetailForm.Create', 'Create')) ->setUseButtonTag(true) ->addExtraClass('ss-ui-action-constructive') ->setAttribute('data-icon', 'add')); // Add a Cancel link which is a button-like link and link back to one level up. $curmbs = $this->Breadcrumbs(); if($curmbs && $curmbs->count()>=2){ $one_level_up = $curmbs->offsetGet($curmbs->count()-2); $text=sprintf( "<a class=\"%s\" href=\"%s\">%s</a>", "crumb ss-ui-button ss-ui-action-destructive cms-panel-link ui-corner-all", // CSS classes $one_level_up->Link, // url _t('GridFieldDetailForm.CancelBtn', 'Cancel') // label ); $actions->push(new LiteralField('cancelbutton', $text)); } } // If we are creating a new record in a has-many list, then // pre-populate the record's foreign key. if($list instanceof HasManyList && !$this->record->isInDB()) { $key=$list->getForeignKey(); $id=$list->getForeignID(); $this->record->$key=$id; } $fields=$this->component->getFields(); if(!$fields) { $fields=($this->record->hasMethod('getFrontEndFields') ? $this->record->getFrontEndFields():$this->record->getCMSFields()); } // If we are creating a new record in a has-many list, then // Disable the form field as it has no effect. if($list instanceof HasManyList) { $key=$list->getForeignKey(); if($field=$fields->dataFieldByName($key)) { $fields->makeFieldReadonly($field); } } // this pushes the current page ID in as a hidden field // this means the request will have the current page ID in it // rather than relying on session which can have been rewritten // by the user having another tab open // see LeftAndMain::currentPageID if($this->controller->hasMethod('currentPageID') && $this->controller->currentPageID()) { $fields->push(new HiddenField('CMSMainCurrentPageID', null, $this->controller->currentPageID())); } // Caution: API violation. Form expects a Controller, but we are giving it a RequestHandler instead. // Thanks to this however, we are able to nest GridFields, and also access the initial Controller by // dereferencing GridFieldDetailForm_ItemRequest->getController() multiple times. See getToplevelController // below. $form=new Form( $this, 'ItemEditForm', $fields, $actions, $this->component->getValidator() ); $form->loadDataFrom($this->record, ($this->record->ID==0 ? Form::MERGE_IGNORE_FALSEISH:Form::MERGE_DEFAULT)); if($this->record->ID && !$canEdit) { // Restrict editing of existing records $form->makeReadonly(); // Hack to re-enable delete button if user can delete if($canDelete) { $form->Actions()->fieldByName('action_doDelete')->setReadonly(false); } }else if(!$this->record->ID && !$canCreate) { // Restrict creation of new records $form->makeReadonly(); } // Load many_many extraData for record. // Fields with the correct 'ManyMany' namespace need to be added manually through getCMSFields(). if($list instanceof ManyManyList) { $extraData=$list->getExtraData('', $this->record->ID); $form->loadDataFrom(array('ManyMany' => $extraData)); } $cb=$this->component->getItemEditFormCallback(); if($cb) { $cb($form, $this); } $this->extend("updateItemEditForm", $form); return $form; }
[ "public", "function", "ItemEditForm", "(", ")", "{", "$", "list", "=", "$", "this", "->", "gridField", "->", "getList", "(", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "record", ")", ")", "{", "$", "controller", "=", "$", "this", "->", ...
Builds an item edit form. The arguments to getFrontEndFields() are the popupController and popupFormName, however this is an experimental API and may change. @return Form
[ "Builds", "an", "item", "edit", "form", ".", "The", "arguments", "to", "getFrontEndFields", "()", "are", "the", "popupController", "and", "popupFormName", "however", "this", "is", "an", "experimental", "API", "and", "may", "change", "." ]
train
https://github.com/webbuilders-group/silverstripe-frontendgridfield/blob/e3ff8d3208c279e9af6e15a750af02632876b914/code/forms/FrontEndGridFieldDetailForm.php#L17-L147
webbuilders-group/silverstripe-frontendgridfield
code/forms/FrontEndGridFieldDetailForm.php
FrontEndGridFieldDetailForm_ItemRequest.view
public function view($request) { if(!$this->record->canView()) { $this->httpError(403); } $controller=$this->getToplevelController(); $form=$this->ItemEditForm($this->gridField, $request); $form->makeReadonly(); return $controller->customise(array( 'Title'=>($this->record && $this->record->ID ? $this->record->Title:sprintf(_t('GridField.NewRecord', 'New %s'), $this->record->i18n_singular_name())), 'ItemEditForm'=>$form ))->renderWith($this->template); }
php
public function view($request) { if(!$this->record->canView()) { $this->httpError(403); } $controller=$this->getToplevelController(); $form=$this->ItemEditForm($this->gridField, $request); $form->makeReadonly(); return $controller->customise(array( 'Title'=>($this->record && $this->record->ID ? $this->record->Title:sprintf(_t('GridField.NewRecord', 'New %s'), $this->record->i18n_singular_name())), 'ItemEditForm'=>$form ))->renderWith($this->template); }
[ "public", "function", "view", "(", "$", "request", ")", "{", "if", "(", "!", "$", "this", "->", "record", "->", "canView", "(", ")", ")", "{", "$", "this", "->", "httpError", "(", "403", ")", ";", "}", "$", "controller", "=", "$", "this", "->", ...
Renders the view form @param {SS_HTTPRequest} $request Request data @return {string} Rendered view form
[ "Renders", "the", "view", "form" ]
train
https://github.com/webbuilders-group/silverstripe-frontendgridfield/blob/e3ff8d3208c279e9af6e15a750af02632876b914/code/forms/FrontEndGridFieldDetailForm.php#L154-L168
webbuilders-group/silverstripe-frontendgridfield
code/forms/FrontEndGridFieldDetailForm.php
FrontEndGridFieldDetailForm_ItemRequest.edit
public function edit($request) { $controller=$this->getToplevelController(); $form=$this->ItemEditForm($this->gridField, $request); return $controller->customise(array( 'Title'=>($this->record && $this->record->ID ? $this->record->Title:sprintf(_t('GridField.NewRecord', 'New %s'), $this->record->i18n_singular_name())), 'ItemEditForm'=>$form, ))->renderWith($this->template); }
php
public function edit($request) { $controller=$this->getToplevelController(); $form=$this->ItemEditForm($this->gridField, $request); return $controller->customise(array( 'Title'=>($this->record && $this->record->ID ? $this->record->Title:sprintf(_t('GridField.NewRecord', 'New %s'), $this->record->i18n_singular_name())), 'ItemEditForm'=>$form, ))->renderWith($this->template); }
[ "public", "function", "edit", "(", "$", "request", ")", "{", "$", "controller", "=", "$", "this", "->", "getToplevelController", "(", ")", ";", "$", "form", "=", "$", "this", "->", "ItemEditForm", "(", "$", "this", "->", "gridField", ",", "$", "request...
Renders the edit form @param {SS_HTTPRequest} $request Request data @return {string} Rendered edit form
[ "Renders", "the", "edit", "form" ]
train
https://github.com/webbuilders-group/silverstripe-frontendgridfield/blob/e3ff8d3208c279e9af6e15a750af02632876b914/code/forms/FrontEndGridFieldDetailForm.php#L175-L184
txj123/zilf
src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Abstract.php
Zend_Validate_Abstract.setMessage
public function setMessage($messageString, $messageKey = null) { if ($messageKey === null) { $keys = array_keys($this->_messageTemplates); $messageKey = current($keys); } if (!isset($this->_messageTemplates[$messageKey])) { include_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception("No message template exists for key '$messageKey'"); } $this->_messageTemplates[$messageKey] = $messageString; return $this; }
php
public function setMessage($messageString, $messageKey = null) { if ($messageKey === null) { $keys = array_keys($this->_messageTemplates); $messageKey = current($keys); } if (!isset($this->_messageTemplates[$messageKey])) { include_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception("No message template exists for key '$messageKey'"); } $this->_messageTemplates[$messageKey] = $messageString; return $this; }
[ "public", "function", "setMessage", "(", "$", "messageString", ",", "$", "messageKey", "=", "null", ")", "{", "if", "(", "$", "messageKey", "===", "null", ")", "{", "$", "keys", "=", "array_keys", "(", "$", "this", "->", "_messageTemplates", ")", ";", ...
Sets the validation failure message template for a particular key @param string $messageString @param string $messageKey OPTIONAL @return Zend_Validate_Abstract Provides a fluent interface @throws Zend_Validate_Exception
[ "Sets", "the", "validation", "failure", "message", "template", "for", "a", "particular", "key" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Abstract.php#L124-L136
txj123/zilf
src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Abstract.php
Zend_Validate_Abstract._createMessage
protected function _createMessage($messageKey, $value) { if (!isset($this->_messageTemplates[$messageKey])) { return null; } $message = $this->_messageTemplates[$messageKey]; if (null !== ($translator = $this->getTranslator())) { if ($translator->isTranslated($message)) { $message = $translator->translate($message); } elseif ($translator->isTranslated($messageKey)) { $message = $translator->translate($messageKey); } } if ($this->getObscureValue()) { $value = str_repeat('*', strlen($value)); } $message = str_replace('%value%', (string) $value, $message); foreach ($this->_messageVariables as $ident => $property) { $message = str_replace("%$ident%", $this->$property, $message); } return $message; }
php
protected function _createMessage($messageKey, $value) { if (!isset($this->_messageTemplates[$messageKey])) { return null; } $message = $this->_messageTemplates[$messageKey]; if (null !== ($translator = $this->getTranslator())) { if ($translator->isTranslated($message)) { $message = $translator->translate($message); } elseif ($translator->isTranslated($messageKey)) { $message = $translator->translate($messageKey); } } if ($this->getObscureValue()) { $value = str_repeat('*', strlen($value)); } $message = str_replace('%value%', (string) $value, $message); foreach ($this->_messageVariables as $ident => $property) { $message = str_replace("%$ident%", $this->$property, $message); } return $message; }
[ "protected", "function", "_createMessage", "(", "$", "messageKey", ",", "$", "value", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_messageTemplates", "[", "$", "messageKey", "]", ")", ")", "{", "return", "null", ";", "}", "$", "message"...
Constructs and returns a validation failure message with the given message key and value. Returns null if and only if $messageKey does not correspond to an existing template. If a translator is available and a translation exists for $messageKey, the translation will be used. @param string $messageKey @param string $value @return string
[ "Constructs", "and", "returns", "a", "validation", "failure", "message", "with", "the", "given", "message", "key", "and", "value", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Abstract.php#L188-L213
txj123/zilf
src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Abstract.php
Zend_Validate_Abstract.setTranslator
public function setTranslator($translator = null) { if ((null === $translator) || ($translator instanceof Zend_Translate_Adapter)) { $this->_translator = $translator; } elseif ($translator instanceof Zend_Translate) { $this->_translator = $translator->getAdapter(); } else { include_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Invalid translator specified'); } return $this; }
php
public function setTranslator($translator = null) { if ((null === $translator) || ($translator instanceof Zend_Translate_Adapter)) { $this->_translator = $translator; } elseif ($translator instanceof Zend_Translate) { $this->_translator = $translator->getAdapter(); } else { include_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Invalid translator specified'); } return $this; }
[ "public", "function", "setTranslator", "(", "$", "translator", "=", "null", ")", "{", "if", "(", "(", "null", "===", "$", "translator", ")", "||", "(", "$", "translator", "instanceof", "Zend_Translate_Adapter", ")", ")", "{", "$", "this", "->", "_translato...
Set translation object @param Zend_Translate|Zend_Translate_Adapter|null $translator @return Zend_Validate_Abstract
[ "Set", "translation", "object" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Abstract.php#L286-L297
txj123/zilf
src/Zilf/Routing/RuleItem.php
RuleItem.setRule
public function setRule($rule) { if ('$' == substr($rule, -1, 1)) { // 是否完整匹配 $rule = substr($rule, 0, -1); $this->option['complete_match'] = true; } $rule = '/' != $rule ? ltrim($rule, '/') : ''; if ($this->parent && $prefix = $this->parent->getFullName()) { $rule = $prefix . ($rule ? '/' . ltrim($rule, '/') : ''); } if (false !== strpos($rule, ':')) { $this->rule = preg_replace(['/\[\:(\w+)\]/', '/\:(\w+)/'], ['<\1?>', '<\1>'], $rule); } else { $this->rule = $rule; } // 生成路由标识的快捷访问 $this->setRuleName(); }
php
public function setRule($rule) { if ('$' == substr($rule, -1, 1)) { // 是否完整匹配 $rule = substr($rule, 0, -1); $this->option['complete_match'] = true; } $rule = '/' != $rule ? ltrim($rule, '/') : ''; if ($this->parent && $prefix = $this->parent->getFullName()) { $rule = $prefix . ($rule ? '/' . ltrim($rule, '/') : ''); } if (false !== strpos($rule, ':')) { $this->rule = preg_replace(['/\[\:(\w+)\]/', '/\:(\w+)/'], ['<\1?>', '<\1>'], $rule); } else { $this->rule = $rule; } // 生成路由标识的快捷访问 $this->setRuleName(); }
[ "public", "function", "setRule", "(", "$", "rule", ")", "{", "if", "(", "'$'", "==", "substr", "(", "$", "rule", ",", "-", "1", ",", "1", ")", ")", "{", "// 是否完整匹配", "$", "rule", "=", "substr", "(", "$", "rule", ",", "0", ",", "-", "1", ")", ...
路由规则预处理 @access public @param string $rule 路由规则 @return void
[ "路由规则预处理" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/RuleItem.php#L58-L81
txj123/zilf
src/Zilf/Routing/RuleItem.php
RuleItem.setRuleName
protected function setRuleName($first = false) { if ($this->name) { $vars = $this->parseVar($this->rule); $name = strtolower($this->name); if (isset($this->option['ext'])) { $suffix = $this->option['ext']; } elseif ($this->parent->getOption('ext')) { $suffix = $this->parent->getOption('ext'); } else { $suffix = null; } $value = [$this->rule, $vars, $this->parent->getDomain(), $suffix, $this->method]; Zilf::$container->getShare('ruleName')->set($name, $value, $first); } if (!$this->hasSetRule) { Zilf::$container->getShare('ruleName')->setRule($this->rule, $this); $this->hasSetRule = true; } }
php
protected function setRuleName($first = false) { if ($this->name) { $vars = $this->parseVar($this->rule); $name = strtolower($this->name); if (isset($this->option['ext'])) { $suffix = $this->option['ext']; } elseif ($this->parent->getOption('ext')) { $suffix = $this->parent->getOption('ext'); } else { $suffix = null; } $value = [$this->rule, $vars, $this->parent->getDomain(), $suffix, $this->method]; Zilf::$container->getShare('ruleName')->set($name, $value, $first); } if (!$this->hasSetRule) { Zilf::$container->getShare('ruleName')->setRule($this->rule, $this); $this->hasSetRule = true; } }
[ "protected", "function", "setRuleName", "(", "$", "first", "=", "false", ")", "{", "if", "(", "$", "this", "->", "name", ")", "{", "$", "vars", "=", "$", "this", "->", "parseVar", "(", "$", "this", "->", "rule", ")", ";", "$", "name", "=", "strto...
设置路由标识 用于URL反解生成 @access protected @param bool $first 是否插入开头 @return void
[ "设置路由标识", "用于URL反解生成" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/RuleItem.php#L117-L140
txj123/zilf
src/Zilf/Routing/RuleItem.php
RuleItem.checkRule
public function checkRule($url, $match = null, $completeMatch = false) { if ($dispatch = $this->checkCrossDomain()) { // 允许跨域 return $dispatch; } // 检查参数有效性 if (!$this->checkOption($this->option)) { return false; } // 合并分组参数 $option = $this->mergeGroupOptions(); $url = $this->urlSuffixCheck($url, $option); if (is_null($match)) { $match = $this->match($url, $option, $completeMatch); } if (false !== $match) { // 检查前置行为 if (isset($option['before']) && false === $this->checkBefore($option['before'])) { return false; } return $this->parseRule($this->rule, $this->route, $url, $option, $match); } return false; }
php
public function checkRule($url, $match = null, $completeMatch = false) { if ($dispatch = $this->checkCrossDomain()) { // 允许跨域 return $dispatch; } // 检查参数有效性 if (!$this->checkOption($this->option)) { return false; } // 合并分组参数 $option = $this->mergeGroupOptions(); $url = $this->urlSuffixCheck($url, $option); if (is_null($match)) { $match = $this->match($url, $option, $completeMatch); } if (false !== $match) { // 检查前置行为 if (isset($option['before']) && false === $this->checkBefore($option['before'])) { return false; } return $this->parseRule($this->rule, $this->route, $url, $option, $match); } return false; }
[ "public", "function", "checkRule", "(", "$", "url", ",", "$", "match", "=", "null", ",", "$", "completeMatch", "=", "false", ")", "{", "if", "(", "$", "dispatch", "=", "$", "this", "->", "checkCrossDomain", "(", ")", ")", "{", "// 允许跨域", "return", "$...
检测路由 @access public @param string $url 访问地址 @param array $match 匹配路由变量 @param bool $completeMatch 路由是否完全匹配 @return Dispatch|false
[ "检测路由" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/RuleItem.php#L150-L180
txj123/zilf
src/Zilf/Routing/RuleItem.php
RuleItem.urlSuffixCheck
protected function urlSuffixCheck($url, $option = []) { // 是否区分 / 地址访问 if (!empty($option['remove_slash']) && '/' != $this->rule) { $this->rule = rtrim($this->rule, '/'); $url = rtrim($url, '|'); } if (isset($option['ext'])) { // 路由ext参数 优先于系统配置的URL伪静态后缀参数 $url = preg_replace('/\.(' . $request->ext() . ')$/i', '', $url); } return $url; }
php
protected function urlSuffixCheck($url, $option = []) { // 是否区分 / 地址访问 if (!empty($option['remove_slash']) && '/' != $this->rule) { $this->rule = rtrim($this->rule, '/'); $url = rtrim($url, '|'); } if (isset($option['ext'])) { // 路由ext参数 优先于系统配置的URL伪静态后缀参数 $url = preg_replace('/\.(' . $request->ext() . ')$/i', '', $url); } return $url; }
[ "protected", "function", "urlSuffixCheck", "(", "$", "url", ",", "$", "option", "=", "[", "]", ")", "{", "// 是否区分 / 地址访问", "if", "(", "!", "empty", "(", "$", "option", "[", "'remove_slash'", "]", ")", "&&", "'/'", "!=", "$", "this", "->", "rule", ")"...
URL后缀及Slash检查 @access protected @param Request $request 请求对象 @param string $url 访问地址 @param array $option 路由参数 @return string
[ "URL后缀及Slash检查" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/RuleItem.php#L203-L217
txj123/zilf
src/Zilf/Routing/RuleItem.php
RuleItem.match
private function match($url, $option, $completeMatch) { if (isset($option['complete_match'])) { $completeMatch = $option['complete_match']; } $pattern = array_merge($this->parent->getPattern(), $this->pattern); $depr = $this->router->config('app.pathinfo_depr'); // 检查完整规则定义 if (isset($pattern['__url__']) && !preg_match(0 === strpos($pattern['__url__'], '/') ? $pattern['__url__'] : '/^' . $pattern['__url__'] . '/', str_replace('|', $depr, $url))) { return false; } $var = []; $url = $depr . str_replace('|', $depr, $url); $rule = $depr . str_replace('/', $depr, $this->rule); if ($depr == $rule && $depr != $url) { return false; } if (false === strpos($rule, '<')) { if (0 === strcasecmp($rule, $url) || (!$completeMatch && 0 === strncasecmp($rule . $depr, $url . $depr, strlen($rule . $depr)))) { return $var; } return false; } $slash = preg_quote('/-' . $depr, '/'); if ($matchRule = preg_split('/[' . $slash . ']?<\w+\??>/', $rule, 2)) { if ($matchRule[0] && 0 !== strncasecmp($rule, $url, strlen($matchRule[0]))) { return false; } } if (preg_match_all('/[' . $slash . ']?<?\w+\??>?/', $rule, $matches)) { $regex = $this->buildRuleRegex($rule, $matches[0], $pattern, $option, $completeMatch); try { if (!preg_match('/^' . $regex . ($completeMatch ? '$' : '') . '/u', $url, $match)) { return false; } } catch (\Exception $e) { throw new Exception('route pattern error'); } foreach ($match as $key => $val) { if (is_string($key)) { $var[$key] = $val; } } } // 成功匹配后返回URL中的动态变量数组 return $var; }
php
private function match($url, $option, $completeMatch) { if (isset($option['complete_match'])) { $completeMatch = $option['complete_match']; } $pattern = array_merge($this->parent->getPattern(), $this->pattern); $depr = $this->router->config('app.pathinfo_depr'); // 检查完整规则定义 if (isset($pattern['__url__']) && !preg_match(0 === strpos($pattern['__url__'], '/') ? $pattern['__url__'] : '/^' . $pattern['__url__'] . '/', str_replace('|', $depr, $url))) { return false; } $var = []; $url = $depr . str_replace('|', $depr, $url); $rule = $depr . str_replace('/', $depr, $this->rule); if ($depr == $rule && $depr != $url) { return false; } if (false === strpos($rule, '<')) { if (0 === strcasecmp($rule, $url) || (!$completeMatch && 0 === strncasecmp($rule . $depr, $url . $depr, strlen($rule . $depr)))) { return $var; } return false; } $slash = preg_quote('/-' . $depr, '/'); if ($matchRule = preg_split('/[' . $slash . ']?<\w+\??>/', $rule, 2)) { if ($matchRule[0] && 0 !== strncasecmp($rule, $url, strlen($matchRule[0]))) { return false; } } if (preg_match_all('/[' . $slash . ']?<?\w+\??>?/', $rule, $matches)) { $regex = $this->buildRuleRegex($rule, $matches[0], $pattern, $option, $completeMatch); try { if (!preg_match('/^' . $regex . ($completeMatch ? '$' : '') . '/u', $url, $match)) { return false; } } catch (\Exception $e) { throw new Exception('route pattern error'); } foreach ($match as $key => $val) { if (is_string($key)) { $var[$key] = $val; } } } // 成功匹配后返回URL中的动态变量数组 return $var; }
[ "private", "function", "match", "(", "$", "url", ",", "$", "option", ",", "$", "completeMatch", ")", "{", "if", "(", "isset", "(", "$", "option", "[", "'complete_match'", "]", ")", ")", "{", "$", "completeMatch", "=", "$", "option", "[", "'complete_mat...
检测URL和规则路由是否匹配 @access private @param string $url URL地址 @param array $option 路由参数 @param bool $completeMatch 路由是否完全匹配 @return array|false
[ "检测URL和规则路由是否匹配" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/RuleItem.php#L227-L284
txj123/zilf
src/Zilf/Cache/Repository.php
Repository.put
public function put($key, $value, $minutes = null) { if (is_array($key)) { return $this->putMany($key, $value); } if (! is_null($minutes = $this->getMinutes($minutes))) { $this->store->put($this->itemKey($key), $value, $minutes); $this->event(new KeyWritten($key, $value, $minutes)); } }
php
public function put($key, $value, $minutes = null) { if (is_array($key)) { return $this->putMany($key, $value); } if (! is_null($minutes = $this->getMinutes($minutes))) { $this->store->put($this->itemKey($key), $value, $minutes); $this->event(new KeyWritten($key, $value, $minutes)); } }
[ "public", "function", "put", "(", "$", "key", ",", "$", "value", ",", "$", "minutes", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "key", ")", ")", "{", "return", "$", "this", "->", "putMany", "(", "$", "key", ",", "$", "value", ")",...
Store an item in the cache. @param string $key @param mixed $value @param \DateTime|float|int $minutes @return void
[ "Store", "an", "item", "in", "the", "cache", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Cache/Repository.php#L168-L179
txj123/zilf
src/Zilf/Cache/Repository.php
Repository.putMany
public function putMany(array $values, $minutes) { if (! is_null($minutes = $this->getMinutes($minutes))) { $this->store->putMany($values, $minutes); foreach ($values as $key => $value) { $this->event(new KeyWritten($key, $value, $minutes)); } } }
php
public function putMany(array $values, $minutes) { if (! is_null($minutes = $this->getMinutes($minutes))) { $this->store->putMany($values, $minutes); foreach ($values as $key => $value) { $this->event(new KeyWritten($key, $value, $minutes)); } } }
[ "public", "function", "putMany", "(", "array", "$", "values", ",", "$", "minutes", ")", "{", "if", "(", "!", "is_null", "(", "$", "minutes", "=", "$", "this", "->", "getMinutes", "(", "$", "minutes", ")", ")", ")", "{", "$", "this", "->", "store", ...
Store multiple items in the cache for a given number of minutes. @param array $values @param float|int $minutes @return void
[ "Store", "multiple", "items", "in", "the", "cache", "for", "a", "given", "number", "of", "minutes", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Cache/Repository.php#L188-L197
txj123/zilf
src/Zilf/Cache/Repository.php
Repository.forever
public function forever($key, $value) { $this->store->forever($this->itemKey($key), $value); $this->event(new KeyWritten($key, $value, 0)); }
php
public function forever($key, $value) { $this->store->forever($this->itemKey($key), $value); $this->event(new KeyWritten($key, $value, 0)); }
[ "public", "function", "forever", "(", "$", "key", ",", "$", "value", ")", "{", "$", "this", "->", "store", "->", "forever", "(", "$", "this", "->", "itemKey", "(", "$", "key", ")", ",", "$", "value", ")", ";", "$", "this", "->", "event", "(", "...
Store an item in the cache indefinitely. @param string $key @param mixed $value @return void
[ "Store", "an", "item", "in", "the", "cache", "indefinitely", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Cache/Repository.php#L265-L270
txj123/zilf
src/Zilf/Cache/Repository.php
Repository.forget
public function forget($key) { return tap( $this->store->forget($this->itemKey($key)), function () use ($key) { $this->event(new KeyForgotten($key)); } ); }
php
public function forget($key) { return tap( $this->store->forget($this->itemKey($key)), function () use ($key) { $this->event(new KeyForgotten($key)); } ); }
[ "public", "function", "forget", "(", "$", "key", ")", "{", "return", "tap", "(", "$", "this", "->", "store", "->", "forget", "(", "$", "this", "->", "itemKey", "(", "$", "key", ")", ")", ",", "function", "(", ")", "use", "(", "$", "key", ")", "...
Remove an item from the cache. @param string $key @return bool
[ "Remove", "an", "item", "from", "the", "cache", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Cache/Repository.php#L337-L344
txj123/zilf
src/Zilf/Cache/Repository.php
Repository.getMinutes
protected function getMinutes($duration) { if ($duration instanceof DateTime) { $duration = (time()-$duration->getTimestamp()) / 60; } return (int) ($duration * 60) > 0 ? $duration : null; }
php
protected function getMinutes($duration) { if ($duration instanceof DateTime) { $duration = (time()-$duration->getTimestamp()) / 60; } return (int) ($duration * 60) > 0 ? $duration : null; }
[ "protected", "function", "getMinutes", "(", "$", "duration", ")", "{", "if", "(", "$", "duration", "instanceof", "DateTime", ")", "{", "$", "duration", "=", "(", "time", "(", ")", "-", "$", "duration", "->", "getTimestamp", "(", ")", ")", "/", "60", ...
Calculate the number of minutes with the given duration. @param \DateTime|float|int $duration @return float|int|null
[ "Calculate", "the", "number", "of", "minutes", "with", "the", "given", "duration", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Cache/Repository.php#L488-L495
txj123/zilf
src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Regex.php
Zend_Validate_Regex.isValid
public function isValid($value) { $valueString = (string) $value; $this->_setValue($valueString); $status = @preg_match($this->_pattern, $valueString); if (false === $status) { /** * @see Zend_Validate_Exception */ include_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception("Internal error matching pattern '$this->_pattern' against value '$valueString'"); } if (!$status) { $this->_error(); return false; } return true; }
php
public function isValid($value) { $valueString = (string) $value; $this->_setValue($valueString); $status = @preg_match($this->_pattern, $valueString); if (false === $status) { /** * @see Zend_Validate_Exception */ include_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception("Internal error matching pattern '$this->_pattern' against value '$valueString'"); } if (!$status) { $this->_error(); return false; } return true; }
[ "public", "function", "isValid", "(", "$", "value", ")", "{", "$", "valueString", "=", "(", "string", ")", "$", "value", ";", "$", "this", "->", "_setValue", "(", "$", "valueString", ")", ";", "$", "status", "=", "@", "preg_match", "(", "$", "this", ...
Defined by Zend_Validate_Interface Returns true if and only if $value matches against the pattern option @param string $value @throws Zend_Validate_Exception if there is a fatal error in pattern matching @return boolean
[ "Defined", "by", "Zend_Validate_Interface" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Regex.php#L104-L123
krafthaus/bauhaus
src/KraftHaus/Bauhaus/Export/Format/CsvFormat.php
CsvFormat.export
public function export() { $result = ''; $fields = []; foreach ($this->getListBuilder()->getMapper()->getFields() as $field) { $fields[] = $field->getLabel(); } $result.= implode(',', $fields) . PHP_EOL; foreach ($this->getListBuilder()->getResult() as $item) { $row = []; foreach ($item->getFields() as $field) { $row[] = $field->getValue(); } $result.= implode(',', $row) . PHP_EOL; } return $this->createResponse($result); }
php
public function export() { $result = ''; $fields = []; foreach ($this->getListBuilder()->getMapper()->getFields() as $field) { $fields[] = $field->getLabel(); } $result.= implode(',', $fields) . PHP_EOL; foreach ($this->getListBuilder()->getResult() as $item) { $row = []; foreach ($item->getFields() as $field) { $row[] = $field->getValue(); } $result.= implode(',', $row) . PHP_EOL; } return $this->createResponse($result); }
[ "public", "function", "export", "(", ")", "{", "$", "result", "=", "''", ";", "$", "fields", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getListBuilder", "(", ")", "->", "getMapper", "(", ")", "->", "getFields", "(", ")", "as", "$", "...
Create the json response. @access public @return JsonResponse|mixed
[ "Create", "the", "json", "response", "." ]
train
https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/KraftHaus/Bauhaus/Export/Format/CsvFormat.php#L41-L62
oscarotero/fly-crud
src/Directory.php
Directory.make
public static function make(string $path, FormatInterface $format): Directory { return new static(new Filesystem(new Local($path)), '', $format); }
php
public static function make(string $path, FormatInterface $format): Directory { return new static(new Filesystem(new Local($path)), '', $format); }
[ "public", "static", "function", "make", "(", "string", "$", "path", ",", "FormatInterface", "$", "format", ")", ":", "Directory", "{", "return", "new", "static", "(", "new", "Filesystem", "(", "new", "Local", "(", "$", "path", ")", ")", ",", "''", ",",...
Creates a new directory instance.
[ "Creates", "a", "new", "directory", "instance", "." ]
train
https://github.com/oscarotero/fly-crud/blob/df826e4db5df954d3cace9c12762ec0309b050bf/src/Directory.php#L23-L26
oscarotero/fly-crud
src/Directory.php
Directory.getDocument
public function getDocument(string $id): Document { if (isset($this->documents[$id])) { return $this->documents[$id]; } if ($this->hasDocument($id)) { $path = $this->getDocumentPath($id); $source = $this->filesystem->read($path); if (is_string($source)) { return $this->documents[$id] = new Document($this->format->parse($source)); } throw new RuntimeException(sprintf('Format error in the file "%s"', $path)); } throw new RuntimeException(sprintf('File "%s" not found', $id)); }
php
public function getDocument(string $id): Document { if (isset($this->documents[$id])) { return $this->documents[$id]; } if ($this->hasDocument($id)) { $path = $this->getDocumentPath($id); $source = $this->filesystem->read($path); if (is_string($source)) { return $this->documents[$id] = new Document($this->format->parse($source)); } throw new RuntimeException(sprintf('Format error in the file "%s"', $path)); } throw new RuntimeException(sprintf('File "%s" not found', $id)); }
[ "public", "function", "getDocument", "(", "string", "$", "id", ")", ":", "Document", "{", "if", "(", "isset", "(", "$", "this", "->", "documents", "[", "$", "id", "]", ")", ")", "{", "return", "$", "this", "->", "documents", "[", "$", "id", "]", ...
Read and return a document.
[ "Read", "and", "return", "a", "document", "." ]
train
https://github.com/oscarotero/fly-crud/blob/df826e4db5df954d3cace9c12762ec0309b050bf/src/Directory.php#L38-L56
oscarotero/fly-crud
src/Directory.php
Directory.getDirectory
public function getDirectory(string $id): Directory { if (isset($this->directories[$id])) { return $this->directories[$id]; } if ($this->hasDirectory($id)) { return $this->directories[$id] = new static($this->filesystem, $this->getDirectoryPath($id), $this->format); } throw new RuntimeException(sprintf('Directory "%s" not found', $id)); }
php
public function getDirectory(string $id): Directory { if (isset($this->directories[$id])) { return $this->directories[$id]; } if ($this->hasDirectory($id)) { return $this->directories[$id] = new static($this->filesystem, $this->getDirectoryPath($id), $this->format); } throw new RuntimeException(sprintf('Directory "%s" not found', $id)); }
[ "public", "function", "getDirectory", "(", "string", "$", "id", ")", ":", "Directory", "{", "if", "(", "isset", "(", "$", "this", "->", "directories", "[", "$", "id", "]", ")", ")", "{", "return", "$", "this", "->", "directories", "[", "$", "id", "...
Read and return a directory.
[ "Read", "and", "return", "a", "directory", "." ]
train
https://github.com/oscarotero/fly-crud/blob/df826e4db5df954d3cace9c12762ec0309b050bf/src/Directory.php#L61-L72
oscarotero/fly-crud
src/Directory.php
Directory.hasDocument
public function hasDocument(string $id): bool { if (isset($this->documents[$id])) { return true; } $path = $this->getDocumentPath($id); if ($this->filesystem->has($path)) { $info = $this->filesystem->getMetadata($path); return $info['type'] === 'file'; } return false; }
php
public function hasDocument(string $id): bool { if (isset($this->documents[$id])) { return true; } $path = $this->getDocumentPath($id); if ($this->filesystem->has($path)) { $info = $this->filesystem->getMetadata($path); return $info['type'] === 'file'; } return false; }
[ "public", "function", "hasDocument", "(", "string", "$", "id", ")", ":", "bool", "{", "if", "(", "isset", "(", "$", "this", "->", "documents", "[", "$", "id", "]", ")", ")", "{", "return", "true", ";", "}", "$", "path", "=", "$", "this", "->", ...
Check whether a document exists.
[ "Check", "whether", "a", "document", "exists", "." ]
train
https://github.com/oscarotero/fly-crud/blob/df826e4db5df954d3cace9c12762ec0309b050bf/src/Directory.php#L77-L92
oscarotero/fly-crud
src/Directory.php
Directory.hasDirectory
public function hasDirectory(string $id): bool { if (isset($this->directories[$id])) { return true; } $path = $this->getDirectoryPath($id); if ($this->filesystem->has($path)) { $info = $this->filesystem->getMetadata($path); return $info['type'] === 'dir'; } return false; }
php
public function hasDirectory(string $id): bool { if (isset($this->directories[$id])) { return true; } $path = $this->getDirectoryPath($id); if ($this->filesystem->has($path)) { $info = $this->filesystem->getMetadata($path); return $info['type'] === 'dir'; } return false; }
[ "public", "function", "hasDirectory", "(", "string", "$", "id", ")", ":", "bool", "{", "if", "(", "isset", "(", "$", "this", "->", "directories", "[", "$", "id", "]", ")", ")", "{", "return", "true", ";", "}", "$", "path", "=", "$", "this", "->",...
Check whether a document or directory exists.
[ "Check", "whether", "a", "document", "or", "directory", "exists", "." ]
train
https://github.com/oscarotero/fly-crud/blob/df826e4db5df954d3cace9c12762ec0309b050bf/src/Directory.php#L97-L112
oscarotero/fly-crud
src/Directory.php
Directory.saveDocument
public function saveDocument(string $id, Document $document): self { $this->documents[$id] = $document; $this->filesystem->put($this->getDocumentPath($id), $this->format->stringify($document->getArrayCopy())); return $this; }
php
public function saveDocument(string $id, Document $document): self { $this->documents[$id] = $document; $this->filesystem->put($this->getDocumentPath($id), $this->format->stringify($document->getArrayCopy())); return $this; }
[ "public", "function", "saveDocument", "(", "string", "$", "id", ",", "Document", "$", "document", ")", ":", "self", "{", "$", "this", "->", "documents", "[", "$", "id", "]", "=", "$", "document", ";", "$", "this", "->", "filesystem", "->", "put", "("...
Saves a document.
[ "Saves", "a", "document", "." ]
train
https://github.com/oscarotero/fly-crud/blob/df826e4db5df954d3cace9c12762ec0309b050bf/src/Directory.php#L117-L123
oscarotero/fly-crud
src/Directory.php
Directory.createDirectory
public function createDirectory(string $id): Directory { $path = $this->getDirectoryPath($id); $this->filesystem->createDir($path); return $this->directories[$id] = new static($this->filesystem, $path, $this->format); }
php
public function createDirectory(string $id): Directory { $path = $this->getDirectoryPath($id); $this->filesystem->createDir($path); return $this->directories[$id] = new static($this->filesystem, $path, $this->format); }
[ "public", "function", "createDirectory", "(", "string", "$", "id", ")", ":", "Directory", "{", "$", "path", "=", "$", "this", "->", "getDirectoryPath", "(", "$", "id", ")", ";", "$", "this", "->", "filesystem", "->", "createDir", "(", "$", "path", ")",...
Creates a new directory.
[ "Creates", "a", "new", "directory", "." ]
train
https://github.com/oscarotero/fly-crud/blob/df826e4db5df954d3cace9c12762ec0309b050bf/src/Directory.php#L128-L134
oscarotero/fly-crud
src/Directory.php
Directory.deleteDocument
public function deleteDocument(string $id): self { $this->filesystem->delete($this->getDocumentPath($id)); unset($this->documents[$id]); return $this; }
php
public function deleteDocument(string $id): self { $this->filesystem->delete($this->getDocumentPath($id)); unset($this->documents[$id]); return $this; }
[ "public", "function", "deleteDocument", "(", "string", "$", "id", ")", ":", "self", "{", "$", "this", "->", "filesystem", "->", "delete", "(", "$", "this", "->", "getDocumentPath", "(", "$", "id", ")", ")", ";", "unset", "(", "$", "this", "->", "docu...
Deletes a document.
[ "Deletes", "a", "document", "." ]
train
https://github.com/oscarotero/fly-crud/blob/df826e4db5df954d3cace9c12762ec0309b050bf/src/Directory.php#L139-L145
oscarotero/fly-crud
src/Directory.php
Directory.deleteDirectory
public function deleteDirectory(string $id): self { $this->filesystem->deleteDir($this->getDirectoryPath($id)); unset($this->directories[$id]); return $this; }
php
public function deleteDirectory(string $id): self { $this->filesystem->deleteDir($this->getDirectoryPath($id)); unset($this->directories[$id]); return $this; }
[ "public", "function", "deleteDirectory", "(", "string", "$", "id", ")", ":", "self", "{", "$", "this", "->", "filesystem", "->", "deleteDir", "(", "$", "this", "->", "getDirectoryPath", "(", "$", "id", ")", ")", ";", "unset", "(", "$", "this", "->", ...
Deletes a directory.
[ "Deletes", "a", "directory", "." ]
train
https://github.com/oscarotero/fly-crud/blob/df826e4db5df954d3cace9c12762ec0309b050bf/src/Directory.php#L150-L156
oscarotero/fly-crud
src/Directory.php
Directory.getAllDocuments
public function getAllDocuments(): array { $documents = []; foreach ($this->filesystem->listContents('/'.$this->path) as $info) { $id = $info['filename']; if ($this->hasDocument($id)) { $documents[$id] = $this->getDocument($id); } } return $documents; }
php
public function getAllDocuments(): array { $documents = []; foreach ($this->filesystem->listContents('/'.$this->path) as $info) { $id = $info['filename']; if ($this->hasDocument($id)) { $documents[$id] = $this->getDocument($id); } } return $documents; }
[ "public", "function", "getAllDocuments", "(", ")", ":", "array", "{", "$", "documents", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "filesystem", "->", "listContents", "(", "'/'", ".", "$", "this", "->", "path", ")", "as", "$", "info", ")"...
Returns all documents.
[ "Returns", "all", "documents", "." ]
train
https://github.com/oscarotero/fly-crud/blob/df826e4db5df954d3cace9c12762ec0309b050bf/src/Directory.php#L161-L174
oscarotero/fly-crud
src/Directory.php
Directory.getAllDirectories
public function getAllDirectories(): array { $directories = []; foreach ($this->filesystem->listContents('/'.$this->path) as $info) { $id = $info['filename']; if ($this->hasDirectory($id)) { $directories[$id] = $this->getDirectory($id); } } return $directories; }
php
public function getAllDirectories(): array { $directories = []; foreach ($this->filesystem->listContents('/'.$this->path) as $info) { $id = $info['filename']; if ($this->hasDirectory($id)) { $directories[$id] = $this->getDirectory($id); } } return $directories; }
[ "public", "function", "getAllDirectories", "(", ")", ":", "array", "{", "$", "directories", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "filesystem", "->", "listContents", "(", "'/'", ".", "$", "this", "->", "path", ")", "as", "$", "info", ...
Returns all directories.
[ "Returns", "all", "directories", "." ]
train
https://github.com/oscarotero/fly-crud/blob/df826e4db5df954d3cace9c12762ec0309b050bf/src/Directory.php#L179-L192
oscarotero/fly-crud
src/Directory.php
Directory.getDocumentPath
private function getDocumentPath(string $id): string { return $this->getDirectoryPath($id).'.'.$this->format->getExtension(); }
php
private function getDocumentPath(string $id): string { return $this->getDirectoryPath($id).'.'.$this->format->getExtension(); }
[ "private", "function", "getDocumentPath", "(", "string", "$", "id", ")", ":", "string", "{", "return", "$", "this", "->", "getDirectoryPath", "(", "$", "id", ")", ".", "'.'", ".", "$", "this", "->", "format", "->", "getExtension", "(", ")", ";", "}" ]
Returns a file path.
[ "Returns", "a", "file", "path", "." ]
train
https://github.com/oscarotero/fly-crud/blob/df826e4db5df954d3cace9c12762ec0309b050bf/src/Directory.php#L197-L200
txj123/zilf
src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/File/FilesSize.php
Zend_Validate_File_FilesSize.isValid
public function isValid($value, $file = null) { if (is_string($value)) { $value = array($value); } foreach ($value as $files) { // Is file readable ? if (!@is_readable($files)) { $this->_throw($file, self::NOT_READABLE); return false; } if (!isset($this->_files[$files])) { $this->_files[$files] = $files; } else { // file already counted... do not count twice continue; } // limited to 2GB files $size = @filesize($files); $this->_size += $size; $this->_setValue($this->_size); if (($this->_max !== null) && ($this->_max < $this->_size)) { $this->_throw($file, self::TOO_BIG); } } // Check that aggregate files are >= minimum size if (($this->_min !== null) && ($this->_size < $this->_min)) { $this->_throw($file, self::TOO_SMALL); } if (count($this->_messages) > 0) { return false; } else { return true; } }
php
public function isValid($value, $file = null) { if (is_string($value)) { $value = array($value); } foreach ($value as $files) { // Is file readable ? if (!@is_readable($files)) { $this->_throw($file, self::NOT_READABLE); return false; } if (!isset($this->_files[$files])) { $this->_files[$files] = $files; } else { // file already counted... do not count twice continue; } // limited to 2GB files $size = @filesize($files); $this->_size += $size; $this->_setValue($this->_size); if (($this->_max !== null) && ($this->_max < $this->_size)) { $this->_throw($file, self::TOO_BIG); } } // Check that aggregate files are >= minimum size if (($this->_min !== null) && ($this->_size < $this->_min)) { $this->_throw($file, self::TOO_SMALL); } if (count($this->_messages) > 0) { return false; } else { return true; } }
[ "public", "function", "isValid", "(", "$", "value", ",", "$", "file", "=", "null", ")", "{", "if", "(", "is_string", "(", "$", "value", ")", ")", "{", "$", "value", "=", "array", "(", "$", "value", ")", ";", "}", "foreach", "(", "$", "value", "...
Defined by Zend_Validate_Interface Returns true if and only if the disk usage of all files is at least min and not bigger than max (when max is not null). @param string|array $value Real file to check for size @param array $file File data from Zend_File_Transfer @return boolean
[ "Defined", "by", "Zend_Validate_Interface" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/File/FilesSize.php#L116-L155
damonjones/Vebra-PHP-API-Wrapper
lib/YDD/Vebra/Model/Branch.php
Branch.fromArray
public function fromArray(array $arr) { foreach ($arr as $key => $value) { $method = 'set' . $key; if (method_exists($this, $method)) { $this->$method($value); } } }
php
public function fromArray(array $arr) { foreach ($arr as $key => $value) { $method = 'set' . $key; if (method_exists($this, $method)) { $this->$method($value); } } }
[ "public", "function", "fromArray", "(", "array", "$", "arr", ")", "{", "foreach", "(", "$", "arr", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "method", "=", "'set'", ".", "$", "key", ";", "if", "(", "method_exists", "(", "$", "this", ",...
Import object properties from an associative array @param array $arr An associative array
[ "Import", "object", "properties", "from", "an", "associative", "array" ]
train
https://github.com/damonjones/Vebra-PHP-API-Wrapper/blob/9de0fb5181a6e4b90700027ffaa6b2e658d279c2/lib/YDD/Vebra/Model/Branch.php#L309-L317
damonjones/Vebra-PHP-API-Wrapper
lib/YDD/Vebra/Model/Branch.php
Branch.toArray
public function toArray() { $arr = array(); foreach ($this as $key => $value) { $method = 'get' . $key; if (method_exists($this, $method)) { $arr[$key] = $this->$method(); } } return $arr; }
php
public function toArray() { $arr = array(); foreach ($this as $key => $value) { $method = 'get' . $key; if (method_exists($this, $method)) { $arr[$key] = $this->$method(); } } return $arr; }
[ "public", "function", "toArray", "(", ")", "{", "$", "arr", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "method", "=", "'get'", ".", "$", "key", ";", "if", "(", "method_exists", ...
Export the object properties to an associative array @return array An associative array
[ "Export", "the", "object", "properties", "to", "an", "associative", "array" ]
train
https://github.com/damonjones/Vebra-PHP-API-Wrapper/blob/9de0fb5181a6e4b90700027ffaa6b2e658d279c2/lib/YDD/Vebra/Model/Branch.php#L324-L335
Kaishiyoku/laravel-menu
src/Kaishiyoku/Menu/Data/LinkRoute.php
LinkRoute.render
public function render($customAttributes = null) { if ($customAttributes != null && count($customAttributes) > 0) { $attributes = array_merge($this->attributes, $customAttributes); } else { $attributes = $this->attributes; if (count(MenuHelper::getConfig()->getAnchorElementClasses()) > 0) { if (!array_key_exists('class', $attributes)) { $attributes['class'] = ''; } foreach (MenuHelper::getConfig()->getAnchorElementClasses() as $listElementClass) { $attributes['class'] .= ' ' . $listElementClass; } } } if (empty($this->name)) { $content = Html::link('#', $this->title, $attributes); } else { $content = Html::linkRoute($this->name, $this->title, $this->parameters, $attributes); } return $content; }
php
public function render($customAttributes = null) { if ($customAttributes != null && count($customAttributes) > 0) { $attributes = array_merge($this->attributes, $customAttributes); } else { $attributes = $this->attributes; if (count(MenuHelper::getConfig()->getAnchorElementClasses()) > 0) { if (!array_key_exists('class', $attributes)) { $attributes['class'] = ''; } foreach (MenuHelper::getConfig()->getAnchorElementClasses() as $listElementClass) { $attributes['class'] .= ' ' . $listElementClass; } } } if (empty($this->name)) { $content = Html::link('#', $this->title, $attributes); } else { $content = Html::linkRoute($this->name, $this->title, $this->parameters, $attributes); } return $content; }
[ "public", "function", "render", "(", "$", "customAttributes", "=", "null", ")", "{", "if", "(", "$", "customAttributes", "!=", "null", "&&", "count", "(", "$", "customAttributes", ")", ">", "0", ")", "{", "$", "attributes", "=", "array_merge", "(", "$", ...
Get the evaluated contents of the object. @param null|array $customAttributes @return string
[ "Get", "the", "evaluated", "contents", "of", "the", "object", "." ]
train
https://github.com/Kaishiyoku/laravel-menu/blob/0a1aa772f19002d354f0c338e603d98c49d10a7a/src/Kaishiyoku/Menu/Data/LinkRoute.php#L65-L90
crysalead/sql-dialect
src/Statement/Update.php
Update.toString
public function toString() { if (!$this->_parts['table']) { throw new SqlException("Invalid `UPDATE` statement, missing `TABLE` clause."); } if (!$this->_parts['values']) { throw new SqlException("Invalid `UPDATE` statement, missing `VALUES` clause."); } return 'UPDATE' . $this->_buildFlags($this->_parts['flags']) . $this->_buildChunk($this->dialect()->names($this->_parts['table'])) . $this->_buildSet() . $this->_buildClause('WHERE', $this->dialect()->conditions($this->_parts['where'], [ 'schemas' => ['' => $this->_schema] ])) . $this->_buildOrder() . $this->_buildClause('LIMIT', $this->_parts['limit']) . $this->_buildClause('RETURNING', $this->dialect()->names($this->_parts['returning'])); }
php
public function toString() { if (!$this->_parts['table']) { throw new SqlException("Invalid `UPDATE` statement, missing `TABLE` clause."); } if (!$this->_parts['values']) { throw new SqlException("Invalid `UPDATE` statement, missing `VALUES` clause."); } return 'UPDATE' . $this->_buildFlags($this->_parts['flags']) . $this->_buildChunk($this->dialect()->names($this->_parts['table'])) . $this->_buildSet() . $this->_buildClause('WHERE', $this->dialect()->conditions($this->_parts['where'], [ 'schemas' => ['' => $this->_schema] ])) . $this->_buildOrder() . $this->_buildClause('LIMIT', $this->_parts['limit']) . $this->_buildClause('RETURNING', $this->dialect()->names($this->_parts['returning'])); }
[ "public", "function", "toString", "(", ")", "{", "if", "(", "!", "$", "this", "->", "_parts", "[", "'table'", "]", ")", "{", "throw", "new", "SqlException", "(", "\"Invalid `UPDATE` statement, missing `TABLE` clause.\"", ")", ";", "}", "if", "(", "!", "$", ...
Render the SQL statement @return string The generated SQL string.
[ "Render", "the", "SQL", "statement" ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Statement/Update.php#L83-L103
crysalead/sql-dialect
src/Statement/Update.php
Update._buildSet
protected function _buildSet() { $values = []; $states = $this->_schema ? ['schema' => $this->_schema] : []; foreach ($this->_parts['values'] as $key => $value) { $states['name'] = $key; $values[] = $this->dialect()->name($key) . ' = ' . $this->dialect()->value($value, $states); } return $values ? ' SET ' . join(', ', $values) : ''; }
php
protected function _buildSet() { $values = []; $states = $this->_schema ? ['schema' => $this->_schema] : []; foreach ($this->_parts['values'] as $key => $value) { $states['name'] = $key; $values[] = $this->dialect()->name($key) . ' = ' . $this->dialect()->value($value, $states); } return $values ? ' SET ' . join(', ', $values) : ''; }
[ "protected", "function", "_buildSet", "(", ")", "{", "$", "values", "=", "[", "]", ";", "$", "states", "=", "$", "this", "->", "_schema", "?", "[", "'schema'", "=>", "$", "this", "->", "_schema", "]", ":", "[", "]", ";", "foreach", "(", "$", "thi...
Build `SET` clause. @return string Returns the `SET` clause.
[ "Build", "SET", "clause", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Statement/Update.php#L110-L119
opis/orm
src/Core/DataMapper.php
DataMapper.executePendingLinkage
public function executePendingLinkage() { foreach ($this->pendingLinks as $item) { /** @var ShareOneOrMany $rel */ $rel = $item['relation']; if ($item['link']) { $rel->link($this, $item['entity']); } else { $rel->unlink($this, $item['entity']); } } $this->pendingLinks = []; }
php
public function executePendingLinkage() { foreach ($this->pendingLinks as $item) { /** @var ShareOneOrMany $rel */ $rel = $item['relation']; if ($item['link']) { $rel->link($this, $item['entity']); } else { $rel->unlink($this, $item['entity']); } } $this->pendingLinks = []; }
[ "public", "function", "executePendingLinkage", "(", ")", "{", "foreach", "(", "$", "this", "->", "pendingLinks", "as", "$", "item", ")", "{", "/** @var ShareOneOrMany $rel */", "$", "rel", "=", "$", "item", "[", "'relation'", "]", ";", "if", "(", "$", "ite...
Execute pending linkage
[ "Execute", "pending", "linkage" ]
train
https://github.com/opis/orm/blob/2723235be55242cd20452b8c9648d4823b7ce8b5/src/Core/DataMapper.php#L436-L449
opis/orm
src/Core/DataMapper.php
DataMapper.hydrate
protected function hydrate() { if (!$this->stale) { return; } $select = new Select($this->manager->getConnection(), $this->mapper->getTable()); foreach ($this->mapper->getPrimaryKey()->getValue($this->rawColumns, true) as $pk_column => $pk_value) { $select->where($pk_column)->is($pk_value); } $columns = $select->select()->fetchAssoc()->first(); if ($columns === false) { $this->deleted = true; return; } $this->rawColumns = $columns; $this->columns = []; $this->relations = []; $this->loaders = []; $this->stale = false; }
php
protected function hydrate() { if (!$this->stale) { return; } $select = new Select($this->manager->getConnection(), $this->mapper->getTable()); foreach ($this->mapper->getPrimaryKey()->getValue($this->rawColumns, true) as $pk_column => $pk_value) { $select->where($pk_column)->is($pk_value); } $columns = $select->select()->fetchAssoc()->first(); if ($columns === false) { $this->deleted = true; return; } $this->rawColumns = $columns; $this->columns = []; $this->relations = []; $this->loaders = []; $this->stale = false; }
[ "protected", "function", "hydrate", "(", ")", "{", "if", "(", "!", "$", "this", "->", "stale", ")", "{", "return", ";", "}", "$", "select", "=", "new", "Select", "(", "$", "this", "->", "manager", "->", "getConnection", "(", ")", ",", "$", "this", ...
Hydrate
[ "Hydrate" ]
train
https://github.com/opis/orm/blob/2723235be55242cd20452b8c9648d4823b7ce8b5/src/Core/DataMapper.php#L530-L554
bitExpert/adrenaline
src/bitExpert/Adrenaline/Domain/DomainPayload.php
DomainPayload.withValues
public function withValues(array $values) : self { $new = clone $this; foreach ($values as $property => $value) { $new->data[$property] = $value; } return $new; }
php
public function withValues(array $values) : self { $new = clone $this; foreach ($values as $property => $value) { $new->data[$property] = $value; } return $new; }
[ "public", "function", "withValues", "(", "array", "$", "values", ")", ":", "self", "{", "$", "new", "=", "clone", "$", "this", ";", "foreach", "(", "$", "values", "as", "$", "property", "=>", "$", "value", ")", "{", "$", "new", "->", "data", "[", ...
Returns a {@link \bitExpert\Adroit\Domain\Payload\DomainPayload} clone with new $values. $values is an array containing the new $property => $value relationships. @return DomainPayload
[ "Returns", "a", "{", "@link", "\\", "bitExpert", "\\", "Adroit", "\\", "Domain", "\\", "Payload", "\\", "DomainPayload", "}", "clone", "with", "new", "$values", ".", "$values", "is", "an", "array", "containing", "the", "new", "$property", "=", ">", "$value...
train
https://github.com/bitExpert/adrenaline/blob/2cb9b79147dee04221261d765d66416f0b796b0f/src/bitExpert/Adrenaline/Domain/DomainPayload.php#L88-L96
railken/search-query
src/Languages/BoomTree/Resolvers/ComparisonOperatorResolver.php
ComparisonOperatorResolver.resolve
public function resolve(NodeContract $node) { $children = $node->getChildren(); if (count($children) > 0) { $this->resolve($node->getChildByIndex(0)); $value = ''; $positions = []; foreach ($node->getChildren() as $child) { if ($child instanceof Nodes\TextNode || $child instanceof Nodes\KeyNode) { $value .= ' '.$child->getValue(); $p = array_fill(0, strlen(' '.$child->getValue()), $child->getIndex()); $positions = array_merge($positions, $p); } } foreach ($this->regex as $regex) { preg_match($regex, $value, $match, PREG_OFFSET_CAPTURE); if ($match) { $new_node = new $this->node(); $start = $match[0][1]; $length = strlen($match[0][0]); $this->groupNode($node, $new_node, $start, $start + $length, $positions); $this->resolveRelationsNode($node, $new_node); // Search for another match in this node. return $this->resolve($node->getParent()); } } } return $node->next() !== null ? $this->resolve($node->next()) : null; }
php
public function resolve(NodeContract $node) { $children = $node->getChildren(); if (count($children) > 0) { $this->resolve($node->getChildByIndex(0)); $value = ''; $positions = []; foreach ($node->getChildren() as $child) { if ($child instanceof Nodes\TextNode || $child instanceof Nodes\KeyNode) { $value .= ' '.$child->getValue(); $p = array_fill(0, strlen(' '.$child->getValue()), $child->getIndex()); $positions = array_merge($positions, $p); } } foreach ($this->regex as $regex) { preg_match($regex, $value, $match, PREG_OFFSET_CAPTURE); if ($match) { $new_node = new $this->node(); $start = $match[0][1]; $length = strlen($match[0][0]); $this->groupNode($node, $new_node, $start, $start + $length, $positions); $this->resolveRelationsNode($node, $new_node); // Search for another match in this node. return $this->resolve($node->getParent()); } } } return $node->next() !== null ? $this->resolve($node->next()) : null; }
[ "public", "function", "resolve", "(", "NodeContract", "$", "node", ")", "{", "$", "children", "=", "$", "node", "->", "getChildren", "(", ")", ";", "if", "(", "count", "(", "$", "children", ")", ">", "0", ")", "{", "$", "this", "->", "resolve", "("...
Resolve token eq node. @param NodeContract $node @return NodeContract|null
[ "Resolve", "token", "eq", "node", "." ]
train
https://github.com/railken/search-query/blob/06e1bfb3eb59347afec9ca764d6f8c3b691d6889/src/Languages/BoomTree/Resolvers/ComparisonOperatorResolver.php#L37-L73
railken/search-query
src/Languages/BoomTree/Resolvers/ComparisonOperatorResolver.php
ComparisonOperatorResolver.resolveNextNode
public function resolveNextNode(NodeContract $node, NodeContract $new_node) { if ($new_node->next() && $new_node->next() instanceof ComparableNodeContract) { $new_node->moveNodeAsChild($new_node->next()); } else { throw new Exceptions\QuerySyntaxException($node->getRoot()->getValue()); } }
php
public function resolveNextNode(NodeContract $node, NodeContract $new_node) { if ($new_node->next() && $new_node->next() instanceof ComparableNodeContract) { $new_node->moveNodeAsChild($new_node->next()); } else { throw new Exceptions\QuerySyntaxException($node->getRoot()->getValue()); } }
[ "public", "function", "resolveNextNode", "(", "NodeContract", "$", "node", ",", "NodeContract", "$", "new_node", ")", "{", "if", "(", "$", "new_node", "->", "next", "(", ")", "&&", "$", "new_node", "->", "next", "(", ")", "instanceof", "ComparableNodeContrac...
Resolve next node match. @param NodeContract $node @param NodeContract $new_node
[ "Resolve", "next", "node", "match", "." ]
train
https://github.com/railken/search-query/blob/06e1bfb3eb59347afec9ca764d6f8c3b691d6889/src/Languages/BoomTree/Resolvers/ComparisonOperatorResolver.php#L96-L103
txj123/zilf
src/Zilf/Db/Transaction.php
Transaction.begin
public function begin($isolationLevel = null) { if ($this->db === null) { throw new InvalidConfigException('Transaction::db must be set.'); } $this->db->open(); if ($this->_level === 0) { if ($isolationLevel !== null) { $this->db->getSchema()->setTransactionIsolationLevel($isolationLevel); } if(Zilf::$app->is_debug){ Log::debug('Begin transaction' . ($isolationLevel ? ' with isolation level ' . $isolationLevel : '') . __METHOD__); } $this->db->trigger(Connection::EVENT_BEGIN_TRANSACTION); $this->db->pdo->beginTransaction(); $this->_level = 1; return; } $schema = $this->db->getSchema(); if ($schema->supportsSavepoint()) { if(Zilf::$app->is_debug) { Log::debug('Set savepoint ' . $this->_level . __METHOD__); } $schema->createSavepoint('LEVEL' . $this->_level); } else { Log::info('Transaction not started: nested transaction not supported' . __METHOD__); } $this->_level++; }
php
public function begin($isolationLevel = null) { if ($this->db === null) { throw new InvalidConfigException('Transaction::db must be set.'); } $this->db->open(); if ($this->_level === 0) { if ($isolationLevel !== null) { $this->db->getSchema()->setTransactionIsolationLevel($isolationLevel); } if(Zilf::$app->is_debug){ Log::debug('Begin transaction' . ($isolationLevel ? ' with isolation level ' . $isolationLevel : '') . __METHOD__); } $this->db->trigger(Connection::EVENT_BEGIN_TRANSACTION); $this->db->pdo->beginTransaction(); $this->_level = 1; return; } $schema = $this->db->getSchema(); if ($schema->supportsSavepoint()) { if(Zilf::$app->is_debug) { Log::debug('Set savepoint ' . $this->_level . __METHOD__); } $schema->createSavepoint('LEVEL' . $this->_level); } else { Log::info('Transaction not started: nested transaction not supported' . __METHOD__); } $this->_level++; }
[ "public", "function", "begin", "(", "$", "isolationLevel", "=", "null", ")", "{", "if", "(", "$", "this", "->", "db", "===", "null", ")", "{", "throw", "new", "InvalidConfigException", "(", "'Transaction::db must be set.'", ")", ";", "}", "$", "this", "->"...
Begins a transaction. @param string|null $isolationLevel The [isolation level][] to use for this transaction. This can be one of [[READ_UNCOMMITTED]], [[READ_COMMITTED]], [[REPEATABLE_READ]] and [[SERIALIZABLE]] but also a string containing DBMS specific syntax to be used after `SET TRANSACTION ISOLATION LEVEL`. If not specified (`null`) the isolation level will not be set explicitly and the DBMS default will be used. > Note: This setting does not work for PostgreSQL, where setting the isolation level before the transaction has no effect. You have to call [[setIsolationLevel()]] in this case after the transaction has started. > Note: Some DBMS allow setting of the isolation level only for the whole connection so subsequent transactions may get the same isolation level even if you did not specify any. When using this feature you may need to set the isolation level for all transactions explicitly to avoid conflicting settings. At the time of this writing affected DBMS are MSSQL and SQLite. [isolation level]: http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels @throws InvalidConfigException if [[db]] is `null`.
[ "Begins", "a", "transaction", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Transaction.php#L121-L156
txj123/zilf
src/Zilf/Db/Transaction.php
Transaction.commit
public function commit() { if (!$this->getIsActive()) { throw new Exception('Failed to commit transaction: transaction was inactive.'); } $this->_level--; if ($this->_level === 0) { Log::debug('Commit transaction' . __METHOD__); $this->db->pdo->commit(); $this->db->trigger(Connection::EVENT_COMMIT_TRANSACTION); return; } $schema = $this->db->getSchema(); if ($schema->supportsSavepoint()) { Log::debug('Release savepoint ' . $this->_level . __METHOD__); $schema->releaseSavepoint('LEVEL' . $this->_level); } else { Log::info('Transaction not committed: nested transaction not supported' . __METHOD__); } }
php
public function commit() { if (!$this->getIsActive()) { throw new Exception('Failed to commit transaction: transaction was inactive.'); } $this->_level--; if ($this->_level === 0) { Log::debug('Commit transaction' . __METHOD__); $this->db->pdo->commit(); $this->db->trigger(Connection::EVENT_COMMIT_TRANSACTION); return; } $schema = $this->db->getSchema(); if ($schema->supportsSavepoint()) { Log::debug('Release savepoint ' . $this->_level . __METHOD__); $schema->releaseSavepoint('LEVEL' . $this->_level); } else { Log::info('Transaction not committed: nested transaction not supported' . __METHOD__); } }
[ "public", "function", "commit", "(", ")", "{", "if", "(", "!", "$", "this", "->", "getIsActive", "(", ")", ")", "{", "throw", "new", "Exception", "(", "'Failed to commit transaction: transaction was inactive.'", ")", ";", "}", "$", "this", "->", "_level", "-...
Commits a transaction. @throws Exception if the transaction is not active
[ "Commits", "a", "transaction", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Transaction.php#L163-L184