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
Aviogram/Common
src/Hydrator/ByConfigBuilder.php
ByConfigBuilder.getFormatter
public function getFormatter($fieldName) { if ($this->hasField($fieldName) === false) { return null; } return $this->mapping[$fieldName]['formatter']; }
php
public function getFormatter($fieldName) { if ($this->hasField($fieldName) === false) { return null; } return $this->mapping[$fieldName]['formatter']; }
@param string $fieldName @return Closure
https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/Hydrator/ByConfigBuilder.php#L202-L209
Aviogram/Common
src/Hydrator/ByConfigBuilder.php
ByConfigBuilder.setCatchAllSetter
public function setCatchAllSetter($setMethod) { if (method_exists($this->getEntityPrototype(), $setMethod) === false) { throw new Exception\ConfigFailed(sprintf($this->exceptions[2], $setMethod, $this->entityClassName), 2); } $this->catchAllSetter = $setMethod; return $this; }
php
public function setCatchAllSetter($setMethod) { if (method_exists($this->getEntityPrototype(), $setMethod) === false) { throw new Exception\ConfigFailed(sprintf($this->exceptions[2], $setMethod, $this->entityClassName), 2); } $this->catchAllSetter = $setMethod; return $this; }
Sets an catchall Setter @param string $setMethod @return $this
https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/Hydrator/ByConfigBuilder.php#L244-L253
holyshared/peridot-temporary-plugin
src/TemporaryScope.php
TemporaryScope.makeDirectory
public function makeDirectory($mode = FileSystemPermission::NORMAL) { $directory = $this->factory->makeDirectory($mode); $this->container->add($directory); return $directory; }
php
public function makeDirectory($mode = FileSystemPermission::NORMAL) { $directory = $this->factory->makeDirectory($mode); $this->container->add($directory); return $directory; }
Create a new temporary directory @param int $mode permission @return \holyshared\peridot\temporary\TemporaryDirectory
https://github.com/holyshared/peridot-temporary-plugin/blob/0d61e7ef8dd0056b9fb4cd118e10295ac0a5456b/src/TemporaryScope.php#L55-L61
holyshared/peridot-temporary-plugin
src/TemporaryScope.php
TemporaryScope.makeFile
public function makeFile($mode = FileSystemPermission::NORMAL) { $file = $this->factory->makeFile($mode); $this->container->add($file); return $file; }
php
public function makeFile($mode = FileSystemPermission::NORMAL) { $file = $this->factory->makeFile($mode); $this->container->add($file); return $file; }
Create a new temporary file @param int $mode permission @return \holyshared\peridot\temporary\TemporaryFile
https://github.com/holyshared/peridot-temporary-plugin/blob/0d61e7ef8dd0056b9fb4cd118e10295ac0a5456b/src/TemporaryScope.php#L69-L75
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.setBaseType
public function setBaseType($base_type) { $base_type = strtoupper($base_type); if (!in_array($base_type, self::getBaseTypes())) { throw new \InvalidArgumentException(sprintf('The "%s" base type is not a valid base type.', $base_type)); } $this->base_type = $base_type; return $this; }
php
public function setBaseType($base_type) { $base_type = strtoupper($base_type); if (!in_array($base_type, self::getBaseTypes())) { throw new \InvalidArgumentException(sprintf('The "%s" base type is not a valid base type.', $base_type)); } $this->base_type = $base_type; return $this; }
Set base_type @param string $base_type @return Site
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L246-L254
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.getBaseType
public function getBaseType() { if ($this->base_type) return $this->base_type; if ($this->getParent()) return $this->getParent()->getBaseType(); return null; }
php
public function getBaseType() { if ($this->base_type) return $this->base_type; if ($this->getParent()) return $this->getParent()->getBaseType(); return null; }
Get base_type @return string
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L261-L268
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.setSecurityModel
public function setSecurityModel($security_model) { $security_model = strtoupper($security_model); if (!isset(self::getSecurityModels()[$security_model])) { throw new \InvalidArgumentException(sprintf('The "%s" security model is not a valid security model.', $security_model)); } $this->security_model = $security_model; return $this; }
php
public function setSecurityModel($security_model) { $security_model = strtoupper($security_model); if (!isset(self::getSecurityModels()[$security_model])) { throw new \InvalidArgumentException(sprintf('The "%s" security model is not a valid security model.', $security_model)); } $this->security_model = $security_model; return $this; }
Set security_model @param string $security_model @return Site
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L295-L303
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.getSecurityModel
public function getSecurityModel() { if ($this->security_model) return $this->security_model; elseif ($this->getParent()) return $this->getParent()->getSecurityModel(); else return null; }
php
public function getSecurityModel() { if ($this->security_model) return $this->security_model; elseif ($this->getParent()) return $this->getParent()->getSecurityModel(); else return null; }
Get security_model @return string
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L310-L318
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.setCallbackFunction
public function setCallbackFunction($callbackFunction) { // If it's the same as any thing in the chain, drop it. if ($callbackFunction == $this->getCallbackFunction()) { return $this; } $this->callbackFunction = $callbackFunction; return $this; }
php
public function setCallbackFunction($callbackFunction) { // If it's the same as any thing in the chain, drop it. if ($callbackFunction == $this->getCallbackFunction()) { return $this; } $this->callbackFunction = $callbackFunction; return $this; }
Set callbackFunction @param string $callbackFunction @return MessageType
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L347-L356
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.getCallbackFunction
public function getCallbackFunction() { if ($this->callbackFunction) return $this->callbackFunction; if ($this->getParent()) return $this->getParent()->getCallbackFunction(); return null; }
php
public function getCallbackFunction() { if ($this->callbackFunction) return $this->callbackFunction; if ($this->getParent()) return $this->getParent()->getCallbackFunction(); return null; }
Get callbackFunction @return string
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L363-L370
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.setCallbackAttributes
public function setCallbackAttributes($callbackAttributes) { // If it's the same as any thing in the chain, drop it. if ($callbackAttributes == $this->getCallbackAttributes()) { return $this; } $this->callbackAttributes = $callbackAttributes; return $this; }
php
public function setCallbackAttributes($callbackAttributes) { // If it's the same as any thing in the chain, drop it. if ($callbackAttributes == $this->getCallbackAttributes()) { return $this; } $this->callbackAttributes = $callbackAttributes; return $this; }
Set callbackAttributes @param string $callbackAttributes @return MessageType
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L378-L387
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.getCallbackAttributes
public function getCallbackAttributes() { if ($this->callbackAttributes) return $this->callbackAttributes; if ($this->getParent()) return $this->getParent()->getCallbackAttributes(); return null; }
php
public function getCallbackAttributes() { if ($this->callbackAttributes) return $this->callbackAttributes; if ($this->getParent()) return $this->getParent()->getCallbackAttributes(); return null; }
Get callbackAttributes @return string I am not gonna merge the attributes with the parents attributes here. That will just be too messy.
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L396-L403
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.setForwardFunction
public function setForwardFunction($forwardFunction) { // If it's the same as any thing in the chain, drop it. if ($forwardFunction == $this->getForwardFunction()) { return $this; } $this->forwardFunction = $forwardFunction; return $this; }
php
public function setForwardFunction($forwardFunction) { // If it's the same as any thing in the chain, drop it. if ($forwardFunction == $this->getForwardFunction()) { return $this; } $this->forwardFunction = $forwardFunction; return $this; }
Set forwardFunction @param string $forwardFunction @return MessageType
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L411-L420
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.getForwardFunction
public function getForwardFunction() { if ($this->forwardFunction) return $this->forwardFunction; if ($this->getParent()) return $this->getParent()->getForwardFunction(); return null; }
php
public function getForwardFunction() { if ($this->forwardFunction) return $this->forwardFunction; if ($this->getParent()) return $this->getParent()->getForwardFunction(); return null; }
Get forwardFunction @return string
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L427-L434
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.setForwardAttributes
public function setForwardAttributes($forwardAttributes) { // If it's the same as any thing in the chain, drop it. if ($forwardAttributes == $this->getForwardAttributes()) { return $this; } $this->forwardAttributes = $forwardAttributes; return $this; }
php
public function setForwardAttributes($forwardAttributes) { // If it's the same as any thing in the chain, drop it. if ($forwardAttributes == $this->getForwardAttributes()) { return $this; } $this->forwardAttributes = $forwardAttributes; return $this; }
Set forwardAttributes @param string $forwardAttributes @return MessageType
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L442-L451
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.getForwardAttributes
public function getForwardAttributes() { if ($this->forwardAttributes) return $this->forwardAttributes; if ($this->getParent()) return $this->getParent()->getForwardAttributes(); return null; }
php
public function getForwardAttributes() { if ($this->forwardAttributes) return $this->forwardAttributes; if ($this->getParent()) return $this->getParent()->getForwardAttributes(); return null; }
Get forwardAttributes @return string I am not gonna merge the attributes with the parents attributes here. That will just be too messy.
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L460-L467
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.addChild
public function addChild(\BisonLab\SakonninBundle\Entity\MessageType $child) { $this->children[] = $child; $child->setParent($this); return $this; }
php
public function addChild(\BisonLab\SakonninBundle\Entity\MessageType $child) { $this->children[] = $child; $child->setParent($this); return $this; }
Add child @param \BisonLab\SakonninBundle\Entity\MessageType $child @return MessageType
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L475-L481
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.removeChild
public function removeChild(\BisonLab\SakonninBundle\Entity\MessageType $child) { $this->children->removeElement($child); }
php
public function removeChild(\BisonLab\SakonninBundle\Entity\MessageType $child) { $this->children->removeElement($child); }
Remove children @param \BisonLab\SakonninBundle\Entity\MessageType $child
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L488-L491
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.setParent
public function setParent(\BisonLab\SakonninBundle\Entity\MessageType $parent = null) { $this->parent = $parent; return $this; }
php
public function setParent(\BisonLab\SakonninBundle\Entity\MessageType $parent = null) { $this->parent = $parent; return $this; }
Set parent @param \BisonLab\SakonninBundle\Entity\MessageType $parent @return MessageType
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L509-L514
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.addMessage
public function addMessage(\BisonLab\SakonninBundle\Entity\Message $messages) { $this->messages[] = $messages; return $this; }
php
public function addMessage(\BisonLab\SakonninBundle\Entity\Message $messages) { $this->messages[] = $messages; return $this; }
Add messages @param \BisonLab\SakonninBundle\Entity\Message $messages @return MessageType
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L532-L537
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.removeMessage
public function removeMessage(\BisonLab\SakonninBundle\Entity\Message $messages) { $this->messages->removeElement($messages); }
php
public function removeMessage(\BisonLab\SakonninBundle\Entity\Message $messages) { $this->messages->removeElement($messages); }
Remove messages @param \BisonLab\SakonninBundle\Entity\Message $messages
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L544-L547
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.getMessages
public function getMessages($include_children = false) { $messages = $this->messages->toArray(); if ($include_children) { foreach ($this->children as $child) { $messages = array_merge($messages, $child->getMessages(true)); } return $messages; } return $this->messages; }
php
public function getMessages($include_children = false) { $messages = $this->messages->toArray(); if ($include_children) { foreach ($this->children as $child) { $messages = array_merge($messages, $child->getMessages(true)); } return $messages; } return $this->messages; }
Get messages @return \Doctrine\Common\Collections\Collection
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L554-L564
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.setExpungeMethod
public function setExpungeMethod($expunge_method) { $expunge_method = strtoupper($expunge_method); if (!isset(self::getExpungeMethods()[$expunge_method])) { throw new \InvalidArgumentException(sprintf('The "%s" expunge method is not a valid expunge method.', $expunge_method)); } $this->expunge_method = $expunge_method; return $this; }
php
public function setExpungeMethod($expunge_method) { $expunge_method = strtoupper($expunge_method); if (!isset(self::getExpungeMethods()[$expunge_method])) { throw new \InvalidArgumentException(sprintf('The "%s" expunge method is not a valid expunge method.', $expunge_method)); } $this->expunge_method = $expunge_method; return $this; }
Set expunge_method @param string $expunge_method @return Site
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L595-L603
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.setExpireMethod
public function setExpireMethod($expire_method) { $expire_method = strtoupper($expire_method); if (!isset(self::getExpungeMethods()[$expire_method])) { throw new \InvalidArgumentException(sprintf('The "%s" expire method is not a valid expire method.', $expire_method)); } $this->expire_method = $expire_method; return $this; }
php
public function setExpireMethod($expire_method) { $expire_method = strtoupper($expire_method); if (!isset(self::getExpungeMethods()[$expire_method])) { throw new \InvalidArgumentException(sprintf('The "%s" expire method is not a valid expire method.', $expire_method)); } $this->expire_method = $expire_method; return $this; }
Set expire_method @param string $expire_method @return Site
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L642-L650
thomasez/BisonLabSakonninBundle
Entity/MessageType.php
MessageType.setSakonninTemplate
public function setSakonninTemplate(\BisonLab\SakonninBundle\Entity\SakonninTemplate $sakonninTemplate = null) { $this->sakonnin_template = $sakonninTemplate; return $this; }
php
public function setSakonninTemplate(\BisonLab\SakonninBundle\Entity\SakonninTemplate $sakonninTemplate = null) { $this->sakonnin_template = $sakonninTemplate; return $this; }
Set sakonnin_template @param \BisonLab\SakonninBundle\Entity\SakonninTemplate $messageType @return Message
https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Entity/MessageType.php#L668-L673
ElioMS/admin-laravel
src/controllers/RoleController.php
RoleController.store
public function store(Request $request) { Role::create($request->all()); session()->flash('success' , 'Rol creado con exito'); return redirect()->route('roles.index'); }
php
public function store(Request $request) { Role::create($request->all()); session()->flash('success' , 'Rol creado con exito'); return redirect()->route('roles.index'); }
Store a newly created resource in storage. @param \Illuminate\Http\Request $request @return \Illuminate\Http\Response
https://github.com/ElioMS/admin-laravel/blob/6fe57edfb6d92beabcb897f25d59bb656d3cd65c/src/controllers/RoleController.php#L39-L45
ElioMS/admin-laravel
src/controllers/RoleController.php
RoleController.update
public function update(Request $request, $id) { $role = Role::find($id); $role->fill($request->all()); $role->save(); session()->flash('success' , 'Rol actualizado con exito'); return redirect()->route('roles.index'); }
php
public function update(Request $request, $id) { $role = Role::find($id); $role->fill($request->all()); $role->save(); session()->flash('success' , 'Rol actualizado con exito'); return redirect()->route('roles.index'); }
Update the specified resource in storage. @param \Illuminate\Http\Request $request @param int $id @return \Illuminate\Http\Response
https://github.com/ElioMS/admin-laravel/blob/6fe57edfb6d92beabcb897f25d59bb656d3cd65c/src/controllers/RoleController.php#L66-L74
djinorm/djin
src/Manager/ModelManager.php
ModelManager.persists
public function persists($models = []): int { if (!is_array($models)) { $models = func_get_args(); } foreach ($models as $model) { if ($model instanceof StubModelInterface) { continue; } $this->guardNotModelInterface($model); $class = get_class($model); $hash = spl_object_hash($model); $this->models[$class][$hash] = $model; } return $this->getModelsCount($this->models); }
php
public function persists($models = []): int { if (!is_array($models)) { $models = func_get_args(); } foreach ($models as $model) { if ($model instanceof StubModelInterface) { continue; } $this->guardNotModelInterface($model); $class = get_class($model); $hash = spl_object_hash($model); $this->models[$class][$hash] = $model; } return $this->getModelsCount($this->models); }
Подготавливает модели для будущего сохранения в базу @param ModelInterface[] $models @return int общее число подготовленных для сохранения моделей @throws NotModelInterfaceException
https://github.com/djinorm/djin/blob/2736226e0d7467154ede40a7d23eb6efaccbcb40/src/Manager/ModelManager.php#L124-L145
djinorm/djin
src/Manager/ModelManager.php
ModelManager.delete
public function delete(ModelInterface $modelToDelete): int { if ($modelToDelete instanceof StubModelInterface) { return $this->getModelsCount($this->modelsToDelete); } $class = get_class($modelToDelete); $hash = spl_object_hash($modelToDelete); unset($this->models[$class][$hash]); $this->modelsToDelete[$class][$hash] = $modelToDelete; return $this->getModelsCount($this->modelsToDelete); }
php
public function delete(ModelInterface $modelToDelete): int { if ($modelToDelete instanceof StubModelInterface) { return $this->getModelsCount($this->modelsToDelete); } $class = get_class($modelToDelete); $hash = spl_object_hash($modelToDelete); unset($this->models[$class][$hash]); $this->modelsToDelete[$class][$hash] = $modelToDelete; return $this->getModelsCount($this->modelsToDelete); }
Подготавливает модели для будущего сохранения в базу @param ModelInterface $modelToDelete @return int общее число подготовленных для удаления моделей
https://github.com/djinorm/djin/blob/2736226e0d7467154ede40a7d23eb6efaccbcb40/src/Manager/ModelManager.php#L185-L198
djinorm/djin
src/Manager/ModelManager.php
ModelManager.freeUpMemory
public function freeUpMemory() { foreach (array_keys($this->modelRepositories) as $modelClass) { $this->getModelRepository($modelClass)->freeUpMemory(); } }
php
public function freeUpMemory() { foreach (array_keys($this->modelRepositories) as $modelClass) { $this->getModelRepository($modelClass)->freeUpMemory(); } }
Освобождает из памяти всех репозиториев загруженные модели. ВНИМАНИЕ: после освобождения памяти в случае сохранения существующей модели через self::save() в БД будет вставлена новая запись вместо обновления существующей @throws UnknownModelException @throws ContainerExceptionInterface @throws NotFoundExceptionInterface
https://github.com/djinorm/djin/blob/2736226e0d7467154ede40a7d23eb6efaccbcb40/src/Manager/ModelManager.php#L292-L297
ScaraMVC/Framework
src/Scara/Session/SessionInitializer.php
SessionInitializer.init
public static function init() { $c = new Configuration(); $cc = $c->from('app')->get('session'); if (strtolower($cc) == 'session') { return new Session(); } elseif (strtolower($cc) == 'file') { return new File(); } elseif (strtolower($cc) == 'cookie') { return new Cookie(); } else { throw new \Exception($cc.' is not a supported session type!'); } }
php
public static function init() { $c = new Configuration(); $cc = $c->from('app')->get('session'); if (strtolower($cc) == 'session') { return new Session(); } elseif (strtolower($cc) == 'file') { return new File(); } elseif (strtolower($cc) == 'cookie') { return new Cookie(); } else { throw new \Exception($cc.' is not a supported session type!'); } }
Initializes session handler. @return mixed
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Session/SessionInitializer.php#L17-L31
uneak/OAuthClientBundle
OAuth/ServicesManager.php
ServicesManager.getService
public function getService($id) { if (!isset($this->services[$id])) { // TODO: execption return null; } if (is_string($this->services[$id])) { $this->services[$id] = $this->container->get($this->services[$id]); } return $this->services[$id]; }
php
public function getService($id) { if (!isset($this->services[$id])) { // TODO: execption return null; } if (is_string($this->services[$id])) { $this->services[$id] = $this->container->get($this->services[$id]); } return $this->services[$id]; }
@param $id @return ServiceInterface
https://github.com/uneak/OAuthClientBundle/blob/e24b7734d63cf0a114167e025aebcae8c04647bb/OAuth/ServicesManager.php#L104-L114
uneak/OAuthClientBundle
OAuth/ServicesManager.php
ServicesManager.getAPI
public function getAPI(TokenInterface $token) { $id = $token->getService(); if (!isset($this->apis[$id])) { // TODO: execption return null; } if (is_string($this->apis[$id])) { $this->apis[$id] = $this->container->get($this->apis[$id]); } $this->apis[$id]->setAccessToken($token); return $this->apis[$id]; }
php
public function getAPI(TokenInterface $token) { $id = $token->getService(); if (!isset($this->apis[$id])) { // TODO: execption return null; } if (is_string($this->apis[$id])) { $this->apis[$id] = $this->container->get($this->apis[$id]); } $this->apis[$id]->setAccessToken($token); return $this->apis[$id]; }
@param AccessTokenInterface $token @return ServiceAPI
https://github.com/uneak/OAuthClientBundle/blob/e24b7734d63cf0a114167e025aebcae8c04647bb/OAuth/ServicesManager.php#L121-L133
uneak/OAuthClientBundle
OAuth/ServicesManager.php
ServicesManager.getUser
public function getUser($user) { if ($user instanceof TokenInterface) { $id = $user->getService(); } else if (is_array($user)) { $id = $user['service']; } else { $id = $user; } if (!isset($this->users[$id])) { // TODO: execption return null; } if (is_string($this->users[$id])) { $this->users[$id] = $this->container->get($this->users[$id]); } if ($user instanceof TokenInterface) { $this->users[$id]->setTokenData($user); } else if (is_array($user)) { $this->users[$id]->setOptions($user); } return $this->users[$id]; }
php
public function getUser($user) { if ($user instanceof TokenInterface) { $id = $user->getService(); } else if (is_array($user)) { $id = $user['service']; } else { $id = $user; } if (!isset($this->users[$id])) { // TODO: execption return null; } if (is_string($this->users[$id])) { $this->users[$id] = $this->container->get($this->users[$id]); } if ($user instanceof TokenInterface) { $this->users[$id]->setTokenData($user); } else if (is_array($user)) { $this->users[$id]->setOptions($user); } return $this->users[$id]; }
@param AccessTokenInterface|array|string $user @return ServiceUserInterface
https://github.com/uneak/OAuthClientBundle/blob/e24b7734d63cf0a114167e025aebcae8c04647bb/OAuth/ServicesManager.php#L140-L164
icicleio/dns
src/Executor/BasicExecutor.php
BasicExecutor.execute
public function execute(string $name, $type, array $options = []): \Generator { $timeout = isset($options['timeout']) ? (float) $options['timeout'] : self::DEFAULT_TIMEOUT; $retries = isset($options['retries']) ? (int) $options['retries'] : self::DEFAULT_RETRIES; if (0 > $retries) { $retries = 0; } $question = $this->createQuestion($name, $type); $request = $this->createRequest($question); $data = $this->encoder->encode($request); /** @var \Icicle\Socket\Socket $socket */ $socket = yield from $this->connector->connect($this->address, $this->port, ['protocol' => self::PROTOCOL]); try { $attempt = 0; do { try { yield from $socket->write($data); $response = yield from $socket->read(self::MAX_PACKET_SIZE, null, $timeout); try { $response = $this->decoder->decode($response); } catch (\Exception $exception) { throw new FailureException($exception); // Wrap in more specific exception. } if (0 !== $response->getResponseCode()) { throw new ResponseCodeException($response); } if ($response->getId() !== $request->getId()) { throw new ResponseIdException($response); } return $response; } catch (TimeoutException $exception) { // Ignore timeout and try the request again. } } while (++$attempt <= $retries); throw new NoResponseException('No response from server.'); } finally { $socket->close(); } }
php
public function execute(string $name, $type, array $options = []): \Generator { $timeout = isset($options['timeout']) ? (float) $options['timeout'] : self::DEFAULT_TIMEOUT; $retries = isset($options['retries']) ? (int) $options['retries'] : self::DEFAULT_RETRIES; if (0 > $retries) { $retries = 0; } $question = $this->createQuestion($name, $type); $request = $this->createRequest($question); $data = $this->encoder->encode($request); /** @var \Icicle\Socket\Socket $socket */ $socket = yield from $this->connector->connect($this->address, $this->port, ['protocol' => self::PROTOCOL]); try { $attempt = 0; do { try { yield from $socket->write($data); $response = yield from $socket->read(self::MAX_PACKET_SIZE, null, $timeout); try { $response = $this->decoder->decode($response); } catch (\Exception $exception) { throw new FailureException($exception); // Wrap in more specific exception. } if (0 !== $response->getResponseCode()) { throw new ResponseCodeException($response); } if ($response->getId() !== $request->getId()) { throw new ResponseIdException($response); } return $response; } catch (TimeoutException $exception) { // Ignore timeout and try the request again. } } while (++$attempt <= $retries); throw new NoResponseException('No response from server.'); } finally { $socket->close(); } }
{@inheritdoc}
https://github.com/icicleio/dns/blob/31ca939e2661f87bd807c54be0e7ad1762a5b14a/src/Executor/BasicExecutor.php#L136-L187
icicleio/dns
src/Executor/BasicExecutor.php
BasicExecutor.createQuestion
protected function createQuestion(string $name, $type): Question { if (!is_int($type)) { $type = strtoupper($type); $types = static::getRecordTypes(); if (!array_key_exists($type, $types)) { throw new InvalidTypeError($type); } $type = $types[$type]; } elseif (0 > $type || 0xffff < $type) { throw new InvalidTypeError($type); } $question = $this->questionFactory->create($type); $question->setName($name); return $question; }
php
protected function createQuestion(string $name, $type): Question { if (!is_int($type)) { $type = strtoupper($type); $types = static::getRecordTypes(); if (!array_key_exists($type, $types)) { throw new InvalidTypeError($type); } $type = $types[$type]; } elseif (0 > $type || 0xffff < $type) { throw new InvalidTypeError($type); } $question = $this->questionFactory->create($type); $question->setName($name); return $question; }
@param string $name @param string|int $type @return \LibDNS\Records\Question @throws \Icicle\Dns\Exception\InvalidTypeError If the record type given is invalid.
https://github.com/icicleio/dns/blob/31ca939e2661f87bd807c54be0e7ad1762a5b14a/src/Executor/BasicExecutor.php#L215-L232
icicleio/dns
src/Executor/BasicExecutor.php
BasicExecutor.createRequest
protected function createRequest(Question $question): Message { $request = $this->messageFactory->create(MessageTypes::QUERY); $request->getQuestionRecords()->add($question); $request->isRecursionDesired(true); $request->setID($this->createId()); return $request; }
php
protected function createRequest(Question $question): Message { $request = $this->messageFactory->create(MessageTypes::QUERY); $request->getQuestionRecords()->add($question); $request->isRecursionDesired(true); $request->setID($this->createId()); return $request; }
@param \LibDNS\Records\Question @return \LibDNS\Messages\Message
https://github.com/icicleio/dns/blob/31ca939e2661f87bd807c54be0e7ad1762a5b14a/src/Executor/BasicExecutor.php#L239-L248
shgysk8zer0/core_api
traits/singleton.php
Singleton.load
final public static function load($arg = null) { if (is_string($arg) or is_null($arg)) { if (! array_key_exists($arg, static::$instances)) { if (is_null($arg)) { static::$instances[$arg] = new self; } else { static::$instances[$arg] =new self($arg); } } return static::$instances[$arg]; } throw new \InvalidArgumentException( 'Static load method requires a string, ' . gettype($arg) . ' given.', \shgysk8zer0\Core_API\Abstracts\Exception_Codes::INVALID_ARGS ); }
php
final public static function load($arg = null) { if (is_string($arg) or is_null($arg)) { if (! array_key_exists($arg, static::$instances)) { if (is_null($arg)) { static::$instances[$arg] = new self; } else { static::$instances[$arg] =new self($arg); } } return static::$instances[$arg]; } throw new \InvalidArgumentException( 'Static load method requires a string, ' . gettype($arg) . ' given.', \shgysk8zer0\Core_API\Abstracts\Exception_Codes::INVALID_ARGS ); }
Checks if $arg is in the private static array of instances. If it is, returns that, otherwise creates one with $arg given to class constructor, stores that instance in the static array for later use, and returns that instance. @param string $arg @return self
https://github.com/shgysk8zer0/core_api/blob/9e9b8baf761af874b95256ad2462e55fbb2b2e58/traits/singleton.php#L44-L62
kambalabs/KmbPuppetDb
src/KmbPuppetDb/Service/Node.php
Node.getByName
public function getByName($name) { $response = $this->getPuppetDbClient()->send(new KmbPuppetDb\Request('/nodes/' . $name)); return $this->createNodeFromData($response->getData()); }
php
public function getByName($name) { $response = $this->getPuppetDbClient()->send(new KmbPuppetDb\Request('/nodes/' . $name)); return $this->createNodeFromData($response->getData()); }
Retrieves a node by its name. @param string $name @return Model\NodeInterface @throws InvalidArgumentException
https://github.com/kambalabs/KmbPuppetDb/blob/df56a275cf00f4402cf121a2e99149168f1f8b2d/src/KmbPuppetDb/Service/Node.php#L59-L63
kambalabs/KmbPuppetDb
src/KmbPuppetDb/Service/Node.php
Node.getAll
public function getAll($query = null, $offset = null, $limit = null, $orderBy = null) { if (is_int($query)) { $orderBy = $limit; $limit = $offset; $offset = $query; $query = null; } $request = new KmbPuppetDb\Request('/nodes', $query, $orderBy); $request->setPaging($offset, $limit); $response = $this->getPuppetDbClient()->send($request); $nodes = array(); foreach ($response->getData() as $data) { $node = $this->createNodeFromData($data); $nodes[] = $node; } return Model\NodesCollection::factory($nodes, $response->getTotal()); }
php
public function getAll($query = null, $offset = null, $limit = null, $orderBy = null) { if (is_int($query)) { $orderBy = $limit; $limit = $offset; $offset = $query; $query = null; } $request = new KmbPuppetDb\Request('/nodes', $query, $orderBy); $request->setPaging($offset, $limit); $response = $this->getPuppetDbClient()->send($request); $nodes = array(); foreach ($response->getData() as $data) { $node = $this->createNodeFromData($data); $nodes[] = $node; } return Model\NodesCollection::factory($nodes, $response->getTotal()); }
Retrieves all nodes matching with specified query, paging and sorting. All nodes are returned if parameters are null. $query can be omitted : $nodeService->getAll(10, 10); @param mixed $query @param int $offset @param mixed $limit @param array $orderBy @return Model\NodesCollection
https://github.com/kambalabs/KmbPuppetDb/blob/df56a275cf00f4402cf121a2e99149168f1f8b2d/src/KmbPuppetDb/Service/Node.php#L77-L95
black-project/common
src/Common/Application/Form/Transformer/ValuetoModelsOrNullTransformer.php
ValuetoModelsOrNullTransformer.reverseTransform
public function reverseTransform($data) { if (null === $data) { return null; } if (is_array($data) || is_object($data)) { $collection = array(); foreach ($data as $id) { $collection[] = $this->manager->getRepository()->findOneBy(['id' => $id]); } return $collection; } $model = $this->manager->getRepository()->findOneBy(['id' => $data]); return $model; }
php
public function reverseTransform($data) { if (null === $data) { return null; } if (is_array($data) || is_object($data)) { $collection = array(); foreach ($data as $id) { $collection[] = $this->manager->getRepository()->findOneBy(['id' => $id]); } return $collection; } $model = $this->manager->getRepository()->findOneBy(['id' => $data]); return $model; }
{@inheritdoc}
https://github.com/black-project/common/blob/d1de2aaae75a7ca7997dbe402897c651d9c7412a/src/Common/Application/Form/Transformer/ValuetoModelsOrNullTransformer.php#L34-L53
black-project/common
src/Common/Application/Form/Transformer/ValuetoModelsOrNullTransformer.php
ValuetoModelsOrNullTransformer.transform
public function transform($data) { if (empty($data)) { return null; } if (is_array($data) || is_object($data)) { $collection = array(); if (in_array('getId', get_class_methods($data))) { return $data->getId(); } foreach ($data as $model) { $collection[] = $model->getId(); } return $collection; } return $data; }
php
public function transform($data) { if (empty($data)) { return null; } if (is_array($data) || is_object($data)) { $collection = array(); if (in_array('getId', get_class_methods($data))) { return $data->getId(); } foreach ($data as $model) { $collection[] = $model->getId(); } return $collection; } return $data; }
{@inheritdoc}
https://github.com/black-project/common/blob/d1de2aaae75a7ca7997dbe402897c651d9c7412a/src/Common/Application/Form/Transformer/ValuetoModelsOrNullTransformer.php#L58-L79
romm/configuration_object
Classes/Core/Service/CacheService.php
CacheService.registerInternalCache
public function registerInternalCache() { $cacheManager = $this->getCacheManager(); if (false === $cacheManager->hasCache(self::CACHE_IDENTIFIER)) { $cacheManager->setCacheConfigurations([self::CACHE_IDENTIFIER => $this->cacheOptions]); } }
php
public function registerInternalCache() { $cacheManager = $this->getCacheManager(); if (false === $cacheManager->hasCache(self::CACHE_IDENTIFIER)) { $cacheManager->setCacheConfigurations([self::CACHE_IDENTIFIER => $this->cacheOptions]); } }
Function called from `ext_localconf` file which will register the internal cache earlier. @internal
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/Core/Service/CacheService.php#L50-L57
romm/configuration_object
Classes/Core/Service/CacheService.php
CacheService.registerDynamicCaches
public function registerDynamicCaches() { $dynamicCaches = $this->getCache()->getByTag(self::CACHE_TAG_DYNAMIC_CACHE); foreach ($dynamicCaches as $cacheData) { $identifier = $cacheData['identifier']; $options = $cacheData['options']; $this->registerCacheInternal($identifier, $options); } }
php
public function registerDynamicCaches() { $dynamicCaches = $this->getCache()->getByTag(self::CACHE_TAG_DYNAMIC_CACHE); foreach ($dynamicCaches as $cacheData) { $identifier = $cacheData['identifier']; $options = $cacheData['options']; $this->registerCacheInternal($identifier, $options); } }
This function will take care of initializing all caches that were defined previously by the `CacheService` which allows dynamic caches to be used for every configuration object type. @see \Romm\ConfigurationObject\Service\Items\Cache\CacheService::initialize() @internal
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/Core/Service/CacheService.php#L67-L77
romm/configuration_object
Classes/Core/Service/CacheService.php
CacheService.registerDynamicCache
public function registerDynamicCache($identifier, array $options) { if (false === $this->getCache()->has($identifier)) { $this->getCache()->set( $identifier, [ 'identifier' => $identifier, 'options' => $options ], [self::CACHE_TAG_DYNAMIC_CACHE] ); } $this->registerCacheInternal($identifier, $options); }
php
public function registerDynamicCache($identifier, array $options) { if (false === $this->getCache()->has($identifier)) { $this->getCache()->set( $identifier, [ 'identifier' => $identifier, 'options' => $options ], [self::CACHE_TAG_DYNAMIC_CACHE] ); } $this->registerCacheInternal($identifier, $options); }
Registers a new dynamic cache: the cache will be added to the cache manager after this function is executed. Its configuration will also be remembered so the cache will be registered properly during the cache framework initialization in further requests. @param string $identifier @param array $options
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/Core/Service/CacheService.php#L88-L102
bazzline/php_component_requirement
source/OrCondition.php
OrCondition.isMet
public function isMet() { if ($this->isDisabled()) { return $this->getReturnValueIfIsDisabled(); } else { if ($this->items->count() == 0) { throw new RuntimeException('No items set in this condition.'); } foreach ($this->items as $item) { if ($item->isMet()) { return true; } } return false; } }
php
public function isMet() { if ($this->isDisabled()) { return $this->getReturnValueIfIsDisabled(); } else { if ($this->items->count() == 0) { throw new RuntimeException('No items set in this condition.'); } foreach ($this->items as $item) { if ($item->isMet()) { return true; } } return false; } }
{$inheritdoc}
https://github.com/bazzline/php_component_requirement/blob/84ee943b6aa8df783e2cfa5897de3a4a70c39990/source/OrCondition.php#L19-L36
netbull/CoreBundle
Form/DataTransformer/PhoneNumberToArrayTransformer.php
PhoneNumberToArrayTransformer.transform
public function transform($phoneNumber) { if (null === $phoneNumber) { return array('country' => '', 'number' => ''); } elseif (false === $phoneNumber instanceof PhoneNumber) { throw new TransformationFailedException('Expected a \libphonenumber\PhoneNumber.'); } $util = PhoneNumberUtil::getInstance(); if (false === in_array($util->getRegionCodeForNumber($phoneNumber), $this->countryChoices)) { throw new TransformationFailedException('Invalid country.'); } return array( 'country' => $util->getRegionCodeForNumber($phoneNumber), 'number' => $util->format($phoneNumber, PhoneNumberFormat::NATIONAL), ); }
php
public function transform($phoneNumber) { if (null === $phoneNumber) { return array('country' => '', 'number' => ''); } elseif (false === $phoneNumber instanceof PhoneNumber) { throw new TransformationFailedException('Expected a \libphonenumber\PhoneNumber.'); } $util = PhoneNumberUtil::getInstance(); if (false === in_array($util->getRegionCodeForNumber($phoneNumber), $this->countryChoices)) { throw new TransformationFailedException('Invalid country.'); } return array( 'country' => $util->getRegionCodeForNumber($phoneNumber), 'number' => $util->format($phoneNumber, PhoneNumberFormat::NATIONAL), ); }
{@inheritdoc}
https://github.com/netbull/CoreBundle/blob/0bacc1d9e4733b6da613027400c48421e5a14645/Form/DataTransformer/PhoneNumberToArrayTransformer.php#L36-L54
netbull/CoreBundle
Form/DataTransformer/PhoneNumberToArrayTransformer.php
PhoneNumberToArrayTransformer.reverseTransform
public function reverseTransform($value) { if (!$value) { return null; } if (!is_array($value)) { throw new TransformationFailedException('Expected an array.'); } if ('' === trim($value['number'])) { return null; } $util = PhoneNumberUtil::getInstance(); try { $phoneNumber = $util->parse($value['number'], $value['country']); } catch (NumberParseException $e) { throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e); } if (false === in_array($util->getRegionCodeForNumber($phoneNumber), $this->countryChoices)) { throw new TransformationFailedException('Invalid country.'); } return $phoneNumber; }
php
public function reverseTransform($value) { if (!$value) { return null; } if (!is_array($value)) { throw new TransformationFailedException('Expected an array.'); } if ('' === trim($value['number'])) { return null; } $util = PhoneNumberUtil::getInstance(); try { $phoneNumber = $util->parse($value['number'], $value['country']); } catch (NumberParseException $e) { throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e); } if (false === in_array($util->getRegionCodeForNumber($phoneNumber), $this->countryChoices)) { throw new TransformationFailedException('Invalid country.'); } return $phoneNumber; }
{@inheritdoc}
https://github.com/netbull/CoreBundle/blob/0bacc1d9e4733b6da613027400c48421e5a14645/Form/DataTransformer/PhoneNumberToArrayTransformer.php#L59-L86
Kris-Kuiper/sFire-Framework
src/Validator/Form/Rules/Accepted.php
Accepted.check
private function check($value) { $values = ['yes', 'on', '1', 'true']; if(true === is_string($value)) { return true === in_array($value, $values); } return false; }
php
private function check($value) { $values = ['yes', 'on', '1', 'true']; if(true === is_string($value)) { return true === in_array($value, $values); } return false; }
Check if rule passes @param mixed $value @return boolean
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Validator/Form/Rules/Accepted.php#L59-L68
R0L/Chuanglan
src/ChuanglanSmsHelper/ChuanglanVoiceApi.php
ChuanglanVoiceApi.sendSMS
public function sendSMS( $mobile, $msg, $needstatus = 'false') { //创蓝接口参数 $postArr = array ( 'account' => $this->apiAccount, 'pswd' => $this->apiPassword, 'msg' => $msg, 'mobile' => $mobile, 'needstatus' => $needstatus ); $result = $this->curlPost( $this->apiSendUrl , $postArr); return $result; }
php
public function sendSMS( $mobile, $msg, $needstatus = 'false') { //创蓝接口参数 $postArr = array ( 'account' => $this->apiAccount, 'pswd' => $this->apiPassword, 'msg' => $msg, 'mobile' => $mobile, 'needstatus' => $needstatus ); $result = $this->curlPost( $this->apiSendUrl , $postArr); return $result; }
发送短信 @param string $mobile 手机号码 @param string $msg 短信内容 @param string $needstatus 是否需要状态报告
https://github.com/R0L/Chuanglan/blob/4bcd593470d752da2ada5f26e664504cf82d7dd0/src/ChuanglanSmsHelper/ChuanglanVoiceApi.php#L47-L60
R0L/Chuanglan
src/ChuanglanSmsHelper/ChuanglanVoiceApi.php
ChuanglanVoiceApi.queryBalance
public function queryBalance() { //查询参数 $postArr = array ( 'account' => $this->apiAccount, 'pswd' => $this->apiPassword, ); $result = $this->curlPost($this->apiBalanceQueryUrl, $postArr); return $result; }
php
public function queryBalance() { //查询参数 $postArr = array ( 'account' => $this->apiAccount, 'pswd' => $this->apiPassword, ); $result = $this->curlPost($this->apiBalanceQueryUrl, $postArr); return $result; }
查询额度 查询地址
https://github.com/R0L/Chuanglan/blob/4bcd593470d752da2ada5f26e664504cf82d7dd0/src/ChuanglanSmsHelper/ChuanglanVoiceApi.php#L67-L76
R0L/Chuanglan
src/ChuanglanSmsHelper/ChuanglanVoiceApi.php
ChuanglanVoiceApi.curlPost
private function curlPost($url,$postFields){ $postFields = http_build_query($postFields); $ch = curl_init (); curl_setopt ( $ch, CURLOPT_POST, 1 ); curl_setopt ( $ch, CURLOPT_HEADER, 0 ); curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt ( $ch, CURLOPT_URL, $url ); curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postFields ); $result = curl_exec ( $ch ); curl_close ( $ch ); return $result; }
php
private function curlPost($url,$postFields){ $postFields = http_build_query($postFields); $ch = curl_init (); curl_setopt ( $ch, CURLOPT_POST, 1 ); curl_setopt ( $ch, CURLOPT_HEADER, 0 ); curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt ( $ch, CURLOPT_URL, $url ); curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postFields ); $result = curl_exec ( $ch ); curl_close ( $ch ); return $result; }
通过CURL发送HTTP请求 @param string $url //请求URL @param array $postFields //请求参数 @return mixed
https://github.com/R0L/Chuanglan/blob/4bcd593470d752da2ada5f26e664504cf82d7dd0/src/ChuanglanSmsHelper/ChuanglanVoiceApi.php#L93-L104
RudyMas/pdoext
src/PDOExt/DBconnect.php
DBconnect.cleanSQL
public function cleanSQL(string $content = null): string { try { return $content === null ? parent::quote(null) : parent::quote($content); } catch (PDOException $exception) { throw $exception; } }
php
public function cleanSQL(string $content = null): string { try { return $content === null ? parent::quote(null) : parent::quote($content); } catch (PDOException $exception) { throw $exception; } }
functon cleanSQL($content) Quotes a string for use in a query. @param string|null $content @return string
https://github.com/RudyMas/pdoext/blob/640b476610abc5155a0d0f8ab770e1b34d1aa9c4/src/PDOExt/DBconnect.php#L198-L205
Wedeto/HTML
src/AssetManager.php
AssetManager.injectInstance
public static function injectInstance(Resolver $resolver) { $sub = $resolver->getResolver('assets'); return $sub !== null ? new static($sub) : null; }
php
public static function injectInstance(Resolver $resolver) { $sub = $resolver->getResolver('assets'); return $sub !== null ? new static($sub) : null; }
Generate an instance for the injector
https://github.com/Wedeto/HTML/blob/9e725288098c42d0d2953a929faebe628ff4e389/src/AssetManager.php#L96-L100
Wedeto/HTML
src/AssetManager.php
AssetManager.addScript
public function addScript(string $script, $depends = null) { $script = $this->stripSuffix($script, ".min", ".js"); $this->scripts[$script] = array("path" => $script, "depends" => $depends); return $this; }
php
public function addScript(string $script, $depends = null) { $script = $this->stripSuffix($script, ".min", ".js"); $this->scripts[$script] = array("path" => $script, "depends" => $depends); return $this; }
Add a javascript file to be loaded. This will strip the .min and .js suffixes and add them to the stack of included scripts. @param string $script The script to be loaded @return AssetManager Provides fluent interface
https://github.com/Wedeto/HTML/blob/9e725288098c42d0d2953a929faebe628ff4e389/src/AssetManager.php#L167-L172
Wedeto/HTML
src/AssetManager.php
AssetManager.addCSS
public function addCSS(string $stylesheet, $media = "screen") { $stylesheet = $this->stripSuffix($stylesheet, ".min", ".css"); $this->CSS[$stylesheet] = array("path" => $stylesheet, "media" => $media); return $this; }
php
public function addCSS(string $stylesheet, $media = "screen") { $stylesheet = $this->stripSuffix($stylesheet, ".min", ".css"); $this->CSS[$stylesheet] = array("path" => $stylesheet, "media" => $media); return $this; }
Add a CSS stylesheet to be loaded. This will strip the .min and .css suffixes and add them to the stack of included stylesheets. @param string $style The style sheet to be loaded @return AssetManager Provides fluent interface
https://github.com/Wedeto/HTML/blob/9e725288098c42d0d2953a929faebe628ff4e389/src/AssetManager.php#L189-L194
Wedeto/HTML
src/AssetManager.php
AssetManager.addVariable
public function addVariable(string $name, $value) { // Convert value to something usable in the output if (WF::is_array_like($value)) { $value = WF::to_array($value); } elseif (is_subclass_of($value, JSONSerializable::class)) { $value = $value->jsonSerialize(); } elseif (!is_scalar($value)) { throw new InvalidArgumentException("Invalid value provided for JS variable $name"); } $this->inline_variables[$name] = $value; return $this; }
php
public function addVariable(string $name, $value) { // Convert value to something usable in the output if (WF::is_array_like($value)) { $value = WF::to_array($value); } elseif (is_subclass_of($value, JSONSerializable::class)) { $value = $value->jsonSerialize(); } elseif (!is_scalar($value)) { throw new InvalidArgumentException("Invalid value provided for JS variable $name"); } $this->inline_variables[$name] = $value; return $this; }
Add a javascript variable to be added to the output document. A script will be generated to definie these variables on page load. @param string $name The name of the variable. Must be a valid javascript variable name. @param mixed The value to set. Should be scalar, array or JSONSerializable
https://github.com/Wedeto/HTML/blob/9e725288098c42d0d2953a929faebe628ff4e389/src/AssetManager.php#L231-L249
Wedeto/HTML
src/AssetManager.php
AssetManager.stripSuffix
protected function stripSuffix(string $path, string $suffix1, string $suffix2) { if (substr($path, -strlen($suffix2)) === $suffix2) $path = substr($path, 0, -strlen($suffix2)); if (substr($path, -strlen($suffix1)) === $suffix1) $path = substr($path, 0, -strlen($suffix1)); return $path; }
php
protected function stripSuffix(string $path, string $suffix1, string $suffix2) { if (substr($path, -strlen($suffix2)) === $suffix2) $path = substr($path, 0, -strlen($suffix2)); if (substr($path, -strlen($suffix1)) === $suffix1) $path = substr($path, 0, -strlen($suffix1)); return $path; }
Remove the suffix from a file name, such as .min.css or .min.js @param string $path The file to strip @param string $suffix1 One suffix to strip. This one is stripped after the second, so it should come second-last. This probably should be .min @param string $suffix2 Another suffix to strip. This one is stripped from the right first, so it should come last in the file name. This probably should be .js or .css @return string The stripped file name.
https://github.com/Wedeto/HTML/blob/9e725288098c42d0d2953a929faebe628ff4e389/src/AssetManager.php#L270-L277
Wedeto/HTML
src/AssetManager.php
AssetManager.resolveAssets
public function resolveAssets(array $list, $type) { if ($this->cache === null) $this->cache = new Dictionary; $urls = array(); foreach ($list as $asset) { $path = ltrim($asset['path'], '/'); $asset['basename'] = basename($path); // If the prefix is vendor, a vendor subfolder structure is assumed. // In this case, the path is not modified: no css or js prefix will be inserted. $prefix = substr($path, 0, 7) === 'vendor/' ? '' : $type . '/'; $relpath = $this->resolve_prefix . $prefix . $asset['path']; $url = $this->url_prefix . $prefix . $asset['path']; $unminified_path = $relpath . "." . $type; $unminified_url = $url . "." . $type; $minified_path = $relpath . ".min." . $type; $minified_url = $url . ".min." . $type; $unminified_file = $this->resolver->resolve($unminified_path); $minified_file = $this->resolver->resolve($minified_path); $asset_path = null; if (!$this->minified && $unminified_file) { $asset['path'] = $unminified_path; $asset['url'] = $unminified_url; $resolved_asset = $unminified_file; } elseif ($minified_file) { $asset['path'] = $minified_path; $asset['url'] = $minified_url; $resolved_asset = $minified_file; } elseif ($unminified_file) { $asset['path'] = $unminified_path; $asset['url'] = $unminified_url; $resolved_asset = $unminified_file; } else { self::$logger->error("Requested asset {0} could not be resolved", [$asset['path']]); continue; } if (!$this->cache->has('asset-mtime', $asset['path'])) { $mtime = file_exists($resolved_asset) ? filemtime($resolved_asset) : null; $this->cache->set('asset-mtime', $asset['path'], $mtime); } $asset['mtime'] = $this->cache->get('asset-mtime', $asset['path']); $asset['url'] .= !empty($asset['mtime']) ? '?' . $asset['mtime'] : ''; $urls[] = $asset; } // Solve dependency tree for assets $urls_sorted = []; $inserted = []; while (!empty($urls)) { $handled = 0; foreach ($urls as $idx => $asset) { $base = $asset['basename']; if (empty($asset['depends']) || isset($inserted[$asset['depends']])) { $urls_sorted[] = $asset; $inserted[$base] = true; unset($urls[$idx]); ++$handled; } } if ($handled === 0) { self::$logger->error("Could not solve dependency tree for assets"); foreach ($urls as $asset) $urls_sorted[] = $asset; break; } } self::$logger->debug("Dependency-sorted list of assets: {0}", [$urls_sorted]); return $urls_sorted; }
php
public function resolveAssets(array $list, $type) { if ($this->cache === null) $this->cache = new Dictionary; $urls = array(); foreach ($list as $asset) { $path = ltrim($asset['path'], '/'); $asset['basename'] = basename($path); // If the prefix is vendor, a vendor subfolder structure is assumed. // In this case, the path is not modified: no css or js prefix will be inserted. $prefix = substr($path, 0, 7) === 'vendor/' ? '' : $type . '/'; $relpath = $this->resolve_prefix . $prefix . $asset['path']; $url = $this->url_prefix . $prefix . $asset['path']; $unminified_path = $relpath . "." . $type; $unminified_url = $url . "." . $type; $minified_path = $relpath . ".min." . $type; $minified_url = $url . ".min." . $type; $unminified_file = $this->resolver->resolve($unminified_path); $minified_file = $this->resolver->resolve($minified_path); $asset_path = null; if (!$this->minified && $unminified_file) { $asset['path'] = $unminified_path; $asset['url'] = $unminified_url; $resolved_asset = $unminified_file; } elseif ($minified_file) { $asset['path'] = $minified_path; $asset['url'] = $minified_url; $resolved_asset = $minified_file; } elseif ($unminified_file) { $asset['path'] = $unminified_path; $asset['url'] = $unminified_url; $resolved_asset = $unminified_file; } else { self::$logger->error("Requested asset {0} could not be resolved", [$asset['path']]); continue; } if (!$this->cache->has('asset-mtime', $asset['path'])) { $mtime = file_exists($resolved_asset) ? filemtime($resolved_asset) : null; $this->cache->set('asset-mtime', $asset['path'], $mtime); } $asset['mtime'] = $this->cache->get('asset-mtime', $asset['path']); $asset['url'] .= !empty($asset['mtime']) ? '?' . $asset['mtime'] : ''; $urls[] = $asset; } // Solve dependency tree for assets $urls_sorted = []; $inserted = []; while (!empty($urls)) { $handled = 0; foreach ($urls as $idx => $asset) { $base = $asset['basename']; if (empty($asset['depends']) || isset($inserted[$asset['depends']])) { $urls_sorted[] = $asset; $inserted[$base] = true; unset($urls[$idx]); ++$handled; } } if ($handled === 0) { self::$logger->error("Could not solve dependency tree for assets"); foreach ($urls as $asset) $urls_sorted[] = $asset; break; } } self::$logger->debug("Dependency-sorted list of assets: {0}", [$urls_sorted]); return $urls_sorted; }
Resolve a list of assets. The assets will be resolved by the Resolver. Depending on the setting of minified, the minified or the unminified version will be preferred. When the preferred type is not available, another one will be used. @return array A list of resolved URLs. Each entry contains a key 'path' to the file in the file system and a key 'url' for the browser.
https://github.com/Wedeto/HTML/blob/9e725288098c42d0d2953a929faebe628ff4e389/src/AssetManager.php#L316-L406
Wedeto/HTML
src/AssetManager.php
AssetManager.replaceTokens
public function replaceTokens(string $HTML) { $scripts = $this->resolveAssets($this->scripts, "js"); $CSS = $this->resolveAssets($this->CSS, "css"); // Initialize all output variables to null $values = new TypedDictionary( [ 'css_document' => new Validator(Type::OBJECT, ['class' => DOMDocument::class]), 'js_document' => new Validator(Type::OBJECT, ['class' => DOMDocument::class]), 'js_inline_document' => new Validator(Type::OBJECT, ['class' => DOMDocument::class]), 'css_files' => Type::ARRAY, 'js_files' => Type::ARRAY, 'js_inline_variables' => Type::ARRAY ], [ 'js_files' => $scripts, 'css_files' => $CSS, 'js_inline_variables' => $this->inline_variables ] ); // Allow hooks to modify the scripts and CSS before modifying them Hook::execute('Wedeto.HTML.AssetManager.replaceTokens.preRender', $values); // Do rendering $js = $values->getArray('js_files'); if (!empty($js) && !$values->has('js_document')) { $js_doc = new DOMDocument; foreach ($js as $script) { $element = $js_doc->createElement('script'); $element->setAttribute('src', $script['url']); $js_doc->appendChild($element); } $values['js_document'] = $js_doc; } $jsv = $values->getArray('js_inline_variables'); if (!empty($jsv) && !$values->has('js_inline_document')) { $js_inline_doc = new DOMDocument; $code_lines = ['window.wdt = {};']; foreach ($jsv as $name => $value) $code_lines[] = "window.wdt.$name = " . json_encode($value) . ";"; $variable_el = $js_inline_doc->createElement('script', implode("\n", $code_lines)); $js_inline_doc->appendChild($variable_el); $values['js_inline_document'] = $js_inline_doc; } $CSS = $values->getArray('css_files'); if (!empty($CSS) && !$values->has('css_document')) { $CSS_doc = new DOMDocument; foreach ($CSS as $stylesheet) { $element = $CSS_doc->createElement('link'); $element->setAttribute('rel', 'stylesheet'); $element->setAttribute('href', $stylesheet['url']); $element->setAttribute('type', 'text/css'); $CSS_doc->appendChild($element); } $values['css_document'] = $CSS_doc; } // Allow hooks to modify the output Hook::execute('Wedeto.HTML.AssetManager.replaceTokens.postRender', $values); $script_HTML = $values->has('js_document') ? trim($values['js_document']->saveHTML()) : ''; $CSS_HTML = $values->has('css_document') ? trim($values['css_document']->saveHTML()) : ''; $inline_script_HTML = $values->has('js_inline_document') ? trim($values['js_inline_document']->saveHTML()) : ''; $count = 0; $HTML = str_replace($this->injectScript(), $script_HTML . $inline_script_HTML, $HTML, $count); if ($count === 0 && !empty($script_HTML)) { self::$logger->warning("No Javascript marker found while there are scripts to insert"); self::$logger->debug("To-be inserted scripts: {0}", $js); } $count = 0; $HTML = str_replace($this->injectCSS(), $CSS_HTML, $HTML, $count); if ($count === 0 && !empty($CSS_HTML)) { self::$logger->warning("No CSS marker found while there are stylesheets to insert"); self::$logger->debug("To-be inserted stylesheets: {0}", [$CSS]); } // Tidy up HTML when configured and available if ($this->tidy) { if (class_exists("Tidy", false)) { $tidy = new \Tidy(); $config = array('indent' => true, 'indent-spaces' => 4, 'wrap' => 120, 'markup' => true, 'doctype' => 'omit'); $HTML = "<!DOCTYPE html>\n" . $tidy->repairString($HTML, $config, "utf8"); } else { // @codeCoverageIgnoreStart self::$logger->warning("Tidy output has been requested, but Tidy extension is not available"); // @codeCoverageIgnoreEnd } } return $HTML; }
php
public function replaceTokens(string $HTML) { $scripts = $this->resolveAssets($this->scripts, "js"); $CSS = $this->resolveAssets($this->CSS, "css"); // Initialize all output variables to null $values = new TypedDictionary( [ 'css_document' => new Validator(Type::OBJECT, ['class' => DOMDocument::class]), 'js_document' => new Validator(Type::OBJECT, ['class' => DOMDocument::class]), 'js_inline_document' => new Validator(Type::OBJECT, ['class' => DOMDocument::class]), 'css_files' => Type::ARRAY, 'js_files' => Type::ARRAY, 'js_inline_variables' => Type::ARRAY ], [ 'js_files' => $scripts, 'css_files' => $CSS, 'js_inline_variables' => $this->inline_variables ] ); // Allow hooks to modify the scripts and CSS before modifying them Hook::execute('Wedeto.HTML.AssetManager.replaceTokens.preRender', $values); // Do rendering $js = $values->getArray('js_files'); if (!empty($js) && !$values->has('js_document')) { $js_doc = new DOMDocument; foreach ($js as $script) { $element = $js_doc->createElement('script'); $element->setAttribute('src', $script['url']); $js_doc->appendChild($element); } $values['js_document'] = $js_doc; } $jsv = $values->getArray('js_inline_variables'); if (!empty($jsv) && !$values->has('js_inline_document')) { $js_inline_doc = new DOMDocument; $code_lines = ['window.wdt = {};']; foreach ($jsv as $name => $value) $code_lines[] = "window.wdt.$name = " . json_encode($value) . ";"; $variable_el = $js_inline_doc->createElement('script', implode("\n", $code_lines)); $js_inline_doc->appendChild($variable_el); $values['js_inline_document'] = $js_inline_doc; } $CSS = $values->getArray('css_files'); if (!empty($CSS) && !$values->has('css_document')) { $CSS_doc = new DOMDocument; foreach ($CSS as $stylesheet) { $element = $CSS_doc->createElement('link'); $element->setAttribute('rel', 'stylesheet'); $element->setAttribute('href', $stylesheet['url']); $element->setAttribute('type', 'text/css'); $CSS_doc->appendChild($element); } $values['css_document'] = $CSS_doc; } // Allow hooks to modify the output Hook::execute('Wedeto.HTML.AssetManager.replaceTokens.postRender', $values); $script_HTML = $values->has('js_document') ? trim($values['js_document']->saveHTML()) : ''; $CSS_HTML = $values->has('css_document') ? trim($values['css_document']->saveHTML()) : ''; $inline_script_HTML = $values->has('js_inline_document') ? trim($values['js_inline_document']->saveHTML()) : ''; $count = 0; $HTML = str_replace($this->injectScript(), $script_HTML . $inline_script_HTML, $HTML, $count); if ($count === 0 && !empty($script_HTML)) { self::$logger->warning("No Javascript marker found while there are scripts to insert"); self::$logger->debug("To-be inserted scripts: {0}", $js); } $count = 0; $HTML = str_replace($this->injectCSS(), $CSS_HTML, $HTML, $count); if ($count === 0 && !empty($CSS_HTML)) { self::$logger->warning("No CSS marker found while there are stylesheets to insert"); self::$logger->debug("To-be inserted stylesheets: {0}", [$CSS]); } // Tidy up HTML when configured and available if ($this->tidy) { if (class_exists("Tidy", false)) { $tidy = new \Tidy(); $config = array('indent' => true, 'indent-spaces' => 4, 'wrap' => 120, 'markup' => true, 'doctype' => 'omit'); $HTML = "<!DOCTYPE html>\n" . $tidy->repairString($HTML, $config, "utf8"); } else { // @codeCoverageIgnoreStart self::$logger->warning("Tidy output has been requested, but Tidy extension is not available"); // @codeCoverageIgnoreEnd } } return $HTML; }
Replace the tokens injected in the generation of the HTML by the correct values. @param string $HTML The HTML containing tokens to be replaced @return string The HTML with the tokens replaced, and optionally with corrected HTML using PHP's Tidy extension.
https://github.com/Wedeto/HTML/blob/9e725288098c42d0d2953a929faebe628ff4e389/src/AssetManager.php#L414-L520
Wedeto/HTML
src/AssetManager.php
AssetManager.executeHook
public function executeHook(Dictionary $params) { $responder = $params['responder'] ?? null; $mime = $params['mime'] ?? null; $result = empty($responder) ? null : $responder->getResult(); $response = empty($result) ? null : $result->getResponse(); if ($response instanceof HTTPError) $response = $response->getResponse(); if ($response instanceof StringResponse && $mime === "text/html") { $output = $response->getOutput($mime); $output = $this->replaceTokens($output); $response->setOutput($output, $mime); } }
php
public function executeHook(Dictionary $params) { $responder = $params['responder'] ?? null; $mime = $params['mime'] ?? null; $result = empty($responder) ? null : $responder->getResult(); $response = empty($result) ? null : $result->getResponse(); if ($response instanceof HTTPError) $response = $response->getResponse(); if ($response instanceof StringResponse && $mime === "text/html") { $output = $response->getOutput($mime); $output = $this->replaceTokens($output); $response->setOutput($output, $mime); } }
Execute the hook to replace the Javascript and CSS tokens in the HTTP Responder. This will be called by Wedeto\Util\Hook through Wedeto\HTTP. It can be called directly when you want to replace the content at a different time. @param Dictionary $params The parameters. Should contain a key 'response' and 'mime'. The res
https://github.com/Wedeto/HTML/blob/9e725288098c42d0d2953a929faebe628ff4e389/src/AssetManager.php#L529-L546
Ydle/HubBundle
Controller/RestRoomController.php
RestRoomController.getRoomsListAction
public function getRoomsListAction(ParamFetcher $paramFetcher) { $page = $paramFetcher->get('page'); $count = $paramFetcher->get('count'); $pager = $this->getRoomManager()->getPager($this->filterCriteria($paramFetcher), $page, $count); return $pager; }
php
public function getRoomsListAction(ParamFetcher $paramFetcher) { $page = $paramFetcher->get('page'); $count = $paramFetcher->get('count'); $pager = $this->getRoomManager()->getPager($this->filterCriteria($paramFetcher), $page, $count); return $pager; }
Retrieve the list of available rooms @QueryParam(name="page", requirements="\d+", default="0", description="Number of page") @QueryParam(name="count", requirements="\d+", default="0", description="Number of room by page") @param ParamFetcher $paramFetcher
https://github.com/Ydle/HubBundle/blob/7fa423241246bcfd115f2ed3ad3997b4b63adb01/Controller/RestRoomController.php#L38-L46
hschletz/NADA
src/Database/AbstractDatabase.php
AbstractDatabase.query
public function query($statement, $params=array()) { if (!is_array($params)) { $params = array($params); } return $this->_link->query($statement, $params); }
php
public function query($statement, $params=array()) { if (!is_array($params)) { $params = array($params); } return $this->_link->query($statement, $params); }
Run database query and return complete result set This method is intended to be used internally by NADA. Application code should preferrably use methods from the underlying database abstraction layer. This method is intended for SELECT and similar commands that return a result set. The result is returned as a 2-dimensional array. The outer array is numeric and contains the rows. The rows are associative arrays with lowercase column identifiers as keys. @param string $statement SQL statement with optional placeholders @param mixed $params Single value or array of values to substitute for placeholders @return array Array of all rows @internal
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Database/AbstractDatabase.php#L196-L202
hschletz/NADA
src/Database/AbstractDatabase.php
AbstractDatabase.exec
public function exec($statement, $params=array()) { if (!is_array($params)) { $params = array($params); } return $this->_link->exec($statement, $params); }
php
public function exec($statement, $params=array()) { if (!is_array($params)) { $params = array($params); } return $this->_link->exec($statement, $params); }
Execute a database statement that does not return a result set This method is intended to be used internally by NADA. Application code should preferrably use methods from the underlying database abstraction layer. SQL commands like UPDATE, INSERT, DELETE, SET etc. don't return a result set. This method is intended for this type of commands. The return value is typically the number of affected rows. @param string $statement SQL statement with optional placeholders @param mixed $params Single value or array of values to substitute for placeholders @return integer Number of affected rows @internal
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Database/AbstractDatabase.php#L220-L226
hschletz/NADA
src/Database/AbstractDatabase.php
AbstractDatabase.prepareIdentifier
public function prepareIdentifier($identifier) { if ($this->quoteAlways or in_array($identifier, $this->quoteKeywords)) { return $this->quoteIdentifier($identifier); } if (!preg_match('/^[_[:alpha:]][_[:alnum:]]*$/', $identifier)) { if ($this->quoteInvalidCharacters) { return $this->quoteIdentifier($identifier); } else { throw new \RuntimeException('Invalid characters in identifier: ' . $identifier); } } return $identifier; }
php
public function prepareIdentifier($identifier) { if ($this->quoteAlways or in_array($identifier, $this->quoteKeywords)) { return $this->quoteIdentifier($identifier); } if (!preg_match('/^[_[:alpha:]][_[:alnum:]]*$/', $identifier)) { if ($this->quoteInvalidCharacters) { return $this->quoteIdentifier($identifier); } else { throw new \RuntimeException('Invalid characters in identifier: ' . $identifier); } } return $identifier; }
Prepare an identifier (table/column name etc.) for insertion into an SQL statement Inserting identifiers from external sources into an SQL statement is tricky and error-prone. They can contain invalid characters, match an SQL keyword on some DBMS, or be abused for SQL injection. This problem is typically addressed by quoting and escaping identifiers from untrusted sources. This raises a new problem: According to SQL standards, quoted identifiers may become case sensitive while unquoted identifiers are case insensitive. Under certain circumstances, the referred object may become impossible to address safely across all DBMS. This method is a more flexible alternative to unconditional quoting. By default, no quoting and escaping is applied for maximum compatibility. Identifiers that would require quoting raise an exception. For maximum portability, this method is rather strict about valid identifiers: They must contain only letters, digits and underscores and must not begin with a digit. To allow identifiers that do not meet these criteria, set the public {@link quoteInvalidCharacters} property to TRUE. This will quote and escape identifiers that contain invalid characters. This is a bad idea and the object should rather be renamed if possible. SQL injection is prevented either way. The public {@link quoteKeywords} property can be set to an array of keywords that would raise an error if inserted unquoted. If $identifier matches one of those keywords, it will be quoted. However, naming a database object with a reserved keyword is a bad idea. Consider renaming it if possible. Concealing the flaw by applying quotes is only a solution if the object cannot be renamed. For this reason, {@link quoteKeywords} is empty by default. Finally, the public {@link quoteAlways} property can be set to TRUE to quote all identifiers unconditionally. This should only be done if an identifier is only known at runtime and nothing is known about it otherwise. Even with proper quoting, bad things may happen if untrusted input is used as an identifier. Don't rely on this method alone - always sanitize input before using it as an identifier. @param string $identifier Identifier to check @return string Identifier, quoted and escaped if necessary @throws \RuntimeException if identifier is invalid and not quoted.
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Database/AbstractDatabase.php#L411-L426
hschletz/NADA
src/Database/AbstractDatabase.php
AbstractDatabase.quoteIdentifier
public function quoteIdentifier($identifier) { $quotedIdentifier = $this->_link->quoteIdentifier($identifier); if ($quotedIdentifier === null) { $quotedIdentifier = $this->_quoteIdentifier($identifier); } return $quotedIdentifier; }
php
public function quoteIdentifier($identifier) { $quotedIdentifier = $this->_link->quoteIdentifier($identifier); if ($quotedIdentifier === null) { $quotedIdentifier = $this->_quoteIdentifier($identifier); } return $quotedIdentifier; }
Quote and escape an identifier (table/column name etc.) for insertion into an SQL statement This method unconditionally quotes an identifier. This is discouraged in favour of {@link prepareIdentifier()}. @param string $identifier Identifier to quote and escape @return string Quoted and escaped identifier
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Database/AbstractDatabase.php#L436-L443
hschletz/NADA
src/Database/AbstractDatabase.php
AbstractDatabase.prepareValue
public function prepareValue($value, $datatype) { if ($value === null) { return 'NULL'; } switch ($datatype) { case Column::TYPE_INTEGER: // Filter explicitly because some DBAL silently convert/truncate to integer $filtered = filter_var($value, FILTER_VALIDATE_INT); if ($filtered === false) { throw new \InvalidArgumentException('Not an integer: '. $value); } return $filtered; // No quotes necessary case Column::TYPE_FLOAT: case Column::TYPE_DECIMAL: // Filter explicitly because some DBAL silently convert/truncate to float $filtered = filter_var($value, FILTER_VALIDATE_FLOAT); if ($filtered === false) { throw new \InvalidArgumentException('Not a number: '. $value); } return $filtered; // No quotes necessary case Column::TYPE_BOOL: if (is_bool($value)) { // filter_var() does not work with real booleans $filtered = $value; } else { $filtered = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); } if ($filtered === null) { throw new \InvalidArgumentException('Not a boolean: ' . $value); } return (integer)$filtered; // Convert to 0/1 for compatibility with emulated booleans case Column::TYPE_BLOB: // Handled differently across DBMS and abstraction layers - refuse by default. throw new \InvalidArgumentException('Cannot prepare BLOB values'); default: return $this->_link->quoteValue($value, $datatype); } }
php
public function prepareValue($value, $datatype) { if ($value === null) { return 'NULL'; } switch ($datatype) { case Column::TYPE_INTEGER: // Filter explicitly because some DBAL silently convert/truncate to integer $filtered = filter_var($value, FILTER_VALIDATE_INT); if ($filtered === false) { throw new \InvalidArgumentException('Not an integer: '. $value); } return $filtered; // No quotes necessary case Column::TYPE_FLOAT: case Column::TYPE_DECIMAL: // Filter explicitly because some DBAL silently convert/truncate to float $filtered = filter_var($value, FILTER_VALIDATE_FLOAT); if ($filtered === false) { throw new \InvalidArgumentException('Not a number: '. $value); } return $filtered; // No quotes necessary case Column::TYPE_BOOL: if (is_bool($value)) { // filter_var() does not work with real booleans $filtered = $value; } else { $filtered = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); } if ($filtered === null) { throw new \InvalidArgumentException('Not a boolean: ' . $value); } return (integer)$filtered; // Convert to 0/1 for compatibility with emulated booleans case Column::TYPE_BLOB: // Handled differently across DBMS and abstraction layers - refuse by default. throw new \InvalidArgumentException('Cannot prepare BLOB values'); default: return $this->_link->quoteValue($value, $datatype); } }
Prepare a literal value for insertion into an SQL statement @param mixed $value Value to prepare @param string $datatype The value's datatype @return string Value, processed, quoted and escaped if necessary
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Database/AbstractDatabase.php#L464-L501
hschletz/NADA
src/Database/AbstractDatabase.php
AbstractDatabase.getName
public function getName() { if (!$this->_name) { $result = $this->query( 'select catalog_name from information_schema.information_schema_catalog_name' ); $this->_name = $result[0]['catalog_name']; } return $this->_name; }
php
public function getName() { if (!$this->_name) { $result = $this->query( 'select catalog_name from information_schema.information_schema_catalog_name' ); $this->_name = $result[0]['catalog_name']; } return $this->_name; }
Return name of the database that the current connection points to @return string Database name
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Database/AbstractDatabase.php#L535-L544
hschletz/NADA
src/Database/AbstractDatabase.php
AbstractDatabase.getTable
public function getTable($name) { if ($name != strtolower($name)) { throw new \DomainException('Table name must be lowercase: ' . $name); } if (!isset($this->_tables[$name])) { $class = 'Nada\Table\\' . $this->getDbmsSuffix(); $this->_tables[$name] = new $class($this, $name); } return $this->_tables[$name]; }
php
public function getTable($name) { if ($name != strtolower($name)) { throw new \DomainException('Table name must be lowercase: ' . $name); } if (!isset($this->_tables[$name])) { $class = 'Nada\Table\\' . $this->getDbmsSuffix(); $this->_tables[$name] = new $class($this, $name); } return $this->_tables[$name]; }
Get access to a specific table The returned object provides access to the given table and its associated database objects (columns etc.). The result is cached internally, so that subsequent calls won't hurt performance. @param string $name Table name (lowercase). An exception gets thrown if the name does not exist. @return \Nada\Table\AbstractTable Table object @throws \DomainException if $name is not lowercase
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Database/AbstractDatabase.php#L556-L567
hschletz/NADA
src/Database/AbstractDatabase.php
AbstractDatabase.getTables
public function getTables() { if (!$this->_allTablesFetched) { // Fetch only once $tables = $this->getTableNames(); // Fetch missing tables foreach ($tables as $table) { $this->getTable($table); // Discard result, still available in cache } // Sort cache ksort($this->_tables); // Set flag for subsequent invocations $this->_allTablesFetched = true; } return $this->_tables; }
php
public function getTables() { if (!$this->_allTablesFetched) { // Fetch only once $tables = $this->getTableNames(); // Fetch missing tables foreach ($tables as $table) { $this->getTable($table); // Discard result, still available in cache } // Sort cache ksort($this->_tables); // Set flag for subsequent invocations $this->_allTablesFetched = true; } return $this->_tables; }
Return all tables The result is cached internally, so that subsequent calls won't hurt performance. @return array Array with table names as keys and \Nada\Table\AbstractTable objects as values
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Database/AbstractDatabase.php#L576-L590
hschletz/NADA
src/Database/AbstractDatabase.php
AbstractDatabase.getViewNames
public function getViewNames() { $names = $this->query( 'SELECT table_name FROM information_schema.tables WHERE table_schema=? AND table_type=?', array( $this->getTableSchema(), 'VIEW' ) ); // Flatten array foreach ($names as &$name) { $name = $name['table_name']; } return $names; }
php
public function getViewNames() { $names = $this->query( 'SELECT table_name FROM information_schema.tables WHERE table_schema=? AND table_type=?', array( $this->getTableSchema(), 'VIEW' ) ); // Flatten array foreach ($names as &$name) { $name = $name['table_name']; } return $names; }
Return list of all view names The default implementation queries information_schema. This can be overridden where information_schema is not available. @return array
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Database/AbstractDatabase.php#L624-L638
hschletz/NADA
src/Database/AbstractDatabase.php
AbstractDatabase.clearCache
public function clearCache($table=null) { if ($table) { unset($this->_tables[$table]); } else { $this->_tables = array(); } $this->_allTablesFetched = false; }
php
public function clearCache($table=null) { if ($table) { unset($this->_tables[$table]); } else { $this->_tables = array(); } $this->_allTablesFetched = false; }
Clear cache NADA caches the database structure internally. The structure manipulation methods maintain the cache automatically. If the structure has been altered without one of NADA's methods, the cache is outdated and needs to be flushed with this method. @param string $table Optional: Flush only the given table instead of the entire cache
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Database/AbstractDatabase.php#L650-L658
hschletz/NADA
src/Database/AbstractDatabase.php
AbstractDatabase.getNativeDatatype
public function getNativeDatatype($type, $length=null, $cast=false) { switch ($type) { case Column::TYPE_INTEGER: if ($length === null) { $length = Column::DEFAULT_LENGTH_INTEGER; } switch ($length) { case 16: return 'SMALLINT'; case 32: return 'INTEGER'; case 64: return 'BIGINT'; default: throw new \DomainException("Invalid length for type $type: $length"); } case Column::TYPE_VARCHAR: if (!ctype_digit((string)$length) or $length < 1) { throw new \InvalidArgumentException('Invalid length: ' . $length); } return "VARCHAR($length)"; case Column::TYPE_TIMESTAMP: return 'TIMESTAMP'; case Column::TYPE_DATE: return 'DATE'; case Column::TYPE_BOOL: return 'BOOLEAN'; case Column::TYPE_BLOB: return 'BLOB'; case Column::TYPE_DECIMAL: if (!preg_match('/^([0-9]+),([0-9]+)$/', $length, $components)) { throw new \InvalidArgumentException('Invalid length: ' . $length); } $precision = (integer)$components[1]; $scale = (integer)$components[2]; if ($precision < $scale) { throw new \InvalidArgumentException('Invalid length: ' . $length); } return "NUMERIC($precision,$scale)"; case Column::TYPE_FLOAT: if ($length === null) { $length = Column::DEFAULT_LENGTH_FLOAT; } elseif (!ctype_digit((string)$length) or $length < 1) { throw new \InvalidArgumentException('Invalid length: ' . $length); } return "FLOAT($length)"; default: throw new \DomainException('Unsupported datatype: ' . $type); } }
php
public function getNativeDatatype($type, $length=null, $cast=false) { switch ($type) { case Column::TYPE_INTEGER: if ($length === null) { $length = Column::DEFAULT_LENGTH_INTEGER; } switch ($length) { case 16: return 'SMALLINT'; case 32: return 'INTEGER'; case 64: return 'BIGINT'; default: throw new \DomainException("Invalid length for type $type: $length"); } case Column::TYPE_VARCHAR: if (!ctype_digit((string)$length) or $length < 1) { throw new \InvalidArgumentException('Invalid length: ' . $length); } return "VARCHAR($length)"; case Column::TYPE_TIMESTAMP: return 'TIMESTAMP'; case Column::TYPE_DATE: return 'DATE'; case Column::TYPE_BOOL: return 'BOOLEAN'; case Column::TYPE_BLOB: return 'BLOB'; case Column::TYPE_DECIMAL: if (!preg_match('/^([0-9]+),([0-9]+)$/', $length, $components)) { throw new \InvalidArgumentException('Invalid length: ' . $length); } $precision = (integer)$components[1]; $scale = (integer)$components[2]; if ($precision < $scale) { throw new \InvalidArgumentException('Invalid length: ' . $length); } return "NUMERIC($precision,$scale)"; case Column::TYPE_FLOAT: if ($length === null) { $length = Column::DEFAULT_LENGTH_FLOAT; } elseif (!ctype_digit((string)$length) or $length < 1) { throw new \InvalidArgumentException('Invalid length: ' . $length); } return "FLOAT($length)"; default: throw new \DomainException('Unsupported datatype: ' . $type); } }
Get DBMS-specific datatype for abstract NADA datatype @param string $type One of \Nada\Column\AbstractColumn's TYPE_* constants @param mixed $length Optional length modifier (default provided for some datatypes) @param bool $cast The result is used for a typecast operation. Some DBMS require different specifiers for casts. @return string SQL fragment representing the datatype @throws \DomainException if the datatype is not supported for the current DBMS @throws \InvalidArgumentException if $length is invalid
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Database/AbstractDatabase.php#L681-L731
hschletz/NADA
src/Database/AbstractDatabase.php
AbstractDatabase.createColumn
public function createColumn( $name, $type, $length=null, $notnull=false, $default=null, $autoIncrement=false, $comment=null ) { $column = $this->createColumnObject(); $column->constructNew($this, $name, $type, $length, $notnull, $default, $autoIncrement, $comment); return $column; }
php
public function createColumn( $name, $type, $length=null, $notnull=false, $default=null, $autoIncrement=false, $comment=null ) { $column = $this->createColumnObject(); $column->constructNew($this, $name, $type, $length, $notnull, $default, $autoIncrement, $comment); return $column; }
Construct a new column Input is not validated at this point, i.e. this method always succeeds. Invalid input is detected once the column data is actually used. The returned object is not linked to a table. It should only be used for adding it to a table. It can be discarded afterwards. @param string $name Column name @param string $type Datatype @param mixed $length Optional length modifier @param bool $notnull NOT NULL constraint (default FALSE) @param mixed $default Default value (default NULL) @param bool $autoIncrement Auto increment property (default FALSE) @param string $comment Column comment (default: NULL) @return \Nada\Column\AbstractColumn Temporary column object
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Database/AbstractDatabase.php#L761-L774
hschletz/NADA
src/Database/AbstractDatabase.php
AbstractDatabase.createColumnFromArray
public function createColumnFromArray(array $data) { return $this->createColumn( $data['name'], $data['type'], $data['length'], !empty($data['notnull']), @$data['default'], !empty($data['autoincrement']), @$data['comment'] ); }
php
public function createColumnFromArray(array $data) { return $this->createColumn( $data['name'], $data['type'], $data['length'], !empty($data['notnull']), @$data['default'], !empty($data['autoincrement']), @$data['comment'] ); }
Construct a new column with data from an array This is a wrapper around createColumn() which gets column data from an associative array. The "name", "type" and "length" elements must always be present. The "notnull" and "autoincrement" elements default to FALSE if not given. The "default" and "comment" elements default to NULL. @param array $data column data: name, type, length, notnull, default, autoincrement, comment @return \Nada\Column\AbstractColumn Temporary column object
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Database/AbstractDatabase.php#L789-L800
hschletz/NADA
src/Database/AbstractDatabase.php
AbstractDatabase.createTable
public function createTable($name, array $columns, $primaryKey=null) { $name = strtolower($name); if (strpos($name, 'sqlite_') === 0) { throw new \InvalidArgumentException('Created table name must not begin with sqlite_'); } if (empty($columns)) { throw new \InvalidArgumentException('No columns specified for new table'); } if ($primaryKey !== null and !is_array($primaryKey)) { $primaryKey = array($primaryKey); } $numAutoIncrement = 0; $autoPk = null; foreach ($columns as &$column) { if (is_array($column)) { $column = $this->createColumnFromArray($column); } if ($column->getAutoIncrement()) { $numAutoIncrement++; $autoPk = $column->getName(); } } unset($column); if ($numAutoIncrement > 1) { throw new \InvalidArgumentException( 'More than 1 autoincrement field specified, given: ' . $numAutoIncrement ); } if ($autoPk) { if ($primaryKey === null) { $primaryKey = array($autoPk); } elseif (count($primaryKey) != 1 or $autoPk != $primaryKey[0]) { throw new \InvalidArgumentException('Invalid primary key: ' . implode(',', $primaryKey)); } } if (!$primaryKey) { throw new \InvalidArgumentException('Missing primary key for table ' . $name); } if (in_array($name, $this->getTableNames())) { throw new \RuntimeException('Table already exists: ' . $name); } $colspecs = array(); foreach ($columns as $column) { $colspecs[] = $this->prepareIdentifier($column->getName()) . ' ' . $column->getDefinition(); } $sql = 'CREATE TABLE ' . $this->prepareIdentifier($name) . " (\n"; $sql .= implode(",\n", $colspecs); $sql .= $this->_getTablePkDeclaration($primaryKey, (bool) $numAutoIncrement); $sql .= "\n)"; $this->exec($sql); return $this->getTable($name); }
php
public function createTable($name, array $columns, $primaryKey=null) { $name = strtolower($name); if (strpos($name, 'sqlite_') === 0) { throw new \InvalidArgumentException('Created table name must not begin with sqlite_'); } if (empty($columns)) { throw new \InvalidArgumentException('No columns specified for new table'); } if ($primaryKey !== null and !is_array($primaryKey)) { $primaryKey = array($primaryKey); } $numAutoIncrement = 0; $autoPk = null; foreach ($columns as &$column) { if (is_array($column)) { $column = $this->createColumnFromArray($column); } if ($column->getAutoIncrement()) { $numAutoIncrement++; $autoPk = $column->getName(); } } unset($column); if ($numAutoIncrement > 1) { throw new \InvalidArgumentException( 'More than 1 autoincrement field specified, given: ' . $numAutoIncrement ); } if ($autoPk) { if ($primaryKey === null) { $primaryKey = array($autoPk); } elseif (count($primaryKey) != 1 or $autoPk != $primaryKey[0]) { throw new \InvalidArgumentException('Invalid primary key: ' . implode(',', $primaryKey)); } } if (!$primaryKey) { throw new \InvalidArgumentException('Missing primary key for table ' . $name); } if (in_array($name, $this->getTableNames())) { throw new \RuntimeException('Table already exists: ' . $name); } $colspecs = array(); foreach ($columns as $column) { $colspecs[] = $this->prepareIdentifier($column->getName()) . ' ' . $column->getDefinition(); } $sql = 'CREATE TABLE ' . $this->prepareIdentifier($name) . " (\n"; $sql .= implode(",\n", $colspecs); $sql .= $this->_getTablePkDeclaration($primaryKey, (bool) $numAutoIncrement); $sql .= "\n)"; $this->exec($sql); return $this->getTable($name); }
Create a table Some constraints are checked before the creation is attempted: - There can be at most 1 autoincrement column. - If there is an autoincrement column, it must be the primary key. - Otherwise, $primaryKey must not be empty. - Table names must not begin with sqlite_. For maximum compatibility, this constraint is enforced for all DBMS, not only for SQLite. The $primaryKey value can be omitted for tables with an autoincrement column because the autoincrement column is automatically made the primary key. @param string $name Table name @param array $columns Array of column objects, created via createColumn(), or associative arrays @param string|array $primaryKey Primary key (column name or aray of column names) @return \Nada\Table\AbstractTable A representation of the created table @throws \InvalidArgumentException if $columns is empty or constraints are violated @throws \RuntimeException if the table already exists
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Database/AbstractDatabase.php#L824-L879
hschletz/NADA
src/Database/AbstractDatabase.php
AbstractDatabase._getTablePkDeclaration
protected function _getTablePkDeclaration(array $primaryKey, $autoIncrement) { foreach ($primaryKey as &$column) { $column = $this->prepareIdentifier($column); } return ",\nPRIMARY KEY (" . implode(', ', $primaryKey) . ')'; }
php
protected function _getTablePkDeclaration(array $primaryKey, $autoIncrement) { foreach ($primaryKey as &$column) { $column = $this->prepareIdentifier($column); } return ",\nPRIMARY KEY (" . implode(', ', $primaryKey) . ')'; }
Get the declaration for a table's primary key This is called by createTable() to get the PRIMARY KEY declaration to be inserted into a CREATE TABLE statement. The default implementation unconditionally returns ", PRIMARY KEY ($column[,$column...])". Other implementations may override this, depending on $autoIncrement. @param array $primaryKey Array of column names for PK @param bool $autoIncrement Whether the table has an autoincrement column @return string
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Database/AbstractDatabase.php#L893-L899
hschletz/NADA
src/Database/AbstractDatabase.php
AbstractDatabase.dropTable
public function dropTable($name) { $this->exec('DROP TABLE ' . $this->prepareIdentifier($name)); $this->clearCache($name); }
php
public function dropTable($name) { $this->exec('DROP TABLE ' . $this->prepareIdentifier($name)); $this->clearCache($name); }
Drop a table @param string $name Table name
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Database/AbstractDatabase.php#L906-L910
geoffadams/bedrest-core
library/BedRest/Mapping/Driver/AbstractAnnotationDriver.php
AbstractAnnotationDriver.indexAnnotationsByType
protected function indexAnnotationsByType(array $annotations) { $indexed = array(); // if we are receiving annotations indexed by number, transform it to by class name if ($annotations && is_numeric(key($annotations))) { foreach ($annotations as $annotation) { $annotationType = get_class($annotation); if (isset($indexed[$annotationType]) && !is_array($indexed[$annotationType])) { $indexed[$annotationType] = array($indexed[$annotationType], $annotation); } elseif (isset($indexed[$annotationType])) { $indexed[$annotationType][] = $annotation; } else { $indexed[$annotationType] = $annotation; } } } return $indexed; }
php
protected function indexAnnotationsByType(array $annotations) { $indexed = array(); // if we are receiving annotations indexed by number, transform it to by class name if ($annotations && is_numeric(key($annotations))) { foreach ($annotations as $annotation) { $annotationType = get_class($annotation); if (isset($indexed[$annotationType]) && !is_array($indexed[$annotationType])) { $indexed[$annotationType] = array($indexed[$annotationType], $annotation); } elseif (isset($indexed[$annotationType])) { $indexed[$annotationType][] = $annotation; } else { $indexed[$annotationType] = $annotation; } } } return $indexed; }
Indexes a numerically-indexed array of annotation instances by their class names. @param array $annotations @return array
https://github.com/geoffadams/bedrest-core/blob/a77bf8b7492dfbfb720b201f7ec91a4f03417b5c/library/BedRest/Mapping/Driver/AbstractAnnotationDriver.php#L56-L76
johnkrovitch/Sam
Filter/FilterBuilder.php
FilterBuilder.build
public function build(array $filterConfigurations) { $resolver = new OptionsResolver(); $filters = []; foreach ($filterConfigurations as $filterName => $filterConfiguration) { $resolver->clear(); if ($filterConfiguration === null) { $filterConfiguration = []; } $configuration = $this->getFilterConfiguration($filterName); $configuration->configureOptions($resolver); $configuration->setParameters($resolver->resolve($filterConfiguration)); $class = $this->mapping[$filterName]; /** @var FilterInterface $filter */ $filter = new $class( // filter's name $filterName, // filter's configuration $configuration, // event dispatcher $this->eventDispatcher ); $filter->checkRequirements(); $filters[$filterName] = $filter; } return $filters; }
php
public function build(array $filterConfigurations) { $resolver = new OptionsResolver(); $filters = []; foreach ($filterConfigurations as $filterName => $filterConfiguration) { $resolver->clear(); if ($filterConfiguration === null) { $filterConfiguration = []; } $configuration = $this->getFilterConfiguration($filterName); $configuration->configureOptions($resolver); $configuration->setParameters($resolver->resolve($filterConfiguration)); $class = $this->mapping[$filterName]; /** @var FilterInterface $filter */ $filter = new $class( // filter's name $filterName, // filter's configuration $configuration, // event dispatcher $this->eventDispatcher ); $filter->checkRequirements(); $filters[$filterName] = $filter; } return $filters; }
Build the filter with the given configuration. @param array $filterConfigurations @return FilterInterface[] @throws Exception
https://github.com/johnkrovitch/Sam/blob/fbd3770c11eecc0a6d8070f439f149062316f606/Filter/FilterBuilder.php#L54-L86
johnkrovitch/Sam
Filter/FilterBuilder.php
FilterBuilder.getFilterConfiguration
protected function getFilterConfiguration($filter) { if (!array_key_exists($filter, $this->mapping)) { throw new Exception($filter.' filter not found in assets mapping. Check your configuration'); } $class = $this->mapping[$filter].'Configuration'; if (!class_exists($class)) { throw new Exception($class.' filter configuration class not found'); } $configuration = new $class(); if (!($configuration instanceof ConfigurationInterface)) { throw new Exception(get_class($configuration).' should be an instance of '.ConfigurationInterface::class); } return $configuration; }
php
protected function getFilterConfiguration($filter) { if (!array_key_exists($filter, $this->mapping)) { throw new Exception($filter.' filter not found in assets mapping. Check your configuration'); } $class = $this->mapping[$filter].'Configuration'; if (!class_exists($class)) { throw new Exception($class.' filter configuration class not found'); } $configuration = new $class(); if (!($configuration instanceof ConfigurationInterface)) { throw new Exception(get_class($configuration).' should be an instance of '.ConfigurationInterface::class); } return $configuration; }
Return filter configuration instance using the configured mapping. @param $filter @return ConfigurationInterface @throws Exception
https://github.com/johnkrovitch/Sam/blob/fbd3770c11eecc0a6d8070f439f149062316f606/Filter/FilterBuilder.php#L95-L112
codeinchq/psr7-responses
src/JsonResponse.php
JsonResponse.getDecodedJson
public function getDecodedJson():array { if (!($array = json_decode($this->json, true))) { throw new \RuntimeException("Unable to decode the response's JSON"); } return json_decode($this->json, true); }
php
public function getDecodedJson():array { if (!($array = json_decode($this->json, true))) { throw new \RuntimeException("Unable to decode the response's JSON"); } return json_decode($this->json, true); }
Returns the decoded JSON string. @uses json_decode() @return array
https://github.com/codeinchq/psr7-responses/blob/d4bb6bc9b4219694e7c1f5ee9b40b75b22362fce/src/JsonResponse.php#L113-L119
DreadLabs/VantomasWebsite
src/ThreatDefense/ReCaptchaResponse.php
ReCaptchaResponse.fromString
public static function fromString($string) { if (is_null($string) || empty($string) || !is_string($string)) { throw new \InvalidArgumentException('The given ReCaptcha response data is invalid.', 1452283305); } $value = (string) $string; $value = filter_var( $value, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH | !FILTER_FLAG_ENCODE_LOW | !FILTER_FLAG_ENCODE_HIGH | FILTER_FLAG_NO_ENCODE_QUOTES ); $value = trim($value); return new static($value); }
php
public static function fromString($string) { if (is_null($string) || empty($string) || !is_string($string)) { throw new \InvalidArgumentException('The given ReCaptcha response data is invalid.', 1452283305); } $value = (string) $string; $value = filter_var( $value, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH | !FILTER_FLAG_ENCODE_LOW | !FILTER_FLAG_ENCODE_HIGH | FILTER_FLAG_NO_ENCODE_QUOTES ); $value = trim($value); return new static($value); }
Creates the ReCaptchaResponse data object @param string $string The value @return self @throws \InvalidArgumentException
https://github.com/DreadLabs/VantomasWebsite/blob/7f85f2b45bdf5ed9fa9d320c805c416bf99cd668/src/ThreatDefense/ReCaptchaResponse.php#L48-L69
buflix/SimpleCollection
src/SimpleCollection/Entity/AbstractEntity.php
AbstractEntity.toArray
public function toArray() { $aReturn = array(); foreach (get_object_vars($this) as $sKey => $mValue) { if (is_object($mValue) and true === method_exists($mValue, 'toArray')) { $aReturn[$sKey] = $mValue->toArray(); } else { $aReturn[$sKey] = $mValue; } } return $aReturn; }
php
public function toArray() { $aReturn = array(); foreach (get_object_vars($this) as $sKey => $mValue) { if (is_object($mValue) and true === method_exists($mValue, 'toArray')) { $aReturn[$sKey] = $mValue->toArray(); } else { $aReturn[$sKey] = $mValue; } } return $aReturn; }
return this entity as array @see EntityInterface::toArray @return array
https://github.com/buflix/SimpleCollection/blob/405504d8be6415a872a5a49ce8223c22a932831a/src/SimpleCollection/Entity/AbstractEntity.php#L19-L32
deesoft/yii2-rest
TransactionTrait.php
TransactionTrait.beginTransaction
protected function beginTransaction() { $modelClass = $this->modelClass; $transaction = $modelClass::getDb()->beginTransaction(); $this->_transaction[] = $transaction; }
php
protected function beginTransaction() { $modelClass = $this->modelClass; $transaction = $modelClass::getDb()->beginTransaction(); $this->_transaction[] = $transaction; }
Begins a transaction.
https://github.com/deesoft/yii2-rest/blob/c33f145fbfa2bc138dffdd2f9408a2a461153128/TransactionTrait.php#L24-L30
deesoft/yii2-rest
TransactionTrait.php
TransactionTrait.commit
protected function commit() { $transaction = array_pop($this->_transaction); if ($transaction && $transaction instanceof Transaction) { $transaction->commit(); } }
php
protected function commit() { $transaction = array_pop($this->_transaction); if ($transaction && $transaction instanceof Transaction) { $transaction->commit(); } }
Commits a transaction. @throws Exception if the transaction is not active
https://github.com/deesoft/yii2-rest/blob/c33f145fbfa2bc138dffdd2f9408a2a461153128/TransactionTrait.php#L36-L42
deesoft/yii2-rest
TransactionTrait.php
TransactionTrait.rollback
protected function rollback() { $transaction = array_pop($this->_transaction); if ($transaction && $transaction instanceof Transaction) { $transaction->rollBack(); } }
php
protected function rollback() { $transaction = array_pop($this->_transaction); if ($transaction && $transaction instanceof Transaction) { $transaction->rollBack(); } }
Rolls back a transaction. @throws Exception if the transaction is not active
https://github.com/deesoft/yii2-rest/blob/c33f145fbfa2bc138dffdd2f9408a2a461153128/TransactionTrait.php#L48-L54
intpro/seo
src/Db/SeoJoiner.php
SeoJoiner.joinByField
public function joinByField(Field $field, $join_array) { $fieldType = $field->getFieldType(); $type_name = $fieldType->getName(); $field_name = $field->getName(); if($type_name !== 'seo') { throw new SeoException('Seo не обрабатывает тип '.$type_name); } $join_q = new QueryBuilder(DB::table('seos')); $join_q->select(['seos.entity_name', 'seos.entity_id', 'seos.value as '.$join_array['full_field_names'][0]]); $join_q->whereRaw('seos.name = "'.$field_name.'"'); return $join_q; }
php
public function joinByField(Field $field, $join_array) { $fieldType = $field->getFieldType(); $type_name = $fieldType->getName(); $field_name = $field->getName(); if($type_name !== 'seo') { throw new SeoException('Seo не обрабатывает тип '.$type_name); } $join_q = new QueryBuilder(DB::table('seos')); $join_q->select(['seos.entity_name', 'seos.entity_id', 'seos.value as '.$join_array['full_field_names'][0]]); $join_q->whereRaw('seos.name = "'.$field_name.'"'); return $join_q; }
@param \Interpro\Core\Contracts\Taxonomy\Fields\Field $field @param array $join_array @return \Interpro\Extractor\Db\QueryBuilder
https://github.com/intpro/seo/blob/5e114d50bf8a2643c4e232cb0484bc5b5e44f375/src/Db/SeoJoiner.php#L26-L43
locomotivemtl/charcoal-factory
src/Charcoal/Factory/GenericResolver.php
GenericResolver.resolve
public function resolve($type) { if (!is_string($type)) { throw new InvalidArgumentException( 'Can not resolve class ident: type must be a string' ); } // Normalize requested type with prefix / suffix, if applicable. $type = $this->prefix.$type.$this->suffix; $capitalizeNext = function(&$i) { $i = ucfirst($i); }; $capitals = $this->capitals; foreach ($capitals as $cap) { $expl = explode($cap, $type); array_walk($expl, $capitalizeNext); $type = implode($cap, $expl); } $replacements = $this->replacements; foreach ($replacements as $rep => $target) { $type = str_replace($rep, $target, $type); } $class = '\\'.trim($type, '\\'); return $class; }
php
public function resolve($type) { if (!is_string($type)) { throw new InvalidArgumentException( 'Can not resolve class ident: type must be a string' ); } // Normalize requested type with prefix / suffix, if applicable. $type = $this->prefix.$type.$this->suffix; $capitalizeNext = function(&$i) { $i = ucfirst($i); }; $capitals = $this->capitals; foreach ($capitals as $cap) { $expl = explode($cap, $type); array_walk($expl, $capitalizeNext); $type = implode($cap, $expl); } $replacements = $this->replacements; foreach ($replacements as $rep => $target) { $type = str_replace($rep, $target, $type); } $class = '\\'.trim($type, '\\'); return $class; }
Resolve the class name from the requested type. @param string $type The "type" of object to resolve (the object ident). @throws InvalidArgumentException If the type parameter is not a string. @return string The resolved class name (FQN).
https://github.com/locomotivemtl/charcoal-factory/blob/c64d40e1e39ef987a0bd0ad0e22379f55acf8f92/src/Charcoal/Factory/GenericResolver.php#L83-L113
Vectrex/vxPHP
src/Form/FormElement/FormElementFactory.php
FormElementFactory.create
public static function create($type, $name, $value = null, array $attributes = [], array $options = [], $required = false, array $modifiers = [], array $validators = [], $validationErrorMessage = null) { $type = strtolower($type); if(is_array($value) && $type !== 'multipleselect') { $elem = self::createSingleElement($type, $name, null, $attributes, $options, $required, $modifiers, $validators, $validationErrorMessage); $elements = []; foreach($value as $k => $v) { $e = clone $elem; $e ->setName(sprintf('%s[%s]', $name, $k)) ->setValue($v) ; $elements[$k] = $e; } unset($elem); return $elements; } else { return self::createSingleElement($type, $name, $value, $attributes, $options, $required, $modifiers, $validators, $validationErrorMessage); } }
php
public static function create($type, $name, $value = null, array $attributes = [], array $options = [], $required = false, array $modifiers = [], array $validators = [], $validationErrorMessage = null) { $type = strtolower($type); if(is_array($value) && $type !== 'multipleselect') { $elem = self::createSingleElement($type, $name, null, $attributes, $options, $required, $modifiers, $validators, $validationErrorMessage); $elements = []; foreach($value as $k => $v) { $e = clone $elem; $e ->setName(sprintf('%s[%s]', $name, $k)) ->setValue($v) ; $elements[$k] = $e; } unset($elem); return $elements; } else { return self::createSingleElement($type, $name, $value, $attributes, $options, $required, $modifiers, $validators, $validationErrorMessage); } }
create either single FormElement or array of FormElements @param string $type , type of element @param string $name , name of element @param mixed $value @param array $attributes @param array $options , array for initializing SelectOptionElements or RadioOptionElements @param boolean $required @param array $modifiers @param array $validators @param string $validationErrorMessage @return FormElement | FormElement[] @throws FormElementFactoryException
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/FormElement/FormElementFactory.php#L47-L72
Vectrex/vxPHP
src/Form/FormElement/FormElementFactory.php
FormElementFactory.createSingleElement
private static function createSingleElement($type, $name, $value, $attributes, $options, $required, $modifiers, $validators, $validationErrorMessage) { switch($type) { case 'input': $elem = new InputElement($name); break; case 'file': $elem = new FileInputElement($name); break; case 'password': $elem = new PasswordInputElement($name); break; case 'submit': $elem = new SubmitInputElement($name); break; case 'checkbox': $elem = new CheckboxElement($name); break; case 'textarea': $elem = new TextareaElement($name); break; case 'image': $elem = new ImageElement($name); break; case 'button': $elem = new ButtonElement($name); if(isset($attributes['type'])) { $elem->setType($attributes['type']); } break; case 'select': $elem = new SelectElement($name); $elem->createOptions($options); break; case 'radio': $elem = new RadioElement($name); $elem->createOptions($options); break; case 'multipleselect': $elem = new MultipleSelectElement($name); $elem->createOptions($options); break; default: throw new FormElementFactoryException(sprintf("Unknown form element '%s''", $type)); } $elem ->setAttributes($attributes) ->setRequired($required) ->setValidationErrorMessage($validationErrorMessage) ; foreach($modifiers as $modifier) { $elem->addModifier($modifier); } foreach($validators as $validator) { $elem->addValidator($validator); } $elem->setValue($value); return $elem; }
php
private static function createSingleElement($type, $name, $value, $attributes, $options, $required, $modifiers, $validators, $validationErrorMessage) { switch($type) { case 'input': $elem = new InputElement($name); break; case 'file': $elem = new FileInputElement($name); break; case 'password': $elem = new PasswordInputElement($name); break; case 'submit': $elem = new SubmitInputElement($name); break; case 'checkbox': $elem = new CheckboxElement($name); break; case 'textarea': $elem = new TextareaElement($name); break; case 'image': $elem = new ImageElement($name); break; case 'button': $elem = new ButtonElement($name); if(isset($attributes['type'])) { $elem->setType($attributes['type']); } break; case 'select': $elem = new SelectElement($name); $elem->createOptions($options); break; case 'radio': $elem = new RadioElement($name); $elem->createOptions($options); break; case 'multipleselect': $elem = new MultipleSelectElement($name); $elem->createOptions($options); break; default: throw new FormElementFactoryException(sprintf("Unknown form element '%s''", $type)); } $elem ->setAttributes($attributes) ->setRequired($required) ->setValidationErrorMessage($validationErrorMessage) ; foreach($modifiers as $modifier) { $elem->addModifier($modifier); } foreach($validators as $validator) { $elem->addValidator($validator); } $elem->setValue($value); return $elem; }
generate a single form element @param $type @param $name @param $value @param $attributes @param $options @param $required @param $modifiers @param $validators @param $validationErrorMessage @return ButtonElement|CheckboxElement|ImageElement|InputElement|PasswordInputElement|SubmitInputElement|TextareaElement @throws FormElementFactoryException
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/FormElement/FormElementFactory.php#L90-L164
anime-db/shikimori-related-items-widget-bundle
src/Controller/WidgetController.php
WidgetController.indexAction
public function indexAction(Item $item, Request $request) { /* @var $response \Symfony\Component\HttpFoundation\Response */ $response = $this->get('cache_time_keeper')->getResponse($item->getDateUpdate(), self::CACHE_LIFETIME); /* @var $widget \AnimeDb\Bundle\ShikimoriWidgetBundle\Service\Widget */ $widget = $this->get('anime_db.shikimori.widget'); // get shikimori item id if (!($item_id = $widget->getItemId($item))) { return $response; } $list = $this->get('anime_db.shikimori.browser') ->get(str_replace('#ID#', $item_id, self::PATH_RELATED_ITEMS)); $list = $this->filter($list); $response->setEtag($this->hash($list)); // response was not modified for this request if ($response->isNotModified($request) || !$list) { return $response; } // build list item entities foreach ($list as $key => $item) { $list[$key] = $widget->getWidgetItem($widget->getItem($item['anime']['id'])); // add relation if (substr($this->container->getParameter('locale'), 0, 2) == 'ru') { $list[$key]->setName($list[$key]->getName().' ('.$item['relation_russian'].')'); } else { $list[$key]->setName($list[$key]->getName().' ('.$item['relation'].')'); } } return $this->render( 'AnimeDbShikimoriRelatedItemsWidgetBundle:Widget:index.html.twig', ['items' => $list], $response ); }
php
public function indexAction(Item $item, Request $request) { /* @var $response \Symfony\Component\HttpFoundation\Response */ $response = $this->get('cache_time_keeper')->getResponse($item->getDateUpdate(), self::CACHE_LIFETIME); /* @var $widget \AnimeDb\Bundle\ShikimoriWidgetBundle\Service\Widget */ $widget = $this->get('anime_db.shikimori.widget'); // get shikimori item id if (!($item_id = $widget->getItemId($item))) { return $response; } $list = $this->get('anime_db.shikimori.browser') ->get(str_replace('#ID#', $item_id, self::PATH_RELATED_ITEMS)); $list = $this->filter($list); $response->setEtag($this->hash($list)); // response was not modified for this request if ($response->isNotModified($request) || !$list) { return $response; } // build list item entities foreach ($list as $key => $item) { $list[$key] = $widget->getWidgetItem($widget->getItem($item['anime']['id'])); // add relation if (substr($this->container->getParameter('locale'), 0, 2) == 'ru') { $list[$key]->setName($list[$key]->getName().' ('.$item['relation_russian'].')'); } else { $list[$key]->setName($list[$key]->getName().' ('.$item['relation'].')'); } } return $this->render( 'AnimeDbShikimoriRelatedItemsWidgetBundle:Widget:index.html.twig', ['items' => $list], $response ); }
New items @param \AnimeDb\Bundle\CatalogBundle\Entity\Item $item @param \Symfony\Component\HttpFoundation\Request $request @return \Symfony\Component\HttpFoundation\Response
https://github.com/anime-db/shikimori-related-items-widget-bundle/blob/ee77d08513efe0f099790ef899ba6080a11abdb3/src/Controller/WidgetController.php#L47-L85
anime-db/shikimori-related-items-widget-bundle
src/Controller/WidgetController.php
WidgetController.filter
protected function filter(array $list) { $tmp = []; foreach ($list as $item) { if ($item['anime']) { $tmp[] = $item; } } return $tmp; }
php
protected function filter(array $list) { $tmp = []; foreach ($list as $item) { if ($item['anime']) { $tmp[] = $item; } } return $tmp; }
Filter a list items @param array $list @return array
https://github.com/anime-db/shikimori-related-items-widget-bundle/blob/ee77d08513efe0f099790ef899ba6080a11abdb3/src/Controller/WidgetController.php#L94-L103
fardus/CRUDBundle
Fardus/Bundle/CrudBundle/Controller/ApiController.php
ApiController.deleteAction
public function deleteAction($entity, $id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository($entity)->find($id); if (!$entity) { throw $this->createNotFoundException("Unable to find $entity entity."); } $em->remove($entity); $em->flush(); $this->get('session')->getFlashBag()->add( 'success', 'The Post has been removed.'); $content = json_encode(array( 'status' => 'deleted', )); $response = new Response($content, 200); return $response; }
php
public function deleteAction($entity, $id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository($entity)->find($id); if (!$entity) { throw $this->createNotFoundException("Unable to find $entity entity."); } $em->remove($entity); $em->flush(); $this->get('session')->getFlashBag()->add( 'success', 'The Post has been removed.'); $content = json_encode(array( 'status' => 'deleted', )); $response = new Response($content, 200); return $response; }
Delete any entity. @param string $entity @param int $id @return Response @throws NotFoundHttpException
https://github.com/fardus/CRUDBundle/blob/5d4180f2a1f30da0fc4cbb16a70f656e9e083c5c/Fardus/Bundle/CrudBundle/Controller/ApiController.php#L24-L46
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.FromFloat
public static function FromFloat( $value, $detail = true ) { if ( $value instanceof XPath2Item ) { $value = $value->getTypedValue(); } if ( $value instanceof DecimalValue ) return $value; if ( ( ! is_numeric( $value ) ) || is_infinite( $value ) || is_nan( $value ) ) { throw XPath2Exception::withErrorCodeAndParams( "FOCA0002", Resources::FOCA0002, array( $value, "Decimal" ) ); } $matched = preg_match( DecimalValue::Pattern, $detail ? sprintf( "%.018g", $value ) : $value, $matches ); if ( ! $matched ) { throw new \InvalidArgumentException( "The number '$value' cannot be parsed" ); } $sign = isset( $matches['sign'] ) && $matches['sign'] == '-' ? "-" : ""; $digits = isset( $matches['digits'] ) ? $matches['digits'] : "0"; $decimals = isset( $matches['decimals'] ) ? "." . $matches['decimals'] : ""; $exponent = isset( $matches['exponent'] ) ? $matches['exponent'] + 0 : false; $factor = str_pad( "1", abs( $exponent ) + 1, "0", STR_PAD_RIGHT ); $decimal = new DecimalValue( "$sign$digits$decimals" ); if ( $exponent ) { if ( $exponent > 0 ) { $result = $decimal->Mul( $factor ); } else if ( $exponent && $exponent < 0 ) { $result = $decimal->Div( $factor ); } $decimal = $result; } return $decimal; }
php
public static function FromFloat( $value, $detail = true ) { if ( $value instanceof XPath2Item ) { $value = $value->getTypedValue(); } if ( $value instanceof DecimalValue ) return $value; if ( ( ! is_numeric( $value ) ) || is_infinite( $value ) || is_nan( $value ) ) { throw XPath2Exception::withErrorCodeAndParams( "FOCA0002", Resources::FOCA0002, array( $value, "Decimal" ) ); } $matched = preg_match( DecimalValue::Pattern, $detail ? sprintf( "%.018g", $value ) : $value, $matches ); if ( ! $matched ) { throw new \InvalidArgumentException( "The number '$value' cannot be parsed" ); } $sign = isset( $matches['sign'] ) && $matches['sign'] == '-' ? "-" : ""; $digits = isset( $matches['digits'] ) ? $matches['digits'] : "0"; $decimals = isset( $matches['decimals'] ) ? "." . $matches['decimals'] : ""; $exponent = isset( $matches['exponent'] ) ? $matches['exponent'] + 0 : false; $factor = str_pad( "1", abs( $exponent ) + 1, "0", STR_PAD_RIGHT ); $decimal = new DecimalValue( "$sign$digits$decimals" ); if ( $exponent ) { if ( $exponent > 0 ) { $result = $decimal->Mul( $factor ); } else if ( $exponent && $exponent < 0 ) { $result = $decimal->Div( $factor ); } $decimal = $result; } return $decimal; }
Creates an instance from a Float value @param float $value @param bool $detail (optional: default = true) Expand the number to the most digits
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L159-L199
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.Compare
public function Compare( $number, $scale = false ) { if ( ! is_numeric( $number ) ) { if ( ! $number instanceof DecimalValue && ! $number instanceof Integer ) { return false; } $number = $number->getValue(); } if ( $scale === false ) { $scale = max( $this->getScale(), $this->scale( $number ) ); } return bccomp( $this->_value, $number, $scale ); }
php
public function Compare( $number, $scale = false ) { if ( ! is_numeric( $number ) ) { if ( ! $number instanceof DecimalValue && ! $number instanceof Integer ) { return false; } $number = $number->getValue(); } if ( $scale === false ) { $scale = max( $this->getScale(), $this->scale( $number ) ); } return bccomp( $this->_value, $number, $scale ); }
Compares this number with another number @param string $number @param int $scale @return int 0 if the number is the same as this number, 1 if this number is larger than the supplied number, -1 otherwise.
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L253-L271
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.Equals
public function Equals( $number, $scale = false ) { $result = $this->Compare( $number, $scale ); if ( $result === false ) return false; return $result == 0; }
php
public function Equals( $number, $scale = false ) { $result = $this->Compare( $number, $scale ); if ( $result === false ) return false; return $result == 0; }
Equals @param object $number @param int $scale @return bool
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L279-L284
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.Gt
public function Gt( $number, $scale = false ) { $result = $this->Compare( $number, $scale ); if ( $result === false ) return false; return $result == 1; }
php
public function Gt( $number, $scale = false ) { $result = $this->Compare( $number, $scale ); if ( $result === false ) return false; return $result == 1; }
Greater than @param object $number @param int $scale @return bool
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L292-L297
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.Add
public function Add( $val ) { $value = $val instanceof DecimalValue ? $val : Convert::ToDecimal( $val ); return new DecimalValue( bcadd( $this->_value, $value->getValue(), max( $this->getScale(), $this->scale( $value ) ) ) ); }
php
public function Add( $val ) { $value = $val instanceof DecimalValue ? $val : Convert::ToDecimal( $val ); return new DecimalValue( bcadd( $this->_value, $value->getValue(), max( $this->getScale(), $this->scale( $value ) ) ) ); }
Add @param ValueProxy $val @return DecimalValue
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L313-L317
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.Sub
public function Sub( $val ) { $value = $val instanceof DecimalValue ? $val : Convert::ToDecimal( $val ); return new DecimalValue( bcsub( $this->_value, $value->getValue(), max( $this->getScale(), $this->scale( $value ) ) ) ); }
php
public function Sub( $val ) { $value = $val instanceof DecimalValue ? $val : Convert::ToDecimal( $val ); return new DecimalValue( bcsub( $this->_value, $value->getValue(), max( $this->getScale(), $this->scale( $value ) ) ) ); }
Sub @param ValueProxy $val @return DecimalValue
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L324-L328