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
wdbo/webdocbook
src/WebDocBook/HttpFundamental/Response.php
Response.send
public function send($content = null, $type = null) { if (!is_null($content)) { $this->setContents(is_array($content) ? $content : array($content)); } if (!is_null($type)) { $this->setContentType($type); } return parent::send(); }
php
public function send($content = null, $type = null) { if (!is_null($content)) { $this->setContents(is_array($content) ? $content : array($content)); } if (!is_null($type)) { $this->setContentType($type); } return parent::send(); }
Send the response to the device @param null $content @param null $type @return mixed
https://github.com/wdbo/webdocbook/blob/7d4e806f674b6222c9a3e85bfed34e72bc9d584e/src/WebDocBook/HttpFundamental/Response.php#L56-L65
wdbo/webdocbook
src/WebDocBook/HttpFundamental/Response.php
Response.redirect
public function redirect($pathinfo, $hash = null) { $uri = is_string($pathinfo) ? $pathinfo : $this->generateUrl($pathinfo); if (!headers_sent()) { header("Location: $uri"); } else { echo <<<MESSAGE <!DOCTYPE HTML> <head> <meta http-equiv='Refresh' content='0; url={$uri}'><title>HTTP 302</title> </head><body> <h1>HTTP 302</h1> <p>Your browser will be automatically redirected. <br />If not, please click on next link: <a href="{$uri}">{$uri}</a>.</p> </body></html> MESSAGE; } exit; }
php
public function redirect($pathinfo, $hash = null) { $uri = is_string($pathinfo) ? $pathinfo : $this->generateUrl($pathinfo); if (!headers_sent()) { header("Location: $uri"); } else { echo <<<MESSAGE <!DOCTYPE HTML> <head> <meta http-equiv='Refresh' content='0; url={$uri}'><title>HTTP 302</title> </head><body> <h1>HTTP 302</h1> <p>Your browser will be automatically redirected. <br />If not, please click on next link: <a href="{$uri}">{$uri}</a>.</p> </body></html> MESSAGE; } exit; }
Make a redirection to a new route (HTTP redirect) @param mixed $pathinfo The path information to redirect to @param string $hash A hash tag to add to the generated URL
https://github.com/wdbo/webdocbook/blob/7d4e806f674b6222c9a3e85bfed34e72bc9d584e/src/WebDocBook/HttpFundamental/Response.php#L72-L90
philipbrown/money
src/Money.php
Money.equals
public function equals(Money $money) { return $this->isSameCurrency($money) && $this->cents == $money->cents; }
php
public function equals(Money $money) { return $this->isSameCurrency($money) && $this->cents == $money->cents; }
Check the equality of two Money objects. First check the currency and then check the value. @param PhilipBrown\Money\Money @return bool
https://github.com/philipbrown/money/blob/2ba3a1e4b52869f8696384a5033459708f25c109/src/Money.php#L86-L89
philipbrown/money
src/Money.php
Money.add
public function add(Money $money) { if($this->isSameCurrency($money)) { return Money::init($this->cents + $money->cents, $this->currency->getIsoCode()); } throw new InvalidCurrencyException("You can't add two Money objects with different currencies"); }
php
public function add(Money $money) { if($this->isSameCurrency($money)) { return Money::init($this->cents + $money->cents, $this->currency->getIsoCode()); } throw new InvalidCurrencyException("You can't add two Money objects with different currencies"); }
Add two the value of two Money objects and return a new Money object. @param PhilipBrown\Money\Money $money @return PhilipBrown\Money\Money
https://github.com/philipbrown/money/blob/2ba3a1e4b52869f8696384a5033459708f25c109/src/Money.php#L97-L105
philipbrown/money
src/Money.php
Money.multiply
public function multiply($number) { return Money::init((int) round($this->cents * $number, 0, PHP_ROUND_HALF_EVEN), $this->currency->getIsoCode()); }
php
public function multiply($number) { return Money::init((int) round($this->cents * $number, 0, PHP_ROUND_HALF_EVEN), $this->currency->getIsoCode()); }
Multiply two Money objects together and return a new Money object @param int $number @return PhilipBrown\Money\Money
https://github.com/philipbrown/money/blob/2ba3a1e4b52869f8696384a5033459708f25c109/src/Money.php#L129-L132
ZhukV/LanguageDetector
src/Ideea/LanguageDetector/LanguageDetector.php
LanguageDetector.addVisitor
public function addVisitor(VisitorInterface $visitor, $priority = 0) { $this->sortedVisitors = null; $this->visitors[spl_object_hash($visitor)] = array( 'priority' => $priority, 'visitor' => $visitor ); return $this; }
php
public function addVisitor(VisitorInterface $visitor, $priority = 0) { $this->sortedVisitors = null; $this->visitors[spl_object_hash($visitor)] = array( 'priority' => $priority, 'visitor' => $visitor ); return $this; }
Add detection visitor @param VisitorInterface $visitor @param int $priority @return LanguageDetector
https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/LanguageDetector.php#L46-L56
ZhukV/LanguageDetector
src/Ideea/LanguageDetector/LanguageDetector.php
LanguageDetector.detect
public function detect($string) { // Remove special chars $codes = Unicode::ordStr($string); $languages = new Languages(); foreach ($this->getVisitors() as $visitor) { $visitor->visit($string, $codes, $languages); } return $languages; }
php
public function detect($string) { // Remove special chars $codes = Unicode::ordStr($string); $languages = new Languages(); foreach ($this->getVisitors() as $visitor) { $visitor->visit($string, $codes, $languages); } return $languages; }
Detect languages @param string $string @return Languages
https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/LanguageDetector.php#L77-L89
ZhukV/LanguageDetector
src/Ideea/LanguageDetector/LanguageDetector.php
LanguageDetector.sortVisitors
private function sortVisitors() { if (null !== $this->sortedVisitors) { // Visitors already sorted return; } uasort($this->visitors, function ($a, $b) { if ($a['priority'] == $b['priority']) { return 0; } return $a['priority'] > $b['priority'] ? 1 : 0; }); $this->sortedVisitors = array(); foreach ($this->visitors as $visitorItem) { $this->sortedVisitors[] = $visitorItem['visitor']; } }
php
private function sortVisitors() { if (null !== $this->sortedVisitors) { // Visitors already sorted return; } uasort($this->visitors, function ($a, $b) { if ($a['priority'] == $b['priority']) { return 0; } return $a['priority'] > $b['priority'] ? 1 : 0; }); $this->sortedVisitors = array(); foreach ($this->visitors as $visitorItem) { $this->sortedVisitors[] = $visitorItem['visitor']; } }
Sort visitors
https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/LanguageDetector.php#L94-L114
ZhukV/LanguageDetector
src/Ideea/LanguageDetector/LanguageDetector.php
LanguageDetector.createDefault
public static function createDefault(DictionaryInterface $dictionary = null) { /** @var LanguageDetector $detector */ $detector = new static(); $dataDirectory = realpath(__DIR__ . '/../../../data'); $alphabetLoader = new AlphabetLoader(); $sectionLoader = new SectionLoader(); $sections = $sectionLoader->load($dataDirectory . '/sections.yml'); $alphabets = $alphabetLoader->load($dataDirectory . '/alphabets.yml'); $detector ->addVisitor(new SectionVisitor($sections), -1024) ->addVisitor(new AlphabetVisitor($alphabets), -512); if ($dictionary) { $detector->addVisitor(new DictionaryVisitor($dictionary), -256); } return $detector; }
php
public static function createDefault(DictionaryInterface $dictionary = null) { /** @var LanguageDetector $detector */ $detector = new static(); $dataDirectory = realpath(__DIR__ . '/../../../data'); $alphabetLoader = new AlphabetLoader(); $sectionLoader = new SectionLoader(); $sections = $sectionLoader->load($dataDirectory . '/sections.yml'); $alphabets = $alphabetLoader->load($dataDirectory . '/alphabets.yml'); $detector ->addVisitor(new SectionVisitor($sections), -1024) ->addVisitor(new AlphabetVisitor($alphabets), -512); if ($dictionary) { $detector->addVisitor(new DictionaryVisitor($dictionary), -256); } return $detector; }
Create default detector @param DictionaryInterface $dictionary @return LanguageDetector
https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/LanguageDetector.php#L123-L145
ekyna/AdminBundle
EventListener/ORMTranslatableListener.php
ORMTranslatableListener.mapTranslatable
private function mapTranslatable(ClassMetadata $metadata) { // In the case A -> B -> TranslatableInterface, B might not have mapping defined as it // is probably defined in A, so in that case, we just return. if (!isset($this->configs[$metadata->name])) { return; } $metadata->mapOneToMany([ 'fieldName' => 'translations', 'targetEntity' => $this->configs[$metadata->name], 'mappedBy' => 'translatable', 'fetch' => ClassMetadataInfo::FETCH_EXTRA_LAZY, 'indexBy' => 'locale', 'cascade' => ['persist', 'merge', 'refresh', 'remove'], 'orphanRemoval' => true, ]); }
php
private function mapTranslatable(ClassMetadata $metadata) { // In the case A -> B -> TranslatableInterface, B might not have mapping defined as it // is probably defined in A, so in that case, we just return. if (!isset($this->configs[$metadata->name])) { return; } $metadata->mapOneToMany([ 'fieldName' => 'translations', 'targetEntity' => $this->configs[$metadata->name], 'mappedBy' => 'translatable', 'fetch' => ClassMetadataInfo::FETCH_EXTRA_LAZY, 'indexBy' => 'locale', 'cascade' => ['persist', 'merge', 'refresh', 'remove'], 'orphanRemoval' => true, ]); }
Add mapping data to a translatable entity. @param ClassMetadata $metadata
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/EventListener/ORMTranslatableListener.php#L60-L77
ekyna/AdminBundle
EventListener/ORMTranslatableListener.php
ORMTranslatableListener.mapTranslation
private function mapTranslation(ClassMetadata $metadata) { // In the case A -> B -> TranslationInterface, B might not have mapping defined as it // is probably defined in A, so in that case, we just return. if (!isset($this->configs[$metadata->name])) { return; } $metadata->mapManyToOne([ 'fieldName' => 'translatable' , 'targetEntity' => $this->configs[$metadata->name], 'inversedBy' => 'translations' , 'joinColumns' => [[ 'name' => 'translatable_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE', 'nullable' => false, ]], ]); if (!$metadata->hasField('locale')) { $metadata->mapField([ 'fieldName' => 'locale', 'type' => 'string', 'nullable' => false, ]); } // Map unique index. $columns = [ $metadata->getSingleAssociationJoinColumnName('translatable'), 'locale' ]; if (!$this->hasUniqueConstraint($metadata, $columns)) { $constraints = isset($metadata->table['uniqueConstraints']) ? $metadata->table['uniqueConstraints'] : []; $constraints[$metadata->getTableName().'_uniq_trans'] = [ 'columns' => $columns, ]; $metadata->setPrimaryTable([ 'uniqueConstraints' => $constraints, ]); } }
php
private function mapTranslation(ClassMetadata $metadata) { // In the case A -> B -> TranslationInterface, B might not have mapping defined as it // is probably defined in A, so in that case, we just return. if (!isset($this->configs[$metadata->name])) { return; } $metadata->mapManyToOne([ 'fieldName' => 'translatable' , 'targetEntity' => $this->configs[$metadata->name], 'inversedBy' => 'translations' , 'joinColumns' => [[ 'name' => 'translatable_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE', 'nullable' => false, ]], ]); if (!$metadata->hasField('locale')) { $metadata->mapField([ 'fieldName' => 'locale', 'type' => 'string', 'nullable' => false, ]); } // Map unique index. $columns = [ $metadata->getSingleAssociationJoinColumnName('translatable'), 'locale' ]; if (!$this->hasUniqueConstraint($metadata, $columns)) { $constraints = isset($metadata->table['uniqueConstraints']) ? $metadata->table['uniqueConstraints'] : []; $constraints[$metadata->getTableName().'_uniq_trans'] = [ 'columns' => $columns, ]; $metadata->setPrimaryTable([ 'uniqueConstraints' => $constraints, ]); } }
Add mapping data to a translation entity. @param ClassMetadata $metadata
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/EventListener/ORMTranslatableListener.php#L84-L129
symm/guzzle-bitpay
src/Symm/BitpayClient/Model/CurrencyCollection.php
CurrencyCollection.fromCommand
public static function fromCommand(OperationCommand $command) { $response = $command->getResponse(); $json = $response->json(); $currencies = array(); foreach ($json as $currency) { $currencies[] = new Currency($currency['code'], $currency['name'], $currency['rate']); } return new self($currencies); }
php
public static function fromCommand(OperationCommand $command) { $response = $command->getResponse(); $json = $response->json(); $currencies = array(); foreach ($json as $currency) { $currencies[] = new Currency($currency['code'], $currency['name'], $currency['rate']); } return new self($currencies); }
Create a response model object from a completed command @param OperationCommand $command That serialized the request @return CurrencyCollection
https://github.com/symm/guzzle-bitpay/blob/a94f4d2b1ec9dd56f513bb8c5f5d67269173024f/src/Symm/BitpayClient/Model/CurrencyCollection.php#L43-L54
znframework/package-hypertext
Lists.php
Lists._element
protected function _element($data, $tab, $start) { static $start; $eof = EOL; $output = ''; $attrs = ''; $tab = str_repeat("\t", $start); if( ! is_array($data) ) { return $data.$eof; } else { foreach( $data as $k => $v ) { if( IS::realNumeric($k) ) { $value = $k; $k = 'li'; } else { $value = NULL; } $end = Base::prefix(Arrays\GetElement::first(explode(' ', $k))); if( ! is_array($v) ) { $output .= "$tab<$k>$v<$end>$eof"; } else { if( stripos($k, 'ul') !== 0 && stripos($k, 'ol') !== 0 && $k !== 'li' ) { $value = $k; $k = 'li'; $end = Base::prefix($k); } else { $value = NULL; } $output .= $tab."<$k>$value$eof".$this->_element($v, $tab, $start++).$tab."<$end>".$tab.$eof; $start--; } } } return $output; }
php
protected function _element($data, $tab, $start) { static $start; $eof = EOL; $output = ''; $attrs = ''; $tab = str_repeat("\t", $start); if( ! is_array($data) ) { return $data.$eof; } else { foreach( $data as $k => $v ) { if( IS::realNumeric($k) ) { $value = $k; $k = 'li'; } else { $value = NULL; } $end = Base::prefix(Arrays\GetElement::first(explode(' ', $k))); if( ! is_array($v) ) { $output .= "$tab<$k>$v<$end>$eof"; } else { if( stripos($k, 'ul') !== 0 && stripos($k, 'ol') !== 0 && $k !== 'li' ) { $value = $k; $k = 'li'; $end = Base::prefix($k); } else { $value = NULL; } $output .= $tab."<$k>$value$eof".$this->_element($v, $tab, $start++).$tab."<$end>".$tab.$eof; $start--; } } } return $output; }
--------------------------------------------------------------------------------------------------------
https://github.com/znframework/package-hypertext/blob/12bbc3bd47a2fae735f638a3e01cc82c1b9c9005/Lists.php#L40-L94
wigedev/farm
src/FormBuilder/FormElement/Checkboxgroup.php
Checkboxgroup.setDefaultValue
public function setDefaultValue($value) : FormElement { if (is_array($value)) { $value = implode(',', $value); } parent::setDefaultValue($value); return $this; }
php
public function setDefaultValue($value) : FormElement { if (is_array($value)) { $value = implode(',', $value); } parent::setDefaultValue($value); return $this; }
Sets the default or database value for the element. Overridden to convert arrays to strings. @param mixed $value The value of the form field. @return FormElement
https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement/Checkboxgroup.php#L31-L38
wigedev/farm
src/FormBuilder/FormElement/Checkboxgroup.php
Checkboxgroup.setUserValue
public function setUserValue(string $value) : FormElement { if (is_array($value)) { $value = implode(',', $value); } parent::setUserValue($value); return $this; }
php
public function setUserValue(string $value) : FormElement { if (is_array($value)) { $value = implode(',', $value); } parent::setUserValue($value); return $this; }
Sets a user value to be validated. Overridden to convert arrays to strings. @param string $value @return FormElement
https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement/Checkboxgroup.php#L46-L53
wigedev/farm
src/FormBuilder/FormElement/Checkboxgroup.php
Checkboxgroup.validate
public function validate() : void { if (null === $this->is_valid) { if (null === $this->user_value && null !== $this->default_value) { // There is a preset value, and its not being changed $this->is_valid = true; } elseif (null != $this->validator && false != $this->validator) { $validator = $this->validator; $valids = array(); $all_valid = true; $pieces = explode(',', $this->user_value); foreach ($pieces as $piece) { $result = $validator::quickValidate($piece, $this->constraints); if (null !== $result) { $valids[] = $result; } else { $all_valid = false; } } $this->user_value = implode(',', $valids); $this->is_valid = $all_valid; if (!$all_valid) { $this->error = 'The provided value is not valid. Please enter a valid value.'; } } else { // This field does not get validated $this->is_valid = true; } } // Check if the input is different from the default value if ($this->is_valid && null !== $this->user_value) { $this->is_changed = ($this->default_value != $this->user_value); } }
php
public function validate() : void { if (null === $this->is_valid) { if (null === $this->user_value && null !== $this->default_value) { // There is a preset value, and its not being changed $this->is_valid = true; } elseif (null != $this->validator && false != $this->validator) { $validator = $this->validator; $valids = array(); $all_valid = true; $pieces = explode(',', $this->user_value); foreach ($pieces as $piece) { $result = $validator::quickValidate($piece, $this->constraints); if (null !== $result) { $valids[] = $result; } else { $all_valid = false; } } $this->user_value = implode(',', $valids); $this->is_valid = $all_valid; if (!$all_valid) { $this->error = 'The provided value is not valid. Please enter a valid value.'; } } else { // This field does not get validated $this->is_valid = true; } } // Check if the input is different from the default value if ($this->is_valid && null !== $this->user_value) { $this->is_changed = ($this->default_value != $this->user_value); } }
Validates the user value according to the validator defined for this element.
https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement/Checkboxgroup.php#L68-L102
wigedev/farm
src/FormBuilder/FormElement/Checkboxgroup.php
Checkboxgroup.outputElement
public function outputElement() : string { $selected = explode(',', $this->getValue()); $disabled = $this->disabled; $hidden = $this->hidden; $return = '<div class="checkboxgroup">'; foreach ($this->options as $val=>$txt) { if (in_array($val, $hidden)) { break; } $d = (in_array($val, $disabled)) ? ' disabled="disabled"' : ''; $s = (in_array($val, $selected)) ? ' checked="checked"' : ''; $return .= '<div><input id="cb-' . $val . '" type="checkbox" name="' . $this->attributes['name'] . '[]" value="' . $val . '" ' . $d . $s . ' /> <label class="cblabel" for="cb-' . $val . '">' . $txt . "</label></div>\n"; } $return .= '</div>'; return $return; }
php
public function outputElement() : string { $selected = explode(',', $this->getValue()); $disabled = $this->disabled; $hidden = $this->hidden; $return = '<div class="checkboxgroup">'; foreach ($this->options as $val=>$txt) { if (in_array($val, $hidden)) { break; } $d = (in_array($val, $disabled)) ? ' disabled="disabled"' : ''; $s = (in_array($val, $selected)) ? ' checked="checked"' : ''; $return .= '<div><input id="cb-' . $val . '" type="checkbox" name="' . $this->attributes['name'] . '[]" value="' . $val . '" ' . $d . $s . ' /> <label class="cblabel" for="cb-' . $val . '">' . $txt . "</label></div>\n"; } $return .= '</div>'; return $return; }
Returns the form element as an HTML tag @return string
https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement/Checkboxgroup.php#L109-L127
old-town/workflow-zf2
src/Factory/AbstractWorkflowFactory.php
AbstractWorkflowFactory.canCreateServiceWithName
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) { if (null === $this->workflowServiceNamePrefix) { $this->workflowServiceNamePrefix = $this->buildWorkflowServiceNamePrefix($serviceLocator); } $flag = 0 === strpos($requestedName, $this->workflowServiceNamePrefix) && strlen($requestedName) > strlen($this->workflowServiceNamePrefix); return $flag; }
php
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) { if (null === $this->workflowServiceNamePrefix) { $this->workflowServiceNamePrefix = $this->buildWorkflowServiceNamePrefix($serviceLocator); } $flag = 0 === strpos($requestedName, $this->workflowServiceNamePrefix) && strlen($requestedName) > strlen($this->workflowServiceNamePrefix); return $flag; }
@param ServiceLocatorInterface $serviceLocator @param $name @param $requestedName @return bool @throws \Zend\ServiceManager\Exception\ServiceNotFoundException
https://github.com/old-town/workflow-zf2/blob/b63910bd0f4c05855e19cfa29e3376eee7c16c77/src/Factory/AbstractWorkflowFactory.php#L80-L88
old-town/workflow-zf2
src/Factory/AbstractWorkflowFactory.php
AbstractWorkflowFactory.createServiceWithName
public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) { if (null === $this->workflowServiceNamePrefix) { $this->workflowServiceNamePrefix = $this->buildWorkflowServiceNamePrefix($serviceLocator); } $managerName = substr($requestedName, strlen($this->workflowServiceNamePrefix)); try { $creationOptions = $this->getCreationOptions(); if (array_key_exists(static::WORKFLOW_CONFIGURATION_NAME, $creationOptions)) { $this->setWorkflowConfigurationName($creationOptions[static::WORKFLOW_CONFIGURATION_NAME]); } /** @var ModuleOptions $moduleOptions */ $moduleOptions = $serviceLocator->get(ModuleOptions::class); $managerOptions = $moduleOptions->getManagerOptions($managerName); $configName = $managerOptions->getConfiguration(); $workflowManagerName = $managerOptions->getName(); $workflowManager = null; if ($serviceLocator->has($workflowManagerName)) { $workflowManager = $serviceLocator->get($workflowManagerName); } elseif (class_exists($workflowManagerName)) { $r = new \ReflectionClass($workflowManagerName); $workflowManager = $r->newInstance($r); } if (!$workflowManager instanceof WorkflowInterface) { $errMsg = sprintf('Workflow not implements %s', WorkflowInterface::class); throw new Exception\InvalidWorkflowException($errMsg); } $configurationOptions = $moduleOptions->getConfigurationOptions($configName); $workflowConfig = $this->buildWorkflowManagerConfig($configurationOptions, $serviceLocator); $workflowManager->setConfiguration($workflowConfig); /** @var Workflow $workflowService */ $workflowService = $serviceLocator->get(Workflow::class); $event = new WorkflowManagerEvent(); $event->setWorkflowManager($workflowManager) ->setName(WorkflowManagerEvent::EVENT_CREATE) ->setTarget($workflowManager); $workflowService->getEventManager()->trigger($event); } catch (\Exception $e) { throw new Exception\FactoryException($e->getMessage(), $e->getCode(), $e); } return $workflowManager; }
php
public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) { if (null === $this->workflowServiceNamePrefix) { $this->workflowServiceNamePrefix = $this->buildWorkflowServiceNamePrefix($serviceLocator); } $managerName = substr($requestedName, strlen($this->workflowServiceNamePrefix)); try { $creationOptions = $this->getCreationOptions(); if (array_key_exists(static::WORKFLOW_CONFIGURATION_NAME, $creationOptions)) { $this->setWorkflowConfigurationName($creationOptions[static::WORKFLOW_CONFIGURATION_NAME]); } /** @var ModuleOptions $moduleOptions */ $moduleOptions = $serviceLocator->get(ModuleOptions::class); $managerOptions = $moduleOptions->getManagerOptions($managerName); $configName = $managerOptions->getConfiguration(); $workflowManagerName = $managerOptions->getName(); $workflowManager = null; if ($serviceLocator->has($workflowManagerName)) { $workflowManager = $serviceLocator->get($workflowManagerName); } elseif (class_exists($workflowManagerName)) { $r = new \ReflectionClass($workflowManagerName); $workflowManager = $r->newInstance($r); } if (!$workflowManager instanceof WorkflowInterface) { $errMsg = sprintf('Workflow not implements %s', WorkflowInterface::class); throw new Exception\InvalidWorkflowException($errMsg); } $configurationOptions = $moduleOptions->getConfigurationOptions($configName); $workflowConfig = $this->buildWorkflowManagerConfig($configurationOptions, $serviceLocator); $workflowManager->setConfiguration($workflowConfig); /** @var Workflow $workflowService */ $workflowService = $serviceLocator->get(Workflow::class); $event = new WorkflowManagerEvent(); $event->setWorkflowManager($workflowManager) ->setName(WorkflowManagerEvent::EVENT_CREATE) ->setTarget($workflowManager); $workflowService->getEventManager()->trigger($event); } catch (\Exception $e) { throw new Exception\FactoryException($e->getMessage(), $e->getCode(), $e); } return $workflowManager; }
@param ServiceLocatorInterface $serviceLocator @param $name @param $requestedName @return WorkflowInterface @throws \Zend\ServiceManager\Exception\ServiceNotFoundException @throws \OldTown\Workflow\ZF2\Factory\Exception\FactoryException
https://github.com/old-town/workflow-zf2/blob/b63910bd0f4c05855e19cfa29e3376eee7c16c77/src/Factory/AbstractWorkflowFactory.php#L100-L153
old-town/workflow-zf2
src/Factory/AbstractWorkflowFactory.php
AbstractWorkflowFactory.buildWorkflowManagerConfig
public function buildWorkflowManagerConfig(ConfigurationOptions $config, ServiceLocatorInterface $serviceLocator) { $resolverServiceName = $config->getResolver(); $resolver = null; if ($resolverServiceName) { if ($serviceLocator->has($resolverServiceName)) { $resolver = $serviceLocator->get($resolverServiceName); } elseif (class_exists($resolverServiceName)) { $r = new \ReflectionClass($resolverServiceName); $resolver = $r->newInstance(); } if (!$resolver instanceof VariableResolverInterface) { $errMsg = sprintf('Resolver not implements %s', VariableResolverInterface::class); throw new Exception\InvalidVariableResolverException($errMsg); } } $factory = null; if ($config->hasFactoryOptions()) { $factoryServiceName = $config->getFactoryOptions()->getName(); if ($serviceLocator->has($factoryServiceName)) { $factory = $serviceLocator->get($factoryServiceName); } elseif (class_exists($resolverServiceName)) { $r = new \ReflectionClass($factoryServiceName); $factory = $r->newInstance(); } if (!$factory instanceof WorkflowFactoryInterface) { $errMsg = sprintf('Factory not implements %s', WorkflowFactoryInterface::class); throw new Exception\InvalidWorkflowFactoryException($errMsg); } $factoryOptions = $config->getFactoryOptions()->getOptions(); $properties = new Properties(); foreach ($factoryOptions as $key => $value) { $properties->setProperty($key, $value); } $factory->init($properties); } $options = [ ArrayConfiguration::PERSISTENCE => $config->getPersistenceOptions()->getName(), ArrayConfiguration::PERSISTENCE_ARGS => $config->getPersistenceOptions()->getOptions(), ArrayConfiguration::VARIABLE_RESOLVER => $resolver, ArrayConfiguration::WORKFLOW_FACTORY => $factory ]; $configServiceName = $this->getWorkflowConfigurationName(); if (!class_exists($configServiceName)) { $errMsg = sprintf('Class %s not found', $configServiceName); throw new Exception\RuntimeException($errMsg); } $r = new \ReflectionClass($configServiceName); $workflowManagerConfig = $r->newInstance($options); if (!$workflowManagerConfig instanceof ConfigurationInterface) { $errMsg = sprintf('Class not implement %s', ConfigurationInterface::class); throw new Exception\RuntimeException($errMsg); } return $workflowManagerConfig; }
php
public function buildWorkflowManagerConfig(ConfigurationOptions $config, ServiceLocatorInterface $serviceLocator) { $resolverServiceName = $config->getResolver(); $resolver = null; if ($resolverServiceName) { if ($serviceLocator->has($resolverServiceName)) { $resolver = $serviceLocator->get($resolverServiceName); } elseif (class_exists($resolverServiceName)) { $r = new \ReflectionClass($resolverServiceName); $resolver = $r->newInstance(); } if (!$resolver instanceof VariableResolverInterface) { $errMsg = sprintf('Resolver not implements %s', VariableResolverInterface::class); throw new Exception\InvalidVariableResolverException($errMsg); } } $factory = null; if ($config->hasFactoryOptions()) { $factoryServiceName = $config->getFactoryOptions()->getName(); if ($serviceLocator->has($factoryServiceName)) { $factory = $serviceLocator->get($factoryServiceName); } elseif (class_exists($resolverServiceName)) { $r = new \ReflectionClass($factoryServiceName); $factory = $r->newInstance(); } if (!$factory instanceof WorkflowFactoryInterface) { $errMsg = sprintf('Factory not implements %s', WorkflowFactoryInterface::class); throw new Exception\InvalidWorkflowFactoryException($errMsg); } $factoryOptions = $config->getFactoryOptions()->getOptions(); $properties = new Properties(); foreach ($factoryOptions as $key => $value) { $properties->setProperty($key, $value); } $factory->init($properties); } $options = [ ArrayConfiguration::PERSISTENCE => $config->getPersistenceOptions()->getName(), ArrayConfiguration::PERSISTENCE_ARGS => $config->getPersistenceOptions()->getOptions(), ArrayConfiguration::VARIABLE_RESOLVER => $resolver, ArrayConfiguration::WORKFLOW_FACTORY => $factory ]; $configServiceName = $this->getWorkflowConfigurationName(); if (!class_exists($configServiceName)) { $errMsg = sprintf('Class %s not found', $configServiceName); throw new Exception\RuntimeException($errMsg); } $r = new \ReflectionClass($configServiceName); $workflowManagerConfig = $r->newInstance($options); if (!$workflowManagerConfig instanceof ConfigurationInterface) { $errMsg = sprintf('Class not implement %s', ConfigurationInterface::class); throw new Exception\RuntimeException($errMsg); } return $workflowManagerConfig; }
Создает конфиг для workflow @param ConfigurationOptions $config @param ServiceLocatorInterface $serviceLocator @return ConfigurationInterface @throws \OldTown\Workflow\ZF2\Factory\Exception\InvalidVariableResolverException @throws \OldTown\Workflow\ZF2\Options\Exception\InvalidServiceConfigException @throws \Zend\ServiceManager\Exception\ServiceNotFoundException @throws \OldTown\Workflow\ZF2\Options\Exception\InvalidPersistenceConfigException @throws \OldTown\Workflow\ZF2\Options\Exception\InvalidFactoryConfigException @throws \OldTown\Workflow\ZF2\Factory\Exception\InvalidWorkflowFactoryException @throws \OldTown\Workflow\ZF2\Factory\Exception\RuntimeException
https://github.com/old-town/workflow-zf2/blob/b63910bd0f4c05855e19cfa29e3376eee7c16c77/src/Factory/AbstractWorkflowFactory.php#L173-L235
umbrella-code/umbrella
src/Umbrella/Console/Command/Doctrine/Schema/UpdateSchemaCommand.php
UpdateSchemaCommand.executeSchemaCommand
protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas) { parent::executeSchemaCommand($input, $output, $schemaTool, $metadatas); }
php
protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas) { parent::executeSchemaCommand($input, $output, $schemaTool, $metadatas); }
{@inheritdoc}
https://github.com/umbrella-code/umbrella/blob/e23d8d367047113933ec22346eb9f002a555bd52/src/Umbrella/Console/Command/Doctrine/Schema/UpdateSchemaCommand.php#L27-L30
Falc/TwigTextExtension
src/TextExtension.php
TextExtension.p2br
public function p2br($data) { // Remove opening <p> tags $data = preg_replace('#<p[^>]*?>#', '', $data); // Remove trailing </p> to prevent it to be replaced with unneeded <br /> $data = preg_replace('#</p>$#', '', $data); // Replace each end of paragraph with two <br /> $data = str_replace('</p>', '<br /><br />', $data); return $data; }
php
public function p2br($data) { // Remove opening <p> tags $data = preg_replace('#<p[^>]*?>#', '', $data); // Remove trailing </p> to prevent it to be replaced with unneeded <br /> $data = preg_replace('#</p>$#', '', $data); // Replace each end of paragraph with two <br /> $data = str_replace('</p>', '<br /><br />', $data); return $data; }
Replaces paragraph formatting with double linebreaks. Example: '<p>This is a text.</p><p>This should be another paragraph.</p>' Output: 'This is a text.<br /><br>This should be another paragraph.' @param string $data Text to format. @return string Formatted text.
https://github.com/Falc/TwigTextExtension/blob/5036da5fddf5c055bd98d42209ae1d8cd88b1889/src/TextExtension.php#L73-L85
Falc/TwigTextExtension
src/TextExtension.php
TextExtension.paragraphs_slice
public function paragraphs_slice($text, $offset = 0, $length = null) { $result = array(); preg_match_all('#<p[^>]*>(.*?)</p>#', $text, $result); // Null length = all the paragraphs if ($length === null) { $length = count($result[0]) - $offset; } return array_slice($result[0], $offset, $length); }
php
public function paragraphs_slice($text, $offset = 0, $length = null) { $result = array(); preg_match_all('#<p[^>]*>(.*?)</p>#', $text, $result); // Null length = all the paragraphs if ($length === null) { $length = count($result[0]) - $offset; } return array_slice($result[0], $offset, $length); }
Extracts paragraphs from a string. This function uses array_slice(). The function signatures are similar. @see http://www.php.net/manual/en/function.array-slice.php @param string $text String containing paragraphs. @param integer $offset Number of paragraphs to offset. Default: 0. @param integer $length Number of paragraphs to extract. Default: null. @return string[]
https://github.com/Falc/TwigTextExtension/blob/5036da5fddf5c055bd98d42209ae1d8cd88b1889/src/TextExtension.php#L99-L110
Falc/TwigTextExtension
src/TextExtension.php
TextExtension.regex_replace
public function regex_replace($subject, $pattern, $replacement, $limit = -1) { return preg_replace($pattern, $replacement, $subject, $limit); }
php
public function regex_replace($subject, $pattern, $replacement, $limit = -1) { return preg_replace($pattern, $replacement, $subject, $limit); }
Performs a regular expression search and replace. @see http://php.net/manual/en/function.preg-replace.php @param string $subject String or array of strings to search and replace. @param mixed $pattern Pattern to search for. It can be either a string or an array with strings. @param mixed $replacement String or array with strings to replace. @param integer $limit Maximum possible replacements for each pattern in each subject string. Default is no limit. @return string
https://github.com/Falc/TwigTextExtension/blob/5036da5fddf5c055bd98d42209ae1d8cd88b1889/src/TextExtension.php#L123-L126
antaresproject/translations
src/Http/Datatables/Languages.php
Languages.ajax
public function ajax() { $canAddLanguage = app('antares.acl')->make('antares/translations')->can('add-language'); return $this->prepare() ->editColumn('name', function ($model) { $code = $model->code; $codeIcon = (($code == 'en') ? 'us' : $code); return '<i class="flag-icon flag-icon-' . $codeIcon . '"></i>' . $model->name; }) ->editColumn('is_default', function ($model) { return ((int) $model->is_default) ? '<span class="label-basic label-basic--success">' . trans('Yes') . '</span>' : '<span class="label-basic label-basic--danger">' . trans('No') . '</span>'; }) ->addColumn('action', $this->getActionsColumn($canAddLanguage)) ->make(true); }
php
public function ajax() { $canAddLanguage = app('antares.acl')->make('antares/translations')->can('add-language'); return $this->prepare() ->editColumn('name', function ($model) { $code = $model->code; $codeIcon = (($code == 'en') ? 'us' : $code); return '<i class="flag-icon flag-icon-' . $codeIcon . '"></i>' . $model->name; }) ->editColumn('is_default', function ($model) { return ((int) $model->is_default) ? '<span class="label-basic label-basic--success">' . trans('Yes') . '</span>' : '<span class="label-basic label-basic--danger">' . trans('No') . '</span>'; }) ->addColumn('action', $this->getActionsColumn($canAddLanguage)) ->make(true); }
{@inheritdoc}
https://github.com/antaresproject/translations/blob/63097aeb97f18c5aeeef7dcf15f0c67959951685/src/Http/Datatables/Languages.php#L50-L66
antaresproject/translations
src/Http/Datatables/Languages.php
Languages.html
public function html() { return $this ->setName('Languages List') ->setQuery($this->query()) ->addColumn(['data' => 'id', 'name' => 'id', 'title' => 'Id']) ->addColumn(['data' => 'code', 'name' => 'code', 'title' => 'Country code']) ->addColumn(['data' => 'name', 'name' => 'name', 'title' => 'Country']) ->addColumn(['data' => 'is_default', 'name' => 'is_default', 'title' => 'Default']) ->addAction(['name' => 'edit', 'title' => '', 'class' => 'mass-actions dt-actions', 'orderable' => false, 'searchable' => false]) ->setDeferedData(); }
php
public function html() { return $this ->setName('Languages List') ->setQuery($this->query()) ->addColumn(['data' => 'id', 'name' => 'id', 'title' => 'Id']) ->addColumn(['data' => 'code', 'name' => 'code', 'title' => 'Country code']) ->addColumn(['data' => 'name', 'name' => 'name', 'title' => 'Country']) ->addColumn(['data' => 'is_default', 'name' => 'is_default', 'title' => 'Default']) ->addAction(['name' => 'edit', 'title' => '', 'class' => 'mass-actions dt-actions', 'orderable' => false, 'searchable' => false]) ->setDeferedData(); }
{@inheritdoc}
https://github.com/antaresproject/translations/blob/63097aeb97f18c5aeeef7dcf15f0c67959951685/src/Http/Datatables/Languages.php#L71-L82
antaresproject/translations
src/Http/Datatables/Languages.php
Languages.getActionsColumn
protected function getActionsColumn($canAddLanguage) { return function ($row) use($canAddLanguage) { $btns = []; $html = app('html'); if ($canAddLanguage && !$row->is_default) { $btns[] = $html->create('li', $html->link(handles("antares::translations/languages/delete/" . $row->id), trans('Delete'), ['class' => "triggerable confirm", 'data-icon' => 'delete', 'data-title' => trans("Are you sure?"), 'data-description' => trans('Deleting language') . ' ' . $row->code])); $btns[] = $html->create('li', $html->link(handles("antares::translations/languages/default/" . $row->id), trans('Set as default'), ['data-icon' => 'spellcheck'])); } if (empty($btns)) { return ''; } $section = $html->create('div', $html->create('section', $html->create('ul', $html->raw(implode('', $btns)))), ['class' => 'mass-actions-menu'])->get(); return '<i class="zmdi zmdi-more"></i>' . $html->raw($section)->get(); }; }
php
protected function getActionsColumn($canAddLanguage) { return function ($row) use($canAddLanguage) { $btns = []; $html = app('html'); if ($canAddLanguage && !$row->is_default) { $btns[] = $html->create('li', $html->link(handles("antares::translations/languages/delete/" . $row->id), trans('Delete'), ['class' => "triggerable confirm", 'data-icon' => 'delete', 'data-title' => trans("Are you sure?"), 'data-description' => trans('Deleting language') . ' ' . $row->code])); $btns[] = $html->create('li', $html->link(handles("antares::translations/languages/default/" . $row->id), trans('Set as default'), ['data-icon' => 'spellcheck'])); } if (empty($btns)) { return ''; } $section = $html->create('div', $html->create('section', $html->create('ul', $html->raw(implode('', $btns)))), ['class' => 'mass-actions-menu'])->get(); return '<i class="zmdi zmdi-more"></i>' . $html->raw($section)->get(); }; }
Actions column for datatable @param boolean $canAddLanguage @return String
https://github.com/antaresproject/translations/blob/63097aeb97f18c5aeeef7dcf15f0c67959951685/src/Http/Datatables/Languages.php#L90-L106
acquiropay/omnipay-acquiropay
src/Message/AbstractRequest.php
AbstractRequest.sendData
public function sendData($data) { $url = $this->getEndpoint(); $body = [ 'form_params' => $data, ]; if ($this->getTestMode()) { $body = [ 'verify' => false, ]; } $response = $this->httpClient->post($url, [], $body); $contents = (string) $response->getBody(); $xml = simplexml_load_string($contents); return $this->createResponse($xml); }
php
public function sendData($data) { $url = $this->getEndpoint(); $body = [ 'form_params' => $data, ]; if ($this->getTestMode()) { $body = [ 'verify' => false, ]; } $response = $this->httpClient->post($url, [], $body); $contents = (string) $response->getBody(); $xml = simplexml_load_string($contents); return $this->createResponse($xml); }
Send the request with specified data. @param mixed $data The data to send @return ResponseInterface
https://github.com/acquiropay/omnipay-acquiropay/blob/0e404a7e25cdbd3d7755e7d7c1f43299a177bed3/src/Message/AbstractRequest.php#L109-L129
open-orchestra/open-orchestra-display-bundle
DisplayBundle/DisplayBlock/Strategies/LanguageListStrategy.php
LanguageListStrategy.show
public function show(ReadBlockInterface $block) { $parameters = $this->requestStack->getMasterRequest()->get('_route_params'); if (!array_key_exists('siteId', $parameters) || !array_key_exists('nodeId', $parameters)) { throw new RouteNotFoundException(); } $site = $this->siteRepository->findOneBySiteId($parameters['siteId']); $routes = array(); if (!\is_null($site)) { foreach ($site->getLanguages() as $language) { try { unset($parameters['_locale']); unset($parameters['aliasId']); $routes[$language] = $this->urlGenerator->generate($parameters['nodeId'], array_merge( $parameters, array(OpenOrchestraDatabaseUrlGenerator::REDIRECT_TO_LANGUAGE => $language) )); } catch (ResourceNotFoundException $e) { } catch (RouteNotFoundException $e) { } catch (MissingMandatoryParametersException $e) { } } } return $this->render( $this->template, array( 'class' => $block->getStyle(), 'id' => $block->getId(), 'routes' => $routes, ) ); }
php
public function show(ReadBlockInterface $block) { $parameters = $this->requestStack->getMasterRequest()->get('_route_params'); if (!array_key_exists('siteId', $parameters) || !array_key_exists('nodeId', $parameters)) { throw new RouteNotFoundException(); } $site = $this->siteRepository->findOneBySiteId($parameters['siteId']); $routes = array(); if (!\is_null($site)) { foreach ($site->getLanguages() as $language) { try { unset($parameters['_locale']); unset($parameters['aliasId']); $routes[$language] = $this->urlGenerator->generate($parameters['nodeId'], array_merge( $parameters, array(OpenOrchestraDatabaseUrlGenerator::REDIRECT_TO_LANGUAGE => $language) )); } catch (ResourceNotFoundException $e) { } catch (RouteNotFoundException $e) { } catch (MissingMandatoryParametersException $e) { } } } return $this->render( $this->template, array( 'class' => $block->getStyle(), 'id' => $block->getId(), 'routes' => $routes, ) ); }
Perform the show action for a block @param ReadBlockInterface $block @throws RouteNotFoundException @return Response
https://github.com/open-orchestra/open-orchestra-display-bundle/blob/0e59e8686dac2d8408b57b63b975b4e5a1aa9472/DisplayBundle/DisplayBlock/Strategies/LanguageListStrategy.php#L78-L111
ekyna/AdminBundle
Operator/ResourceOperator.php
ResourceOperator.create
public function create($resourceOrEvent) { $event = $resourceOrEvent instanceof ResourceEvent ? $resourceOrEvent : $this->createResourceEvent($resourceOrEvent); $this->dispatcher->dispatch($this->config->getEventName('pre_create'), $event); if (!$event->isPropagationStopped()) { $this->persistResource($event); $this->dispatcher->dispatch($this->config->getEventName('post_create'), $event); } return $event; }
php
public function create($resourceOrEvent) { $event = $resourceOrEvent instanceof ResourceEvent ? $resourceOrEvent : $this->createResourceEvent($resourceOrEvent); $this->dispatcher->dispatch($this->config->getEventName('pre_create'), $event); if (!$event->isPropagationStopped()) { $this->persistResource($event); $this->dispatcher->dispatch($this->config->getEventName('post_create'), $event); } return $event; }
{@inheritdoc}
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Operator/ResourceOperator.php#L97-L109
ekyna/AdminBundle
Operator/ResourceOperator.php
ResourceOperator.delete
public function delete($resourceOrEvent, $hard = false) { $event = $resourceOrEvent instanceof ResourceEvent ? $resourceOrEvent : $this->createResourceEvent($resourceOrEvent); $event->setHard($event->getHard() || $hard); $this->dispatcher->dispatch($this->config->getEventName('pre_delete'), $event); if (!$event->isPropagationStopped()) { $eventManager = $this->manager->getEventManager(); $disabledListeners = []; if ($event->getHard()) { foreach ($eventManager->getListeners() as $eventName => $listeners) { foreach ($listeners as $listener) { if ($listener instanceof SoftDeleteableListener) { $eventManager->removeEventListener($eventName, $listener); $disabledListeners[$eventName] = $listener; } } } } $this->removeResource($event); if (!empty($disabledListeners)) { foreach($disabledListeners as $eventName => $listener) { $eventManager->addEventListener($eventName, $listener); } } $this->dispatcher->dispatch($this->config->getEventName('post_delete'), $event); } return $event; }
php
public function delete($resourceOrEvent, $hard = false) { $event = $resourceOrEvent instanceof ResourceEvent ? $resourceOrEvent : $this->createResourceEvent($resourceOrEvent); $event->setHard($event->getHard() || $hard); $this->dispatcher->dispatch($this->config->getEventName('pre_delete'), $event); if (!$event->isPropagationStopped()) { $eventManager = $this->manager->getEventManager(); $disabledListeners = []; if ($event->getHard()) { foreach ($eventManager->getListeners() as $eventName => $listeners) { foreach ($listeners as $listener) { if ($listener instanceof SoftDeleteableListener) { $eventManager->removeEventListener($eventName, $listener); $disabledListeners[$eventName] = $listener; } } } } $this->removeResource($event); if (!empty($disabledListeners)) { foreach($disabledListeners as $eventName => $listener) { $eventManager->addEventListener($eventName, $listener); } } $this->dispatcher->dispatch($this->config->getEventName('post_delete'), $event); } return $event; }
{@inheritdoc}
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Operator/ResourceOperator.php#L131-L163
ekyna/AdminBundle
Operator/ResourceOperator.php
ResourceOperator.persistResource
protected function persistResource(ResourceEvent $event) { $resource = $event->getResource(); // TODO Validation ? try { $this->manager->persist($resource); $this->manager->flush(); } catch(DBALException $e) { if ($this->debug) { throw $e; } $event->addMessage(new ResourceMessage( 'ekyna_admin.resource.message.persist.failure', ResourceMessage::TYPE_ERROR )); return $event; } return $event->addMessage(new ResourceMessage( 'ekyna_admin.resource.message.persist.success', ResourceMessage::TYPE_SUCCESS )); }
php
protected function persistResource(ResourceEvent $event) { $resource = $event->getResource(); // TODO Validation ? try { $this->manager->persist($resource); $this->manager->flush(); } catch(DBALException $e) { if ($this->debug) { throw $e; } $event->addMessage(new ResourceMessage( 'ekyna_admin.resource.message.persist.failure', ResourceMessage::TYPE_ERROR )); return $event; } return $event->addMessage(new ResourceMessage( 'ekyna_admin.resource.message.persist.success', ResourceMessage::TYPE_SUCCESS )); }
Persists a resource. @param ResourceEvent $event @return ResourceEvent @throws DBALException @throws \Exception
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Operator/ResourceOperator.php#L173-L197
ekyna/AdminBundle
Operator/ResourceOperator.php
ResourceOperator.createResourceEvent
protected function createResourceEvent($resource) { if (null !== $eventClass = $this->config->getEventClass()) { $event = new $eventClass($resource); } else { $event = new ResourceEvent(); $event->setResource($resource); } return $event; }
php
protected function createResourceEvent($resource) { if (null !== $eventClass = $this->config->getEventClass()) { $event = new $eventClass($resource); } else { $event = new ResourceEvent(); $event->setResource($resource); } return $event; }
Creates the resource event. @param object $resource @return ResourceEvent
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Operator/ResourceOperator.php#L245-L254
crodas/ConcurrentFileWriter
src/ConcurrentFileWriter/Util.php
Util.delete
public static function delete($path) { if (!is_readable($path)) { return false; } if (!is_dir($path)) { unlink($path); return true; } foreach (scandir($path) as $file) { if ($file === '.' || $file === '..') { continue; } $file = $path . '/' . $file; if (is_dir($file)) { self::delete($file); } else { unlink($file); } } rmdir($path); return true; }
php
public static function delete($path) { if (!is_readable($path)) { return false; } if (!is_dir($path)) { unlink($path); return true; } foreach (scandir($path) as $file) { if ($file === '.' || $file === '..') { continue; } $file = $path . '/' . $file; if (is_dir($file)) { self::delete($file); } else { unlink($file); } } rmdir($path); return true; }
Deletes a file or directory recursively.
https://github.com/crodas/ConcurrentFileWriter/blob/13f88d8c2daf5fe9c70f8be6aeb3d862cd2a5e5a/src/ConcurrentFileWriter/Util.php#L21-L47
PhoxPHP/Glider
src/Query/Parameters.php
Parameters.setParameter
public function setParameter(String $key, $value, Bool $override=false) { if ($this->getParameter($key)) { $defValue = $this->getParameter($key); $this->parameters[$key] = [$defValue]; $this->parameters[$key][] = $value; return; } $this->parameters[$key] = $value; }
php
public function setParameter(String $key, $value, Bool $override=false) { if ($this->getParameter($key)) { $defValue = $this->getParameter($key); $this->parameters[$key] = [$defValue]; $this->parameters[$key][] = $value; return; } $this->parameters[$key] = $value; }
Sets a parameter key and value. @param $key <String> @param $value <Mixed> @param $override <Boolean> If this option is set to true, the parameter value will be overriden if a value has already been set. @access public @return <void>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Query/Parameters.php#L44-L54
PhoxPHP/Glider
src/Query/Parameters.php
Parameters.getType
public function getType($parameter='') { $parameterType = null; switch (gettype($parameter)) { case 'string': $parameterType = 's'; break; case 'numeric': case 'integer': $parameterType = 'i'; break; case 'double': $parameterType = 'd'; break; default: $parameterType = null; break; } return $parameterType; }
php
public function getType($parameter='') { $parameterType = null; switch (gettype($parameter)) { case 'string': $parameterType = 's'; break; case 'numeric': case 'integer': $parameterType = 'i'; break; case 'double': $parameterType = 'd'; break; default: $parameterType = null; break; } return $parameterType; }
Return a parameter type. @param $paramter <Mixed> @access public @return <Mixed>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Query/Parameters.php#L97-L117
bruno-barros/w.eloquent-framework
src/weloquent/Core/Console/OptimizeCommand.php
OptimizeCommand.compileClasses
protected function compileClasses() { $this->registerClassPreloaderCommand(); $outputPath = $this->laravel['path.storage'] . '/compiled.php'; $this->callSilent('compile', array( '--config' => implode(',', $this->getClassFiles()), '--output' => $outputPath, '--strip_comments' => 1, )); }
php
protected function compileClasses() { $this->registerClassPreloaderCommand(); $outputPath = $this->laravel['path.storage'] . '/compiled.php'; $this->callSilent('compile', array( '--config' => implode(',', $this->getClassFiles()), '--output' => $outputPath, '--strip_comments' => 1, )); }
Generate the compiled class file. @return void
https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Core/Console/OptimizeCommand.php#L18-L29
thienhungho/yii2-contact-management
src/models/ContactForm.php
ContactForm.sendEmail
public function sendEmail($email) { return send_mail( 'no-reply', get_app_name(), $email, $this->subject, $this->body, 'html', '/contact/html', [ 'title' => 'This is title', 'contact_name' => $this->name, 'contact_email' => $this->email, ] ); }
php
public function sendEmail($email) { return send_mail( 'no-reply', get_app_name(), $email, $this->subject, $this->body, 'html', '/contact/html', [ 'title' => 'This is title', 'contact_name' => $this->name, 'contact_email' => $this->email, ] ); }
@param $email @return \BaseApp\mail\modules\Mail\Mailer|bool @throws \yii\base\InvalidConfigException
https://github.com/thienhungho/yii2-contact-management/blob/652d7b0ee628eb924e197ad956ce3c6045b878eb/src/models/ContactForm.php#L51-L66
atelierspierrot/patterns
src/Patterns/Abstracts/AbstractAccessible.php
AbstractAccessible.__isset
public function __isset($var) { if (!property_exists($this, $var)) { throw new RuntimeException( sprintf('Property "%s" does not exist in object "%s"!', $var, get_class($this)) ); } $accessor = $this->getAccessorName($var, 'isset'); if (method_exists($this, $accessor) && is_callable(array($this, $accessor))) { return call_user_func(array($this, $accessor)); } else { return isset($this->{$var}); } }
php
public function __isset($var) { if (!property_exists($this, $var)) { throw new RuntimeException( sprintf('Property "%s" does not exist in object "%s"!', $var, get_class($this)) ); } $accessor = $this->getAccessorName($var, 'isset'); if (method_exists($this, $accessor) && is_callable(array($this, $accessor))) { return call_user_func(array($this, $accessor)); } else { return isset($this->{$var}); } }
Test if an object property has been set, using the "issetVariable" method if defined Called when you write `isset($obj->property)` or `empty($obj->property)` @param string $var The property object to test @return bool True if the property is already set @throws \RuntimeException if the property doesn't exist in the object
https://github.com/atelierspierrot/patterns/blob/b7a8313e98bbfb6525e1672d0a726a1ead6f156e/src/Patterns/Abstracts/AbstractAccessible.php#L150-L163
stratedge/wye
src/Wye.php
Wye.makeBinding
public static function makeBinding( $parameter, $value, $data_type = PDO::PARAM_STR ) { $binding = new Binding(new static, $parameter, $value, $data_type); return $binding; }
php
public static function makeBinding( $parameter, $value, $data_type = PDO::PARAM_STR ) { $binding = new Binding(new static, $parameter, $value, $data_type); return $binding; }
Creates a new instance of Stratedge\Wye\Binding. @param int|string $parameter @param mixed $value @param int $data_type @return BindingInterface
https://github.com/stratedge/wye/blob/9d3d32b4ea56c711d67b8498ab1a05d0aded40ea/src/Wye.php#L154-L161
stratedge/wye
src/Wye.php
Wye.executeStatement
public static function executeStatement( PDOStatement $statement, array $params = null ) { //Add the statement to the list of those run static::addStatement($statement); //Add bindings to the statement if (is_array($params)) { $statement->getBindings() ->hydrateFromArray($params); } $result = static::getOrCreateResultAt(static::numQueries()); //Add the result to the statement $statement->setResult($result); //If a transaction is open, add the statement to it if (static::inTransaction()) { static::currentTransaction()->addStatement($statement); } //Increment number of queries run static::incrementNumQueries(); if (static::shouldLogBacktrace()) { $statement->setBacktrace( static::makeBacktraceCollection( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, static::resolveBacktraceLimit() ) ) ); } }
php
public static function executeStatement( PDOStatement $statement, array $params = null ) { //Add the statement to the list of those run static::addStatement($statement); //Add bindings to the statement if (is_array($params)) { $statement->getBindings() ->hydrateFromArray($params); } $result = static::getOrCreateResultAt(static::numQueries()); //Add the result to the statement $statement->setResult($result); //If a transaction is open, add the statement to it if (static::inTransaction()) { static::currentTransaction()->addStatement($statement); } //Increment number of queries run static::incrementNumQueries(); if (static::shouldLogBacktrace()) { $statement->setBacktrace( static::makeBacktraceCollection( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, static::resolveBacktraceLimit() ) ) ); } }
Records a simulation of a query execution. @todo Raise an error if there are parameters already bound and params are provided. @param PDOStatement $statement @param array $params @return void
https://github.com/stratedge/wye/blob/9d3d32b4ea56c711d67b8498ab1a05d0aded40ea/src/Wye.php#L219-L255
stratedge/wye
src/Wye.php
Wye.beginTransaction
public static function beginTransaction() { if (static::inTransaction()) { throw new PDOException(); } static::inTransaction(true); $transaction = static::makeTransaction(static::countTransactions()); static::addTransaction($transaction); }
php
public static function beginTransaction() { if (static::inTransaction()) { throw new PDOException(); } static::inTransaction(true); $transaction = static::makeTransaction(static::countTransactions()); static::addTransaction($transaction); }
Places Wye into transaction mode and increments number of transactions. If a transaction is already open, throws a PDOException @todo Flesh out the details for the PDOException properly @throws PDOException @return void
https://github.com/stratedge/wye/blob/9d3d32b4ea56c711d67b8498ab1a05d0aded40ea/src/Wye.php#L288-L299
stratedge/wye
src/Wye.php
Wye.getOrCreateResultAt
public static function getOrCreateResultAt($index = 0) { $results = static::getResultAt($index); if (is_null($results)) { $results = static::makeResult()->attachAtIndex($index); } return $results; }
php
public static function getOrCreateResultAt($index = 0) { $results = static::getResultAt($index); if (is_null($results)) { $results = static::makeResult()->attachAtIndex($index); } return $results; }
Retrieve a result at a specific index. If no result is found, a new, blank result will be generated, stored at the index, and returned. @param integer $index @return Result
https://github.com/stratedge/wye/blob/9d3d32b4ea56c711d67b8498ab1a05d0aded40ea/src/Wye.php#L604-L613
stratedge/wye
src/Wye.php
Wye.addResultAtIndex
public static function addResultAtIndex(Result $result, $index) { // Add result $results = static::getResults(); $results[$index] = $result; // Store results static::setResults($results); }
php
public static function addResultAtIndex(Result $result, $index) { // Add result $results = static::getResults(); $results[$index] = $result; // Store results static::setResults($results); }
Attach a result at a specific index. If a result already exists the current one will be replaced with the new one. @param Result $result @param integer $index
https://github.com/stratedge/wye/blob/9d3d32b4ea56c711d67b8498ab1a05d0aded40ea/src/Wye.php#L642-L650
vi-kon/laravel-parser-markdown
src/ViKon/ParserMarkdown/Rule/Block/FencedCodeBlockRule.php
FencedCodeBlockRule.handleEntryState
protected function handleEntryState($content, $position, TokenList $tokenList) { $lang = trim($content, " `\t\n\r\0\x0B"); $tokenList->addToken($this->name . self::OPEN, $position) ->set('lang', $lang); }
php
protected function handleEntryState($content, $position, TokenList $tokenList) { $lang = trim($content, " `\t\n\r\0\x0B"); $tokenList->addToken($this->name . self::OPEN, $position) ->set('lang', $lang); }
Handle lexers entry state @param string $content @param int $position @param \ViKon\Parser\TokenList $tokenList
https://github.com/vi-kon/laravel-parser-markdown/blob/4b258b407df95f6b6be284252762ef3ddbef1e35/src/ViKon/ParserMarkdown/Rule/Block/FencedCodeBlockRule.php#L48-L52
phavour/phavour
Phavour/Helper/FileSystem/Directory.php
Directory.createPath
public function createPath($base, $path) { if (!is_dir($base) || !is_writable($base)) { return false; } if (empty($path)) { return false; } $pieces = explode(self::DS, $path); $dir = $base; foreach ($pieces as $directory) { if (empty($directory)) { // @codeCoverageIgnoreStart continue; // Handle the / from the exploded path // @codeCoverageIgnoreEnd } $singlePath = $dir . self::DS . $directory; if (!file_exists($singlePath) || !is_dir($singlePath)) { $create = @mkdir($singlePath); if ($create === false) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } } $dir = $singlePath; } return true; }
php
public function createPath($base, $path) { if (!is_dir($base) || !is_writable($base)) { return false; } if (empty($path)) { return false; } $pieces = explode(self::DS, $path); $dir = $base; foreach ($pieces as $directory) { if (empty($directory)) { // @codeCoverageIgnoreStart continue; // Handle the / from the exploded path // @codeCoverageIgnoreEnd } $singlePath = $dir . self::DS . $directory; if (!file_exists($singlePath) || !is_dir($singlePath)) { $create = @mkdir($singlePath); if ($create === false) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } } $dir = $singlePath; } return true; }
Create a new path on top of a base directory @param string $base @param string $path @return boolean
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Helper/FileSystem/Directory.php#L51-L83
phavour/phavour
Phavour/Helper/FileSystem/Directory.php
Directory.recursivelyDeleteFromDirectory
public function recursivelyDeleteFromDirectory($baseDirectory) { if (!is_dir($baseDirectory)) { return; } $iterator = new \RecursiveDirectoryIterator($baseDirectory); $files = new \RecursiveIteratorIterator( $iterator, \RecursiveIteratorIterator::CHILD_FIRST ); foreach ($files as $file) { $fname = $file->getFilename(); if ($fname == '.' || $fname == '..') { continue; } if ($file->isDir()) { $this->recursivelyDeleteFromDirectory($file->getRealPath()); } else { unlink($file->getRealPath()); } } rmdir($baseDirectory); return; }
php
public function recursivelyDeleteFromDirectory($baseDirectory) { if (!is_dir($baseDirectory)) { return; } $iterator = new \RecursiveDirectoryIterator($baseDirectory); $files = new \RecursiveIteratorIterator( $iterator, \RecursiveIteratorIterator::CHILD_FIRST ); foreach ($files as $file) { $fname = $file->getFilename(); if ($fname == '.' || $fname == '..') { continue; } if ($file->isDir()) { $this->recursivelyDeleteFromDirectory($file->getRealPath()); } else { unlink($file->getRealPath()); } } rmdir($baseDirectory); return; }
Recursively delete files and folders, when given a base path @param string $baseDirectory @return void
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Helper/FileSystem/Directory.php#L90-L118
villermen/runescape-lookup-commons
src/ActivityFeed/ActivityFeedItem.php
ActivityFeedItem.equals
public function equals(ActivityFeedItem $otherItem): bool { return $this->getTime()->format("Ymd") == $otherItem->getTime()->format("Ymd") && $this->getTitle() == $otherItem->getTitle() && $this->getDescription() == $otherItem->getDescription(); }
php
public function equals(ActivityFeedItem $otherItem): bool { return $this->getTime()->format("Ymd") == $otherItem->getTime()->format("Ymd") && $this->getTitle() == $otherItem->getTitle() && $this->getDescription() == $otherItem->getDescription(); }
Compares this feed item to another. Only the date part of the time is compared, because adventurer's log feeds only contain accurate date parts. @param ActivityFeedItem $otherItem @return bool
https://github.com/villermen/runescape-lookup-commons/blob/3e24dadbdc5e20b755280e5110f4ca0a1758b04c/src/ActivityFeed/ActivityFeedItem.php#L61-L66
valu-digital/valuso
src/ValuSo/Feature/IdentityTrait.php
IdentityTrait.getIdentity
public function getIdentity($spec = null, $default = null) { if ($spec !== null) { return isset($this->identity[$spec]) ? $this->identity[$spec] : $default; } else { return $this->identity; } }
php
public function getIdentity($spec = null, $default = null) { if ($spec !== null) { return isset($this->identity[$spec]) ? $this->identity[$spec] : $default; } else { return $this->identity; } }
Retrieve identity or identity spec @param string|null $spec @param mixed $default @return \ArrayAccess|null
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Feature/IdentityTrait.php#L22-L29
headzoo/web-tools
src/Headzoo/Web/Tools/Utils.php
Utils.normalizeHeaderName
public static function normalizeHeaderName($headerName, $stripX = false) { if (is_array($headerName)) { array_walk($headerName, function(&$name) use($stripX) { $name = self::normalizeHeaderName($name, $stripX); }); } else { $headerName = trim((string)$headerName, " \t:"); if (count(explode(":", $headerName)) > 1 || preg_match("/[^\\w\\s-]/", $headerName)) { throw new Exceptions\InvalidArgumentException( "String '{$headerName}' cannot be normalized because of bad formatting." ); } $headerName = str_replace(["-", "_"], " ", $headerName); $headerName = ucwords(strtolower($headerName)); $headerName = str_replace(" ", "-", $headerName); if ($stripX && substr($headerName, 0, 2) === "X-") { $headerName = substr($headerName, 2); } $index = Arrays::findString(self::$headerSpecialCases, $headerName); if (false !== $index) { $headerName = self::$headerSpecialCases[$index]; } } return $headerName; }
php
public static function normalizeHeaderName($headerName, $stripX = false) { if (is_array($headerName)) { array_walk($headerName, function(&$name) use($stripX) { $name = self::normalizeHeaderName($name, $stripX); }); } else { $headerName = trim((string)$headerName, " \t:"); if (count(explode(":", $headerName)) > 1 || preg_match("/[^\\w\\s-]/", $headerName)) { throw new Exceptions\InvalidArgumentException( "String '{$headerName}' cannot be normalized because of bad formatting." ); } $headerName = str_replace(["-", "_"], " ", $headerName); $headerName = ucwords(strtolower($headerName)); $headerName = str_replace(" ", "-", $headerName); if ($stripX && substr($headerName, 0, 2) === "X-") { $headerName = substr($headerName, 2); } $index = Arrays::findString(self::$headerSpecialCases, $headerName); if (false !== $index) { $headerName = self::$headerSpecialCases[$index]; } } return $headerName; }
Normalizes a header name Changes the value of $headerName to the format "Camel-Case-String" from any other format. For example the string "CONTENT_TYPE" becomes "Content-Type". Special cases are handled for header fields which typically use non-standard formatting. For example the headers "XSS-Protection" and "ETag". The value "xss-protection" is normalized to "XSS-Protection" rather than "Xss-Protection". The experimental header prefix "X-" is removed when $stripX is true. Prefixes are never added to the field names. When $headerName is an array, each value in the array will be normalized. Examples: ```php // The output from these method calls will be exactly "Content-Type". echo Utils::normalizeHeaderName("content-type"); echo Utils::normalizeHeaderName("content_type"); echo Utils::normalizeHeaderName("CONTENT-TYPE"); echo Utils::normalizeHeaderName("CONTENT_TYPE"); echo Utils::normalizeHeaderName("content type"); echo Utils::normalizeHeaderName(" content-type "); echo Utils::normalizeHeaderName("Content-Type: "); // The output from these method calls will be exactly "XSS-Protection". echo Utils::normalizeHeaderName("xss-protection"); echo Utils::normalizeHeaderName("XSS_PROTECTION"); echo Utils::normalizeHeaderName("X-XSS-Protection", true); // This method call throws an exception because it's a full header, and not just a name. echo Utils::normalizeHeaderName("content-type: text/html"); // This method call throws an exception because it contains special characters. echo Utils::normalizeHeaderName("content*type"); // Using an array of header names. $names = ["CONTENT_TYPE", "XSS_PROTECTION"]; $normal = Utils::normalizeHeaderName($names); // Produces: ["Content-Type", "XSS-Protection"] ``` @param string|array $headerName The header name or array of header names @param bool $stripX Should the experimental "X-" prefix be removed? @return string @throws Exceptions\InvalidArgumentException When the header name cannot be normalized
https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/Utils.php#L76-L104
headzoo/web-tools
src/Headzoo/Web/Tools/Utils.php
Utils.appendUrlQuery
public static function appendUrlQuery($url, $query) { if (is_array($query)) { $query = http_build_query($query); } $query = ltrim($query, "?&"); $joiner = strpos($url, "?") === false ? "?" : "&"; return "{$url}{$joiner}{$query}"; }
php
public static function appendUrlQuery($url, $query) { if (is_array($query)) { $query = http_build_query($query); } $query = ltrim($query, "?&"); $joiner = strpos($url, "?") === false ? "?" : "&"; return "{$url}{$joiner}{$query}"; }
Appends the query string to the url Used when you need to append a query string to a url which may already have a query string. The $query argument be either a string, or an array. Note: This method does not merge values from the query string which are already in the url. @param string $url The base rul @param string|array $query The query string to append @return string
https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/Utils.php#L119-L128
diasbruno/stc
lib/stc/MarkdownRender.php
MarkdownRender.render
public function render($template, $options = array()) { $pre_render = view($template, $options); $md = new \Parsedown(); return $md->text($pre_render); }
php
public function render($template, $options = array()) { $pre_render = view($template, $options); $md = new \Parsedown(); return $md->text($pre_render); }
Render the template with options. @param $template string | The template name. @param $options array | A hash with options to render. @return string
https://github.com/diasbruno/stc/blob/43f62c3b28167bff76274f954e235413a9e9c707/lib/stc/MarkdownRender.php#L25-L31
CandleLight-Project/Framework
src/Migration.php
Migration.execUp
public function execUp(string $name): void{ DB::connection('default')->table('migrations')->insert(['name' => $name]); $this->up(); }
php
public function execUp(string $name): void{ DB::connection('default')->table('migrations')->insert(['name' => $name]); $this->up(); }
Kicks of the Migration-Up Process
https://github.com/CandleLight-Project/Framework/blob/13c5cc34bd1118601406b0129f7b61c7b78d08f4/src/Migration.php#L54-L57
CandleLight-Project/Framework
src/Migration.php
Migration.execDown
public function execDown(string $name): void{ $this->down(); DB::connection('default')->table('migrations')->where('name', $name)->delete(); }
php
public function execDown(string $name): void{ $this->down(); DB::connection('default')->table('migrations')->where('name', $name)->delete(); }
Kicks of the Migration-Down Process
https://github.com/CandleLight-Project/Framework/blob/13c5cc34bd1118601406b0129f7b61c7b78d08f4/src/Migration.php#L62-L65
CandleLight-Project/Framework
src/Migration.php
Migration.hasMigrated
public static function hasMigrated(string $name){ $res = DB::connection('default')->table('migrations')->where('name', $name)->first(); return !is_null($res); }
php
public static function hasMigrated(string $name){ $res = DB::connection('default')->table('migrations')->where('name', $name)->first(); return !is_null($res); }
Checks if the given migration has been done already @param string $name @return bool
https://github.com/CandleLight-Project/Framework/blob/13c5cc34bd1118601406b0129f7b61c7b78d08f4/src/Migration.php#L82-L85
CandleLight-Project/Framework
src/Migration.php
Migration.getLastMigration
public static function getLastMigration(App $app){ $res = DB::connection('default')->table('migrations')->orderBy('id', 'desc')->first(); if (is_null($res) || !$app->hasMigration($res->name)){ return false; } return $res->name; }
php
public static function getLastMigration(App $app){ $res = DB::connection('default')->table('migrations')->orderBy('id', 'desc')->first(); if (is_null($res) || !$app->hasMigration($res->name)){ return false; } return $res->name; }
Returns the last migration-name, which has been done @param App $app CDL Application instance @return string|bool migration name or false if no migrations have been found
https://github.com/CandleLight-Project/Framework/blob/13c5cc34bd1118601406b0129f7b61c7b78d08f4/src/Migration.php#L92-L98
CandleLight-Project/Framework
src/Migration.php
Migration.prepareMigrationTable
public static function prepareMigrationTable(App $app): void{ $migration = new class($app) extends Migration{ /** * Create the migration table if it does not exist yet */ public function up(): void{ $schema = $this->getSchema('default'); if (!$schema->hasTable('migrations')) { $schema->create('migrations', function (Blueprint $table){ $table->increments('id'); $table->string('name', 255); }); } } /** * Is not needed, but add it nevertheless */ public function down(): void{ $this->getSchema('default')->drop('migrations'); } }; $migration->up(); }
php
public static function prepareMigrationTable(App $app): void{ $migration = new class($app) extends Migration{ /** * Create the migration table if it does not exist yet */ public function up(): void{ $schema = $this->getSchema('default'); if (!$schema->hasTable('migrations')) { $schema->create('migrations', function (Blueprint $table){ $table->increments('id'); $table->string('name', 255); }); } } /** * Is not needed, but add it nevertheless */ public function down(): void{ $this->getSchema('default')->drop('migrations'); } }; $migration->up(); }
Prepares the migration table @param App $app
https://github.com/CandleLight-Project/Framework/blob/13c5cc34bd1118601406b0129f7b61c7b78d08f4/src/Migration.php#L104-L128
UnionOfRAD/li3_quality
qa/rules/syntax/HasExplicitPropertyAndMethodVisibility.php
HasExplicitPropertyAndMethodVisibility.apply
public function apply($testable, array $config = array()) { $message = '{:name} has no declared visibility.'; $tokens = $testable->tokens(); $classes = $testable->findAll(array(T_CLASS)); $filtered = $testable->findAll($this->inspectableTokens); foreach ($classes as $classId) { $children = $tokens[$classId]['children']; foreach ($children as $member) { if (!in_array($member, $filtered)) { continue; } $modifiers = Parser::modifiers($member, $tokens); $visibility = $testable->findNext($this->findTokens, $modifiers); if ($visibility === false) { $token = $tokens[$member]; $this->addViolation(array( 'modifiers' => $modifiers, 'message' => String::insert($message, $token), 'line' => $token['line'], )); } } } }
php
public function apply($testable, array $config = array()) { $message = '{:name} has no declared visibility.'; $tokens = $testable->tokens(); $classes = $testable->findAll(array(T_CLASS)); $filtered = $testable->findAll($this->inspectableTokens); foreach ($classes as $classId) { $children = $tokens[$classId]['children']; foreach ($children as $member) { if (!in_array($member, $filtered)) { continue; } $modifiers = Parser::modifiers($member, $tokens); $visibility = $testable->findNext($this->findTokens, $modifiers); if ($visibility === false) { $token = $tokens[$member]; $this->addViolation(array( 'modifiers' => $modifiers, 'message' => String::insert($message, $token), 'line' => $token['line'], )); } } } }
Will iterate all the tokens looking for tokens in inspectableTokens The token needs an access modifier if it is a T_FUNCTION or T_VARIABLE and is in the first level of T_CLASS. This prevents functions and variables inside methods and outside classes to register violations. @param Testable $testable The testable object @return void
https://github.com/UnionOfRAD/li3_quality/blob/acb72a43ae835e6d200bc0eba1a61aee610e36bf/qa/rules/syntax/HasExplicitPropertyAndMethodVisibility.php#L46-L70
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.email
public function email($message = null) { $this->setRule(__FUNCTION__, function($email) { if (strlen($email) == 0) return true; $isValid = true; $atIndex = strrpos($email, '@'); if (is_bool($atIndex) && !$atIndex) { $isValid = false; } else { $domain = substr($email, $atIndex+1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); $domainLen = strlen($domain); if ($localLen < 1 || $localLen > 64) { $isValid = false; } else if ($domainLen < 1 || $domainLen > 255) { // domain part length exceeded $isValid = false; } else if ($local[0] == '.' || $local[$localLen-1] == '.') { // local part starts or ends with '.' $isValid = false; } else if (preg_match('/\\.\\./', $local)) { // local part has two consecutive dots $isValid = false; } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { // character not valid in domain part $isValid = false; } else if (preg_match('/\\.\\./', $domain)) { // domain part has two consecutive dots $isValid = false; } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) { // character not valid in local part unless // local part is quoted if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; } } // check DNS if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) { // hmm, the domain has no MX records if (checkdnsrr('gmail.com',"MX")) { // but Gmail does. the other domain must be dodgy $isValid = false; } // otherwise: probably running off-line or maybe DNS service is not working } } return $isValid; }, $message); return $this; }
php
public function email($message = null) { $this->setRule(__FUNCTION__, function($email) { if (strlen($email) == 0) return true; $isValid = true; $atIndex = strrpos($email, '@'); if (is_bool($atIndex) && !$atIndex) { $isValid = false; } else { $domain = substr($email, $atIndex+1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); $domainLen = strlen($domain); if ($localLen < 1 || $localLen > 64) { $isValid = false; } else if ($domainLen < 1 || $domainLen > 255) { // domain part length exceeded $isValid = false; } else if ($local[0] == '.' || $local[$localLen-1] == '.') { // local part starts or ends with '.' $isValid = false; } else if (preg_match('/\\.\\./', $local)) { // local part has two consecutive dots $isValid = false; } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { // character not valid in domain part $isValid = false; } else if (preg_match('/\\.\\./', $domain)) { // domain part has two consecutive dots $isValid = false; } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) { // character not valid in local part unless // local part is quoted if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; } } // check DNS if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) { // hmm, the domain has no MX records if (checkdnsrr('gmail.com',"MX")) { // but Gmail does. the other domain must be dodgy $isValid = false; } // otherwise: probably running off-line or maybe DNS service is not working } } return $isValid; }, $message); return $this; }
Field, if completed, has to be a valid email address. @param string $message @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L65-L122
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.required
public function required($message = null) { $this->setRule(__FUNCTION__, function($val) { if (is_scalar($val)) { $val = trim($val); } return !empty($val); }, $message); return $this; }
php
public function required($message = null) { $this->setRule(__FUNCTION__, function($val) { if (is_scalar($val)) { $val = trim($val); } return !empty($val); }, $message); return $this; }
Field must be filled in. @param string $message @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L130-L140
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.exists
public function exists( $message = null) { $this->setRule(__FUNCTION__, function ($val) { return null !== $val; }, $message); return $this; }
php
public function exists( $message = null) { $this->setRule(__FUNCTION__, function ($val) { return null !== $val; }, $message); return $this; }
Field must exist, even if empty @param null $message @return $this
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L148-L154
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.float
public function float($message = null) { $this->setRule(__FUNCTION__, function($val) { return !(filter_var($val, FILTER_VALIDATE_FLOAT) === FALSE); }, $message); return $this; }
php
public function float($message = null) { $this->setRule(__FUNCTION__, function($val) { return !(filter_var($val, FILTER_VALIDATE_FLOAT) === FALSE); }, $message); return $this; }
Field must contain a valid float value. @param string $message @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L162-L169
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.integer
public function integer($message = null) { $this->setRule(__FUNCTION__, function($val) { return !(filter_var($val, FILTER_VALIDATE_INT) === FALSE); }, $message); return $this; }
php
public function integer($message = null) { $this->setRule(__FUNCTION__, function($val) { return !(filter_var($val, FILTER_VALIDATE_INT) === FALSE); }, $message); return $this; }
Field must contain a valid integer value. @param string $message @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L177-L184
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.digits
public function digits($message = null) { $this->setRule(__FUNCTION__, function($val) { return (strlen($val) === 0 || ctype_digit((string) $val)); }, $message); return $this; }
php
public function digits($message = null) { $this->setRule(__FUNCTION__, function($val) { return (strlen($val) === 0 || ctype_digit((string) $val)); }, $message); return $this; }
Every character in field, if completed, must be a digit. This is just like integer(), except there is no upper limit. @param string $message @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L193-L200
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.min
public function min($limit, $include = TRUE, $message = null) { $this->setRule(__FUNCTION__, function($val, $args) { if (strlen($val) === 0) { return TRUE; } $val = (float) $val; $limit = (float) $args[0]; $inc = (bool) $args[1]; return ($val > $limit || ($inc === TRUE && $val === $limit)); }, $message, array($limit, $include)); return $this; }
php
public function min($limit, $include = TRUE, $message = null) { $this->setRule(__FUNCTION__, function($val, $args) { if (strlen($val) === 0) { return TRUE; } $val = (float) $val; $limit = (float) $args[0]; $inc = (bool) $args[1]; return ($val > $limit || ($inc === TRUE && $val === $limit)); }, $message, array($limit, $include)); return $this; }
Field must be a number greater than [or equal to] X. @param numeric $limit @param bool $include Whether to include limit value. @param string $message @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L210-L225
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.between
public function between($min, $max, $include = TRUE, $message = null) { $message = $this->_getDefaultMessage(__FUNCTION__, array($min, $max, $include)); $this->min($min, $include, $message)->max($max, $include, $message); return $this; }
php
public function between($min, $max, $include = TRUE, $message = null) { $message = $this->_getDefaultMessage(__FUNCTION__, array($min, $max, $include)); $this->min($min, $include, $message)->max($max, $include, $message); return $this; }
Field must be a number between X and Y. @param numeric $min @param numeric $max @param bool $include Whether to include limit value. @param string $message @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L261-L267
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.minlength
public function minlength($len, $message = null) { $this->setRule(__FUNCTION__, function($val, $args) { return !(strlen(trim($val)) < $args[0]); }, $message, array($len)); return $this; }
php
public function minlength($len, $message = null) { $this->setRule(__FUNCTION__, function($val, $args) { return !(strlen(trim($val)) < $args[0]); }, $message, array($len)); return $this; }
Field has to be greater than or equal to X characters long. @param int $len @param string $message @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L276-L283
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.betweenlength
public function betweenlength($minlength, $maxlength, $message = null) { $message = empty($message) ? self::getDefaultMessage(__FUNCTION__, array($minlength, $maxlength)) : NULL; $this->minlength($minlength, $message)->max($maxlength, $message); return $this; }
php
public function betweenlength($minlength, $maxlength, $message = null) { $message = empty($message) ? self::getDefaultMessage(__FUNCTION__, array($minlength, $maxlength)) : NULL; $this->minlength($minlength, $message)->max($maxlength, $message); return $this; }
Field has to be between minlength and maxlength characters long. @param int $minlength @param int $maxlength @
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L308-L314
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.matches
public function matches($field, $label, $message = null) { $this->setRule(__FUNCTION__, function($val, $args) { return ((string) $args[0] == (string) $val); }, $message, array($this->_getVal($field), $label)); return $this; }
php
public function matches($field, $label, $message = null) { $this->setRule(__FUNCTION__, function($val, $args) { return ((string) $args[0] == (string) $val); }, $message, array($this->_getVal($field), $label)); return $this; }
Field is the same as another one (password comparison etc). @param string $field @param string $label @param string $message @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L340-L347
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.endsWith
public function endsWith($sub, $message = null) { $this->setRule(__FUNCTION__, function($val, $args) { $sub = $args[0]; return (strlen($val) === 0 || substr($val, -strlen($sub)) === $sub); }, $message, array($sub)); return $this; }
php
public function endsWith($sub, $message = null) { $this->setRule(__FUNCTION__, function($val, $args) { $sub = $args[0]; return (strlen($val) === 0 || substr($val, -strlen($sub)) === $sub); }, $message, array($sub)); return $this; }
Field must end with a specific substring. @param string $sub @param string $message @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L407-L415
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.ip
public function ip($message = null) { $this->setRule(__FUNCTION__, function($val) { return (strlen(trim($val)) === 0 || filter_var($val, FILTER_VALIDATE_IP) !== FALSE); }, $message); return $this; }
php
public function ip($message = null) { $this->setRule(__FUNCTION__, function($val) { return (strlen(trim($val)) === 0 || filter_var($val, FILTER_VALIDATE_IP) !== FALSE); }, $message); return $this; }
Field has to be valid IP address. @param string $message @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L440-L447
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.url
public function url($message = null) { $this->setRule(__FUNCTION__, function($val) { return (strlen(trim($val)) === 0 || filter_var($val, FILTER_VALIDATE_URL) !== FALSE); }, $message); return $this; }
php
public function url($message = null) { $this->setRule(__FUNCTION__, function($val) { return (strlen(trim($val)) === 0 || filter_var($val, FILTER_VALIDATE_URL) !== FALSE); }, $message); return $this; }
Field has to be valid internet address. @param string $message @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L455-L462
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.date
public function date($message = null, $format = null, $separator = '') { $this->setRule(__FUNCTION__, function($val, $args) { if (strlen(trim($val)) === 0) { return TRUE; } try { $dt = new \DateTime($val, new \DateTimeZone("UTC")); return true; } catch(\Exception $e) { return false; } }, $message, array($format, $separator)); return $this; }
php
public function date($message = null, $format = null, $separator = '') { $this->setRule(__FUNCTION__, function($val, $args) { if (strlen(trim($val)) === 0) { return TRUE; } try { $dt = new \DateTime($val, new \DateTimeZone("UTC")); return true; } catch(\Exception $e) { return false; } }, $message, array($format, $separator)); return $this; }
Field has to be a valid date. @param string $message @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L479-L497
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.minDate
public function minDate($date = 0, $format = null, $message = null) { if (empty($format)) { $format = $this->_getDefaultDateFormat(); } if (is_numeric($date)) { $date = new \DateTime($date . ' days'); // Days difference from today } else { $fieldValue = $this->_getVal($date); $date = ($fieldValue == FALSE) ? $date : $fieldValue; $date = \DateTime::createFromFormat($format, $date); } $this->setRule(__FUNCTION__, function($val, $args) { $format = $args[1]; $limitDate = $args[0]; return ($limitDate > \DateTime::createFromFormat($format, $val)) ? FALSE : TRUE; }, $message, array($date, $format)); return $this; }
php
public function minDate($date = 0, $format = null, $message = null) { if (empty($format)) { $format = $this->_getDefaultDateFormat(); } if (is_numeric($date)) { $date = new \DateTime($date . ' days'); // Days difference from today } else { $fieldValue = $this->_getVal($date); $date = ($fieldValue == FALSE) ? $date : $fieldValue; $date = \DateTime::createFromFormat($format, $date); } $this->setRule(__FUNCTION__, function($val, $args) { $format = $args[1]; $limitDate = $args[0]; return ($limitDate > \DateTime::createFromFormat($format, $val)) ? FALSE : TRUE; }, $message, array($date, $format)); return $this; }
Field has to be a date later than or equal to X. @param string|int $date Limit date @param string $format Date format @param string $message @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L507-L529
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.ccnum
public function ccnum($message = null) { $this->setRule(__FUNCTION__, function($value) { $value = str_replace(' ', '', $value); $length = strlen($value); if ($length < 13 || $length > 19) { return FALSE; } $sum = 0; $weight = 2; for ($i = $length - 2; $i >= 0; $i--) { $digit = $weight * $value[$i]; $sum += floor($digit / 10) + $digit % 10; $weight = $weight % 2 + 1; } $mod = (10 - $sum % 10) % 10; return ($mod == $value[$length - 1]); }, $message); return $this; }
php
public function ccnum($message = null) { $this->setRule(__FUNCTION__, function($value) { $value = str_replace(' ', '', $value); $length = strlen($value); if ($length < 13 || $length > 19) { return FALSE; } $sum = 0; $weight = 2; for ($i = $length - 2; $i >= 0; $i--) { $digit = $weight * $value[$i]; $sum += floor($digit / 10) + $digit % 10; $weight = $weight % 2 + 1; } $mod = (10 - $sum % 10) % 10; return ($mod == $value[$length - 1]); }, $message); return $this; }
Field has to be a valid credit card number format. @see https://github.com/funkatron/inspekt/blob/master/Inspekt.php @param string $message @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L570-L595
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.oneOf
public function oneOf($allowed, $message = null) { if (is_string($allowed)) { $allowed = explode(',', $allowed); } $this->setRule(__FUNCTION__, function($val, $args) { return in_array($val, $args[0]); }, $message, array($allowed)); return $this; }
php
public function oneOf($allowed, $message = null) { if (is_string($allowed)) { $allowed = explode(',', $allowed); } $this->setRule(__FUNCTION__, function($val, $args) { return in_array($val, $args[0]); }, $message, array($allowed)); return $this; }
Field has to be one of the allowed ones. @param string|array $allowed Allowed values. @param string $message @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L604-L615
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.callback
public function callback($callback, $message = '', $params = NULL) { if(!is_callable($callback)) { throw new \Exception(sprintf('%s is not callable.', $callback)); } // needs a unique name to avoid collisions in the rules array $name = 'callback_' . sha1(uniqid()); $this->setRule( $name, function($value) use ($params, $callback) { if(!$params) $params = array(); return call_user_func_array( $callback, array_merge(array($value), $params) ); }, $message ); return $this; }
php
public function callback($callback, $message = '', $params = NULL) { if(!is_callable($callback)) { throw new \Exception(sprintf('%s is not callable.', $callback)); } // needs a unique name to avoid collisions in the rules array $name = 'callback_' . sha1(uniqid()); $this->setRule( $name, function($value) use ($params, $callback) { if(!$params) $params = array(); return call_user_func_array( $callback, array_merge(array($value), $params) ); }, $message ); return $this; }
callback @param string $name @param mixed $function @param string $message @param mixed $params @return FormValidator
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L627-L649
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator._applyFilter
protected function _applyFilter(&$val) { if (is_array($val)) { foreach($val as $key => &$item) { $this->_applyFilter($item); } } else { foreach($this->filters as $filter) { $val = $filter($val); } } }
php
protected function _applyFilter(&$val) { if (is_array($val)) { foreach($val as $key => &$item) { $this->_applyFilter($item); } } else { foreach($this->filters as $filter) { $val = $filter($val); } } }
recursively apply filters to a value @access protected @param mixed $val reference @return void
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L686-L697
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.validate
public function validate($key, $label = '') { // set up field name for error message $this->fields[$key] = (empty($label)) ? 'Field with the name of "' . $key . '"' : $label; // apply filters to the data $this->_applyFilters($key); $val = $this->_getVal($key); // validate the piece of data $this->_validate($key, $val); // reset rules $this->rules = array(); $this->filters = array(); return $val; }
php
public function validate($key, $label = '') { // set up field name for error message $this->fields[$key] = (empty($label)) ? 'Field with the name of "' . $key . '"' : $label; // apply filters to the data $this->_applyFilters($key); $val = $this->_getVal($key); // validate the piece of data $this->_validate($key, $val); // reset rules $this->rules = array(); $this->filters = array(); return $val; }
validate @param string $key @param string $label @return bool
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L705-L722
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator._validate
protected function _validate($key, $val) { // try each rule function foreach ($this->rules as $rule => $is_true) { if ($is_true) { $function = $this->functions[$rule]; $args = $this->arguments[$rule]; // Arguments of rule $valid = true; if(is_array($val)) { foreach($val as $v) { $valid = $valid && (empty($args)) ? $function($v) : $function($v, $args); } } else { $valid = (empty($args)) ? $function($val) : $function($val, $args); } if ($valid === FALSE) { $this->registerError($rule, $key); $this->rules = array(); // reset rules $this->filters = array(); return FALSE; } } } $this->validData[$key] = $val; return TRUE; }
php
protected function _validate($key, $val) { // try each rule function foreach ($this->rules as $rule => $is_true) { if ($is_true) { $function = $this->functions[$rule]; $args = $this->arguments[$rule]; // Arguments of rule $valid = true; if(is_array($val)) { foreach($val as $v) { $valid = $valid && (empty($args)) ? $function($v) : $function($v, $args); } } else { $valid = (empty($args)) ? $function($val) : $function($val, $args); } if ($valid === FALSE) { $this->registerError($rule, $key); $this->rules = array(); // reset rules $this->filters = array(); return FALSE; } } } $this->validData[$key] = $val; return TRUE; }
recursively validates a value @access protected @param string $key @param mixed $val @return bool
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L732-L761
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.getAllErrors
public function getAllErrors($keys = true) { return ($keys == true) ? $this->errors : array_values($this->errors); }
php
public function getAllErrors($keys = true) { return ($keys == true) ? $this->errors : array_values($this->errors); }
Get all errors. @return array
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L788-L791
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator._getVal
protected function _getVal($key) { // handle multi-dimensional arrays if (strpos($key, '.') !== FALSE) { $arrData = NULL; $keys = explode('.', $key); $keyLen = count($keys); for ($i = 0; $i < $keyLen; ++$i) { if (trim($keys[$i]) == '') { return false; } else { if (is_null($arrData)) { if (!isset($this->data[$keys[$i]])) { return false; } $arrData = $this->data[$keys[$i]]; } else { if (!isset($arrData[$keys[$i]])) { return false; } $arrData = $arrData[$keys[$i]]; } } } return $arrData; } else { return (isset($this->data[$key])) ? $this->data[$key] : FALSE; } }
php
protected function _getVal($key) { // handle multi-dimensional arrays if (strpos($key, '.') !== FALSE) { $arrData = NULL; $keys = explode('.', $key); $keyLen = count($keys); for ($i = 0; $i < $keyLen; ++$i) { if (trim($keys[$i]) == '') { return false; } else { if (is_null($arrData)) { if (!isset($this->data[$keys[$i]])) { return false; } $arrData = $this->data[$keys[$i]]; } else { if (!isset($arrData[$keys[$i]])) { return false; } $arrData = $arrData[$keys[$i]]; } } } return $arrData; } else { return (isset($this->data[$key])) ? $this->data[$key] : FALSE; } }
_getVal with added support for retrieving values from numeric and associative multi-dimensional arrays. When doing so, use DOT notation to indicate a break in keys, i.e.: key = "one.two.three" would search the array: array('one' => array( 'two' => array( 'three' => 'RETURN THIS' ) ); @param string $key @return mixed
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L816-L844
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.registerError
protected function registerError($rule, $key, $message = null) { if (empty($message)) { $message = $this->messages[$rule]; } $this->errors[$key] = sprintf($message, $this->fields[$key]); }
php
protected function registerError($rule, $key, $message = null) { if (empty($message)) { $message = $this->messages[$rule]; } $this->errors[$key] = sprintf($message, $this->fields[$key]); }
Register error. @param string $rule @param string $key @param string $message
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L853-L860
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.setRule
public function setRule($rule, $function, $message = '', $args = array()) { if (!array_key_exists($rule, $this->rules)) { $this->rules[$rule] = TRUE; if (!array_key_exists($rule, $this->functions)) { if (!is_callable($function)) { die('Invalid function for rule: ' . $rule); } $this->functions[$rule] = $function; } $this->arguments[$rule] = $args; // Specific arguments for rule $this->messages[$rule] = (empty($message)) ? $this->_getDefaultMessage($rule, $args) : $message; } }
php
public function setRule($rule, $function, $message = '', $args = array()) { if (!array_key_exists($rule, $this->rules)) { $this->rules[$rule] = TRUE; if (!array_key_exists($rule, $this->functions)) { if (!is_callable($function)) { die('Invalid function for rule: ' . $rule); } $this->functions[$rule] = $function; } $this->arguments[$rule] = $args; // Specific arguments for rule $this->messages[$rule] = (empty($message)) ? $this->_getDefaultMessage($rule, $args) : $message; } }
Set rule. @param string $rule @param closure $function @param string $message @param array $args
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L870-L884
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator._getDefaultMessage
protected function _getDefaultMessage($rule, $args = null) { switch ($rule) { case 'email': $message = '%s is an invalid email address.'; break; case 'ip': $message = '%s is an invalid IP address.'; break; case 'url': $message = '%s is an invalid url.'; break; case 'required': $message = '%s is required.'; break; case 'float': $message = '%s must consist of numbers only.'; break; case 'integer': $message = '%s must consist of integer value.'; break; case 'digits': $message = '%s must consist only of digits.'; break; case 'min': $message = '%s must be greater than '; if ($args[1] == TRUE) { $message .= 'or equal to '; } $message .= $args[0] . '.'; break; case 'max': $message = '%s must be less than '; if ($args[1] == TRUE) { $message .= 'or equal to '; } $message .= $args[0] . '.'; break; case 'between': $message = '%s must be between ' . $args[0] . ' and ' . $args[1] . '.'; if ($args[2] == FALSE) { $message .= '(Without limits)'; } break; case 'minlength': $message = '%s must be at least ' . $args[0] . ' characters or longer.'; break; case 'maxlength': $message = '%s must be no longer than ' . $args[0] . ' characters.'; break; case 'length': $message = '%s must be exactly ' . $args[0] . ' characters in length.'; break; case 'matches': $message = '%s must match ' . $args[1] . '.'; break; case 'notmatches': $message = '%s must not match ' . $args[1] . '.'; break; case 'startsWith': $message = '%s must start with "' . $args[0] . '".'; break; case 'notstartsWith': $message = '%s must not start with "' . $args[0] . '".'; break; case 'endsWith': $message = '%s must end with "' . $args[0] . '".'; break; case 'notendsWith': $message = '%s must not end with "' . $args[0] . '".'; break; case 'date': $message = '%s is not valid date.'; break; case 'mindate': $message = '%s must be later than ' . $args[0]->format($args[1]) . '.'; break; case 'maxdate': $message = '%s must be before ' . $args[0]->format($args[1]) . '.'; break; case 'oneof': $message = '%s must be one of ' . implode(', ', $args[0]) . '.'; break; case 'ccnum': $message = '%s must be a valid credit card number.'; break; default: $message = '%s has an error.'; break; } return $message; }
php
protected function _getDefaultMessage($rule, $args = null) { switch ($rule) { case 'email': $message = '%s is an invalid email address.'; break; case 'ip': $message = '%s is an invalid IP address.'; break; case 'url': $message = '%s is an invalid url.'; break; case 'required': $message = '%s is required.'; break; case 'float': $message = '%s must consist of numbers only.'; break; case 'integer': $message = '%s must consist of integer value.'; break; case 'digits': $message = '%s must consist only of digits.'; break; case 'min': $message = '%s must be greater than '; if ($args[1] == TRUE) { $message .= 'or equal to '; } $message .= $args[0] . '.'; break; case 'max': $message = '%s must be less than '; if ($args[1] == TRUE) { $message .= 'or equal to '; } $message .= $args[0] . '.'; break; case 'between': $message = '%s must be between ' . $args[0] . ' and ' . $args[1] . '.'; if ($args[2] == FALSE) { $message .= '(Without limits)'; } break; case 'minlength': $message = '%s must be at least ' . $args[0] . ' characters or longer.'; break; case 'maxlength': $message = '%s must be no longer than ' . $args[0] . ' characters.'; break; case 'length': $message = '%s must be exactly ' . $args[0] . ' characters in length.'; break; case 'matches': $message = '%s must match ' . $args[1] . '.'; break; case 'notmatches': $message = '%s must not match ' . $args[1] . '.'; break; case 'startsWith': $message = '%s must start with "' . $args[0] . '".'; break; case 'notstartsWith': $message = '%s must not start with "' . $args[0] . '".'; break; case 'endsWith': $message = '%s must end with "' . $args[0] . '".'; break; case 'notendsWith': $message = '%s must not end with "' . $args[0] . '".'; break; case 'date': $message = '%s is not valid date.'; break; case 'mindate': $message = '%s must be later than ' . $args[0]->format($args[1]) . '.'; break; case 'maxdate': $message = '%s must be before ' . $args[0]->format($args[1]) . '.'; break; case 'oneof': $message = '%s must be one of ' . implode(', ', $args[0]) . '.'; break; case 'ccnum': $message = '%s must be a valid credit card number.'; break; default: $message = '%s has an error.'; break; } return $message; }
Get default error message. @param string $key @param array $args @return string
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L893-L1010
gregorybesson/PlaygroundFlow
src/Service/Action.php
Action.getActionMapper
public function getActionMapper() { if (null === $this->actionMapper) { $this->actionMapper = $this->serviceLocator->get('playgroundflow_action_mapper'); } return $this->actionMapper; }
php
public function getActionMapper() { if (null === $this->actionMapper) { $this->actionMapper = $this->serviceLocator->get('playgroundflow_action_mapper'); } return $this->actionMapper; }
getActionMapper @return ActionMapperInterface
https://github.com/gregorybesson/PlaygroundFlow/blob/f97493f8527e425d46223ac7b5c41331ab8b3022/src/Service/Action.php#L79-L86
datto/core-enumerator
src/Core/Enumerator.php
Enumerator.getClasses
public static function getClasses($namespace, $conditions = []) { self::_setupRoot(); $namespace = explode('\\', trim($namespace, '\\')); $composerNamespaces = self::getComposerNamespaces(); $searchPaths = []; // for each Composer namespace, assess whether it may contain the namespace $namespace. foreach ( $composerNamespaces as $ns => $paths ) { $nsTrimmed = explode('\\', trim($ns, '\\')); for ( $i = min(count($nsTrimmed), count($namespace)); $i > 0; $i-- ) { if ( array_slice($nsTrimmed, 0, $i) === array_slice($namespace, 0, $i) ) { $searchPaths[] = [ 'prefix' => $nsTrimmed , 'paths' => $paths ]; continue; } } } // $searchPaths now contains a list of PSR-4 namespaces we must search for // classes under the namespace $namespace. // FIXME crawling everything under the sun is potentially very time-consuming. It would make a lot of // sense to be able to generate a cache classes specifying what interfaces each class implements, etc. $result = []; foreach ( $searchPaths as $pathspec ) { foreach ( $pathspec['paths'] as $path ) { // Determine the path under which the namespace we are searching for will exist for this pathspace $path = $path . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, array_slice($namespace, count($pathspec['prefix']))); $prefix = count($pathspec['prefix']) > count($namespace) ? implode('\\', $pathspec['prefix']) : implode('\\', $namespace); // if that path exists, go ahead and search it for class files and append them to the result. if ( is_dir($path) ) { $result = array_merge($result, self::searchPath($prefix, rtrim($path, DIRECTORY_SEPARATOR), $conditions)); } } } return $result; }
php
public static function getClasses($namespace, $conditions = []) { self::_setupRoot(); $namespace = explode('\\', trim($namespace, '\\')); $composerNamespaces = self::getComposerNamespaces(); $searchPaths = []; // for each Composer namespace, assess whether it may contain the namespace $namespace. foreach ( $composerNamespaces as $ns => $paths ) { $nsTrimmed = explode('\\', trim($ns, '\\')); for ( $i = min(count($nsTrimmed), count($namespace)); $i > 0; $i-- ) { if ( array_slice($nsTrimmed, 0, $i) === array_slice($namespace, 0, $i) ) { $searchPaths[] = [ 'prefix' => $nsTrimmed , 'paths' => $paths ]; continue; } } } // $searchPaths now contains a list of PSR-4 namespaces we must search for // classes under the namespace $namespace. // FIXME crawling everything under the sun is potentially very time-consuming. It would make a lot of // sense to be able to generate a cache classes specifying what interfaces each class implements, etc. $result = []; foreach ( $searchPaths as $pathspec ) { foreach ( $pathspec['paths'] as $path ) { // Determine the path under which the namespace we are searching for will exist for this pathspace $path = $path . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, array_slice($namespace, count($pathspec['prefix']))); $prefix = count($pathspec['prefix']) > count($namespace) ? implode('\\', $pathspec['prefix']) : implode('\\', $namespace); // if that path exists, go ahead and search it for class files and append them to the result. if ( is_dir($path) ) { $result = array_merge($result, self::searchPath($prefix, rtrim($path, DIRECTORY_SEPARATOR), $conditions)); } } } return $result; }
Return a list of classes under a given namespace. It is an error to enumerate the root namespace. @param string Namespace name. Trailing backslash may be omitted. @param Limiting rules. An array of constraints on the returned results. Currently the only supported constraints are "implements" (string - class name) and "abstract" (boolean). Use it: [ ['implements' => 'Some\Interface', 'abstract' => false] ] @return array @static
https://github.com/datto/core-enumerator/blob/90cdcc90cc0453c35e7b2d2e941d23abd6e9cf39/src/Core/Enumerator.php#L53-L102
datto/core-enumerator
src/Core/Enumerator.php
Enumerator.getComposerModule
public static function getComposerModule($className) { global $Composer; if ( $result = $Composer->findFile($className) ) { $result = substr($result, strlen(self::$root)); if ( preg_match('#^vendor/([a-z0-9_-]+/[a-z0-9_-]+)/#', $result, $match) ) { return $match[1]; } } return null; }
php
public static function getComposerModule($className) { global $Composer; if ( $result = $Composer->findFile($className) ) { $result = substr($result, strlen(self::$root)); if ( preg_match('#^vendor/([a-z0-9_-]+/[a-z0-9_-]+)/#', $result, $match) ) { return $match[1]; } } return null; }
Return the name of the composer module where a given class lives. @param string Class name @return mixed String if it lives in a module, or null if the root
https://github.com/datto/core-enumerator/blob/90cdcc90cc0453c35e7b2d2e941d23abd6e9cf39/src/Core/Enumerator.php#L110-L123
datto/core-enumerator
src/Core/Enumerator.php
Enumerator.getComposerNamespaces
private static function getComposerNamespaces() { static $result = null; if ( !is_array($result) ) { $result = require self::$root . 'vendor/composer/autoload_namespaces.php'; foreach ( $result as $ns => &$paths ) { $subpath = trim(str_replace('\\', DIRECTORY_SEPARATOR, $ns), DIRECTORY_SEPARATOR); foreach ( $paths as &$path ) { $path = rtrim($path, DIRECTORY_SEPARATOR); if ( is_dir("$path/$subpath") ) { $path = "$path/$subpath"; } } unset($path); } unset($paths); $psr4 = require self::$root . 'vendor/composer/autoload_psr4.php'; foreach ( $psr4 as $ns => $paths ) { if ( isset($result[$ns]) ) { $result[$ns] = array_merge($result[$ns], $paths); } else { $result[$ns] = $paths; } } } return $result; }
php
private static function getComposerNamespaces() { static $result = null; if ( !is_array($result) ) { $result = require self::$root . 'vendor/composer/autoload_namespaces.php'; foreach ( $result as $ns => &$paths ) { $subpath = trim(str_replace('\\', DIRECTORY_SEPARATOR, $ns), DIRECTORY_SEPARATOR); foreach ( $paths as &$path ) { $path = rtrim($path, DIRECTORY_SEPARATOR); if ( is_dir("$path/$subpath") ) { $path = "$path/$subpath"; } } unset($path); } unset($paths); $psr4 = require self::$root . 'vendor/composer/autoload_psr4.php'; foreach ( $psr4 as $ns => $paths ) { if ( isset($result[$ns]) ) { $result[$ns] = array_merge($result[$ns], $paths); } else { $result[$ns] = $paths; } } } return $result; }
Get Composer's namespace list. @return array @access private @static
https://github.com/datto/core-enumerator/blob/90cdcc90cc0453c35e7b2d2e941d23abd6e9cf39/src/Core/Enumerator.php#L132-L165
datto/core-enumerator
src/Core/Enumerator.php
Enumerator.searchPath
private static function searchPath($prefix, $path, $conditions) { $result = []; $dir = new DirectoryIterator($path); foreach ( $dir as $entry ) { if ( $entry->isDot() ) { continue; } $de = $entry->getFilename(); if ( $entry->isDir() && preg_match('/^[A-Za-z_]+$/', $de) ) { // it's a subdirectory, search it $result = array_merge($result, self::searchPath("$prefix\\$de", $path . DIRECTORY_SEPARATOR . $de, $conditions)); } else if ( preg_match('/\.php$/', $de) ) { // FIXME I'm using a regex test here because that in theory is quicker than having // PHP parse the file. Also, this is deliberately designed to exclude abstract classes, // which will cause class_exists() to return (bool)true. $foundNamespace = $foundClass = false; $className = preg_replace('/\.php$/', '', $de); if ( $fp = @fopen($filePath = "$path/$de", 'r') ) { while ( !feof($fp) && ($line = fgets($fp)) ) { // FIXME PHP leaves pretty little room for error in the namespace declaration // line. This is still a little needlessly picky - if someone has a space between // the namespace name and the semicolon this test will fail, as well as dumber // stuff like the word "namespace" being mixed case/uppercase. if ( trim($line) === "namespace $prefix;" ) { $foundNamespace = true; } // This fairly complicated regexp covers "implements" with multiple inheritance, // "extends" and a fair amount of syntactical deviation. else if ( preg_match('/^\s*class ([A-Za-z0-9_]+)(?:\s+(?:extends|implements) [A-Za-z0-9_\\\\]+(?:\s*,\s*[A-Za-z0-9_]+)*)*\s*[\{,]?$/', trim($line), $match) && ($match[1] === "\\$prefix\\$className" || $match[1] === $className) ) { $foundClass = true; } // if we have found the namespace declaration and the class declaration, // we no longer need any more information from this file, so break and // close the handle. if ( $foundNamespace && $foundClass ) { break; } } fclose($fp); } // if we found the namespace declaration and the class declaration, append // the discovered class to the result list. if ( $foundNamespace && $foundClass ) { // fully qualified class name $fqcn = "$prefix\\$className"; // conditions are an OR between each, AND within an individual condition $condCount = 0; // ReflectionClass instance - created only if necessary $rfl = null; foreach ( $conditions as $cond ) { $condResult = true; foreach ( $cond as $test => $value ) { switch($test) { case 'implements': if ( empty($rfl) ) { $rfl = new \ReflectionClass($fqcn); } if ( !$rfl->implementsInterface($value) ) { $condResult = false; break 2; // lazy evaluation } break; case 'extends': if ( empty($rfl) ) { $rfl = new \ReflectionClass($fqcn); } if ( $rfl->getParentClass()->getName() !== $value ) { $condResult = false; break 2; // lazy evaluation } break; case 'abstract': if ( empty($rfl) ) { $rfl = new \ReflectionClass($fqcn); } if ( $rfl->isAbstract() !== $value ) { $condResult = false; break 2; // lazy evaluation } break; } } if ( $condResult ) { $condCount++; } } if ( $condCount || count($conditions) === 0 ) { $result[] = $fqcn; } } } } return $result; }
php
private static function searchPath($prefix, $path, $conditions) { $result = []; $dir = new DirectoryIterator($path); foreach ( $dir as $entry ) { if ( $entry->isDot() ) { continue; } $de = $entry->getFilename(); if ( $entry->isDir() && preg_match('/^[A-Za-z_]+$/', $de) ) { // it's a subdirectory, search it $result = array_merge($result, self::searchPath("$prefix\\$de", $path . DIRECTORY_SEPARATOR . $de, $conditions)); } else if ( preg_match('/\.php$/', $de) ) { // FIXME I'm using a regex test here because that in theory is quicker than having // PHP parse the file. Also, this is deliberately designed to exclude abstract classes, // which will cause class_exists() to return (bool)true. $foundNamespace = $foundClass = false; $className = preg_replace('/\.php$/', '', $de); if ( $fp = @fopen($filePath = "$path/$de", 'r') ) { while ( !feof($fp) && ($line = fgets($fp)) ) { // FIXME PHP leaves pretty little room for error in the namespace declaration // line. This is still a little needlessly picky - if someone has a space between // the namespace name and the semicolon this test will fail, as well as dumber // stuff like the word "namespace" being mixed case/uppercase. if ( trim($line) === "namespace $prefix;" ) { $foundNamespace = true; } // This fairly complicated regexp covers "implements" with multiple inheritance, // "extends" and a fair amount of syntactical deviation. else if ( preg_match('/^\s*class ([A-Za-z0-9_]+)(?:\s+(?:extends|implements) [A-Za-z0-9_\\\\]+(?:\s*,\s*[A-Za-z0-9_]+)*)*\s*[\{,]?$/', trim($line), $match) && ($match[1] === "\\$prefix\\$className" || $match[1] === $className) ) { $foundClass = true; } // if we have found the namespace declaration and the class declaration, // we no longer need any more information from this file, so break and // close the handle. if ( $foundNamespace && $foundClass ) { break; } } fclose($fp); } // if we found the namespace declaration and the class declaration, append // the discovered class to the result list. if ( $foundNamespace && $foundClass ) { // fully qualified class name $fqcn = "$prefix\\$className"; // conditions are an OR between each, AND within an individual condition $condCount = 0; // ReflectionClass instance - created only if necessary $rfl = null; foreach ( $conditions as $cond ) { $condResult = true; foreach ( $cond as $test => $value ) { switch($test) { case 'implements': if ( empty($rfl) ) { $rfl = new \ReflectionClass($fqcn); } if ( !$rfl->implementsInterface($value) ) { $condResult = false; break 2; // lazy evaluation } break; case 'extends': if ( empty($rfl) ) { $rfl = new \ReflectionClass($fqcn); } if ( $rfl->getParentClass()->getName() !== $value ) { $condResult = false; break 2; // lazy evaluation } break; case 'abstract': if ( empty($rfl) ) { $rfl = new \ReflectionClass($fqcn); } if ( $rfl->isAbstract() !== $value ) { $condResult = false; break 2; // lazy evaluation } break; } } if ( $condResult ) { $condCount++; } } if ( $condCount || count($conditions) === 0 ) { $result[] = $fqcn; } } } } return $result; }
Search one directory recursively for classes belonging to a given namespace. @param string Namespace to search for @param string Directory to search @param array Search conditions @return array @access private @static
https://github.com/datto/core-enumerator/blob/90cdcc90cc0453c35e7b2d2e941d23abd6e9cf39/src/Core/Enumerator.php#L177-L287
datto/core-enumerator
src/Core/Enumerator.php
Enumerator._setupRoot
private static function _setupRoot() { if ( !empty(self::$root) ) { // avoid duplicating efforts... only set root if it's not already set return; } if ( defined('ROOT') ) { self::$root = rtrim(ROOT, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } else if ( !empty($GLOBALS['baseDir']) ) { self::$root = rtrim($GLOBALS['baseDir'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } else if ( strpos(__FILE__, DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR) !== false ) { // fall back to guessing the project root from the path... // we're in /vendor/datto/core-enumerator/src/Core $path = __FILE__; // up 5 levels while (!file_exists("$path/autoload.php")) { $path = dirname($path); } $path = dirname($path); self::$root = $path . DIRECTORY_SEPARATOR; } else if ( class_exists("Composer\\Autoload\\ClassLoader") ) { // go up until we find vendor/autoload.php - last resort $path = dirname(__FILE__); while ( $path && !file_exists($path . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php') ) { $path = dirname($path); } if ( !empty($path) ) { var_dump($path); self::$root = $path . DIRECTORY_SEPARATOR; } } if ( empty(self::$root) ) { throw new \Exception("Unable to determine project base directory"); } }
php
private static function _setupRoot() { if ( !empty(self::$root) ) { // avoid duplicating efforts... only set root if it's not already set return; } if ( defined('ROOT') ) { self::$root = rtrim(ROOT, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } else if ( !empty($GLOBALS['baseDir']) ) { self::$root = rtrim($GLOBALS['baseDir'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } else if ( strpos(__FILE__, DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR) !== false ) { // fall back to guessing the project root from the path... // we're in /vendor/datto/core-enumerator/src/Core $path = __FILE__; // up 5 levels while (!file_exists("$path/autoload.php")) { $path = dirname($path); } $path = dirname($path); self::$root = $path . DIRECTORY_SEPARATOR; } else if ( class_exists("Composer\\Autoload\\ClassLoader") ) { // go up until we find vendor/autoload.php - last resort $path = dirname(__FILE__); while ( $path && !file_exists($path . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php') ) { $path = dirname($path); } if ( !empty($path) ) { var_dump($path); self::$root = $path . DIRECTORY_SEPARATOR; } } if ( empty(self::$root) ) { throw new \Exception("Unable to determine project base directory"); } }
Determine the project root directory.
https://github.com/datto/core-enumerator/blob/90cdcc90cc0453c35e7b2d2e941d23abd6e9cf39/src/Core/Enumerator.php#L292-L335
austinkregel/formmodel
src/FormModel/Frameworks/Plain.php
Plain.form
public function form(array $options = []) { $this->options = $options; $this->form = parent::form(array_merge([ 'form' => [ 'class' => 'form-horizontal', 'action' => request()->url(), 'method' => 'POST', ], ], $this->options)); return view('formmodel::form_types.plain', [ 'form_' => $this->form, 'components' => $this->vue_components, 'type' => $this->options['method'], ]); }
php
public function form(array $options = []) { $this->options = $options; $this->form = parent::form(array_merge([ 'form' => [ 'class' => 'form-horizontal', 'action' => request()->url(), 'method' => 'POST', ], ], $this->options)); return view('formmodel::form_types.plain', [ 'form_' => $this->form, 'components' => $this->vue_components, 'type' => $this->options['method'], ]); }
@param Model $model @param array $options @return mixed
https://github.com/austinkregel/formmodel/blob/49943a8f563d2e9028f6bc992708e104f9be22e3/src/FormModel/Frameworks/Plain.php#L58-L75
phramework/phramework
src/URIStrategy/URITemplate.php
URITemplate.URI
public static function URI() { $REDIRECT_QUERY_STRING = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : ''; $REDIRECT_URL = ''; if (isset($_SERVER['REQUEST_URI'])) { $url_parts = parse_url($_SERVER['REQUEST_URI']); $REDIRECT_URL = $url_parts['path']; } $URI = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/'); if (substr($REDIRECT_URL, 0, strlen($URI)) == $URI) { $URI = substr($REDIRECT_URL, strlen($URI)); } $URI = urldecode($URI) . '/'; $URI = trim($URI, '/'); $parameters = []; //Extract parameters from QUERY string parse_str($REDIRECT_QUERY_STRING, $parameters); return [$URI, $parameters]; }
php
public static function URI() { $REDIRECT_QUERY_STRING = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : ''; $REDIRECT_URL = ''; if (isset($_SERVER['REQUEST_URI'])) { $url_parts = parse_url($_SERVER['REQUEST_URI']); $REDIRECT_URL = $url_parts['path']; } $URI = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/'); if (substr($REDIRECT_URL, 0, strlen($URI)) == $URI) { $URI = substr($REDIRECT_URL, strlen($URI)); } $URI = urldecode($URI) . '/'; $URI = trim($URI, '/'); $parameters = []; //Extract parameters from QUERY string parse_str($REDIRECT_QUERY_STRING, $parameters); return [$URI, $parameters]; }
Get current URI and GET parameters from the requested URI @return string[2] Returns an array with current URI and GET parameters
https://github.com/phramework/phramework/blob/40041d1ef23b1f8cdbd26fb112448d6a3dbef012/src/URIStrategy/URITemplate.php#L120-L150
phramework/phramework
src/URIStrategy/URITemplate.php
URITemplate.invoke
public function invoke( &$requestParameters, $requestMethod, $requestHeaders, $requestUser ) { // Get request uri and uri parameters list($URI, $URI_parameters) = self::URI(); foreach ($this->templates as $template) { $templateMethod = (isset($template[3]) ? $template[3] : Phramework::METHOD_ANY); $requiresAuthentication = (isset($template[4]) ? $template[4] : false); // Ignore if not a valid method if ((is_array($templateMethod) && !in_array($requestMethod, $templateMethod)) || (!is_array($templateMethod) && $templateMethod != Phramework::METHOD_ANY && $templateMethod !== $requestMethod ) ) { continue; } list($URITemplate, $class, $method) = $template; //Test if uri matches the current uri template $test = $this->test($URITemplate, $URI); if ($test !== false) { if ($requiresAuthentication && $requestUser === false) { throw new \Phramework\Exceptions\UnauthorizedException(); } list($URI_parameters) = $test; //Merge all available parameters $requestParameters = (object)array_merge( (array)$requestParameters, $URI_parameters, $test[0] ); /** * Check if the requested controller and it's method is callable * In order to be callable : * @todo complete documentation * @todo log to server */ if (!is_callable($class . '::' . $method)) { throw new NotFoundException('Method not found'); } //Call handler method call_user_func_array( [$class, $method], array_merge( [ $requestParameters, $requestMethod, $requestHeaders ], $URI_parameters ) ); return [$class, $method]; } } throw new NotFoundException('Method not found'); }
php
public function invoke( &$requestParameters, $requestMethod, $requestHeaders, $requestUser ) { // Get request uri and uri parameters list($URI, $URI_parameters) = self::URI(); foreach ($this->templates as $template) { $templateMethod = (isset($template[3]) ? $template[3] : Phramework::METHOD_ANY); $requiresAuthentication = (isset($template[4]) ? $template[4] : false); // Ignore if not a valid method if ((is_array($templateMethod) && !in_array($requestMethod, $templateMethod)) || (!is_array($templateMethod) && $templateMethod != Phramework::METHOD_ANY && $templateMethod !== $requestMethod ) ) { continue; } list($URITemplate, $class, $method) = $template; //Test if uri matches the current uri template $test = $this->test($URITemplate, $URI); if ($test !== false) { if ($requiresAuthentication && $requestUser === false) { throw new \Phramework\Exceptions\UnauthorizedException(); } list($URI_parameters) = $test; //Merge all available parameters $requestParameters = (object)array_merge( (array)$requestParameters, $URI_parameters, $test[0] ); /** * Check if the requested controller and it's method is callable * In order to be callable : * @todo complete documentation * @todo log to server */ if (!is_callable($class . '::' . $method)) { throw new NotFoundException('Method not found'); } //Call handler method call_user_func_array( [$class, $method], array_merge( [ $requestParameters, $requestMethod, $requestHeaders ], $URI_parameters ) ); return [$class, $method]; } } throw new NotFoundException('Method not found'); }
Invoke URIStrategy @param object $requestParameters Request parameters @param string $requestMethod HTTP request method @param array $requestHeaders Request headers @param object|false $requestUser Use object if successful authenticated otherwise false @throws \Phramework\Exceptions\NotFoundException @throws \Phramework\Exceptions\UnauthorizedException @todo Use named parameters in future if available by PHP @return string[2] This method should return `[$class, $method]` on success
https://github.com/phramework/phramework/blob/40041d1ef23b1f8cdbd26fb112448d6a3dbef012/src/URIStrategy/URITemplate.php#L164-L233
cube-group/myaf-net
src/LDing.php
LDing.send
public function send($msg) { if (!$this->url) { return false; } $data = ["msgtype" => "text", "text" => ["content" => $msg], "at" => ["isAtAll" => true]]; $curl = new LCurl(LCurl::POST_JSON, 3); $result = $curl->post( $this->url, $data ); if (!$result || (int)Arrays::get($result, 'errcode') != 0) { return false; } return true; }
php
public function send($msg) { if (!$this->url) { return false; } $data = ["msgtype" => "text", "text" => ["content" => $msg], "at" => ["isAtAll" => true]]; $curl = new LCurl(LCurl::POST_JSON, 3); $result = $curl->post( $this->url, $data ); if (!$result || (int)Arrays::get($result, 'errcode') != 0) { return false; } return true; }
发送钉钉消息 @param $msg string @return bool
https://github.com/cube-group/myaf-net/blob/ff3253939fbfbe3ade0bcf126c74fccb882e1f0e/src/LDing.php#L39-L54
ThomasMarinissen/FileDownloader
src/FileDownloader/Exceptions/DownloadException.php
DownloadException.codeToMessage
private function codeToMessage($code) { // get the error message belong to the given code switch ($code) { case \Th\FileDownloader::FILE_WRONG_MIME: $message = "File is of the wrong MIME type"; break; case \Th\FileDownloader::FILE_WRONG_EXTENSION: $message = "File is of the wrong extension"; break; case \Th\FileDownloader::INVALID_DOWNLOAD_DIR: $message = "User set download directory does not exist"; break; default: $message = "Unknown download error"; break; } // done, return the error message return $message; }
php
private function codeToMessage($code) { // get the error message belong to the given code switch ($code) { case \Th\FileDownloader::FILE_WRONG_MIME: $message = "File is of the wrong MIME type"; break; case \Th\FileDownloader::FILE_WRONG_EXTENSION: $message = "File is of the wrong extension"; break; case \Th\FileDownloader::INVALID_DOWNLOAD_DIR: $message = "User set download directory does not exist"; break; default: $message = "Unknown download error"; break; } // done, return the error message return $message; }
Method that switches the error code constants till it finds the messages that belongs to the error code and then returns the message. @param int The error code @return string The error message
https://github.com/ThomasMarinissen/FileDownloader/blob/a69a1c88674038597bcd2e8f0777abf39f58c215/src/FileDownloader/Exceptions/DownloadException.php#L33-L52
hal-platform/hal-core
src/Entity/Target.php
Target.isAWS
public function isAWS() { return in_array($this->type(), [TargetEnum::TYPE_CD, TargetEnum::TYPE_EB, TargetEnum::TYPE_S3]); }
php
public function isAWS() { return in_array($this->type(), [TargetEnum::TYPE_CD, TargetEnum::TYPE_EB, TargetEnum::TYPE_S3]); }
Is this group for AWS? @return bool
https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Entity/Target.php#L253-L256
hal-platform/hal-core
src/Entity/Target.php
Target.formatParameters
public function formatParameters() { switch ($this->type()) { case TargetEnum::TYPE_CD: return $this->parameter('group') ?: '???'; case TargetEnum::TYPE_EB: return $this->parameter('environment') ?: '???'; case TargetEnum::TYPE_S3: $bucket = $this->parameter('bucket') ?: '???'; if ($path = $this->parameter('path')) { $bucket = sprintf('%s/%s', $bucket, $path); if ($source = $this->parameter('source')) { $bucket = sprintf('%s:%s', $source, $bucket); } } return $bucket; case TargetEnum::TYPE_SCRIPT: return $this->parameter('context') ?: '???'; case TargetEnum::TYPE_RSYNC: return $this->parameter('path') ?: '???'; default: return 'Unknown'; } }
php
public function formatParameters() { switch ($this->type()) { case TargetEnum::TYPE_CD: return $this->parameter('group') ?: '???'; case TargetEnum::TYPE_EB: return $this->parameter('environment') ?: '???'; case TargetEnum::TYPE_S3: $bucket = $this->parameter('bucket') ?: '???'; if ($path = $this->parameter('path')) { $bucket = sprintf('%s/%s', $bucket, $path); if ($source = $this->parameter('source')) { $bucket = sprintf('%s:%s', $source, $bucket); } } return $bucket; case TargetEnum::TYPE_SCRIPT: return $this->parameter('context') ?: '???'; case TargetEnum::TYPE_RSYNC: return $this->parameter('path') ?: '???'; default: return 'Unknown'; } }
Format parameters into something readable. @return string
https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Entity/Target.php#L263-L293
ncou/Chiron-Pipeline
src/Pipeline.php
Pipeline.pipe
public function pipe($middlewares): self { //Add middleware to the end of the stack => Append //array_push($this->middlewares, $this->decorate($middleware)); if (! is_array($middlewares)) { $middlewares = [$middlewares]; } foreach ($middlewares as $middleware) { $this->middlewares[] = $this->decorate($middleware); } return $this; }
php
public function pipe($middlewares): self { //Add middleware to the end of the stack => Append //array_push($this->middlewares, $this->decorate($middleware)); if (! is_array($middlewares)) { $middlewares = [$middlewares]; } foreach ($middlewares as $middleware) { $this->middlewares[] = $this->decorate($middleware); } return $this; }
@param string|callable|MiddlewareInterface|RequestHandlerInterface|ResponseInterface $middlewares It could also be an array of such arguments. @return self
https://github.com/ncou/Chiron-Pipeline/blob/dda743d797bc85c24a947dc332f3cfb41f6bf05a/src/Pipeline.php#L50-L64
ncou/Chiron-Pipeline
src/Pipeline.php
Pipeline.pipeIf
public function pipeIf($middlewares, callable $predicate): self { if (! is_array($middlewares)) { $middlewares = [$middlewares]; } foreach ($middlewares as $middleware) { $this->middlewares[] = new PredicateDecorator($this->decorate($middleware), $predicate); } return $this; }
php
public function pipeIf($middlewares, callable $predicate): self { if (! is_array($middlewares)) { $middlewares = [$middlewares]; } foreach ($middlewares as $middleware) { $this->middlewares[] = new PredicateDecorator($this->decorate($middleware), $predicate); } return $this; }
@param string|callable|MiddlewareInterface|RequestHandlerInterface|ResponseInterface $middlewares It could also be an array of such arguments. @param callable $predicate Used to determine if the middleware should be executed @return self
https://github.com/ncou/Chiron-Pipeline/blob/dda743d797bc85c24a947dc332f3cfb41f6bf05a/src/Pipeline.php#L72-L83