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_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
fxpio/fxp-doctrine-extensions
Validator/Constraints/UniqueEntityValidator.php
UniqueEntityValidator.isValidResult
private function isValidResult($result, $entity) { return 0 === \count($result) || (1 === \count($result) && $entity === ($result instanceof \Iterator ? $result->current() : current($result))); }
php
private function isValidResult($result, $entity) { return 0 === \count($result) || (1 === \count($result) && $entity === ($result instanceof \Iterator ? $result->current() : current($result))); }
Check if the result is valid. If no entity matched the query criteria or a single entity matched, which is the same as the entity being validated, the criteria is unique. @param array|\Iterator $result @param object $entity @return bool
https://github.com/fxpio/fxp-doctrine-extensions/blob/82942f51d47cdd79a20a5725ee1b3ecfc69e9d77/Validator/Constraints/UniqueEntityValidator.php#L149-L154
fxpio/fxp-doctrine-extensions
Validator/Constraints/UniqueEntityValidator.php
UniqueEntityValidator.findFieldCriteria
private function findFieldCriteria(array $criteria, Constraint $constraint, ObjectManager $em, ClassMetadata $class, $entity, $fieldName) { $this->validateFieldCriteria($class, $fieldName); /* @var \Doctrine\ORM\Mapping\ClassMetadata $class */ $criteria[$fieldName] = $class->reflFields[$fieldName]->getValue($entity); /** @var UniqueEntity $constraint */ if ($constraint->ignoreNull && null === $criteria[$fieldName]) { $criteria = null; } else { $this->findFieldCriteriaStep2($criteria, $em, $class, $fieldName); } return $criteria; }
php
private function findFieldCriteria(array $criteria, Constraint $constraint, ObjectManager $em, ClassMetadata $class, $entity, $fieldName) { $this->validateFieldCriteria($class, $fieldName); /* @var \Doctrine\ORM\Mapping\ClassMetadata $class */ $criteria[$fieldName] = $class->reflFields[$fieldName]->getValue($entity); /** @var UniqueEntity $constraint */ if ($constraint->ignoreNull && null === $criteria[$fieldName]) { $criteria = null; } else { $this->findFieldCriteriaStep2($criteria, $em, $class, $fieldName); } return $criteria; }
@param array $criteria @param Constraint $constraint @param ObjectManager $em @param ClassMetadata $class @param object $entity @param string $fieldName @throws ConstraintDefinitionException @return null|array The new criteria
https://github.com/fxpio/fxp-doctrine-extensions/blob/82942f51d47cdd79a20a5725ee1b3ecfc69e9d77/Validator/Constraints/UniqueEntityValidator.php#L168-L183
fxpio/fxp-doctrine-extensions
Validator/Constraints/UniqueEntityValidator.php
UniqueEntityValidator.validateFieldCriteria
private function validateFieldCriteria(ClassMetadata $class, $fieldName): void { if (!$class->hasField($fieldName) && !$class->hasAssociation($fieldName)) { throw new ConstraintDefinitionException(sprintf("The field '%s' is not mapped by Doctrine, so it cannot be validated for uniqueness.", $fieldName)); } }
php
private function validateFieldCriteria(ClassMetadata $class, $fieldName): void { if (!$class->hasField($fieldName) && !$class->hasAssociation($fieldName)) { throw new ConstraintDefinitionException(sprintf("The field '%s' is not mapped by Doctrine, so it cannot be validated for uniqueness.", $fieldName)); } }
@param ClassMetadata $class @param string $fieldName @throws ConstraintDefinitionException
https://github.com/fxpio/fxp-doctrine-extensions/blob/82942f51d47cdd79a20a5725ee1b3ecfc69e9d77/Validator/Constraints/UniqueEntityValidator.php#L191-L196
fxpio/fxp-doctrine-extensions
Validator/Constraints/UniqueEntityValidator.php
UniqueEntityValidator.findFieldCriteriaStep2
private function findFieldCriteriaStep2(array &$criteria, ObjectManager $em, ClassMetadata $class, $fieldName): void { if (null !== $criteria[$fieldName] && $class->hasAssociation($fieldName)) { /* Ensure the Proxy is initialized before using reflection to * read its identifiers. This is necessary because the wrapped * getter methods in the Proxy are being bypassed. */ $em->initializeObject($criteria[$fieldName]); $relatedClass = $em->getClassMetadata($class->getAssociationTargetClass($fieldName)); $relatedId = $relatedClass->getIdentifierValues($criteria[$fieldName]); if (\count($relatedId) > 1) { throw new ConstraintDefinitionException( 'Associated entities are not allowed to have more than one identifier field to be '. 'part of a unique constraint in: '.$class->getName().'#'.$fieldName ); } $value = array_pop($relatedId); $criteria[$fieldName] = Util::getFormattedIdentifier($relatedClass, $criteria, $fieldName, $value); } }
php
private function findFieldCriteriaStep2(array &$criteria, ObjectManager $em, ClassMetadata $class, $fieldName): void { if (null !== $criteria[$fieldName] && $class->hasAssociation($fieldName)) { /* Ensure the Proxy is initialized before using reflection to * read its identifiers. This is necessary because the wrapped * getter methods in the Proxy are being bypassed. */ $em->initializeObject($criteria[$fieldName]); $relatedClass = $em->getClassMetadata($class->getAssociationTargetClass($fieldName)); $relatedId = $relatedClass->getIdentifierValues($criteria[$fieldName]); if (\count($relatedId) > 1) { throw new ConstraintDefinitionException( 'Associated entities are not allowed to have more than one identifier field to be '. 'part of a unique constraint in: '.$class->getName().'#'.$fieldName ); } $value = array_pop($relatedId); $criteria[$fieldName] = Util::getFormattedIdentifier($relatedClass, $criteria, $fieldName, $value); } }
Finds the criteria for the entity field. @param array $criteria @param ObjectManager $em @param ClassMetadata $class @param string $fieldName @throws ConstraintDefinitionException
https://github.com/fxpio/fxp-doctrine-extensions/blob/82942f51d47cdd79a20a5725ee1b3ecfc69e9d77/Validator/Constraints/UniqueEntityValidator.php#L208-L230
kambalabs/KmbCache
src/KmbCache/Service/AbstractCacheManager.php
AbstractCacheManager.refreshExpiredCacheForContext
protected function refreshExpiredCacheForContext($context = null, $forceRefresh = false) { $key = $this->getKey($context); if ($forceRefresh || $this->needRefresh($key)) { $this->logger->debug("Refreshing cache for $key ..."); $this->cacheStorage->setItem($this->statusKeyFor($key), static::PENDING); $this->cacheStorage->setItem($key, serialize($this->getDataFromRealService($context))); $this->cacheStorage->setItem($this->statusKeyFor($key), static::COMPLETED); $this->cacheStorage->setItem($this->refreshedAtKeyFor($key), serialize($this->getDateTimeFactory()->now())); $this->logger->debug("Cache for $key has been refreshed !"); return true; } return false; }
php
protected function refreshExpiredCacheForContext($context = null, $forceRefresh = false) { $key = $this->getKey($context); if ($forceRefresh || $this->needRefresh($key)) { $this->logger->debug("Refreshing cache for $key ..."); $this->cacheStorage->setItem($this->statusKeyFor($key), static::PENDING); $this->cacheStorage->setItem($key, serialize($this->getDataFromRealService($context))); $this->cacheStorage->setItem($this->statusKeyFor($key), static::COMPLETED); $this->cacheStorage->setItem($this->refreshedAtKeyFor($key), serialize($this->getDateTimeFactory()->now())); $this->logger->debug("Cache for $key has been refreshed !"); return true; } return false; }
Refresh cache if necessary. @param mixed $context @param bool $forceRefresh @return bool
https://github.com/kambalabs/KmbCache/blob/9865ccde8f17fa5ad0ace103e50c164559a389f0/src/KmbCache/Service/AbstractCacheManager.php#L103-L116
climphp/Clim
Clim/Cli/MiddlewareStack.php
MiddlewareStack.push
public function push(callable $callable) { if ($this->kernel) { throw new RuntimeException('Middleware can’t be added once the stack is dequeuing'); } if (is_null($this->head)) { $next = function (ContextInterface $context) { $result = call_user_func($this->kernel, $context); return $this->handleResult($context, $result); }; } else { $next = $this->head; } $this->head = function (ContextInterface $context) use ( $callable, $next ) { $result = call_user_func($callable, $context, $next); return $this->handleResult($context, $result); }; }
php
public function push(callable $callable) { if ($this->kernel) { throw new RuntimeException('Middleware can’t be added once the stack is dequeuing'); } if (is_null($this->head)) { $next = function (ContextInterface $context) { $result = call_user_func($this->kernel, $context); return $this->handleResult($context, $result); }; } else { $next = $this->head; } $this->head = function (ContextInterface $context) use ( $callable, $next ) { $result = call_user_func($callable, $context, $next); return $this->handleResult($context, $result); }; }
Add middleware This method pushs new middleware to themiddleware stack. @param callable $callable Any callable that accepts two arguments: 1. A ContextInterface object 2. A "next" middleware callable @throws RuntimeException If middleware is added while the stack is dequeuing @throws UnexpectedValueException If the middleware doesn't return a ContextInterface
https://github.com/climphp/Clim/blob/d2d09a82e1b7a0b8d454e585e6db421ff02ec8e4/Clim/Cli/MiddlewareStack.php#L41-L63
climphp/Clim
Clim/Cli/MiddlewareStack.php
MiddlewareStack.run
public function run(ContextInterface $context, callable $kernel) { if (empty($this->head)) { return $this->handleResult($context, call_user_func($kernel, $context)); } $this->kernel = $kernel; /** @var callable $start */ $start = $this->head; $context = $start($context); $this->kernel = null; return $context; }
php
public function run(ContextInterface $context, callable $kernel) { if (empty($this->head)) { return $this->handleResult($context, call_user_func($kernel, $context)); } $this->kernel = $kernel; /** @var callable $start */ $start = $this->head; $context = $start($context); $this->kernel = null; return $context; }
Call middleware stack @param ContextInterface $context A context object @param callable $kernel A core of middleware task @return ContextInterface
https://github.com/climphp/Clim/blob/d2d09a82e1b7a0b8d454e585e6db421ff02ec8e4/Clim/Cli/MiddlewareStack.php#L73-L88
climphp/Clim
Clim/Cli/MiddlewareStack.php
MiddlewareStack.handleResult
protected function handleResult(ContextInterface $context, $result) { $validated = $this->validateResult($result); if (is_null($validated)) { $validated = $result; } if ($validated instanceof ContextInterface) { $context = $validated; } elseif (!is_null($validated)) { $context->setResult($validated); } return $context; }
php
protected function handleResult(ContextInterface $context, $result) { $validated = $this->validateResult($result); if (is_null($validated)) { $validated = $result; } if ($validated instanceof ContextInterface) { $context = $validated; } elseif (!is_null($validated)) { $context->setResult($validated); } return $context; }
Validate middleware result. Imprementer shall invoke exceptions in this method if result is not valid. @param ContextInterface $context A context object @param mixed $result @return ContextInterface|null
https://github.com/climphp/Clim/blob/d2d09a82e1b7a0b8d454e585e6db421ff02ec8e4/Clim/Cli/MiddlewareStack.php#L111-L125
TransformCore/CSR-Fast-Stream-Domain-Model
src/TransformCore/Bundle/CsrFastStreamBundle/DataFixtures/ORM/LoadApplicantData.php
LoadApplicantData.load
public function load(ObjectManager $manager) { $this->manager = $manager; $this->addStandardApplicant( 'Admin1', function ($applicant) { $applicant->setPlainPassword('password'); } ); $this->addStandardApplicant('Disposable1'); $this->addStandardApplicant('Three'); $this->addStandardApplicant('Four'); $this->addStandardApplicant('Five'); $this->addStandardApplicant('Six'); $this->addStandardApplicant('Seven'); $this->addStandardApplicant('Eight'); $this->addStandardApplicant('Nine'); $manager->flush(); }
php
public function load(ObjectManager $manager) { $this->manager = $manager; $this->addStandardApplicant( 'Admin1', function ($applicant) { $applicant->setPlainPassword('password'); } ); $this->addStandardApplicant('Disposable1'); $this->addStandardApplicant('Three'); $this->addStandardApplicant('Four'); $this->addStandardApplicant('Five'); $this->addStandardApplicant('Six'); $this->addStandardApplicant('Seven'); $this->addStandardApplicant('Eight'); $this->addStandardApplicant('Nine'); $manager->flush(); }
{@inheritDoc}
https://github.com/TransformCore/CSR-Fast-Stream-Domain-Model/blob/cb8e4c446f814082663a20f3c5d4cea8292bd8d6/src/TransformCore/Bundle/CsrFastStreamBundle/DataFixtures/ORM/LoadApplicantData.php#L25-L46
TransformCore/CSR-Fast-Stream-Domain-Model
src/TransformCore/Bundle/CsrFastStreamBundle/DataFixtures/ORM/LoadApplicantData.php
LoadApplicantData.addStandardApplicant
private function addStandardApplicant( $firstName, callable $callback = null ) { $applicant = new Applicant(); $eligibility = new Eligibility(); $nationality = new Nationality(); $registration = new Registration(); $nationality->setName('British'); $eligibility->setPresentNationality($nationality); $eligibility->setSubjectToImmigrationControls(true); $eligibility->setSubjectToImmigrationControlsDetails('I require a Visa'); $eligibility->setResidencyOrEmploymentRestrictions(false); $eligibility->setPermissionToCheckBackground(true); $registration->setHeardAboutUs('I have heard'); $registration->setDisabledDetails('I am disabled'); $registration->setDisabledAdjustmentDetails('I would like an adjustment'); $applicant->setEnabled(true); $applicant->setEmail(strtolower($firstName).'@test.com'); $applicant->setPlainPassword('P@ssword1'); $applicant->setUsername(md5($firstName)); $applicant->setFirstname($firstName); $applicant->setLastname('Persona'); $applicant->setAddress( (new Address()) ->setLine1('123 Some Street') ->setTown('Some Town') ->setCounty('Some County') ->setPostcode('AB12 3CD') ->setCountry('GB') ); $applicant->setPhoneNumber( (new PhoneNumber()) ->setNumber('123456789') ); $applicant->setEligibility($eligibility); $applicant->setRegistration($registration); if ($callback != null) { $callback($applicant); } $this->manager->persist($applicant); return $applicant; }
php
private function addStandardApplicant( $firstName, callable $callback = null ) { $applicant = new Applicant(); $eligibility = new Eligibility(); $nationality = new Nationality(); $registration = new Registration(); $nationality->setName('British'); $eligibility->setPresentNationality($nationality); $eligibility->setSubjectToImmigrationControls(true); $eligibility->setSubjectToImmigrationControlsDetails('I require a Visa'); $eligibility->setResidencyOrEmploymentRestrictions(false); $eligibility->setPermissionToCheckBackground(true); $registration->setHeardAboutUs('I have heard'); $registration->setDisabledDetails('I am disabled'); $registration->setDisabledAdjustmentDetails('I would like an adjustment'); $applicant->setEnabled(true); $applicant->setEmail(strtolower($firstName).'@test.com'); $applicant->setPlainPassword('P@ssword1'); $applicant->setUsername(md5($firstName)); $applicant->setFirstname($firstName); $applicant->setLastname('Persona'); $applicant->setAddress( (new Address()) ->setLine1('123 Some Street') ->setTown('Some Town') ->setCounty('Some County') ->setPostcode('AB12 3CD') ->setCountry('GB') ); $applicant->setPhoneNumber( (new PhoneNumber()) ->setNumber('123456789') ); $applicant->setEligibility($eligibility); $applicant->setRegistration($registration); if ($callback != null) { $callback($applicant); } $this->manager->persist($applicant); return $applicant; }
@param string $firstName @param callable $callback @return Applicant
https://github.com/TransformCore/CSR-Fast-Stream-Domain-Model/blob/cb8e4c446f814082663a20f3c5d4cea8292bd8d6/src/TransformCore/Bundle/CsrFastStreamBundle/DataFixtures/ORM/LoadApplicantData.php#L54-L107
Wedeto/HTTP
src/Response/FileResponse.php
FileResponse.output
public function output(string $mime) { // Nothing to output, the webserver will handle it if ($this->xsendfile) return; $bytes = readfile($this->filename); if (!empty($this->length) && $bytes != $this->length) { self::getLogger()->warning( "FileResponse promised to send {0} bytes but {1} were actually transfered of file {2}", [$this->length, $bytes, $this->output_filename] ); } }
php
public function output(string $mime) { // Nothing to output, the webserver will handle it if ($this->xsendfile) return; $bytes = readfile($this->filename); if (!empty($this->length) && $bytes != $this->length) { self::getLogger()->warning( "FileResponse promised to send {0} bytes but {1} were actually transfered of file {2}", [$this->length, $bytes, $this->output_filename] ); } }
Serve the file to the user
https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Response/FileResponse.php#L142-L156
Vectrex/vxPHP
src/Routing/Route.php
Route.getPath
public function getPath(array $pathParameters = null) { $path = $this->path; //insert path parameters if(!empty($this->placeholders)) { foreach ($this->placeholders as $placeholder) { // use path parameter if it was passed on $regExp = '~\{' . $placeholder['name'] . '(=.*?)?\}~'; if($pathParameters && array_key_exists($placeholder['name'], $pathParameters)) { $path = preg_replace($regExp, $pathParameters[$placeholder['name']], $path); } // try to use previously set path parameter else if($this->pathParameters && array_key_exists($placeholder['name'], $this->pathParameters)) { $path = preg_replace($regExp, $this->pathParameters[$placeholder['name']], $path); } // no path parameter value passed on, but default defined else if(isset($placeholder['default'])){ $path = preg_replace($regExp, $placeholder['default'], $path); } else { throw new \RuntimeException(sprintf("Path parameter '%s' not set.", $placeholder['name'])); } } } // remove trailing slashes which might stem from one or more empty path parameters return rtrim($path, '/'); }
php
public function getPath(array $pathParameters = null) { $path = $this->path; //insert path parameters if(!empty($this->placeholders)) { foreach ($this->placeholders as $placeholder) { // use path parameter if it was passed on $regExp = '~\{' . $placeholder['name'] . '(=.*?)?\}~'; if($pathParameters && array_key_exists($placeholder['name'], $pathParameters)) { $path = preg_replace($regExp, $pathParameters[$placeholder['name']], $path); } // try to use previously set path parameter else if($this->pathParameters && array_key_exists($placeholder['name'], $this->pathParameters)) { $path = preg_replace($regExp, $this->pathParameters[$placeholder['name']], $path); } // no path parameter value passed on, but default defined else if(isset($placeholder['default'])){ $path = preg_replace($regExp, $placeholder['default'], $path); } else { throw new \RuntimeException(sprintf("Path parameter '%s' not set.", $placeholder['name'])); } } } // remove trailing slashes which might stem from one or more empty path parameters return rtrim($path, '/'); }
get path of route When path parameters are passed on to method a path using these parameter values is generated, but path parameters are not stored and do not overwrite previously set path parameters. When no (or only some) path parameters are passed on previously set path parameters are considered when generating the path. expects path parameters when required by route @param array $pathParameters @throws \RuntimeException @return string
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Routing/Route.php#L301-L344
Vectrex/vxPHP
src/Routing/Route.php
Route.getUrl
public function getUrl(array $pathParameters = null) { // avoid building URL in subsequent calls if(!$this->url) { $application = Application::getInstance(); $urlSegments = []; if($application->getRouter()->getServerSideRewrite()) { if(($scriptName = basename($this->scriptName, '.php')) !== 'index') { $urlSegments[] = $scriptName; } } else { if($application->getRelativeAssetsPath()) { $urlSegments[] = trim($application->getRelativeAssetsPath(), '/'); } $urlSegments[] = $this->scriptName; } $this->url = rtrim('/' . implode('/', $urlSegments), '/'); } // add path and path parameters $path = $this->getPath($pathParameters); if($path) { return $this->url . '/' . $path; } return $this->url; }
php
public function getUrl(array $pathParameters = null) { // avoid building URL in subsequent calls if(!$this->url) { $application = Application::getInstance(); $urlSegments = []; if($application->getRouter()->getServerSideRewrite()) { if(($scriptName = basename($this->scriptName, '.php')) !== 'index') { $urlSegments[] = $scriptName; } } else { if($application->getRelativeAssetsPath()) { $urlSegments[] = trim($application->getRelativeAssetsPath(), '/'); } $urlSegments[] = $this->scriptName; } $this->url = rtrim('/' . implode('/', $urlSegments), '/'); } // add path and path parameters $path = $this->getPath($pathParameters); if($path) { return $this->url . '/' . $path; } return $this->url; }
get URL of this route considers mod_rewrite settings (nice_uri) When path parameters are passed on to method an URL using these parameter values is generated, but path parameters are not stored and do not overwrite previously set path parameters. When no (or only some) path parameters are passed on previously set parameters are considered when generating the URL. @param array $pathParameters @return string @throws \vxPHP\Application\Exception\ApplicationException
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Routing/Route.php#L361-L401
Vectrex/vxPHP
src/Routing/Route.php
Route.setRequestMethods
public function setRequestMethods(array $requestMethods) { $requestMethods = array_map('strtoupper', $requestMethods); $allowedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']; foreach($requestMethods as $requestMethod) { if(!in_array($requestMethod, $allowedMethods)) { throw new \InvalidArgumentException(sprintf("Invalid request method '%s'.", $requestMethod)); } } $this->requestMethods = $requestMethods; return $this; }
php
public function setRequestMethods(array $requestMethods) { $requestMethods = array_map('strtoupper', $requestMethods); $allowedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']; foreach($requestMethods as $requestMethod) { if(!in_array($requestMethod, $allowedMethods)) { throw new \InvalidArgumentException(sprintf("Invalid request method '%s'.", $requestMethod)); } } $this->requestMethods = $requestMethods; return $this; }
set all allowed request methods for a route @param array $requestMethods @return \vxPHP\Routing\Route
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Routing/Route.php#L469-L484
Vectrex/vxPHP
src/Routing/Route.php
Route.allowsRequestMethod
public function allowsRequestMethod($requestMethod) { return empty($this->requestMethods) || in_array(strtoupper($requestMethod), $this->requestMethods); }
php
public function allowsRequestMethod($requestMethod) { return empty($this->requestMethods) || in_array(strtoupper($requestMethod), $this->requestMethods); }
check whether a request method is allowed with the route @param string $requestMethod @return boolean
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Routing/Route.php#L492-L496
Vectrex/vxPHP
src/Routing/Route.php
Route.getPathParameter
public function getPathParameter($name, $default = null) { // lazy initialization of parameters if(empty($this->pathParameters) && !is_null($this->placeholders)) { // collect all placeholder names $names = array_keys($this->placeholders); // extract values if(preg_match('~' . $this->match . '~', ltrim(Request::createFromGlobals()->getPathInfo(), '/'), $values)) { array_shift($values); // if not all parameters are set, try to fill up with defaults $offset = count($values); if($offset < count($names)) { while($offset < count($names)) { if(isset($this->placeholders[$names[$offset]]['default'])) { $values[] = $this->placeholders[$names[$offset]]['default']; } ++$offset; } } // only set parameters when count of placeholders matches count of values, that can be evaluated if(count($values) === count($names)) { $this->pathParameters = array_combine($names, $values); } } } $name = strtolower($name); if(isset($this->pathParameters[$name])) { // both bool false and null are returned as null if($this->pathParameters[$name] === false || is_null($this->pathParameters[$name])) { return null; } return $this->pathParameters[$name]; } return $default; }
php
public function getPathParameter($name, $default = null) { // lazy initialization of parameters if(empty($this->pathParameters) && !is_null($this->placeholders)) { // collect all placeholder names $names = array_keys($this->placeholders); // extract values if(preg_match('~' . $this->match . '~', ltrim(Request::createFromGlobals()->getPathInfo(), '/'), $values)) { array_shift($values); // if not all parameters are set, try to fill up with defaults $offset = count($values); if($offset < count($names)) { while($offset < count($names)) { if(isset($this->placeholders[$names[$offset]]['default'])) { $values[] = $this->placeholders[$names[$offset]]['default']; } ++$offset; } } // only set parameters when count of placeholders matches count of values, that can be evaluated if(count($values) === count($names)) { $this->pathParameters = array_combine($names, $values); } } } $name = strtolower($name); if(isset($this->pathParameters[$name])) { // both bool false and null are returned as null if($this->pathParameters[$name] === false || is_null($this->pathParameters[$name])) { return null; } return $this->pathParameters[$name]; } return $default; }
get path parameter @param string $name @param string $default @return string
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Routing/Route.php#L522-L576
Vectrex/vxPHP
src/Routing/Route.php
Route.setPathParameter
public function setPathParameter($name, $value) { // check whether path parameter $name exists if(empty($this->placeholders)) { throw new \InvalidArgumentException(sprintf("Unknown path parameter '%s'.", $name)); } $found = false; foreach($this->placeholders as $placeholder) { if($placeholder['name'] === $name) { $found = true; break; } } if(!$found) { throw new \InvalidArgumentException(sprintf("Unknown path parameter '%s'.", $name)); } $this->pathParameters[$name] = $value; return $this; }
php
public function setPathParameter($name, $value) { // check whether path parameter $name exists if(empty($this->placeholders)) { throw new \InvalidArgumentException(sprintf("Unknown path parameter '%s'.", $name)); } $found = false; foreach($this->placeholders as $placeholder) { if($placeholder['name'] === $name) { $found = true; break; } } if(!$found) { throw new \InvalidArgumentException(sprintf("Unknown path parameter '%s'.", $name)); } $this->pathParameters[$name] = $value; return $this; }
set path parameter $name will only accept parameter names which have been previously defined @param string $name @param string $value @throws \InvalidArgumentException @return \vxPHP\Routing\Route
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Routing/Route.php#L599-L623
Vectrex/vxPHP
src/Routing/Route.php
Route.redirect
public function redirect($queryParams = [], $statusCode = 302) { $request = Request::createFromGlobals(); $application = Application::getInstance(); $urlSegments = [ $request->getSchemeAndHttpHost() ]; if($application->getRouter()->getServerSideRewrite()) { if(($scriptName = basename($request->getScriptName(), '.php')) !== 'index') { $urlSegments[] = $scriptName; } } else { $urlSegments[] = trim($request->getScriptName(), '/'); } if(count($queryParams)) { $query = '?' . http_build_query($queryParams); } else { $query = ''; } return new RedirectResponse(implode('/', $urlSegments) . '/' . $this->redirect . $query, $statusCode); }
php
public function redirect($queryParams = [], $statusCode = 302) { $request = Request::createFromGlobals(); $application = Application::getInstance(); $urlSegments = [ $request->getSchemeAndHttpHost() ]; if($application->getRouter()->getServerSideRewrite()) { if(($scriptName = basename($request->getScriptName(), '.php')) !== 'index') { $urlSegments[] = $scriptName; } } else { $urlSegments[] = trim($request->getScriptName(), '/'); } if(count($queryParams)) { $query = '?' . http_build_query($queryParams); } else { $query = ''; } return new RedirectResponse(implode('/', $urlSegments) . '/' . $this->redirect . $query, $statusCode); }
redirect using configured redirect information if route has no redirect set, redirect will lead to "start page" @param array $queryParams @param int $statusCode @return RedirectResponse @throws \vxPHP\Application\Exception\ApplicationException
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Routing/Route.php#L634-L662
as3io/As3ModlrBundle
DependencyInjection/Utility.php
Utility.appendParameter
public static function appendParameter($name, $key, $value, ContainerBuilder $container) { $name = self::getAliasedName($name); if (false === $container->hasParameter($name)) { $current = []; } else { $current = (Array) $container->getParameter($name); } $current[$key] = $value; $container->setParameter($name, $current); }
php
public static function appendParameter($name, $key, $value, ContainerBuilder $container) { $name = self::getAliasedName($name); if (false === $container->hasParameter($name)) { $current = []; } else { $current = (Array) $container->getParameter($name); } $current[$key] = $value; $container->setParameter($name, $current); }
Appends a key/value pair to a container parameter. If the parameter name currently isn't set, the parameter is created. @param string $name @param string $key @param mixed $value @param ContainerBuilder $container
https://github.com/as3io/As3ModlrBundle/blob/7ce2abb7390c7eaf4081c5b7e00b96e7001774a4/DependencyInjection/Utility.php#L45-L56
as3io/As3ModlrBundle
DependencyInjection/Utility.php
Utility.locateResource
public static function locateResource($path, ContainerBuilder $container) { if (0 === stripos($path, '@')) { // Treat as a bundle path, e.g. @SomeBundle/path/to/something. // Correct backslashed paths. $path = str_replace('\\', '/', $path); $parts = explode('/', $path); $bundle = array_shift($parts); $bundleName = str_replace('@', '', $bundle); $bundleClass = null; foreach ($container->getParameter('kernel.bundles') as $name => $class) { if ($name === $bundleName) { $bundleClass = $class; break; } } if (null === $bundleClass) { throw new \RuntimeException(sprintf('Unable to find a bundle named "%s" for resource path "%s"', $bundleName, $path)); } $refl = new \ReflectionClass($bundleClass); $bundleDir = dirname($refl->getFileName()); return sprintf('%s/%s', $bundleDir, implode('/', $parts)); } return $path; }
php
public static function locateResource($path, ContainerBuilder $container) { if (0 === stripos($path, '@')) { // Treat as a bundle path, e.g. @SomeBundle/path/to/something. // Correct backslashed paths. $path = str_replace('\\', '/', $path); $parts = explode('/', $path); $bundle = array_shift($parts); $bundleName = str_replace('@', '', $bundle); $bundleClass = null; foreach ($container->getParameter('kernel.bundles') as $name => $class) { if ($name === $bundleName) { $bundleClass = $class; break; } } if (null === $bundleClass) { throw new \RuntimeException(sprintf('Unable to find a bundle named "%s" for resource path "%s"', $bundleName, $path)); } $refl = new \ReflectionClass($bundleClass); $bundleDir = dirname($refl->getFileName()); return sprintf('%s/%s', $bundleDir, implode('/', $parts)); } return $path; }
Locates a file resource path for a given config path. Is needed in order to retrieve a bundle's directory, if used. @static @param string $path @param ContainerBuilder $container @return string @throws \RuntimeException
https://github.com/as3io/As3ModlrBundle/blob/7ce2abb7390c7eaf4081c5b7e00b96e7001774a4/DependencyInjection/Utility.php#L116-L145
horntell/php-sdk
lib/guzzle/GuzzleHttp/Exception/RequestException.php
RequestException.create
public static function create( RequestInterface $request, ResponseInterface $response = null, \Exception $previous = null ) { if (!$response) { return new self('Error completing request', $request, null, $previous); } $level = $response->getStatusCode()[0]; if ($level == '4') { $label = 'Client error response'; $className = __NAMESPACE__ . '\\ClientException'; } elseif ($level == '5') { $label = 'Server error response'; $className = __NAMESPACE__ . '\\ServerException'; } else { $label = 'Unsuccessful response'; $className = __CLASS__; } $message = $label . ' [url] ' . $request->getUrl() . ' [status code] ' . $response->getStatusCode() . ' [reason phrase] ' . $response->getReasonPhrase(); return new $className($message, $request, $response, $previous); }
php
public static function create( RequestInterface $request, ResponseInterface $response = null, \Exception $previous = null ) { if (!$response) { return new self('Error completing request', $request, null, $previous); } $level = $response->getStatusCode()[0]; if ($level == '4') { $label = 'Client error response'; $className = __NAMESPACE__ . '\\ClientException'; } elseif ($level == '5') { $label = 'Server error response'; $className = __NAMESPACE__ . '\\ServerException'; } else { $label = 'Unsuccessful response'; $className = __CLASS__; } $message = $label . ' [url] ' . $request->getUrl() . ' [status code] ' . $response->getStatusCode() . ' [reason phrase] ' . $response->getReasonPhrase(); return new $className($message, $request, $response, $previous); }
Factory method to create a new exception with a normalized error message @param RequestInterface $request Request @param ResponseInterface $response Response received @param \Exception $previous Previous exception @return self
https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/lib/guzzle/GuzzleHttp/Exception/RequestException.php#L46-L72
horntell/php-sdk
lib/guzzle/GuzzleHttp/Exception/RequestException.php
RequestException.emittedError
public function emittedError($value = null) { if ($value === null) { return $this->emittedErrorEvent; } elseif ($value === true) { $this->emittedErrorEvent = true; } else { throw new \InvalidArgumentException('You cannot set the emitted ' . 'error value to false.'); } }
php
public function emittedError($value = null) { if ($value === null) { return $this->emittedErrorEvent; } elseif ($value === true) { $this->emittedErrorEvent = true; } else { throw new \InvalidArgumentException('You cannot set the emitted ' . 'error value to false.'); } }
Check or set if the exception was emitted in an error event. This value is used in the RequestEvents::emitBefore() method to check to see if an exception has already been emitted in an error event. @param bool|null Set to true to set the exception as having emitted an error. Leave null to retrieve the current setting. @return null|bool @throws \InvalidArgumentException if you attempt to set the value to false
https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/lib/guzzle/GuzzleHttp/Exception/RequestException.php#L116-L126
erenmustafaozdal/laravel-modules-base
src/Requests/BaseRequest.php
BaseRequest.messages
public function messages() { $messages = []; // photo message eklenir if ( ( $this->has('photo') || $this->file('photo') ) && is_array($this->photo)) { foreach ($this->photo as $key => $val) { $item = $key + 1; $messages['photo.' . $key . '.required'] = "{$item}. Fotoğraf alanı gereklidir."; $messages['photo.' . $key . '.elfinder_max'] = "{$item}. Fotoğraf alanı en fazla :size bayt boyutunda olmalıdır."; $messages['photo.' . $key . '.elfinder'] = "{$item}. Fotoğraf dosya biçimi :values olmalıdır."; $messages['photo.' . $key . '.max'] = "{$item}. Fotoğraf değeri :max kilobayt değerinden küçük olmalıdır."; $messages['photo.' . $key . '.image'] = "{$item}. Fotoğraf alanı resim dosyası olmalıdır."; $messages['photo.' . $key . '.mimes'] = "{$item}. Fotoğraf dosya biçimi :values olmalıdır."; } } return $messages; }
php
public function messages() { $messages = []; // photo message eklenir if ( ( $this->has('photo') || $this->file('photo') ) && is_array($this->photo)) { foreach ($this->photo as $key => $val) { $item = $key + 1; $messages['photo.' . $key . '.required'] = "{$item}. Fotoğraf alanı gereklidir."; $messages['photo.' . $key . '.elfinder_max'] = "{$item}. Fotoğraf alanı en fazla :size bayt boyutunda olmalıdır."; $messages['photo.' . $key . '.elfinder'] = "{$item}. Fotoğraf dosya biçimi :values olmalıdır."; $messages['photo.' . $key . '.max'] = "{$item}. Fotoğraf değeri :max kilobayt değerinden küçük olmalıdır."; $messages['photo.' . $key . '.image'] = "{$item}. Fotoğraf alanı resim dosyası olmalıdır."; $messages['photo.' . $key . '.mimes'] = "{$item}. Fotoğraf dosya biçimi :values olmalıdır."; } } return $messages; }
get message of the rules @return array
https://github.com/erenmustafaozdal/laravel-modules-base/blob/c26600543817642926bcf16ada84009e00d784e0/src/Requests/BaseRequest.php#L28-L46
erenmustafaozdal/laravel-modules-base
src/Requests/BaseRequest.php
BaseRequest.addFileRule
protected function addFileRule($attribute, $size, $mimes, $count = 1, $isRequired = false) { if ($this->has($attribute) && is_string($this->$attribute)) { $this->rules[$attribute] = "elfinder_max:{$size}|elfinder:{$mimes}"; } else if ($this->file($attribute) && is_array($this->$attribute)){ $this->rules[$attribute] = "array|max:{$count}"; foreach($this->file($attribute) as $key => $file) { if(array_search($key, ['x','y','width','height']) !== false) { continue; } $this->rules[$attribute . '.' . $key] = "max:{$size}|image|mimes:{$mimes}"; if ($isRequired) { $this->rules[$attribute . '.' . $key] = "required|{$this->rules[$attribute . '.' . $key]}"; } } } else if ($this->has($attribute) && is_array($this->$attribute)) { $this->rules[$attribute] = "array|max:{$count}"; foreach($this->get($attribute) as $key => $file) { if(array_search($key, ['x','y','width','height']) !== false) { continue; } $this->rules[$attribute . '.' . $key] = "elfinder_max:{$size}|elfinder:{$mimes}"; if ($isRequired) { $this->rules[$attribute . '.' . $key] = "required|{$this->rules[$attribute . '.' . $key]}"; } } } else if ($this->file($attribute)) { $this->rules[$attribute] = "max:{$size}|image|mimes:{$mimes}"; } if ($isRequired) { $this->rules[$attribute] = "required|{$this->rules[$attribute]}"; } }
php
protected function addFileRule($attribute, $size, $mimes, $count = 1, $isRequired = false) { if ($this->has($attribute) && is_string($this->$attribute)) { $this->rules[$attribute] = "elfinder_max:{$size}|elfinder:{$mimes}"; } else if ($this->file($attribute) && is_array($this->$attribute)){ $this->rules[$attribute] = "array|max:{$count}"; foreach($this->file($attribute) as $key => $file) { if(array_search($key, ['x','y','width','height']) !== false) { continue; } $this->rules[$attribute . '.' . $key] = "max:{$size}|image|mimes:{$mimes}"; if ($isRequired) { $this->rules[$attribute . '.' . $key] = "required|{$this->rules[$attribute . '.' . $key]}"; } } } else if ($this->has($attribute) && is_array($this->$attribute)) { $this->rules[$attribute] = "array|max:{$count}"; foreach($this->get($attribute) as $key => $file) { if(array_search($key, ['x','y','width','height']) !== false) { continue; } $this->rules[$attribute . '.' . $key] = "elfinder_max:{$size}|elfinder:{$mimes}"; if ($isRequired) { $this->rules[$attribute . '.' . $key] = "required|{$this->rules[$attribute . '.' . $key]}"; } } } else if ($this->file($attribute)) { $this->rules[$attribute] = "max:{$size}|image|mimes:{$mimes}"; } if ($isRequired) { $this->rules[$attribute] = "required|{$this->rules[$attribute]}"; } }
add file rule to rules @param string $attribute @param string $size @param string $mimes @param integer $count @param boolean $isRequired @return void
https://github.com/erenmustafaozdal/laravel-modules-base/blob/c26600543817642926bcf16ada84009e00d784e0/src/Requests/BaseRequest.php#L58-L93
ProjetPP/PPP-LibModule-PHP
src/DataModel/ModuleResponse.php
ModuleResponse.equals
public function equals($target) { return $target instanceof self && $this->languageCode === $target->languageCode && $this->sentenceTree->equals($target->sentenceTree) && $this->measures == $target->measures; }
php
public function equals($target) { return $target instanceof self && $this->languageCode === $target->languageCode && $this->sentenceTree->equals($target->sentenceTree) && $this->measures == $target->measures; }
Returns if $target is equals to the current response @param mixed $target @return boolean
https://github.com/ProjetPP/PPP-LibModule-PHP/blob/c63feea1deba5ad6d5a1c8ed2a2c57042637b721/src/DataModel/ModuleResponse.php#L82-L87
phospr/DoubleEntryBundle
Model/Vendor.php
Vendor.addJournal
public function addJournal(JournalInterface $journal) { $this->journals->add($journal); $journal->setJournal($this); }
php
public function addJournal(JournalInterface $journal) { $this->journals->add($journal); $journal->setJournal($this); }
Add journal @author Tom Haskins-Vaughan <[email protected]> @since 0.8.0 @param JournalInterface $journal
https://github.com/phospr/DoubleEntryBundle/blob/d9c421f30922b461483731983c59beb26047fb7f/Model/Vendor.php#L144-L148
MBHFramework/mbh-rest
Mbh/App.php
App.getSetting
public function getSetting($key, $defaultValue = null) { return $this->hasSetting($key) ? $this->settings[$key] : $defaultValue; }
php
public function getSetting($key, $defaultValue = null) { return $this->hasSetting($key) ? $this->settings[$key] : $defaultValue; }
Get app setting with given key @param string $key @param mixed $defaultValue @return mixed
https://github.com/MBHFramework/mbh-rest/blob/e23b4e66dc2b8da35e06312dcfdba41c4cfc2c83/Mbh/App.php#L169-L172
MBHFramework/mbh-rest
Mbh/App.php
App.get
public function get($pattern, $callback = null, $inject = null) { return $this->map([ 'GET', 'HEAD' ], $pattern, $callback, $inject); }
php
public function get($pattern, $callback = null, $inject = null) { return $this->map([ 'GET', 'HEAD' ], $pattern, $callback, $inject); }
Adds a new route for the HTTP request method `GET` @param string $route the route to match, e.g. `/users/jane` @param callable|null $callback (optional) the callback to execute, e.g. an anonymous function @param array|null $inject (optional) any arguments that should be prepended to those matched in the route @return bool whether the route matched the current request
https://github.com/MBHFramework/mbh-rest/blob/e23b4e66dc2b8da35e06312dcfdba41c4cfc2c83/Mbh/App.php#L206-L209
MBHFramework/mbh-rest
Mbh/App.php
App.post
public function post($pattern, $callback = null, $inject = null) { return $this->map([ 'POST' ], $pattern, $callback, $inject); }
php
public function post($pattern, $callback = null, $inject = null) { return $this->map([ 'POST' ], $pattern, $callback, $inject); }
Adds a new route for the HTTP request method `POST` @param string $pattern the route to match, e.g. `/users/jane` @param callable|null $callback (optional) the callback to execute, e.g. an anonymous function @param array|null $inject (optional) any arguments that should be prepended to those matched in the route @return bool whether the route matched the current request
https://github.com/MBHFramework/mbh-rest/blob/e23b4e66dc2b8da35e06312dcfdba41c4cfc2c83/Mbh/App.php#L219-L222
MBHFramework/mbh-rest
Mbh/App.php
App.put
public function put($pattern, $callback = null, $inject = null) { return $this->map([ 'PUT' ], $pattern, $callback, $inject); }
php
public function put($pattern, $callback = null, $inject = null) { return $this->map([ 'PUT' ], $pattern, $callback, $inject); }
Adds a new route for the HTTP request method `PUT` @param string $pattern the route to match, e.g. `/users/jane` @param callable|null $callback (optional) the callback to execute, e.g. an anonymous function @param array|null $inject (optional) any arguments that should be prepended to those matched in the route @return bool whether the route matched the current request
https://github.com/MBHFramework/mbh-rest/blob/e23b4e66dc2b8da35e06312dcfdba41c4cfc2c83/Mbh/App.php#L232-L235
MBHFramework/mbh-rest
Mbh/App.php
App.patch
public function patch($pattern, $callback = null, $inject = null) { return $this->map([ 'PATCH' ], $pattern, $callback, $inject); }
php
public function patch($pattern, $callback = null, $inject = null) { return $this->map([ 'PATCH' ], $pattern, $callback, $inject); }
Adds a new route for the HTTP request method `PATCH` @param string $pattern the route to match, e.g. `/users/jane` @param callable|null $callback (optional) the callback to execute, e.g. an anonymous function @param array|null $inject (optional) any arguments that should be prepended to those matched in the route @return bool whether the route matched the current request
https://github.com/MBHFramework/mbh-rest/blob/e23b4e66dc2b8da35e06312dcfdba41c4cfc2c83/Mbh/App.php#L245-L248
MBHFramework/mbh-rest
Mbh/App.php
App.delete
public function delete($pattern, $callback = null, $inject = null) { return $this->map([ 'DELETE' ], $pattern, $callback, $inject); }
php
public function delete($pattern, $callback = null, $inject = null) { return $this->map([ 'DELETE' ], $pattern, $callback, $inject); }
Adds a new route for the HTTP request method `DELETE` @param string $pattern the route to match, e.g. `/users/jane` @param callable|null $callback (optional) the callback to execute, e.g. an anonymous function @param array|null $inject (optional) any arguments that should be prepended to those matched in the route @return bool whether the route matched the current request
https://github.com/MBHFramework/mbh-rest/blob/e23b4e66dc2b8da35e06312dcfdba41c4cfc2c83/Mbh/App.php#L258-L261
MBHFramework/mbh-rest
Mbh/App.php
App.head
public function head($pattern, $callback = null, $inject = null) { return $this->map([ 'HEAD' ], $pattern, $callback, $inject); }
php
public function head($pattern, $callback = null, $inject = null) { return $this->map([ 'HEAD' ], $pattern, $callback, $inject); }
Adds a new route for the HTTP request method `HEAD` @param string $pattern the route to match, e.g. `/users/jane` @param callable|null $callback (optional) the callback to execute, e.g. an anonymous function @param array|null $inject (optional) any arguments that should be prepended to those matched in the route @return bool whether the route matched the current request
https://github.com/MBHFramework/mbh-rest/blob/e23b4e66dc2b8da35e06312dcfdba41c4cfc2c83/Mbh/App.php#L271-L274
MBHFramework/mbh-rest
Mbh/App.php
App.trace
public function trace($pattern, $callback = null, $inject = null) { return $this->map([ 'TRACE' ], $pattern, $callback, $inject); }
php
public function trace($pattern, $callback = null, $inject = null) { return $this->map([ 'TRACE' ], $pattern, $callback, $inject); }
Adds a new route for the HTTP request method `TRACE` @param string $pattern the route to match, e.g. `/users/jane` @param callable|null $callback (optional) the callback to execute, e.g. an anonymous function @param array|null $inject (optional) any arguments that should be prepended to those matched in the route @return bool whether the route matched the current request
https://github.com/MBHFramework/mbh-rest/blob/e23b4e66dc2b8da35e06312dcfdba41c4cfc2c83/Mbh/App.php#L284-L287
MBHFramework/mbh-rest
Mbh/App.php
App.options
public function options($pattern, $callback = null, $inject = null) { return $this->map([ 'OPTIONS' ], $pattern, $callback, $inject); }
php
public function options($pattern, $callback = null, $inject = null) { return $this->map([ 'OPTIONS' ], $pattern, $callback, $inject); }
Adds a new route for the HTTP request method `OPTIONS` @param string $pattern the route to match, e.g. `/users/jane` @param callable|null $callback (optional) the callback to execute, e.g. an anonymous function @param array|null $inject (optional) any arguments that should be prepended to those matched in the route @return bool whether the route matched the current request
https://github.com/MBHFramework/mbh-rest/blob/e23b4e66dc2b8da35e06312dcfdba41c4cfc2c83/Mbh/App.php#L297-L300
MBHFramework/mbh-rest
Mbh/App.php
App.connect
public function connect($pattern, $callback = null, $inject = null) { return $this->map([ 'CONNECT' ], $pattern, $callback, $inject); }
php
public function connect($pattern, $callback = null, $inject = null) { return $this->map([ 'CONNECT' ], $pattern, $callback, $inject); }
Adds a new route for the HTTP request method `CONNECT` @param string $pattern the route to match, e.g. `/users/jane` @param callable|null $callback (optional) the callback to execute, e.g. an anonymous function @param array|null $inject (optional) any arguments that should be prepended to those matched in the route @return bool whether the route matched the current request
https://github.com/MBHFramework/mbh-rest/blob/e23b4e66dc2b8da35e06312dcfdba41c4cfc2c83/Mbh/App.php#L310-L313
MBHFramework/mbh-rest
Mbh/App.php
App.any
public function any($pattern, $callback = null, $inject = null) { return $this->getRouter() ->map([ 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'TRACE', 'OPTIONS', 'CONNECT' ], $pattern, $callback, $inject); }
php
public function any($pattern, $callback = null, $inject = null) { return $this->getRouter() ->map([ 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'TRACE', 'OPTIONS', 'CONNECT' ], $pattern, $callback, $inject); }
Adds a new route for all of the specified HTTP request methods @param string $pattern the route to match, e.g. `/users/jane` @param callable|null $callback (optional) the callback to execute, e.g. an anonymous function @param array|null $inject (optional) any arguments that should be prepended to those matched in the route @return bool whether the route matched the current request
https://github.com/MBHFramework/mbh-rest/blob/e23b4e66dc2b8da35e06312dcfdba41c4cfc2c83/Mbh/App.php#L323-L337
MBHFramework/mbh-rest
Mbh/App.php
App.map
public function map($methods, $pattern, $callback = null, $inject = null) { $methods = is_string($methods) ? [$methods] : $methods; return $this->getRouter()->map($methods, $pattern, $callback, $inject); }
php
public function map($methods, $pattern, $callback = null, $inject = null) { $methods = is_string($methods) ? [$methods] : $methods; return $this->getRouter()->map($methods, $pattern, $callback, $inject); }
Checks the specified request method and route against the current request to see whether it matches @param string|string[] $methods the request methods, one of which must be detected in order to have a match @param string $pattern the route that must be found in order to have a match @param callable|null $callback (optional) the callback to execute, e.g. an anonymous function @param array|null $inject (optional) any arguments that should be prepended to those matched in the route @return bool whether the route matched the current request
https://github.com/MBHFramework/mbh-rest/blob/e23b4e66dc2b8da35e06312dcfdba41c4cfc2c83/Mbh/App.php#L348-L352
PenoaksDev/Milky-Framework
src/Milky/Database/Eloquent/Relations/MorphOneOrMany.php
MorphOneOrMany.setForeignAttributesForCreate
protected function setForeignAttributesForCreate(Model $model) { $model->{$this->getPlainForeignKey()} = $this->getParentKey(); $model->{last(explode('.', $this->morphType))} = $this->morphClass; }
php
protected function setForeignAttributesForCreate(Model $model) { $model->{$this->getPlainForeignKey()} = $this->getParentKey(); $model->{last(explode('.', $this->morphType))} = $this->morphClass; }
Set the foreign ID and type for creating a related model. @param Model $model @return void
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Database/Eloquent/Relations/MorphOneOrMany.php#L196-L201
Vectrex/vxPHP
src/Controller/Controller.php
Controller.renderResponse
public function renderResponse() { if(isset($this->methodName)) { $methodName = $this->methodName; $this->$methodName()->send(); } else { $this->execute()->send(); } }
php
public function renderResponse() { if(isset($this->methodName)) { $methodName = $this->methodName; $this->$methodName()->send(); } else { $this->execute()->send(); } }
renders a complete response including headers either calls an explicitly set method or execute()
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Controller/Controller.php#L137-L147
Vectrex/vxPHP
src/Controller/Controller.php
Controller.render
public function render() { if(isset($this->methodName)) { $methodName = $this->methodName; $this->$methodName()->sendContent(); } else { $this->execute()->sendContent(); } }
php
public function render() { if(isset($this->methodName)) { $methodName = $this->methodName; $this->$methodName()->sendContent(); } else { $this->execute()->sendContent(); } }
renders content of response either calls an explicitly set method or execute()
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Controller/Controller.php#L153-L163
Vectrex/vxPHP
src/Controller/Controller.php
Controller.createControllerFromRoute
public static function createControllerFromRoute(Route $route, array $parameters = null) { $controllerClass = Application::getInstance()->getApplicationNamespace() . $route->getControllerClassName(); /** * @var Controller */ $instance = new $controllerClass($route, $parameters); if($method = $instance->route->getMethodName()) { $instance->setExecutedMethod($method); } else { $instance->setExecutedMethod('execute'); } return $instance; }
php
public static function createControllerFromRoute(Route $route, array $parameters = null) { $controllerClass = Application::getInstance()->getApplicationNamespace() . $route->getControllerClassName(); /** * @var Controller */ $instance = new $controllerClass($route, $parameters); if($method = $instance->route->getMethodName()) { $instance->setExecutedMethod($method); } else { $instance->setExecutedMethod('execute'); } return $instance; }
determines controller class name from a routes controllerString property and returns a controller instance an additional parameters array will be passed on to the constructor @param Route $route @param array $parameters @return \vxPHP\Controller\Controller @throws \vxPHP\Application\Exception\ApplicationException
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Controller/Controller.php#L190-L208
Vectrex/vxPHP
src/Controller/Controller.php
Controller.redirect
protected function redirect($url = null, $queryParams = [], $statusCode = 302) { if(is_null($url)) { return $this->route->redirect($queryParams, $statusCode); } if($queryParams) { $query = (strpos($url, '?') === false ? '?' : '&') . http_build_query($queryParams); } else { $query = ''; } return new RedirectResponse($url . $query, $statusCode); }
php
protected function redirect($url = null, $queryParams = [], $statusCode = 302) { if(is_null($url)) { return $this->route->redirect($queryParams, $statusCode); } if($queryParams) { $query = (strpos($url, '?') === false ? '?' : '&') . http_build_query($queryParams); } else { $query = ''; } return new RedirectResponse($url . $query, $statusCode); }
prepares and executes a Route::redirect @param string destination page id @param array $queryParams @param int $statusCode @return RedirectResponse @throws \vxPHP\Application\Exception\ApplicationException
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Controller/Controller.php#L219-L235
Vectrex/vxPHP
src/Controller/Controller.php
Controller.generateHttpError
protected function generateHttpError($errorCode = 404) { $content = '<h1>' . $errorCode . ' ' . Response::$statusTexts[$errorCode] . '</h1>'; Response::create($content, $errorCode)->send(); exit(); }
php
protected function generateHttpError($errorCode = 404) { $content = '<h1>' . $errorCode . ' ' . Response::$statusTexts[$errorCode] . '</h1>'; Response::create($content, $errorCode)->send(); exit(); }
generate error and (optional) error page content @param integer $errorCode
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Controller/Controller.php#L242-L254
Vectrex/vxPHP
src/Controller/Controller.php
Controller.addEchoToJsonResponse
protected function addEchoToJsonResponse(JsonResponse $r) { // handle JSON encoded request data if($this->isXhr && $this->xhrBag && $this->xhrBag->get('echo') == 1) { // echo is the original xmlHttpRequest sans echo property $echo = json_decode($this->xhrBag->get('xmlHttpRequest')); unset($echo->echo); } // handle plain POST or GET data else { if($this->request->getMethod() === 'POST' && $this->request->request->get('echo')) { $echo = $this->request->request->all(); unset($echo['echo']); } else if($this->request->query->get('echo')) { $echo = $this->request->query->all(); unset($echo['echo']); } } if(isset($echo)) { $r->setPayload([ 'echo' => $echo, 'response' => json_decode($r->getContent()) ]); } return $r; }
php
protected function addEchoToJsonResponse(JsonResponse $r) { // handle JSON encoded request data if($this->isXhr && $this->xhrBag && $this->xhrBag->get('echo') == 1) { // echo is the original xmlHttpRequest sans echo property $echo = json_decode($this->xhrBag->get('xmlHttpRequest')); unset($echo->echo); } // handle plain POST or GET data else { if($this->request->getMethod() === 'POST' && $this->request->request->get('echo')) { $echo = $this->request->request->all(); unset($echo['echo']); } else if($this->request->query->get('echo')) { $echo = $this->request->query->all(); unset($echo['echo']); } } if(isset($echo)) { $r->setPayload([ 'echo' => $echo, 'response' => json_decode($r->getContent()) ]); } return $r; }
add an echo property to a JsonResponse, if request indicates that echo was requested useful with vxJS.xhr based widgets @param JsonResponse $r @return JsonResponse @throws \Exception
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Controller/Controller.php#L264-L302
Vectrex/vxPHP
src/Controller/Controller.php
Controller.prepareForXhr
private function prepareForXhr() { // do we have a GET XHR? if($this->request->getMethod() === 'GET' && $this->request->query->get('xmlHttpRequest')) { $this->xhrBag = $this->request->query; foreach(json_decode($this->xhrBag->get('xmlHttpRequest'), TRUE) as $key => $value) { $this->xhrBag->set($key, $value); } } // do we have a POST XHR? else if($this->request->getMethod() === 'POST' && $this->request->request->get('xmlHttpRequest')) { $this->xhrBag = $this->request->request; foreach(json_decode($this->xhrBag->get('xmlHttpRequest'), TRUE) as $key => $value) { $this->xhrBag->set($key, $value); } } // do we have an iframe upload? else if($this->request->query->get('ifuRequest')) { // POST already contains all the parameters $this->request->request->set('httpRequest', 'ifuSubmit'); } // otherwise no XHR according to the above rules was detected else { $this->isXhr = FALSE; return; } $this->isXhr = TRUE; // handle request for apc upload poll, this will not be left to individual controller if($this->xhrBag && $this->xhrBag->get('httpRequest') === 'apcPoll') { $id = $this->xhrBag->get('id'); if($this->config->server['apc_on'] && $id) { $apcData = apc_fetch('upload_' . $id); } if(isset($apcData['done']) && $apcData['done'] == 1) { apc_clear_cache('user'); } JsonResponse::create($apcData)->send(); exit(); } }
php
private function prepareForXhr() { // do we have a GET XHR? if($this->request->getMethod() === 'GET' && $this->request->query->get('xmlHttpRequest')) { $this->xhrBag = $this->request->query; foreach(json_decode($this->xhrBag->get('xmlHttpRequest'), TRUE) as $key => $value) { $this->xhrBag->set($key, $value); } } // do we have a POST XHR? else if($this->request->getMethod() === 'POST' && $this->request->request->get('xmlHttpRequest')) { $this->xhrBag = $this->request->request; foreach(json_decode($this->xhrBag->get('xmlHttpRequest'), TRUE) as $key => $value) { $this->xhrBag->set($key, $value); } } // do we have an iframe upload? else if($this->request->query->get('ifuRequest')) { // POST already contains all the parameters $this->request->request->set('httpRequest', 'ifuSubmit'); } // otherwise no XHR according to the above rules was detected else { $this->isXhr = FALSE; return; } $this->isXhr = TRUE; // handle request for apc upload poll, this will not be left to individual controller if($this->xhrBag && $this->xhrBag->get('httpRequest') === 'apcPoll') { $id = $this->xhrBag->get('id'); if($this->config->server['apc_on'] && $id) { $apcData = apc_fetch('upload_' . $id); } if(isset($apcData['done']) && $apcData['done'] == 1) { apc_clear_cache('user'); } JsonResponse::create($apcData)->send(); exit(); } }
check whether a an XMLHttpRequest was submitted this will look for a key 'xmlHttpRequest' in both GET and POST and set the Controller::isXhr flag and decode the parameters accordingly into their ParameterBages in addition the presence of ifuRequest in GET is checked for handling IFRAME uploads this method is geared to fully support the vxJS.widget.xhrForm()
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Controller/Controller.php#L313-L374
Linkvalue-Interne/MajoraFrameworkExtraBundle
src/Majora/Framework/Domain/Action/Dal/DalActionTrait.php
DalActionTrait.assertEntityIsValid
protected function assertEntityIsValid($entity, $scope = null) { if (!$this->validator) { throw new \BadMethodCallException(sprintf( 'Method %s() cannot be used while validator is not configured.', __METHOD__ )); } $scopes = $scope ? (array) $scope : null; $violationList = $this->validator->validate( $entity, null, $scopes ); if (!count($violationList)) { return; } throw new ValidationException($entity, $violationList, $scopes); }
php
protected function assertEntityIsValid($entity, $scope = null) { if (!$this->validator) { throw new \BadMethodCallException(sprintf( 'Method %s() cannot be used while validator is not configured.', __METHOD__ )); } $scopes = $scope ? (array) $scope : null; $violationList = $this->validator->validate( $entity, null, $scopes ); if (!count($violationList)) { return; } throw new ValidationException($entity, $violationList, $scopes); }
assert given entity is valid on given scope. @param object $entity @param string|array $scope @throws ValidationException If given object is invalid on given scope
https://github.com/Linkvalue-Interne/MajoraFrameworkExtraBundle/blob/6f368380cfc39d27fafb0844e9a53b4d86d7c034/src/Majora/Framework/Domain/Action/Dal/DalActionTrait.php#L55-L77
Linkvalue-Interne/MajoraFrameworkExtraBundle
src/Majora/Framework/Domain/Action/Dal/DalActionTrait.php
DalActionTrait.fireEvent
protected function fireEvent($eventName, Event $event) { if (!$this->eventDispatcher) { throw new \BadMethodCallException(sprintf( 'Method %s() cannot be used while event dispatcher is not configured.', __METHOD__ )); } $this->eventDispatcher->dispatch($eventName, $event); }
php
protected function fireEvent($eventName, Event $event) { if (!$this->eventDispatcher) { throw new \BadMethodCallException(sprintf( 'Method %s() cannot be used while event dispatcher is not configured.', __METHOD__ )); } $this->eventDispatcher->dispatch($eventName, $event); }
fire given event. @param string $eventName @param Event $event @throws \BadMethodCallException If any event dispatcher set
https://github.com/Linkvalue-Interne/MajoraFrameworkExtraBundle/blob/6f368380cfc39d27fafb0844e9a53b4d86d7c034/src/Majora/Framework/Domain/Action/Dal/DalActionTrait.php#L87-L97
pipaslot/forms
src/Forms/Rendering/Bootstrap3StackRenderer.php
Bootstrap3StackRenderer.prepareForm
protected function prepareForm(Form $form) { $form->getElementPrototype()->class[] = 'form-horizontal'; $translator = $form->getTranslator(); foreach ($form->controls as $control) { /** @var BaseControl $control */ if ($control instanceof HiddenField) { continue; } elseif ($control instanceof Button) { $control->controlPrototype->class[] = "btn-block btn-lg"; } else { if ($control->getLabel()) { $control->setAttribute('placeholder', $control->caption); if (empty($control->controlPrototype->attrs['title'])) { $control->setAttribute('title', $translator ? $translator->translate($control->caption) : $control->caption); } $control->getLabelPrototype()->attrs["style"] = "display:none"; } } } BootstrapHelper::ApplyBootstrapToControls($form); }
php
protected function prepareForm(Form $form) { $form->getElementPrototype()->class[] = 'form-horizontal'; $translator = $form->getTranslator(); foreach ($form->controls as $control) { /** @var BaseControl $control */ if ($control instanceof HiddenField) { continue; } elseif ($control instanceof Button) { $control->controlPrototype->class[] = "btn-block btn-lg"; } else { if ($control->getLabel()) { $control->setAttribute('placeholder', $control->caption); if (empty($control->controlPrototype->attrs['title'])) { $control->setAttribute('title', $translator ? $translator->translate($control->caption) : $control->caption); } $control->getLabelPrototype()->attrs["style"] = "display:none"; } } } BootstrapHelper::ApplyBootstrapToControls($form); }
Make form and controls compatible with Twitter Bootstrap @param Form $form
https://github.com/pipaslot/forms/blob/9e1d48db512f843270fd4079ed3ff1b1729c951b/src/Forms/Rendering/Bootstrap3StackRenderer.php#L37-L58
clacy-builders/graphics-php
src/Points.php
Points.rectangle
public static function rectangle(Point $corner, $width, $height, $ccw = false) { $points = new Points($corner); $points->addPoint($corner); $points->addPoint($corner)->translateX($width); $points->addPoint($corner)->translate($width, $height); $points->addPoint($corner)->translateY($height); $points->reverseIfCcw($ccw); return $points; }
php
public static function rectangle(Point $corner, $width, $height, $ccw = false) { $points = new Points($corner); $points->addPoint($corner); $points->addPoint($corner)->translateX($width); $points->addPoint($corner)->translate($width, $height); $points->addPoint($corner)->translateY($height); $points->reverseIfCcw($ccw); return $points; }
Calculates the points for a rectangle. @param Point $corner The top left corner. @param float $width @param float $height @param boolean $ccw Whether to list the points counterclockwise or not.
https://github.com/clacy-builders/graphics-php/blob/c56556c9265ea4537efdc14ae89a8f36454812d9/src/Points.php#L52-L61
clacy-builders/graphics-php
src/Points.php
Points.polygon
public static function polygon(Point $center, $n, $radius, $ccw = false) { return self::star($center, $n, $radius, [], $ccw); }
php
public static function polygon(Point $center, $n, $radius, $ccw = false) { return self::star($center, $n, $radius, [], $ccw); }
Calculates the points for a regular polygon. @param Point $center @param int $n Number of corners. @param float $radius @param boolean $ccw Whether to list the points counterclockwise or not.
https://github.com/clacy-builders/graphics-php/blob/c56556c9265ea4537efdc14ae89a8f36454812d9/src/Points.php#L71-L74
clacy-builders/graphics-php
src/Points.php
Points.star
public static function star(Point $center, $n, $radius, $starRadii = [], $ccw = false) { $points = new Points($center); if (!is_array($starRadii)) { $starRadii = [$starRadii]; } $radii = array_merge([$radius], $starRadii); $count = count($radii); $delta = deg2rad(360) / $n / $count; $angle = Angle::create(0); for ($i = 0; $i < $n; $i++) { foreach ($radii as $k => $radius) { $points->addPoint($center)->translateY(-$radius)->rotate($center, $angle); $angle->add($delta); } } $points->reverseIfCcw($ccw); return $points; }
php
public static function star(Point $center, $n, $radius, $starRadii = [], $ccw = false) { $points = new Points($center); if (!is_array($starRadii)) { $starRadii = [$starRadii]; } $radii = array_merge([$radius], $starRadii); $count = count($radii); $delta = deg2rad(360) / $n / $count; $angle = Angle::create(0); for ($i = 0; $i < $n; $i++) { foreach ($radii as $k => $radius) { $points->addPoint($center)->translateY(-$radius)->rotate($center, $angle); $angle->add($delta); } } $points->reverseIfCcw($ccw); return $points; }
Calculates the Points for a regular star polygon. @param Point $center @param int $n Number of corners of the underlying polygon. @param float $radius @param float|float[] $starRadii @param boolean $ccw Whether to list the points counterclockwise or not.
https://github.com/clacy-builders/graphics-php/blob/c56556c9265ea4537efdc14ae89a8f36454812d9/src/Points.php#L85-L103
clacy-builders/graphics-php
src/Points.php
Points.sector
public static function sector(Point $center, Angle $start, Angle $stop, $radius, $ccw = false) { $points = new Points($center); $points->addPoint($center); $points->addPoint($center)->translateX($radius)->rotate($center, $start); $points->addPoint($center)->translateX($radius)->rotate($center, $stop); $points->reverseIfCcw($ccw); return $points; }
php
public static function sector(Point $center, Angle $start, Angle $stop, $radius, $ccw = false) { $points = new Points($center); $points->addPoint($center); $points->addPoint($center)->translateX($radius)->rotate($center, $start); $points->addPoint($center)->translateX($radius)->rotate($center, $stop); $points->reverseIfCcw($ccw); return $points; }
Calculates the points for a sector of a circle. @param Point $center @param Angle $start @param Angle $stop Must be greater than <code>$start</code>. @param float $radius @param boolean $ccw Whether to list the points counterclockwise or not.
https://github.com/clacy-builders/graphics-php/blob/c56556c9265ea4537efdc14ae89a8f36454812d9/src/Points.php#L129-L137
clacy-builders/graphics-php
src/Points.php
Points.ringSector
public static function ringSector(Point $center, Angle $start, Angle $stop, $radius, $innerRadius, $ccw = false) { $points = new Points($center, false); if ($ccw) { $swap = $start; $start = $stop; $stop = $swap; } $points->addPoint($center)->translateX($radius)->rotate($center, $start); $points->addPoint($center)->translateX($radius)->rotate($center, $stop); $points->addPoint($center)->translateX($innerRadius)->rotate($center, $stop); $points->addPoint($center)->translateX($innerRadius)->rotate($center, $start); return $points; }
php
public static function ringSector(Point $center, Angle $start, Angle $stop, $radius, $innerRadius, $ccw = false) { $points = new Points($center, false); if ($ccw) { $swap = $start; $start = $stop; $stop = $swap; } $points->addPoint($center)->translateX($radius)->rotate($center, $start); $points->addPoint($center)->translateX($radius)->rotate($center, $stop); $points->addPoint($center)->translateX($innerRadius)->rotate($center, $stop); $points->addPoint($center)->translateX($innerRadius)->rotate($center, $start); return $points; }
Calculates the points for a sector of a ring. @param Point $center @param Angle $start @param Angle $stop Must be greater than <code>$start</code>. @param float $radius @param float $innerRadius @param boolean $ccw Whether to list the points counterclockwise or not.
https://github.com/clacy-builders/graphics-php/blob/c56556c9265ea4537efdc14ae89a8f36454812d9/src/Points.php#L149-L159
clacy-builders/graphics-php
src/Points.php
Points.roundedRectangle
public static function roundedRectangle(Point $corner, $width, $height, $radius, $ccw = false) { $points = new Points($corner, false); $points->addPoint($corner)->translateX($width - $radius); $points->addPoint($corner)->translate($width, $radius); $points->addPoint($corner)->translate($width, $height - $radius); $points->addPoint($corner)->translate($width - $radius, $height); $points->addPoint($corner)->translate($radius, $height); $points->addPoint($corner)->translateY($height - $radius); $points->addPoint($corner)->translateY($radius); $points->addPoint($corner)->translateX($radius); $points->reverseIfCcw($ccw); return $points; }
php
public static function roundedRectangle(Point $corner, $width, $height, $radius, $ccw = false) { $points = new Points($corner, false); $points->addPoint($corner)->translateX($width - $radius); $points->addPoint($corner)->translate($width, $radius); $points->addPoint($corner)->translate($width, $height - $radius); $points->addPoint($corner)->translate($width - $radius, $height); $points->addPoint($corner)->translate($radius, $height); $points->addPoint($corner)->translateY($height - $radius); $points->addPoint($corner)->translateY($radius); $points->addPoint($corner)->translateX($radius); $points->reverseIfCcw($ccw); return $points; }
Calculates the points for a rounded rectangle. @param Point $corner The top left corner. @param float $width @param float $height @param float $radius @param boolean $ccw Whether to list the points counterclockwise or not.
https://github.com/clacy-builders/graphics-php/blob/c56556c9265ea4537efdc14ae89a8f36454812d9/src/Points.php#L170-L183
clacy-builders/graphics-php
src/Points.php
Points.scale
public function scale(Point $center, $factor) { foreach ($this->points as $point) { $point->scale($center, $factor); } $this->start->scale($center, $factor); return $this; }
php
public function scale(Point $center, $factor) { foreach ($this->points as $point) { $point->scale($center, $factor); } $this->start->scale($center, $factor); return $this; }
Scales points. @param Point $center @param float $factor
https://github.com/clacy-builders/graphics-php/blob/c56556c9265ea4537efdc14ae89a8f36454812d9/src/Points.php#L206-L213
clacy-builders/graphics-php
src/Points.php
Points.scaleX
public function scaleX(Point $center, $factor) { foreach ($this->points as $point) { $point->scaleX($center, $factor); } $this->start->scaleX($center, $factor); $this->reverseIfCcw($factor < 0); return $this; }
php
public function scaleX(Point $center, $factor) { foreach ($this->points as $point) { $point->scaleX($center, $factor); } $this->start->scaleX($center, $factor); $this->reverseIfCcw($factor < 0); return $this; }
Scales points along the X-axis. @param Point $center @param float $factor
https://github.com/clacy-builders/graphics-php/blob/c56556c9265ea4537efdc14ae89a8f36454812d9/src/Points.php#L221-L229
clacy-builders/graphics-php
src/Points.php
Points.skewX
public function skewX(Point $center, Angle $angle) { foreach ($this->points as $point) { $point->skewX($center, $angle); } $this->start->skewX($center, $angle); return $this; }
php
public function skewX(Point $center, Angle $angle) { foreach ($this->points as $point) { $point->skewX($center, $angle); } $this->start->skewX($center, $angle); return $this; }
A skew transformation along the X-axis. @param Point $center @param Angle $angle
https://github.com/clacy-builders/graphics-php/blob/c56556c9265ea4537efdc14ae89a8f36454812d9/src/Points.php#L253-L260
clacy-builders/graphics-php
src/Points.php
Points.translate
public function translate($deltaX, $deltaY) { foreach ($this->points as $point) { $point->translate($deltaX, $deltaY); } $this->start->translate($deltaX, $deltaY); return $this; }
php
public function translate($deltaX, $deltaY) { foreach ($this->points as $point) { $point->translate($deltaX, $deltaY); } $this->start->translate($deltaX, $deltaY); return $this; }
Translates points. @param float $deltaX @param float $deltaY
https://github.com/clacy-builders/graphics-php/blob/c56556c9265ea4537efdc14ae89a8f36454812d9/src/Points.php#L283-L290
clacy-builders/graphics-php
src/Points.php
Points.translateX
public function translateX($deltaX) { foreach ($this->points as $point) { $point->translateX($deltaX); } $this->start->translateX($deltaX); return $this; }
php
public function translateX($deltaX) { foreach ($this->points as $point) { $point->translateX($deltaX); } $this->start->translateX($deltaX); return $this; }
Translates points along the X-axis. @param float $deltaX @param float $deltaY
https://github.com/clacy-builders/graphics-php/blob/c56556c9265ea4537efdc14ae89a8f36454812d9/src/Points.php#L298-L305
clacy-builders/graphics-php
src/Points.php
Points.translateY
public function translateY($deltaY) { foreach ($this->points as $point) { $point->translateY($deltaY); } $this->start->translateY($deltaY); return $this; }
php
public function translateY($deltaY) { foreach ($this->points as $point) { $point->translateY($deltaY); } $this->start->translateY($deltaY); return $this; }
Translates points along the Y-axis. @param float $deltaX @param float $deltaY
https://github.com/clacy-builders/graphics-php/blob/c56556c9265ea4537efdc14ae89a8f36454812d9/src/Points.php#L313-L320
zodream/html
src/MarkDown.php
MarkDown.blockCode
protected function blockCode($Line, $Block = null) { if (isset($Block) && !isset($Block['type']) && !isset($Block['interrupted'])) { return; } if ($Line['indent'] >= 4) { $text = substr($Line['body'], 4); $Block = array( 'element' => array( 'name' => 'pre', 'handler' => 'element', 'text' => array( 'name' => 'code', 'text' => $text, ), ), ); return $Block; } }
php
protected function blockCode($Line, $Block = null) { if (isset($Block) && !isset($Block['type']) && !isset($Block['interrupted'])) { return; } if ($Line['indent'] >= 4) { $text = substr($Line['body'], 4); $Block = array( 'element' => array( 'name' => 'pre', 'handler' => 'element', 'text' => array( 'name' => 'code', 'text' => $text, ), ), ); return $Block; } }
# Code
https://github.com/zodream/html/blob/bc21574091380007742bbc5c1c6d78bb87c47896/src/MarkDown.php#L271-L294
zodream/html
src/MarkDown.php
MarkDown.blockComment
protected function blockComment($Line) { if ($this->markupEscaped) { return; } if (isset($Line['text'][3]) && $Line['text'][3] === '-' && $Line['text'][2] === '-' && $Line['text'][1] === '!') { $Block = array( 'markup' => $Line['body'], ); if (preg_match('/-->$/', $Line['text'])) { $Block['closed'] = true; } return $Block; } }
php
protected function blockComment($Line) { if ($this->markupEscaped) { return; } if (isset($Line['text'][3]) && $Line['text'][3] === '-' && $Line['text'][2] === '-' && $Line['text'][1] === '!') { $Block = array( 'markup' => $Line['body'], ); if (preg_match('/-->$/', $Line['text'])) { $Block['closed'] = true; } return $Block; } }
# Comment
https://github.com/zodream/html/blob/bc21574091380007742bbc5c1c6d78bb87c47896/src/MarkDown.php#L327-L346
zodream/html
src/MarkDown.php
MarkDown.blockHeader
protected function blockHeader($Line) { if (isset($Line['text'][1])) { $level = 1; while (isset($Line['text'][$level]) && $Line['text'][$level] === '#') { $level ++; } if ($level > 6) { return; } $text = trim($Line['text'], '# '); $Block = array( 'element' => array( 'name' => 'h' . min(6, $level), 'text' => $text, 'handler' => 'line', ), ); return $Block; } }
php
protected function blockHeader($Line) { if (isset($Line['text'][1])) { $level = 1; while (isset($Line['text'][$level]) && $Line['text'][$level] === '#') { $level ++; } if ($level > 6) { return; } $text = trim($Line['text'], '# '); $Block = array( 'element' => array( 'name' => 'h' . min(6, $level), 'text' => $text, 'handler' => 'line', ), ); return $Block; } }
# Header
https://github.com/zodream/html/blob/bc21574091380007742bbc5c1c6d78bb87c47896/src/MarkDown.php#L431-L456
zodream/html
src/MarkDown.php
MarkDown.blockTable
protected function blockTable($Line, array $Block = null) { if (!isset($Block) || isset($Block['type']) || isset($Block['interrupted'])) { return; } if (strpos($Block['element']['text'], '|') !== false && chop($Line['text'], ' -:|') === '') { $alignments = array(); $divider = $Line['text']; $divider = trim($divider); $divider = trim($divider, '|'); $dividerCells = explode('|', $divider); foreach ($dividerCells as $dividerCell) { $dividerCell = trim($dividerCell); if ($dividerCell === '') { continue; } $alignment = null; if ($dividerCell[0] === ':') { $alignment = 'left'; } if (substr($dividerCell, - 1) === ':') { $alignment = $alignment === 'left' ? 'center' : 'right'; } $alignments []= $alignment; } # ~ $HeaderElements = array(); $header = $Block['element']['text']; $header = trim($header); $header = trim($header, '|'); $headerCells = explode('|', $header); foreach ($headerCells as $index => $headerCell) { $headerCell = trim($headerCell); $HeaderElement = array( 'name' => 'th', 'text' => $headerCell, 'handler' => 'line', ); if (isset($alignments[$index])) { $alignment = $alignments[$index]; $HeaderElement['attributes'] = array( 'style' => 'text-align: '.$alignment.';', ); } $HeaderElements []= $HeaderElement; } # ~ $Block = array( 'alignments' => $alignments, 'identified' => true, 'element' => array( 'name' => 'table', 'handler' => 'elements', ), ); $Block['element']['text'] []= array( 'name' => 'thead', 'handler' => 'elements', ); $Block['element']['text'] []= array( 'name' => 'tbody', 'handler' => 'elements', 'text' => array(), ); $Block['element']['text'][0]['text'] []= array( 'name' => 'tr', 'handler' => 'elements', 'text' => $HeaderElements, ); return $Block; } }
php
protected function blockTable($Line, array $Block = null) { if (!isset($Block) || isset($Block['type']) || isset($Block['interrupted'])) { return; } if (strpos($Block['element']['text'], '|') !== false && chop($Line['text'], ' -:|') === '') { $alignments = array(); $divider = $Line['text']; $divider = trim($divider); $divider = trim($divider, '|'); $dividerCells = explode('|', $divider); foreach ($dividerCells as $dividerCell) { $dividerCell = trim($dividerCell); if ($dividerCell === '') { continue; } $alignment = null; if ($dividerCell[0] === ':') { $alignment = 'left'; } if (substr($dividerCell, - 1) === ':') { $alignment = $alignment === 'left' ? 'center' : 'right'; } $alignments []= $alignment; } # ~ $HeaderElements = array(); $header = $Block['element']['text']; $header = trim($header); $header = trim($header, '|'); $headerCells = explode('|', $header); foreach ($headerCells as $index => $headerCell) { $headerCell = trim($headerCell); $HeaderElement = array( 'name' => 'th', 'text' => $headerCell, 'handler' => 'line', ); if (isset($alignments[$index])) { $alignment = $alignments[$index]; $HeaderElement['attributes'] = array( 'style' => 'text-align: '.$alignment.';', ); } $HeaderElements []= $HeaderElement; } # ~ $Block = array( 'alignments' => $alignments, 'identified' => true, 'element' => array( 'name' => 'table', 'handler' => 'elements', ), ); $Block['element']['text'] []= array( 'name' => 'thead', 'handler' => 'elements', ); $Block['element']['text'] []= array( 'name' => 'tbody', 'handler' => 'elements', 'text' => array(), ); $Block['element']['text'][0]['text'] []= array( 'name' => 'tr', 'handler' => 'elements', 'text' => $HeaderElements, ); return $Block; } }
# Table
https://github.com/zodream/html/blob/bc21574091380007742bbc5c1c6d78bb87c47896/src/MarkDown.php#L717-L816
net-tools/core
src/ExceptionHandlers/Formatters/PublicFormatter.php
PublicFormatter.body
protected function body(\Throwable $e, $h1, $stackTraceContent) { // prepare email attachment with appropriate formatters : html body + minimum stack first + hr + complete stack $html_email = (new HtmlFormatter(new MinimumAndFullHtmlStackTraceFormatter()))->format($e, $h1); // prepare email body as plain text, with a mimimum stack trace $plaintext = (new PlainTextFormatter(new MinimumPlainTextStackTraceFormatter()))->format($e, $h1); // send email $sep = sha1(uniqid()); $headers = "Content-Type: multipart/mixed; boundary=\"$sep\"\r\n" . "From: {$this->_getSender()};"; $msg = "--$sep\r\nContent-Type: text/html;\r\n\r\n<pre>{$plaintext}</pre>\r\n\r\n" . "--$sep\r\nContent-Type: text/html; name=\"stack-trace.html\"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\"stack-trace.html\"\r\n\r\n" . trim(chunk_split(base64_encode($html_email))) . "\r\n\r\n" . "--$sep--"; mail($this->_getRecipient(), $this->_getSubject($e, $h1), $msg, $headers); // no stack track for public output return parent::body($e, $h1, $stackTraceContent); }
php
protected function body(\Throwable $e, $h1, $stackTraceContent) { // prepare email attachment with appropriate formatters : html body + minimum stack first + hr + complete stack $html_email = (new HtmlFormatter(new MinimumAndFullHtmlStackTraceFormatter()))->format($e, $h1); // prepare email body as plain text, with a mimimum stack trace $plaintext = (new PlainTextFormatter(new MinimumPlainTextStackTraceFormatter()))->format($e, $h1); // send email $sep = sha1(uniqid()); $headers = "Content-Type: multipart/mixed; boundary=\"$sep\"\r\n" . "From: {$this->_getSender()};"; $msg = "--$sep\r\nContent-Type: text/html;\r\n\r\n<pre>{$plaintext}</pre>\r\n\r\n" . "--$sep\r\nContent-Type: text/html; name=\"stack-trace.html\"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\"stack-trace.html\"\r\n\r\n" . trim(chunk_split(base64_encode($html_email))) . "\r\n\r\n" . "--$sep--"; mail($this->_getRecipient(), $this->_getSubject($e, $h1), $msg, $headers); // no stack track for public output return parent::body($e, $h1, $stackTraceContent); }
Output exception body @param \Throwable $e Exception to format @param string $h1 Title of error page (such as "an error has occured") @param string $stackTraceContent @return string
https://github.com/net-tools/core/blob/51446641cee22c0cf53d2b409c76cc8bd1a187e7/src/ExceptionHandlers/Formatters/PublicFormatter.php#L62-L83
joegreen88/zf1-component-validate
src/Zend/Validate/Alpha.php
Zend_Validate_Alpha.isValid
public function isValid($value) { if (!is_string($value)) { $this->_error(self::INVALID); return false; } $this->_setValue($value); if ('' === $value) { $this->_error(self::STRING_EMPTY); return false; } if (null === self::$_filter) { /** * @see Zend_Filter_Alpha */ self::$_filter = new Zend_Filter_Alpha(); } self::$_filter->allowWhiteSpace = $this->allowWhiteSpace; if ($value !== self::$_filter->filter($value)) { $this->_error(self::NOT_ALPHA); return false; } return true; }
php
public function isValid($value) { if (!is_string($value)) { $this->_error(self::INVALID); return false; } $this->_setValue($value); if ('' === $value) { $this->_error(self::STRING_EMPTY); return false; } if (null === self::$_filter) { /** * @see Zend_Filter_Alpha */ self::$_filter = new Zend_Filter_Alpha(); } self::$_filter->allowWhiteSpace = $this->allowWhiteSpace; if ($value !== self::$_filter->filter($value)) { $this->_error(self::NOT_ALPHA); return false; } return true; }
Defined by Zend_Validate_Interface Returns true if and only if $value contains only alphabetic characters @param string $value @return boolean
https://github.com/joegreen88/zf1-component-validate/blob/88d9ea016f73d48ff0ba7d06ecbbf28951fd279e/src/Zend/Validate/Alpha.php#L118-L148
prolic/HumusMvc
src/HumusMvc/DispatchListener.php
DispatchListener.onDispatch
public function onDispatch(MvcEvent $e) { $application = $e->getApplication(); $sm = $application->getServiceManager(); $front = $sm->get('FrontController'); $front->returnResponse(true); // Response must be always returned $default = $front->getDefaultModule(); if (null === $front->getControllerDirectory($default)) { throw new Exception\RuntimeException( 'No default controller directory registered with front controller' ); } $response = $front->dispatch(); return $this->complete($response, $e); }
php
public function onDispatch(MvcEvent $e) { $application = $e->getApplication(); $sm = $application->getServiceManager(); $front = $sm->get('FrontController'); $front->returnResponse(true); // Response must be always returned $default = $front->getDefaultModule(); if (null === $front->getControllerDirectory($default)) { throw new Exception\RuntimeException( 'No default controller directory registered with front controller' ); } $response = $front->dispatch(); return $this->complete($response, $e); }
Listen to the "dispatch" event @param MvcEvent $e @return mixed
https://github.com/prolic/HumusMvc/blob/09e8c6422d84b57745cc643047e10761be2a21a7/src/HumusMvc/DispatchListener.php#L65-L79
Wedeto/Log
src/Logger.php
Logger.getLogger
public static function getLogger($module = "") { if (is_object($module)) $module = get_class($module); elseif (empty($module) || strtoupper($module) === "ROOT") $module = ""; $module = trim(str_replace('\\', '.', $module), ". \\"); if (!isset(self::$module_loggers[$module])) self::$module_loggers[$module] = new Logger($module); return self::$module_loggers[$module]; }
php
public static function getLogger($module = "") { if (is_object($module)) $module = get_class($module); elseif (empty($module) || strtoupper($module) === "ROOT") $module = ""; $module = trim(str_replace('\\', '.', $module), ". \\"); if (!isset(self::$module_loggers[$module])) self::$module_loggers[$module] = new Logger($module); return self::$module_loggers[$module]; }
Get a logger for a specific module. @param mixed $module A string indicating the module, or a class name or object that will be used to find the appropriate name. @return Logger The instance for the specified module
https://github.com/Wedeto/Log/blob/88252c5052089fdcc5dae466d1ad5889bb2b735f/src/Logger.php#L100-L112
Wedeto/Log
src/Logger.php
Logger.resetGlobalState
public static function resetGlobalState() { foreach (self::$module_loggers as $logger) $logger->removeLogWriters(); self::$module_loggers = []; self::$accept_mode = self::MODE_ACCEPT_MOST_SPECIFIC; }
php
public static function resetGlobalState() { foreach (self::$module_loggers as $logger) $logger->removeLogWriters(); self::$module_loggers = []; self::$accept_mode = self::MODE_ACCEPT_MOST_SPECIFIC; }
This method will reset all global state in the Logger object. It will remove all writers from all loggers and then remove all loggers. Note that this will not remove existing logger instances from other objects - this is why the writers are removed.
https://github.com/Wedeto/Log/blob/88252c5052089fdcc5dae466d1ad5889bb2b735f/src/Logger.php#L120-L126
Wedeto/Log
src/Logger.php
Logger.setAcceptMode
public static function setAcceptMode(int $mode) { if ($mode !== self::MODE_ACCEPT_MOST_SPECIFIC && $mode !== self::MODE_ACCEPT_MOST_GENERIC) throw new \InvalidArgumentException("Invalid accept mode: " . $mode); self::$accept_mode = $mode; }
php
public static function setAcceptMode(int $mode) { if ($mode !== self::MODE_ACCEPT_MOST_SPECIFIC && $mode !== self::MODE_ACCEPT_MOST_GENERIC) throw new \InvalidArgumentException("Invalid accept mode: " . $mode); self::$accept_mode = $mode; }
Set the accept mode of the logger structure. This will determine how messages are accepted and bubbled. There are two modes: Logger::MODE_ACCEPT_MOST_SPECIFIC - The most specific logger to accept the message has the final say, once accepted, any more generic loggers will not reject it. Logger::MODE_ACCEPT_MOST_GENERIC - Any logger can reject messages, regardless of if more specific loggers have already accepted the message. In both cases, whether the message is actually written depends on the log level of the writer.
https://github.com/Wedeto/Log/blob/88252c5052089fdcc5dae466d1ad5889bb2b735f/src/Logger.php#L139-L145
Wedeto/Log
src/Logger.php
Logger.setLevel
public function setLevel(string $level) { if (!defined(LogLevel::class . '::' . strtoupper($level))) throw new \DomainException("Invalid log level: $level"); $this->level = $level; $this->level_num = self::$LEVEL_NUMERIC[$level]; return $this; }
php
public function setLevel(string $level) { if (!defined(LogLevel::class . '::' . strtoupper($level))) throw new \DomainException("Invalid log level: $level"); $this->level = $level; $this->level_num = self::$LEVEL_NUMERIC[$level]; return $this; }
Set the log level for this module. Any log messages with a severity lower than this threshold will not bubble up. @param string $level The minimum log level of messages to handle
https://github.com/Wedeto/Log/blob/88252c5052089fdcc5dae466d1ad5889bb2b735f/src/Logger.php#L203-L211
Wedeto/Log
src/Logger.php
Logger.log
public function log($level, $message, array $context = array()) { if (!defined(LogLevel::class . '::' . strtoupper($level))) throw new \Psr\Log\InvalidArgumentException("Invalid log level: $level"); if ($this->level_num === null && $this->level !== null) $this->level_num = self::LEVEL_NUMERIC[$this->level]; $level_num = self::$LEVEL_NUMERIC[$level]; if ( $this->level !== null && $level_num < $this->level_num ) { // This logger is configured to reject this message. In mode GENERIC, // the message will be dropped. In mode SPECIFIC, it depends on whether // a more specific logger has already accepted the message. if (self::$accept_mode === self::MODE_ACCEPT_MOST_GENERIC || !isset($context['_accept'])) return; } if ($this->level !== null && $level_num >= $this->level_num && !isset($context['_accept'])) { // This logger is configured to accept this message. Store the logger that made // this decision to inform parent loggers that it has been accepted. In accept mode // SPECIFIC, this will instruct parents not to reject it. $context['_accept'] = $this->module; } if (!isset($context['_module'])) $context['_module'] = $this->module; if (!isset($context['_level'])) $context['_level'] = $level; foreach ($this->writers as $writer) $writer->write($level, $message, $context); // Bubble up to parent loggers $parent = $this->getParentLogger(); if ($parent) $parent->log($level, $message, $context); }
php
public function log($level, $message, array $context = array()) { if (!defined(LogLevel::class . '::' . strtoupper($level))) throw new \Psr\Log\InvalidArgumentException("Invalid log level: $level"); if ($this->level_num === null && $this->level !== null) $this->level_num = self::LEVEL_NUMERIC[$this->level]; $level_num = self::$LEVEL_NUMERIC[$level]; if ( $this->level !== null && $level_num < $this->level_num ) { // This logger is configured to reject this message. In mode GENERIC, // the message will be dropped. In mode SPECIFIC, it depends on whether // a more specific logger has already accepted the message. if (self::$accept_mode === self::MODE_ACCEPT_MOST_GENERIC || !isset($context['_accept'])) return; } if ($this->level !== null && $level_num >= $this->level_num && !isset($context['_accept'])) { // This logger is configured to accept this message. Store the logger that made // this decision to inform parent loggers that it has been accepted. In accept mode // SPECIFIC, this will instruct parents not to reject it. $context['_accept'] = $this->module; } if (!isset($context['_module'])) $context['_module'] = $this->module; if (!isset($context['_level'])) $context['_level'] = $level; foreach ($this->writers as $writer) $writer->write($level, $message, $context); // Bubble up to parent loggers $parent = $this->getParentLogger(); if ($parent) $parent->log($level, $message, $context); }
The log() call logs a message for this module. @param string $level The LogLevel for this message @param string $mesage The message to log @param array $context The context - can be used to format the message
https://github.com/Wedeto/Log/blob/88252c5052089fdcc5dae466d1ad5889bb2b735f/src/Logger.php#L295-L338
Wedeto/Log
src/Logger.php
Logger.fillPlaceholders
public static function fillPlaceholders(string $message, array $context) { $message = (string)$message; foreach ($context as $key => $value) { $placeholder = '{' . $key . '}'; $strval = null; $pos = 0; while (($pos = strpos($message, $placeholder, $pos)) !== false) { $strval = $strval ?: WF::str($value); $message = substr($message, 0, $pos) . $strval . substr($message, $pos + strlen($placeholder)); $pos = $pos + strlen($strval); } } return $message; }
php
public static function fillPlaceholders(string $message, array $context) { $message = (string)$message; foreach ($context as $key => $value) { $placeholder = '{' . $key . '}'; $strval = null; $pos = 0; while (($pos = strpos($message, $placeholder, $pos)) !== false) { $strval = $strval ?: WF::str($value); $message = substr($message, 0, $pos) . $strval . substr($message, $pos + strlen($placeholder)); $pos = $pos + strlen($strval); } } return $message; }
Fill the place holders in the message with values from the context array @param string $message The message to format. Any {var} placeholders will be replaced with a value from the context array. @param array $context Contains the values to replace the placeholders with. @return string The message with placeholders replaced
https://github.com/Wedeto/Log/blob/88252c5052089fdcc5dae466d1ad5889bb2b735f/src/Logger.php#L347-L366
Wedeto/Log
src/Logger.php
Logger.getLevelNumeric
public static function getLevelNumeric(string $level) { return isset(self::$LEVEL_NUMERIC[$level]) ? self::$LEVEL_NUMERIC[$level] : 0; }
php
public static function getLevelNumeric(string $level) { return isset(self::$LEVEL_NUMERIC[$level]) ? self::$LEVEL_NUMERIC[$level] : 0; }
Get the severity number for a specific LogLevel. @param string $level The LogLevel to convert to a number @return int The severity - 0 is less important, 7 is most important.
https://github.com/Wedeto/Log/blob/88252c5052089fdcc5dae466d1ad5889bb2b735f/src/Logger.php#L373-L376
wobblecode/WobbleCodeUserBundle
Document/Role.php
Role.setUser
public function setUser(\WobbleCode\UserBundle\Document\User $user) { $this->user = $user; return $this; }
php
public function setUser(\WobbleCode\UserBundle\Document\User $user) { $this->user = $user; return $this; }
Set user @param \WobbleCode\UserBundle\Document\User $user @return Roles
https://github.com/wobblecode/WobbleCodeUserBundle/blob/7b8206f8b4a50fbc61f7bfe4f83eb466cad96440/Document/Role.php#L85-L90
wobblecode/WobbleCodeUserBundle
Document/Role.php
Role.setUpdatedBy
public function setUpdatedBy(\WobbleCode\UserBundle\Document\User $updatedBy = null) { $this->updatedBy = $updatedBy; return $this; }
php
public function setUpdatedBy(\WobbleCode\UserBundle\Document\User $updatedBy = null) { $this->updatedBy = $updatedBy; return $this; }
Set updatedBy @param \WobbleCode\UserBundle\Document\User $updatedBy @return Roles
https://github.com/wobblecode/WobbleCodeUserBundle/blob/7b8206f8b4a50fbc61f7bfe4f83eb466cad96440/Document/Role.php#L246-L251
squareproton/Bond
src/Bond/Pg/ConnectionFactory.php
ConnectionFactory.get
public function get( $connection, $cache = true ) { if( !is_string( $connection ) ) { throw new BadTypeException( $connection, 'string' ); } // use the multiton if( !isset( $this->instances[$connection] ) or !$cache ) { if( !isset( $this->connectionSettings[$connection]) ) { throw new UnknownNamedConnectionException( $connection ); } $resource = new Resource( $this->connectionSettings[$connection], $this ); if( $cache ) { $this->instances[$connection] = $resource; } // get the resource from the multiton } else { $resource = $this->instances[$connection]; } return new Pg( $resource, $connection ); }
php
public function get( $connection, $cache = true ) { if( !is_string( $connection ) ) { throw new BadTypeException( $connection, 'string' ); } // use the multiton if( !isset( $this->instances[$connection] ) or !$cache ) { if( !isset( $this->connectionSettings[$connection]) ) { throw new UnknownNamedConnectionException( $connection ); } $resource = new Resource( $this->connectionSettings[$connection], $this ); if( $cache ) { $this->instances[$connection] = $resource; } // get the resource from the multiton } else { $resource = $this->instances[$connection]; } return new Pg( $resource, $connection ); }
Get the singleton pg connection @param string $connection @param boolean $cache @return \Bond\Pg
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Pg/ConnectionFactory.php#L56-L82
squareproton/Bond
src/Bond/Pg/ConnectionFactory.php
ConnectionFactory.remove
public function remove( Resource $resource ) { $cnt = 0; if( false !== $key = array_search( $resource, $this->instances, true ) ) { unset( $this->instances[$key] ); $cnt++; } return $cnt; }
php
public function remove( Resource $resource ) { $cnt = 0; if( false !== $key = array_search( $resource, $this->instances, true ) ) { unset( $this->instances[$key] ); $cnt++; } return $cnt; }
Remove a resource from the multiton cache @param Bond\Pg\Resource @return int
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Pg/ConnectionFactory.php#L89-L97
WellCommerce/ShippingBundle
DataFixtures/ORM/LoadShippingMethodData.php
LoadShippingMethodData.load
public function load(ObjectManager $manager) { if (!$this->isEnabled()) { return; } $tax = $this->randomizeSamples('tax', LoadTaxData::$samples); $currency = $this->randomizeSamples('currency', LoadCurrencyData::$samples); $shops = new ArrayCollection([$this->getReference('shop')]); $fedEx = new ShippingMethod(); $fedEx->setCalculator('price_table'); $fedEx->setTax($tax); $fedEx->setCurrency($currency); foreach ($this->getLocales() as $locale) { $fedEx->translate($locale->getCode())->setName('FedEx'); } $fedEx->mergeNewTranslations(); $fedEx->setCosts($this->getShippingCostsCollection($fedEx)); $fedEx->setShops($shops); $manager->persist($fedEx); $ups = new ShippingMethod(); $ups->setCalculator('price_table'); $ups->setTax($tax); $ups->setCurrency($currency); foreach ($this->getLocales() as $locale) { $fedEx->translate($locale->getCode())->setName('UPS'); } $ups->mergeNewTranslations(); $ups->setCosts($this->getShippingCostsCollection($ups)); $fedEx->setShops($shops); $manager->persist($ups); $manager->flush(); $this->setReference('shipping_method_fedex', $fedEx); $this->setReference('shipping_method_ups', $ups); }
php
public function load(ObjectManager $manager) { if (!$this->isEnabled()) { return; } $tax = $this->randomizeSamples('tax', LoadTaxData::$samples); $currency = $this->randomizeSamples('currency', LoadCurrencyData::$samples); $shops = new ArrayCollection([$this->getReference('shop')]); $fedEx = new ShippingMethod(); $fedEx->setCalculator('price_table'); $fedEx->setTax($tax); $fedEx->setCurrency($currency); foreach ($this->getLocales() as $locale) { $fedEx->translate($locale->getCode())->setName('FedEx'); } $fedEx->mergeNewTranslations(); $fedEx->setCosts($this->getShippingCostsCollection($fedEx)); $fedEx->setShops($shops); $manager->persist($fedEx); $ups = new ShippingMethod(); $ups->setCalculator('price_table'); $ups->setTax($tax); $ups->setCurrency($currency); foreach ($this->getLocales() as $locale) { $fedEx->translate($locale->getCode())->setName('UPS'); } $ups->mergeNewTranslations(); $ups->setCosts($this->getShippingCostsCollection($ups)); $fedEx->setShops($shops); $manager->persist($ups); $manager->flush(); $this->setReference('shipping_method_fedex', $fedEx); $this->setReference('shipping_method_ups', $ups); }
{@inheritDoc}
https://github.com/WellCommerce/ShippingBundle/blob/c298c571440f3058b0efd64744df194b461198f3/DataFixtures/ORM/LoadShippingMethodData.php#L35-L73
PenoaksDev/Milky-Framework
src/Milky/Http/Middleware/CheckPermission.php
CheckPermission.handle
public function handle( $request, Closure $next, $perm = null ) { if ( $perm == null || empty( $perm ) ) return $next( $request ); if ( Acct::check() ) { if ( PermissionManager::checkPermission( $perm ) ) return $next( $request ); else { // TODO Redirect to login with error message? return View::render( "permissions.denied" ); } } return Redirect::to( 'acct/login' ); }
php
public function handle( $request, Closure $next, $perm = null ) { if ( $perm == null || empty( $perm ) ) return $next( $request ); if ( Acct::check() ) { if ( PermissionManager::checkPermission( $perm ) ) return $next( $request ); else { // TODO Redirect to login with error message? return View::render( "permissions.denied" ); } } return Redirect::to( 'acct/login' ); }
Handle an incoming request. @param Request $request @param \Closure $next @return mixed
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Http/Middleware/CheckPermission.php#L18-L35
mvccore/ext-router-media
src/MvcCore/Ext/Routers/Media/PropsGettersSetters.php
PropsGettersSetters.redirectMediaGetUrlValueAndUnsetGet
protected function redirectMediaGetUrlValueAndUnsetGet ($targetMediaSiteVersion) { $mediaVersionUrlParam = static::URL_PARAM_MEDIA_VERSION; if (isset($this->requestGlobalGet[$mediaVersionUrlParam])) { if ($targetMediaSiteVersion === static::MEDIA_VERSION_FULL) { unset($this->requestGlobalGet[$mediaVersionUrlParam]); } else { $this->requestGlobalGet[$mediaVersionUrlParam] = $targetMediaSiteVersion; } $targetMediaUrlValue = NULL; } else { $targetMediaUrlValue = $this->allowedMediaVersionsAndUrlValues[$targetMediaSiteVersion]; } return $targetMediaUrlValue; }
php
protected function redirectMediaGetUrlValueAndUnsetGet ($targetMediaSiteVersion) { $mediaVersionUrlParam = static::URL_PARAM_MEDIA_VERSION; if (isset($this->requestGlobalGet[$mediaVersionUrlParam])) { if ($targetMediaSiteVersion === static::MEDIA_VERSION_FULL) { unset($this->requestGlobalGet[$mediaVersionUrlParam]); } else { $this->requestGlobalGet[$mediaVersionUrlParam] = $targetMediaSiteVersion; } $targetMediaUrlValue = NULL; } else { $targetMediaUrlValue = $this->allowedMediaVersionsAndUrlValues[$targetMediaSiteVersion]; } return $targetMediaUrlValue; }
Return media site version string value for redirection URL but if media site version is defined by `GET` query string param, return `NULL` and set target media site version string into `GET` params to complete query string params into redirect URL later. But if the target media site version string is the same as full media site version (default value), unset this param from `GET` params array and return `NULL` in query string media site version definition case. @param string $targetMediaSiteVersion Media site version string. @return string|NULL
https://github.com/mvccore/ext-router-media/blob/976e83290cf25ad6bc32e4824790b5e0d5d4c08b/src/MvcCore/Ext/Routers/Media/PropsGettersSetters.php#L147-L160
rawphp/RawCodeStandards
RawPHP/Sniffs/Commenting/FunctionCommentSniff.php
RawPHP_Sniffs_Commenting_FunctionCommentSniff.processReturn
protected function processReturn($commentStart, $commentEnd) { $tokens = $this->currentFile->getTokens(); $funcPtr = $this->currentFile->findNext(T_FUNCTION, $commentEnd); // Only check for a return comment if a non-void return statement exists if (isset($tokens[$funcPtr]['scope_opener'])) { $start = $tokens[$funcPtr]['scope_opener']; // iterate over all return statements of this function, // run the check on the first which is not only 'return;' while ($returnToken = $this->currentFile->findNext(T_RETURN, $start, $tokens[$funcPtr]['scope_closer'])) { if ($this->isMatchingReturn($tokens, $returnToken)) { parent::processReturn($commentStart, $commentEnd); break; } $start = $returnToken + 1; } } }
php
protected function processReturn($commentStart, $commentEnd) { $tokens = $this->currentFile->getTokens(); $funcPtr = $this->currentFile->findNext(T_FUNCTION, $commentEnd); // Only check for a return comment if a non-void return statement exists if (isset($tokens[$funcPtr]['scope_opener'])) { $start = $tokens[$funcPtr]['scope_opener']; // iterate over all return statements of this function, // run the check on the first which is not only 'return;' while ($returnToken = $this->currentFile->findNext(T_RETURN, $start, $tokens[$funcPtr]['scope_closer'])) { if ($this->isMatchingReturn($tokens, $returnToken)) { parent::processReturn($commentStart, $commentEnd); break; } $start = $returnToken + 1; } } }
Process the return comment of this function comment. @param int $commentStart The position in the stack where the comment started. @param int $commentEnd The position in the stack where the comment ended. @return void
https://github.com/rawphp/RawCodeStandards/blob/aa40b4b085bfb3317843883124da246c32c4bb92/RawPHP/Sniffs/Commenting/FunctionCommentSniff.php#L32-L52
shampeak/GracePack
src/Vo/Vo.php
Vo.getInstance
public static function getInstance($config = []){ if(!(self::$_instance instanceof self)){ self::$_instance = new self($config); } return self::$_instance; }
php
public static function getInstance($config = []){ if(!(self::$_instance instanceof self)){ self::$_instance = new self($config); } return self::$_instance; }
/* |------------------------------------------------------------ | 单例调用 |------------------------------------------------------------
https://github.com/shampeak/GracePack/blob/2ae989d0ff05ac13b6a650d915abe798c73fa792/src/Vo/Vo.php#L46-L51
shampeak/GracePack
src/Vo/Vo.php
Vo.make
public function make($abstract,$parameters=[]) { $abstract = ucfirst($abstract); if (isset($this->instances[$abstract])) { return $this->instances[$abstract]; } //未定义的服务类 报错; if (!isset($this->Providers[$abstract])) { //报错 die("miss class : $abstract"); return null; } // echo $abstract; $parameters = $parameters?:isset($this->ObjectConfig[$abstract])?$this->ObjectConfig[$abstract]:[]; $this->instances[$abstract] = $this->build($abstract,$parameters); return $this->instances[$abstract]; }
php
public function make($abstract,$parameters=[]) { $abstract = ucfirst($abstract); if (isset($this->instances[$abstract])) { return $this->instances[$abstract]; } //未定义的服务类 报错; if (!isset($this->Providers[$abstract])) { //报错 die("miss class : $abstract"); return null; } // echo $abstract; $parameters = $parameters?:isset($this->ObjectConfig[$abstract])?$this->ObjectConfig[$abstract]:[]; $this->instances[$abstract] = $this->build($abstract,$parameters); return $this->instances[$abstract]; }
/* |------------------------------------------------------------ | 实例化注册类 |------------------------------------------------------------
https://github.com/shampeak/GracePack/blob/2ae989d0ff05ac13b6a650d915abe798c73fa792/src/Vo/Vo.php#L58-L76
shampeak/GracePack
src/Vo/Vo.php
Vo.makeModel
public function makeModel($abstract) { if (isset($this->Mo[$abstract])) { return $this->Mo[$abstract]; } if(!class_exists($abstract)){ //没有找到执行方法 //执行404; echo '<br>Miss file : <br>'; echo $abstract; D(); } //检查类文件是否存在 $this->Mo[$abstract] = new $abstract(); //模型存储 return $this->Mo[$abstract]; }
php
public function makeModel($abstract) { if (isset($this->Mo[$abstract])) { return $this->Mo[$abstract]; } if(!class_exists($abstract)){ //没有找到执行方法 //执行404; echo '<br>Miss file : <br>'; echo $abstract; D(); } //检查类文件是否存在 $this->Mo[$abstract] = new $abstract(); //模型存储 return $this->Mo[$abstract]; }
/* |------------------------------------------------------------ | 实例化一个模型 |------------------------------------------------------------
https://github.com/shampeak/GracePack/blob/2ae989d0ff05ac13b6a650d915abe798c73fa792/src/Vo/Vo.php#L83-L99
cravler/CravlerRemoteBundle
DependencyInjection/Configuration.php
Configuration.getConfigTreeBuilder
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('cravler_remote'); $rootNode ->children() ->scalarNode('user_provider') ->defaultValue(false) //security.user.provider.concrete.[provider_name] ->cannotBeEmpty() ->end() ->scalarNode('app_port') ->defaultValue(8080) ->cannotBeEmpty() ->end() ->scalarNode('remote_port') ->defaultValue(8081) ->cannotBeEmpty() ->end() ->scalarNode('remote_host') ->defaultValue('127.0.0.1') ->cannotBeEmpty() ->end() ->scalarNode('server_port') ->defaultValue(8082) ->cannotBeEmpty() ->end() ->scalarNode('server_host') ->defaultValue('127.0.0.1') ->cannotBeEmpty() ->end() ->scalarNode('secret') ->defaultValue('ThisTokenIsNotSoSecretChangeIt') ->cannotBeEmpty() ->end() ->end(); return $treeBuilder; }
php
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('cravler_remote'); $rootNode ->children() ->scalarNode('user_provider') ->defaultValue(false) //security.user.provider.concrete.[provider_name] ->cannotBeEmpty() ->end() ->scalarNode('app_port') ->defaultValue(8080) ->cannotBeEmpty() ->end() ->scalarNode('remote_port') ->defaultValue(8081) ->cannotBeEmpty() ->end() ->scalarNode('remote_host') ->defaultValue('127.0.0.1') ->cannotBeEmpty() ->end() ->scalarNode('server_port') ->defaultValue(8082) ->cannotBeEmpty() ->end() ->scalarNode('server_host') ->defaultValue('127.0.0.1') ->cannotBeEmpty() ->end() ->scalarNode('secret') ->defaultValue('ThisTokenIsNotSoSecretChangeIt') ->cannotBeEmpty() ->end() ->end(); return $treeBuilder; }
{@inheritDoc}
https://github.com/cravler/CravlerRemoteBundle/blob/b13e182007850063781d277ab5b0e4e69d415e2b/DependencyInjection/Configuration.php#L20-L58
mrbase/Smesg
src/Smesg/Provider/InMobileProvider.php
InMobileProvider.send
public function send($dry_run = false) { switch (count($this->messages)) { case 0: throw new \RuntimeException("No messages to send."); case 1: return $this->sendOne($dry_run); } // create xml document $xml = new SimpleXMLExtended('<?xml version="1.0" encoding="utf-8" ?><push></push>'); $xml->addChild('user', $this->config['user']); $xml->addChild('password', $this->config['password']); $xml->addChild('serviceid', $this->config['serviceid']); $ts = date('d-m-Y H:i:00'); // attach messages foreach ($this->messages as $message) { $batch = $xml->addChild('smsbatch'); $batch->addChild('sendtime', $ts); if ($message->options['from']) { $batch->addChild('sender', $message->options['from']); } else { $batch->addChild('sender', $this->config['from']); } $batch->addChild('price', $this->config['price']); $cdata = $batch->addChild('message'); $cdata->addCData($message->message); $recipient = $batch->addChild('recipients'); $recipient->addChild('msisdn', $message->to); } $adapter = $this->getAdapter(); $adapter->setEndpoint(self::BATCH_ENDPOINT); $adapter->setBody($xml->asXML()); if ($dry_run) { return $adapter->dryRun(); } else { $response = $adapter->post(); } /** * inmobile returns 2 kinds of response * * 1: integer 2 to -18 error results * 2: xml containing the result of your success request * * we have asked inmobile to change this in new versions to always send back xml */ if (strlen($response->getBody()) <= 3) { $xml = new SimpleXMLExtended('<?xml version="1.0" encoding="utf-8" ?><response></response>'); $error = $xml->addChild('error'); $error->addChild('code', $response->getBody()); $error->addChild('message', $this->error_codes[$response->getBody()]); $response = new Response($response->getHeaders(), $xml->asXML(), $response->getRequest()); } return $response; }
php
public function send($dry_run = false) { switch (count($this->messages)) { case 0: throw new \RuntimeException("No messages to send."); case 1: return $this->sendOne($dry_run); } // create xml document $xml = new SimpleXMLExtended('<?xml version="1.0" encoding="utf-8" ?><push></push>'); $xml->addChild('user', $this->config['user']); $xml->addChild('password', $this->config['password']); $xml->addChild('serviceid', $this->config['serviceid']); $ts = date('d-m-Y H:i:00'); // attach messages foreach ($this->messages as $message) { $batch = $xml->addChild('smsbatch'); $batch->addChild('sendtime', $ts); if ($message->options['from']) { $batch->addChild('sender', $message->options['from']); } else { $batch->addChild('sender', $this->config['from']); } $batch->addChild('price', $this->config['price']); $cdata = $batch->addChild('message'); $cdata->addCData($message->message); $recipient = $batch->addChild('recipients'); $recipient->addChild('msisdn', $message->to); } $adapter = $this->getAdapter(); $adapter->setEndpoint(self::BATCH_ENDPOINT); $adapter->setBody($xml->asXML()); if ($dry_run) { return $adapter->dryRun(); } else { $response = $adapter->post(); } /** * inmobile returns 2 kinds of response * * 1: integer 2 to -18 error results * 2: xml containing the result of your success request * * we have asked inmobile to change this in new versions to always send back xml */ if (strlen($response->getBody()) <= 3) { $xml = new SimpleXMLExtended('<?xml version="1.0" encoding="utf-8" ?><response></response>'); $error = $xml->addChild('error'); $error->addChild('code', $response->getBody()); $error->addChild('message', $this->error_codes[$response->getBody()]); $response = new Response($response->getHeaders(), $xml->asXML(), $response->getRequest()); } return $response; }
{@inheritDoc}
https://github.com/mrbase/Smesg/blob/e9692ed5915f5a9cd4dca0df875935a2c528e128/src/Smesg/Provider/InMobileProvider.php#L120-L181
mrbase/Smesg
src/Smesg/Provider/InMobileProvider.php
InMobileProvider.sendOne
protected function sendOne($dry_run) { $message = $this->messages[0]; $adapter = $this->getAdapter(); $adapter->setEndpoint(self::SINGLE_ENDPOINT); $adapter->setParameters(array( 'user' => $this->config['user'], 'password' => $this->config['password'], 'serviceid' => $this->config['serviceid'], 'sender' => ($message->options['from'] ?: $this->config['from']), 'message' => $message->message, 'msisdn' => $message->to, 'price' => $this->config['price'], 'overcharge' => $this->config['overcharge'], )); if ($dry_run) { return $adapter->dryRun(); } return $adapter->post(); }
php
protected function sendOne($dry_run) { $message = $this->messages[0]; $adapter = $this->getAdapter(); $adapter->setEndpoint(self::SINGLE_ENDPOINT); $adapter->setParameters(array( 'user' => $this->config['user'], 'password' => $this->config['password'], 'serviceid' => $this->config['serviceid'], 'sender' => ($message->options['from'] ?: $this->config['from']), 'message' => $message->message, 'msisdn' => $message->to, 'price' => $this->config['price'], 'overcharge' => $this->config['overcharge'], )); if ($dry_run) { return $adapter->dryRun(); } return $adapter->post(); }
We use smspush for sending single messages. @return string $response;
https://github.com/mrbase/Smesg/blob/e9692ed5915f5a9cd4dca0df875935a2c528e128/src/Smesg/Provider/InMobileProvider.php#L188-L210
dms-org/common.structure
src/Type/Persistence/StringValueObjectMapper.php
StringValueObjectMapper.define
protected function define(MapperDefinition $map) { $map->type($this->classType()); $this->defineStringColumnType($map->property(StringValueObject::STRING)->to($this->columnName)); }
php
protected function define(MapperDefinition $map) { $map->type($this->classType()); $this->defineStringColumnType($map->property(StringValueObject::STRING)->to($this->columnName)); }
Defines the value object mapper @param MapperDefinition $map @return void
https://github.com/dms-org/common.structure/blob/23f122182f60df5ec847047a81a39c8aab019ff1/src/Type/Persistence/StringValueObjectMapper.php#L40-L45
kambalabs/KmbZendDbInfrastructure
src/KmbZendDbInfrastructure/Hydrator/RevisionLogHydrator.php
RevisionLogHydrator.hydrate
public function hydrate(array $data, $object) { $object->setId($this->getData('id', $data)); $createdAt = $this->getData('created_at', $data); $object->setCreatedAt(isset($createdAt) ? new \DateTime($createdAt) : null); $object->setCreatedBy($this->getData('created_by', $data)); $object->setComment($this->getData('comment', $data)); return $object; }
php
public function hydrate(array $data, $object) { $object->setId($this->getData('id', $data)); $createdAt = $this->getData('created_at', $data); $object->setCreatedAt(isset($createdAt) ? new \DateTime($createdAt) : null); $object->setCreatedBy($this->getData('created_by', $data)); $object->setComment($this->getData('comment', $data)); return $object; }
Hydrate $object with the provided $data. @param array $data @param RevisionLogInterface $object @return RevisionLogInterface
https://github.com/kambalabs/KmbZendDbInfrastructure/blob/9bf4df4272d2064965202d0e689f944d56a4c6bb/src/KmbZendDbInfrastructure/Hydrator/RevisionLogHydrator.php#L57-L65
brightnucleus/values
src/Value/EmailAddressValue.php
EmailAddressValue.validate
public function validate($value) { $value = filter_var($value, FILTER_VALIDATE_EMAIL); if (false === $value) { throw FailedToValidate::fromValueForClass($value, static::class); } return $value; }
php
public function validate($value) { $value = filter_var($value, FILTER_VALIDATE_EMAIL); if (false === $value) { throw FailedToValidate::fromValueForClass($value, static::class); } return $value; }
Return the validated form of the value. @since 0.1.1 @param mixed $value Value to validate. @return mixed Validated value. @throws ValidationException If the value could not be validated.
https://github.com/brightnucleus/values/blob/e9bdfbec949f6f964631aacaccaa98a0f13d916f/src/Value/EmailAddressValue.php#L42-L49
brightnucleus/values
src/Value/EmailAddressValue.php
EmailAddressValue.sanitize
public function sanitize() { $value = filter_var($this->value, FILTER_SANITIZE_EMAIL, FILTER_NULL_ON_FAILURE); if (null === $value) { throw FailedToSanitize::fromValueForClass($this->value, $this); } return $value; }
php
public function sanitize() { $value = filter_var($this->value, FILTER_SANITIZE_EMAIL, FILTER_NULL_ON_FAILURE); if (null === $value) { throw FailedToSanitize::fromValueForClass($this->value, $this); } return $value; }
Get a sanitized version of the value. @since 0.1.1 @return mixed Sanitized version of the value.
https://github.com/brightnucleus/values/blob/e9bdfbec949f6f964631aacaccaa98a0f13d916f/src/Value/EmailAddressValue.php#L58-L67
openWorkers/RedObject
src/RedObject/RedObject.php
RedObject.offsetGet
public function offsetGet($offset) { $type = $this->redis->type($this->getStorageKey($offset)); switch($type) { case Redis::REDIS_STRING: $output = $this->redis->get($this->getStorageKey($offset)); return $this->ioHandler->handleOutput($output); case Redis::REDIS_NOT_FOUND: default: return null; } }
php
public function offsetGet($offset) { $type = $this->redis->type($this->getStorageKey($offset)); switch($type) { case Redis::REDIS_STRING: $output = $this->redis->get($this->getStorageKey($offset)); return $this->ioHandler->handleOutput($output); case Redis::REDIS_NOT_FOUND: default: return null; } }
(PHP 5 &gt;= 5.0.0)<br/> Offset to retrieve @link http://php.net/manual/en/arrayaccess.offsetget.php @param mixed $offset <p> The offset to retrieve. </p> @return mixed Can return all value types.
https://github.com/openWorkers/RedObject/blob/ce60d782352f97154294d7d200e7c87df80aa41a/src/RedObject/RedObject.php#L90-L102
openWorkers/RedObject
src/RedObject/RedObject.php
RedObject.offsetSet
public function offsetSet($offset, $value) { if ($offset === null) { $offset = uniqid('uid'); } if (is_string($value)) { $this->redis->set($this->getStorageKey($offset), "!".$value); } else { $this->redis->set($this->getStorageKey($offset), serialize($value)); } }
php
public function offsetSet($offset, $value) { if ($offset === null) { $offset = uniqid('uid'); } if (is_string($value)) { $this->redis->set($this->getStorageKey($offset), "!".$value); } else { $this->redis->set($this->getStorageKey($offset), serialize($value)); } }
(PHP 5 &gt;= 5.0.0)<br/> Offset to set @link http://php.net/manual/en/arrayaccess.offsetset.php @param mixed $offset <p> The offset to assign the value to. </p> @param mixed $value <p> The value to set. </p> @return void
https://github.com/openWorkers/RedObject/blob/ce60d782352f97154294d7d200e7c87df80aa41a/src/RedObject/RedObject.php#L116-L126
joegreen88/zf1-component-validate
src/Zend/Validate/Sitemap/Changefreq.php
Zend_Validate_Sitemap_Changefreq.isValid
public function isValid($value) { if (!is_string($value)) { $this->_error(self::INVALID); return false; } $this->_setValue($value); if (!is_string($value)) { return false; } if (!in_array($value, $this->_changeFreqs, true)) { $this->_error(self::NOT_VALID); return false; } return true; }
php
public function isValid($value) { if (!is_string($value)) { $this->_error(self::INVALID); return false; } $this->_setValue($value); if (!is_string($value)) { return false; } if (!in_array($value, $this->_changeFreqs, true)) { $this->_error(self::NOT_VALID); return false; } return true; }
Validates if a string is valid as a sitemap changefreq @link http://www.sitemaps.org/protocol.php#changefreqdef <changefreq> @param string $value value to validate @return boolean
https://github.com/joegreen88/zf1-component-validate/blob/88d9ea016f73d48ff0ba7d06ecbbf28951fd279e/src/Zend/Validate/Sitemap/Changefreq.php#L76-L94
duncan3dc/php-ini
src/Ini.php
Ini.restore
public function restore(string $key): self { if (array_key_exists($key, $this->original)) { ini_set($key, $this->original[$key]); } return $this; }
php
public function restore(string $key): self { if (array_key_exists($key, $this->original)) { ini_set($key, $this->original[$key]); } return $this; }
Restore a previous ini setting. @return $this
https://github.com/duncan3dc/php-ini/blob/e07435d7ddbbc466e535783e5c4d2b92e3715c7a/src/Ini.php#L53-L60
duncan3dc/php-ini
src/Ini.php
Ini.cleanup
public function cleanup(): self { foreach ($this->original as $key => $value) { ini_set($key, $value); } $this->original = []; return $this; }
php
public function cleanup(): self { foreach ($this->original as $key => $value) { ini_set($key, $value); } $this->original = []; return $this; }
Restore the previous ini settings. @return $this
https://github.com/duncan3dc/php-ini/blob/e07435d7ddbbc466e535783e5c4d2b92e3715c7a/src/Ini.php#L68-L77
zarathustra323/modlr-data
src/Zarathustra/ModlrData/DataTypes/TypeFactory.php
TypeFactory.getType
public function getType($name) { if (false === $this->hasType($name)) { throw new InvalidArgumentException(sprintf('The type "%s" was not found.', $name)); } if (isset($this->loaded[$name])) { return $this->loaded[$name]; } $fqcn = $this->types[$name]; $type = new $fqcn; if (!$type instanceof TypeInterface) { throw new InvalidArgumentException(sprintf('The class "%s" must implement the "%s\\Types\TypeInterface"', $fqcn, __NAMESPACE__)); } return $this->loaded[$name] = new $fqcn; }
php
public function getType($name) { if (false === $this->hasType($name)) { throw new InvalidArgumentException(sprintf('The type "%s" was not found.', $name)); } if (isset($this->loaded[$name])) { return $this->loaded[$name]; } $fqcn = $this->types[$name]; $type = new $fqcn; if (!$type instanceof TypeInterface) { throw new InvalidArgumentException(sprintf('The class "%s" must implement the "%s\\Types\TypeInterface"', $fqcn, __NAMESPACE__)); } return $this->loaded[$name] = new $fqcn; }
Gets a type object. @param string $name @return DataTypes\Types\Type @throws InvalidArgumentException If the type wasn't found.
https://github.com/zarathustra323/modlr-data/blob/7c2c767216055f75abf8cf22e2200f11998ed24e/src/Zarathustra/ModlrData/DataTypes/TypeFactory.php#L84-L100
zarathustra323/modlr-data
src/Zarathustra/ModlrData/DataTypes/TypeFactory.php
TypeFactory.addType
public function addType($name, $fqcn) { if (true === $this->hasType($name)) { throw new InvalidArgumentException(sprintf('The type "%s" already exists.', $name)); } return $this->setType($name, $fqcn); }
php
public function addType($name, $fqcn) { if (true === $this->hasType($name)) { throw new InvalidArgumentException(sprintf('The type "%s" already exists.', $name)); } return $this->setType($name, $fqcn); }
Adds a type object. @param string $name @param string $fqcn @return self @throws InvalidArgumentException If the type already exists.
https://github.com/zarathustra323/modlr-data/blob/7c2c767216055f75abf8cf22e2200f11998ed24e/src/Zarathustra/ModlrData/DataTypes/TypeFactory.php#L110-L116