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
|
---|---|---|---|---|---|---|---|
temp/media-converter | src/Converter/VideoConverter.php | VideoConverter.createFormat | private function createFormat($videoFormat)
{
switch ($videoFormat) {
case 'flv':
$format = new Flv();
break;
case 'ogg':
$format = new Ogg();
break;
case 'webm':
$format = new WebM();
break;
case 'wmv':
$format = new WMV();
break;
case 'wmv3':
$format = new WMV3();
break;
case '3gp':
$format = new ThreeGP();
break;
case 'mp4':
case 'x264':
default:
$format = new X264();
break;
}
return $format;
} | php | private function createFormat($videoFormat)
{
switch ($videoFormat) {
case 'flv':
$format = new Flv();
break;
case 'ogg':
$format = new Ogg();
break;
case 'webm':
$format = new WebM();
break;
case 'wmv':
$format = new WMV();
break;
case 'wmv3':
$format = new WMV3();
break;
case '3gp':
$format = new ThreeGP();
break;
case 'mp4':
case 'x264':
default:
$format = new X264();
break;
}
return $format;
} | @param string $videoFormat
@return DefaultVideo | https://github.com/temp/media-converter/blob/a6e8768c583aa461be568f13e592ae49294e5e33/src/Converter/VideoConverter.php#L71-L106 |
atelierspierrot/patterns | src/Patterns/Abstracts/AbstractView.php | AbstractView.getParams | public function getParams($alone = false)
{
if ($alone) {
return $this->params;
} else {
return array_merge($this->getDefaultViewParams(), $this->params);
}
} | php | public function getParams($alone = false)
{
if ($alone) {
return $this->params;
} else {
return array_merge($this->getDefaultViewParams(), $this->params);
}
} | Get the parameters for the current view
@param bool $alone Get the stack of parameters without the default params (default is `false`)
@return array The array of parameters | https://github.com/atelierspierrot/patterns/blob/b7a8313e98bbfb6525e1672d0a726a1ead6f156e/src/Patterns/Abstracts/AbstractView.php#L168-L175 |
YiMAproject/yimaAdminor | src/yimaAdminor/Mvc/OffCanvasAdminThemeResolver.php | OffCanvasAdminThemeResolver.getName | public function getName()
{
$name = false;
// - we are on admin
$sm = $this->themeLocator->getServiceLocator();
// get registered PermissionsManager service and retrieve plugin
$permissionsManager = $sm->get('yimaAuthorize.AuthServiceManager');
/** @var $permission \yimaAdminor\Auth\AuthService */
$permission = $permissionsManager->get('yima_adminor');
if (!$permission->identity()->hasAuthenticated())
// user not authorized to adminor
return false;
$config = $sm->get('config');
if (isset($config['yima_adminor']) && is_array($config['yima_adminor'])) {
$name = (isset($config['yima_adminor']['default_theme']))
? $config['yima_adminor']['default_theme']
: false;
}
return $name;
} | php | public function getName()
{
$name = false;
// - we are on admin
$sm = $this->themeLocator->getServiceLocator();
// get registered PermissionsManager service and retrieve plugin
$permissionsManager = $sm->get('yimaAuthorize.AuthServiceManager');
/** @var $permission \yimaAdminor\Auth\AuthService */
$permission = $permissionsManager->get('yima_adminor');
if (!$permission->identity()->hasAuthenticated())
// user not authorized to adminor
return false;
$config = $sm->get('config');
if (isset($config['yima_adminor']) && is_array($config['yima_adminor'])) {
$name = (isset($config['yima_adminor']['default_theme']))
? $config['yima_adminor']['default_theme']
: false;
}
return $name;
} | Get default admin template name from merged config
@return bool | https://github.com/YiMAproject/yimaAdminor/blob/7a6c66e05aedaef8061c8998dfa44ac1ce9cc319/src/yimaAdminor/Mvc/OffCanvasAdminThemeResolver.php#L25-L50 |
Elephant418/Staq | src/Staq/Core/View/Stack/Router.php | Router.render | protected function render($view)
{
$view = parent::render($view);
if (!\Staq\Util::isStack($view, 'Stack\\View')) {
$page = new \Stack\View;
$page['content'] = $view;
$view = $page;
}
return $view->render();
} | php | protected function render($view)
{
$view = parent::render($view);
if (!\Staq\Util::isStack($view, 'Stack\\View')) {
$page = new \Stack\View;
$page['content'] = $view;
$view = $page;
}
return $view->render();
} | /* PRIVATE METHODS
*********************************************************************** | https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Core/View/Stack/Router.php#L14-L23 |
eloquent/endec | src/Base32/Base32DecodeTransform.php | Base32DecodeTransform.mapByte | protected function mapByte($data, $index)
{
$byte = ord($data[$index]);
if ($byte > 49) {
if ($byte < 56) {
return $byte - 24;
}
if ($byte > 64 && $byte < 91) {
return $byte - 65;
}
}
throw new InvalidEncodedDataException($this->key(), $data);
} | php | protected function mapByte($data, $index)
{
$byte = ord($data[$index]);
if ($byte > 49) {
if ($byte < 56) {
return $byte - 24;
}
if ($byte > 64 && $byte < 91) {
return $byte - 65;
}
}
throw new InvalidEncodedDataException($this->key(), $data);
} | Map a byte to its relevant alphabet entry.
@param string $data The data to be decoded.
@param integer $index The index into the data at which the relevant byte is located.
@return integer The relevant alphabet entry.
@throws EncodingExceptionInterface If there is no relevant alphabet entry. | https://github.com/eloquent/endec/blob/90043a26439739d6bac631cc57dab3ecf5cafdc3/src/Base32/Base32DecodeTransform.php#L48-L61 |
chilimatic/chilimatic-framework | lib/cache/engine/CacheFactory.php | CacheFactory.make | public static function make($name, $credentials = [])
{
if (!$name && !$credentials) {
return null;
}
try {
$cacheName = (empty($name)) ? self::CACHE_DEFAULT_TYPE : $name;
$c = '\\' . __NAMESPACE__ . '\\' . ucfirst($cacheName);
// check if the class exists or can be loaded
if (!class_exists($c, true)) {
throw new CacheException(_('The Cache is not implemented or not installed:') . $c, self::ERROR_CACHE_MISSING, Error::SEVERITY_CRIT, __FILE__, __LINE__);
}
/**
* @var CacheTrait $cache
*/
$cache = new $c($credentials);
if ($cache->isConnected() == false) {
throw new CacheException(_('The Cache could not establish connection:') . $c, self::ERROR_CACHE_MISSING, Error::SEVERITY_CRIT, __FILE__, __LINE__);
}
} catch (CacheException $e) {
throw $e;
}
return $cache;
} | php | public static function make($name, $credentials = [])
{
if (!$name && !$credentials) {
return null;
}
try {
$cacheName = (empty($name)) ? self::CACHE_DEFAULT_TYPE : $name;
$c = '\\' . __NAMESPACE__ . '\\' . ucfirst($cacheName);
// check if the class exists or can be loaded
if (!class_exists($c, true)) {
throw new CacheException(_('The Cache is not implemented or not installed:') . $c, self::ERROR_CACHE_MISSING, Error::SEVERITY_CRIT, __FILE__, __LINE__);
}
/**
* @var CacheTrait $cache
*/
$cache = new $c($credentials);
if ($cache->isConnected() == false) {
throw new CacheException(_('The Cache could not establish connection:') . $c, self::ERROR_CACHE_MISSING, Error::SEVERITY_CRIT, __FILE__, __LINE__);
}
} catch (CacheException $e) {
throw $e;
}
return $cache;
} | Init like always enables to reset the class
@param $name
@param array $credentials
@throws \chilimatic\lib\exception\CacheException|\Exception
@return mixed | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/cache/engine/CacheFactory.php#L47-L75 |
parfumix/eloquent-translatable | src/TranslatableTrait.php | TranslatableTrait.removeTranslation | public function removeTranslation($locale = null) {
$translation = $this->translate($locale);
if(! is_null($translation))
$translation->delete();
return $this;
} | php | public function removeTranslation($locale = null) {
$translation = $this->translate($locale);
if(! is_null($translation))
$translation->delete();
return $this;
} | Remove translation by locale .
@param null $locale
@return $this
@throws TranslatableException | https://github.com/parfumix/eloquent-translatable/blob/53a4d5c7288219a035d8c512892efbe670029a79/src/TranslatableTrait.php#L21-L28 |
parfumix/eloquent-translatable | src/TranslatableTrait.php | TranslatableTrait.translate | public function translate($locale = null) {
$locale = isset($locale) ? $locale : Locale\get_active_locale();
if( in_array( $locale, Locale\get_locales() ) )
throw new TranslatableException(
_('Invalid locale')
);
$language = $this->getByLocale($locale);
return $this->translations()
->where('language_id', $language->id)
->first();
} | php | public function translate($locale = null) {
$locale = isset($locale) ? $locale : Locale\get_active_locale();
if( in_array( $locale, Locale\get_locales() ) )
throw new TranslatableException(
_('Invalid locale')
);
$language = $this->getByLocale($locale);
return $this->translations()
->where('language_id', $language->id)
->first();
} | Translate attribute by locale .
@param null $locale
@return mixed
@throws TranslatableException | https://github.com/parfumix/eloquent-translatable/blob/53a4d5c7288219a035d8c512892efbe670029a79/src/TranslatableTrait.php#L48-L61 |
parfumix/eloquent-translatable | src/TranslatableTrait.php | TranslatableTrait.save | public function save(array $options = []) {
$saved = parent::save($options);
array_walk($this->translations, function($translation, $locale) {
if(! array_filter($translation))
return false;
$this->newTranslation($locale, $translation)
->save();
});
return $saved;
} | php | public function save(array $options = []) {
$saved = parent::save($options);
array_walk($this->translations, function($translation, $locale) {
if(! array_filter($translation))
return false;
$this->newTranslation($locale, $translation)
->save();
});
return $saved;
} | Save eloquent model .
@param array $options
@return mixed | https://github.com/parfumix/eloquent-translatable/blob/53a4d5c7288219a035d8c512892efbe670029a79/src/TranslatableTrait.php#L70-L82 |
parfumix/eloquent-translatable | src/TranslatableTrait.php | TranslatableTrait.fill | public function fill(array $attributes) {
$locales = Locale\get_locales();
foreach($locales as $locale => $options)
if( in_array($locale, array_keys($attributes)) )
$this->translations[$locale] = array_pull($attributes, $locale);
return parent::fill($attributes);
} | php | public function fill(array $attributes) {
$locales = Locale\get_locales();
foreach($locales as $locale => $options)
if( in_array($locale, array_keys($attributes)) )
$this->translations[$locale] = array_pull($attributes, $locale);
return parent::fill($attributes);
} | Fill attributes and save locales if exists .
@param array $attributes
@return mixed | https://github.com/parfumix/eloquent-translatable/blob/53a4d5c7288219a035d8c512892efbe670029a79/src/TranslatableTrait.php#L90-L98 |
parfumix/eloquent-translatable | src/TranslatableTrait.php | TranslatableTrait.newTranslation | protected function newTranslation($locale = null, array $attributes) {
$locale = isset($locale) ? $locale : Locale\get_active_locale();
$language = $this->getByLocale($locale);
$class = $this->classTranslation();
$update = [
'language_id' => $language->id,
isset($this->translation_id) ? $this->translation_id : str_singular($this->getModel()->getTable()) . '_id' => $this->id,
];
$attributes = array_merge($update, $attributes);
return $class::updateOrCreate($update, $attributes);
} | php | protected function newTranslation($locale = null, array $attributes) {
$locale = isset($locale) ? $locale : Locale\get_active_locale();
$language = $this->getByLocale($locale);
$class = $this->classTranslation();
$update = [
'language_id' => $language->id,
isset($this->translation_id) ? $this->translation_id : str_singular($this->getModel()->getTable()) . '_id' => $this->id,
];
$attributes = array_merge($update, $attributes);
return $class::updateOrCreate($update, $attributes);
} | Get new translation instance .
@param null $locale
@param array $attributes
@return mixed | https://github.com/parfumix/eloquent-translatable/blob/53a4d5c7288219a035d8c512892efbe670029a79/src/TranslatableTrait.php#L108-L123 |
parfumix/eloquent-translatable | src/TranslatableTrait.php | TranslatableTrait.classTranslation | protected function classTranslation() {
if(! $classTranslation = $this['translationClass'])
$classTranslation = sprintf('App\\%s%s', ucfirst(str_singular($this->getModel()->getTable())), 'Translations');
return $classTranslation;
} | php | protected function classTranslation() {
if(! $classTranslation = $this['translationClass'])
$classTranslation = sprintf('App\\%s%s', ucfirst(str_singular($this->getModel()->getTable())), 'Translations');
return $classTranslation;
} | Get Class Translations .
@return string | https://github.com/parfumix/eloquent-translatable/blob/53a4d5c7288219a035d8c512892efbe670029a79/src/TranslatableTrait.php#L142-L147 |
parfumix/eloquent-translatable | src/TranslatableTrait.php | TranslatableTrait.translatedAttributes | public function translatedAttributes() {
if(! $attributes = isset($this['translatedAttributes']) ? $this['translatedAttributes'] : null) {
$class = $this->classTranslation();
$attributes = (new $class)
->getFillable();
$attributes = array_except(array_flip($attributes), [
'language_id' ,
str_singular($this->getModel()->getTable()) . '_id'
]);
$attributes = array_flip($attributes);
}
return $attributes;
} | php | public function translatedAttributes() {
if(! $attributes = isset($this['translatedAttributes']) ? $this['translatedAttributes'] : null) {
$class = $this->classTranslation();
$attributes = (new $class)
->getFillable();
$attributes = array_except(array_flip($attributes), [
'language_id' ,
str_singular($this->getModel()->getTable()) . '_id'
]);
$attributes = array_flip($attributes);
}
return $attributes;
} | Get translatedAttributes .
@return mixed | https://github.com/parfumix/eloquent-translatable/blob/53a4d5c7288219a035d8c512892efbe670029a79/src/TranslatableTrait.php#L167-L183 |
rkeet/zf-doctrine-mvc | src/Controller/AbstractDoctrineActionController.php | AbstractDoctrineActionController.isEntity | function isEntity(string $classFQCN) : bool
{
if ( ! class_exists($classFQCN)) {
throw new ClassNotFoundException(sprintf('Given class FQCN "%s" does not exist.', $classFQCN));
}
if ( ! is_object($classFQCN)) {
throw new EntityNotFoundException(sprintf('Given class "%s" is not a Doctrine Entity.', $classFQCN));
}
return ! $this->getObjectManager()
->getMetadataFactory()
->isTransient(ClassUtils::getClass($classFQCN));
} | php | function isEntity(string $classFQCN) : bool
{
if ( ! class_exists($classFQCN)) {
throw new ClassNotFoundException(sprintf('Given class FQCN "%s" does not exist.', $classFQCN));
}
if ( ! is_object($classFQCN)) {
throw new EntityNotFoundException(sprintf('Given class "%s" is not a Doctrine Entity.', $classFQCN));
}
return ! $this->getObjectManager()
->getMetadataFactory()
->isTransient(ClassUtils::getClass($classFQCN));
} | Tests if a received class name is in fact a Doctrine Entity
Based on @link https://stackoverflow.com/a/27121978/1155833
@param string $classFQCN
@return boolean
@throws EntityNotFoundException | https://github.com/rkeet/zf-doctrine-mvc/blob/ec5fb19e453824383b39570d15bd77b85cec3ca1/src/Controller/AbstractDoctrineActionController.php#L39-L54 |
rkeet/zf-doctrine-mvc | src/Controller/AbstractDoctrineActionController.php | AbstractDoctrineActionController.getRouteParams | public function getRouteParams(AbstractEntity $entity, array $routeParams = [])
{
if (count($routeParams) === 0) {
return [];
}
$params = [];
foreach ($routeParams as $param) {
if ( ! method_exists($entity, 'get' . ucfirst($param))) {
trigger_error(
'Function "get' . ucfirst($param) . '" does not exist on "' . get_class($entity) . '". Skipping.'
);
continue;
}
$params[$param] = $entity->{'get' . ucfirst($param)}();
}
return $params;
} | php | public function getRouteParams(AbstractEntity $entity, array $routeParams = [])
{
if (count($routeParams) === 0) {
return [];
}
$params = [];
foreach ($routeParams as $param) {
if ( ! method_exists($entity, 'get' . ucfirst($param))) {
trigger_error(
'Function "get' . ucfirst($param) . '" does not exist on "' . get_class($entity) . '". Skipping.'
);
continue;
}
$params[$param] = $entity->{'get' . ucfirst($param)}();
}
return $params;
} | Gets the route parameters based on generic naming
i.e. -> Giving a parameter ['id'] will cause $entity->getId() to be executed and returned as ['id' => 123]
@param AbstractEntity $entity
@param array $routeParams
@return array | https://github.com/rkeet/zf-doctrine-mvc/blob/ec5fb19e453824383b39570d15bd77b85cec3ca1/src/Controller/AbstractDoctrineActionController.php#L65-L86 |
webfactory/content-mapping | src/Synchronizer.php | Synchronizer.synchronize | public function synchronize($className, $force)
{
$this->logger->notice(
'Start of ' . ($force ? 'forced ' : '') . 'synchronization for {className}.',
array('className' => $className)
);
$this->className = $className;
$this->mapper->setForce($force);
$this->sourceQueue = $this->source->getObjectsOrderedById();
$this->sourceQueue->rewind();
$this->destinationQueue = $this->destination->getObjectsOrderedById($className);
$this->destinationQueue->rewind();
while ($this->sourceQueue->valid() && $this->destinationQueue->valid()) {
$this->compareQueuesAndReactAccordingly();
}
$this->insertRemainingSourceObjects();
$this->deleteRemainingDestinationObjects();
$this->destination->commit();
$this->logger->notice('End of synchronization for {className}.', array('className' => $className));
} | php | public function synchronize($className, $force)
{
$this->logger->notice(
'Start of ' . ($force ? 'forced ' : '') . 'synchronization for {className}.',
array('className' => $className)
);
$this->className = $className;
$this->mapper->setForce($force);
$this->sourceQueue = $this->source->getObjectsOrderedById();
$this->sourceQueue->rewind();
$this->destinationQueue = $this->destination->getObjectsOrderedById($className);
$this->destinationQueue->rewind();
while ($this->sourceQueue->valid() && $this->destinationQueue->valid()) {
$this->compareQueuesAndReactAccordingly();
}
$this->insertRemainingSourceObjects();
$this->deleteRemainingDestinationObjects();
$this->destination->commit();
$this->logger->notice('End of synchronization for {className}.', array('className' => $className));
} | Synchronizes the $className objects from the source system to the destination system.
@param string $className
@param bool $force | https://github.com/webfactory/content-mapping/blob/bba6e3ef282b9f69c62a489cf571bb5ce43f2926/src/Synchronizer.php#L79-L104 |
4devs/serializer | Visibility/Group.php | Group.isVisibleProperty | public function isVisibleProperty($propertyName, array $options, array $context)
{
return isset($context[$options['key']]) ? count(array_intersect((array) $context[$options['key']], $options['groups'])) > 0 : !$options['required'];
} | php | public function isVisibleProperty($propertyName, array $options, array $context)
{
return isset($context[$options['key']]) ? count(array_intersect((array) $context[$options['key']], $options['groups'])) > 0 : !$options['required'];
} | {@inheritdoc} | https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Visibility/Group.php#L20-L23 |
LoggerEssentials/LoggerEssentials | src/Common/ExtendedPsrLoggerWrapper.php | ExtendedPsrLoggerWrapper.log | public function log($level, $message, array $context = array()) {
$captions = $this->captionTrail->getCaptions();
$message = $this->messageRenderer->render($message, $captions);
$context = $this->contextExtender->extend($this->context, $context);
$this->logger->log($level, $message, $context);
} | php | public function log($level, $message, array $context = array()) {
$captions = $this->captionTrail->getCaptions();
$message = $this->messageRenderer->render($message, $captions);
$context = $this->contextExtender->extend($this->context, $context);
$this->logger->log($level, $message, $context);
} | Logs with an arbitrary level.
@param mixed $level
@param string $message
@param array $context
@return void | https://github.com/LoggerEssentials/LoggerEssentials/blob/f32f9b865eacfccced90697f3eb69dc4ad80dc96/src/Common/ExtendedPsrLoggerWrapper.php#L145-L150 |
ghousseyn/phiber | library/oosql/collection.php | collection.objectWhere | public function objectWhere($property, $value)
{
foreach ($this->objects as $key => $obj) {
if ($obj->{$property} === $value) {
return $this->objects[$key];
}
}
return false;
} | php | public function objectWhere($property, $value)
{
foreach ($this->objects as $key => $obj) {
if ($obj->{$property} === $value) {
return $this->objects[$key];
}
}
return false;
} | /*
get an obj based on one of it's properties. i.e. a User obj with the
property 'username' and a value of 'someUser' can be retrieved by
Collection::objectWhere('username', 'someUser') | https://github.com/ghousseyn/phiber/blob/2574249d49b6930a0123a310a32073a105cdd486/library/oosql/collection.php#L42-L50 |
ghousseyn/phiber | library/oosql/collection.php | collection.keyWhere | public function keyWhere($property, $value)
{
foreach ($this->objects as $key => $obj) {
if ($obj->{$property} === $value) {
$keys[] = $key;
}
}
if (count($keys)) {
return $keys;
}
return false;
} | php | public function keyWhere($property, $value)
{
foreach ($this->objects as $key => $obj) {
if ($obj->{$property} === $value) {
$keys[] = $key;
}
}
if (count($keys)) {
return $keys;
}
return false;
} | /*
get matched objects keys based on one of it's properties. i.e. a User obj key
with the property 'username' and a value of 'someUser' can be retrieved by
Collection::keyWhere('username', 'someUser') | https://github.com/ghousseyn/phiber/blob/2574249d49b6930a0123a310a32073a105cdd486/library/oosql/collection.php#L84-L95 |
ghousseyn/phiber | library/oosql/collection.php | collection.countWhere | public function countWhere($property, $value)
{
$count = 0;
foreach ($this->objects as $key => $obj) {
if ($obj->{$property} === $value) {
$count++;
}
}
return $count;
} | php | public function countWhere($property, $value)
{
$count = 0;
foreach ($this->objects as $key => $obj) {
if ($obj->{$property} === $value) {
$count++;
}
}
return $count;
} | /*
get the number of objects that have a property with a value matches the
given value i.e. if there are objs with a property of 'verified' set to 1
the number of these objects can be retrieved by:
Collection::countWhere('verified', 1) | https://github.com/ghousseyn/phiber/blob/2574249d49b6930a0123a310a32073a105cdd486/library/oosql/collection.php#L103-L113 |
ghousseyn/phiber | library/oosql/collection.php | collection.removeWhere | public function removeWhere($property, $value)
{
$results = array();
foreach ($this->objects as $key => $obj) {
if ($obj->{$property} === $value) {
$this->deletedObjects[] = $this->objects[$key];
$results[] = $this->objects[$key];
unset($this->objects[$key]);
$this->numObjects--;
}
}
$this->objects = array_values($this->objects);
return $results;
} | php | public function removeWhere($property, $value)
{
$results = array();
foreach ($this->objects as $key => $obj) {
if ($obj->{$property} === $value) {
$this->deletedObjects[] = $this->objects[$key];
$results[] = $this->objects[$key];
unset($this->objects[$key]);
$this->numObjects--;
}
}
$this->objects = array_values($this->objects);
return $results;
} | /*
remove an obj based on one of it's properties. i.e. a User obj with the
property 'username' and a value of 'someUser' can be removed by
Collection::removeWhere('username', 'someUser') | https://github.com/ghousseyn/phiber/blob/2574249d49b6930a0123a310a32073a105cdd486/library/oosql/collection.php#L120-L133 |
ghousseyn/phiber | library/oosql/collection.php | collection.sortByProperty | public function sortByProperty($property, $type = 'r')
{
$tempArray = array();
$newObjects = array();
foreach ($this->objects as $obj) {
$tempArray[] = $obj->{$property};
}
switch ($type) {
case 'r':
asort($tempArray);
break;
case 'rr':
arsort($tempArray);
break;
case 'n':
asort($tempArray, SORT_NUMERIC);
break;
case 'nr':
arsort($tempArray, SORT_NUMERIC);
break;
case 's':
asort($tempArray, SORT_STRING);
break;
case 'sr':
arsort($tempArray, SORT_STRING);
break;
default:
return false;
}
foreach ($tempArray as $key => $val) {
$newObjects[] = $this->objects[$key];
}
$this->objects = $newObjects;
} | php | public function sortByProperty($property, $type = 'r')
{
$tempArray = array();
$newObjects = array();
foreach ($this->objects as $obj) {
$tempArray[] = $obj->{$property};
}
switch ($type) {
case 'r':
asort($tempArray);
break;
case 'rr':
arsort($tempArray);
break;
case 'n':
asort($tempArray, SORT_NUMERIC);
break;
case 'nr':
arsort($tempArray, SORT_NUMERIC);
break;
case 's':
asort($tempArray, SORT_STRING);
break;
case 'sr':
arsort($tempArray, SORT_STRING);
break;
default:
return false;
}
foreach ($tempArray as $key => $val) {
$newObjects[] = $this->objects[$key];
}
$this->objects = $newObjects;
} | /*
sort the objects by the value of each objects property $type: r regular,
ascending rr regular, descending' n numeric, ascending nr numeric,
descending s string, ascending sr string, descending | https://github.com/ghousseyn/phiber/blob/2574249d49b6930a0123a310a32073a105cdd486/library/oosql/collection.php#L182-L215 |
borobudur-php/borobudur | src/Borobudur/Component/Http/Request.php | Request.getRequestFormat | public function getRequestFormat($default = 'html'): string
{
if (null === $this->format) {
$this->format = $this->getAttribute('_format');
}
return null === $this->format ? $default : $this->format;
} | php | public function getRequestFormat($default = 'html'): string
{
if (null === $this->format) {
$this->format = $this->getAttribute('_format');
}
return null === $this->format ? $default : $this->format;
} | {@inheritdoc} | https://github.com/borobudur-php/borobudur/blob/6ab0d97e1819ba0b96dc4c3bca3a7c9b1217bd44/src/Borobudur/Component/Http/Request.php#L38-L45 |
borobudur-php/borobudur | src/Borobudur/Component/Http/Request.php | Request.getQueryParam | public function getQueryParam(string $key, $default = null)
{
$params = $this->getQueryParams();
return $this->has($key) ? $params[$key] : $default;
} | php | public function getQueryParam(string $key, $default = null)
{
$params = $this->getQueryParams();
return $this->has($key) ? $params[$key] : $default;
} | {@inheritdoc} | https://github.com/borobudur-php/borobudur/blob/6ab0d97e1819ba0b96dc4c3bca3a7c9b1217bd44/src/Borobudur/Component/Http/Request.php#L50-L55 |
borobudur-php/borobudur | src/Borobudur/Component/Http/Request.php | Request.get | public function get(string $key, $default = null)
{
if ($this !== $result = $this->getAttribute($key, $this)) {
return $result;
}
if ($this !== $result = $this->getQueryParam($key, $this)) {
return $result;
}
if ($this !== $result = $this->getBodyData($key, $this)) {
return $result;
}
return $default;
} | php | public function get(string $key, $default = null)
{
if ($this !== $result = $this->getAttribute($key, $this)) {
return $result;
}
if ($this !== $result = $this->getQueryParam($key, $this)) {
return $result;
}
if ($this !== $result = $this->getBodyData($key, $this)) {
return $result;
}
return $default;
} | {@inheritdoc} | https://github.com/borobudur-php/borobudur/blob/6ab0d97e1819ba0b96dc4c3bca3a7c9b1217bd44/src/Borobudur/Component/Http/Request.php#L68-L83 |
borobudur-php/borobudur | src/Borobudur/Component/Http/Request.php | Request.getBodyData | private function getBodyData(string $key, $default = null)
{
$body = $this->getParsedBody();
if (is_array($body)) {
return array_key_exists($key, $body) ? $body[$key] : $default;
}
if (is_object($body)) {
return property_exists($body, $key) ? $body->{$key} : $default;
}
return $default;
} | php | private function getBodyData(string $key, $default = null)
{
$body = $this->getParsedBody();
if (is_array($body)) {
return array_key_exists($key, $body) ? $body[$key] : $default;
}
if (is_object($body)) {
return property_exists($body, $key) ? $body->{$key} : $default;
}
return $default;
} | Gets parsed body data with specified key.
@param string $key
@param mixed $default
@return mixed | https://github.com/borobudur-php/borobudur/blob/6ab0d97e1819ba0b96dc4c3bca3a7c9b1217bd44/src/Borobudur/Component/Http/Request.php#L101-L114 |
brainexe/core | src/Redis/Command/Import.php | Import.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$file = $input->getArgument('file');
$content = file_get_contents($file);
if ($input->getOption('flush')) {
$this->getRedis()->flushdb();
}
$this->handleImport($content);
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$file = $input->getArgument('file');
$content = file_get_contents($file);
if ($input->getOption('flush')) {
$this->getRedis()->flushdb();
}
$this->handleImport($content);
} | {@inheritdoc} | https://github.com/brainexe/core/blob/9ef69c6f045306abd20e271572386970db9b3e54/src/Redis/Command/Import.php#L36-L46 |
chilimatic/chilimatic-framework | lib/route/routesystem/NodeRoute.php | NodeRoute.getRoute | public function getRoute(array $urlParts = null)
{
if (($map = $this->binaryTree->findByKey(implode($urlParts)))) {
return $map;
}
if (($map = $this->getStandardRoute($urlParts))) {
return $map;
}
return $this->getRoot()->getData();
} | php | public function getRoute(array $urlParts = null)
{
if (($map = $this->binaryTree->findByKey(implode($urlParts)))) {
return $map;
}
if (($map = $this->getStandardRoute($urlParts))) {
return $map;
}
return $this->getRoot()->getData();
} | @param null $path
@param array|null $urlParts
@return mixed|null | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/route/routesystem/NodeRoute.php#L59-L70 |
chilimatic/chilimatic-framework | lib/route/routesystem/NodeRoute.php | NodeRoute.addRoute | public function addRoute($uri, $callback, $delimiter = Map::DEFAULT_URL_DELIMITER)
{
try {
/**
* if the uri is empty throw an exception
*/
if (empty($uri)) {
throw new RouteException(sprintf(_('There is no Route entered %s'), $uri));
}
// class for mapping
$route = new Map($uri, $callback, $delimiter);
$this->rootNode->appendToBranch($uri, $route, Map::DEFAULT_URL_DELIMITER);
} catch (RouteException $e) {
throw $e;
}
} | php | public function addRoute($uri, $callback, $delimiter = Map::DEFAULT_URL_DELIMITER)
{
try {
/**
* if the uri is empty throw an exception
*/
if (empty($uri)) {
throw new RouteException(sprintf(_('There is no Route entered %s'), $uri));
}
// class for mapping
$route = new Map($uri, $callback, $delimiter);
$this->rootNode->appendToBranch($uri, $route, Map::DEFAULT_URL_DELIMITER);
} catch (RouteException $e) {
throw $e;
}
} | register a new custom Route / overwrite an old one
@param string $uri
@param mixed $callback
@param $delimiter
@throws RouteException
@return void | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/route/routesystem/NodeRoute.php#L82-L100 |
fxpio/fxp-doctrine-console | Command/Base.php | Base.configure | protected function configure()
{
$adp = $this->adapter;
$this
->setName($adp->getCommandPrefix().':'.$this->action)
->setDescription(sprintf($adp->getCommandDescription(), $this->action, $adp->getClass()))
;
foreach ($this->configArguments as $name => $config) {
$this->addArgument($name, $config['mode'], $config['description'], $config['default']);
}
foreach ($this->configOptions as $name => $config) {
$this->addOption($name, $config['shortcut'], $config['mode'], $config['description'], $config['default']);
}
if ('create' !== $this->action && !$this->getDefinition()->hasArgument($adp->getIdentifierArgument())) {
$this->addArgument($adp->getIdentifierArgument(), InputArgument::REQUIRED, sprintf($adp->getIdentifierArgumentDescription(), $adp->getShortName()));
}
if ($this->injectFieldOptions) {
$this->helper->injectFieldOptions($this->getDefinition(), $this->adapter->getClass());
}
} | php | protected function configure()
{
$adp = $this->adapter;
$this
->setName($adp->getCommandPrefix().':'.$this->action)
->setDescription(sprintf($adp->getCommandDescription(), $this->action, $adp->getClass()))
;
foreach ($this->configArguments as $name => $config) {
$this->addArgument($name, $config['mode'], $config['description'], $config['default']);
}
foreach ($this->configOptions as $name => $config) {
$this->addOption($name, $config['shortcut'], $config['mode'], $config['description'], $config['default']);
}
if ('create' !== $this->action && !$this->getDefinition()->hasArgument($adp->getIdentifierArgument())) {
$this->addArgument($adp->getIdentifierArgument(), InputArgument::REQUIRED, sprintf($adp->getIdentifierArgumentDescription(), $adp->getShortName()));
}
if ($this->injectFieldOptions) {
$this->helper->injectFieldOptions($this->getDefinition(), $this->adapter->getClass());
}
} | {@inheritdoc} | https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Command/Base.php#L77-L100 |
fxpio/fxp-doctrine-console | Command/Base.php | Base.showMessage | protected function showMessage(OutputInterface $output, $instance, $message)
{
$methodGet = $this->adapter->getDisplayNameMethod();
$output->writeln([
'',
sprintf($message, strtolower($this->adapter->getShortName()), $instance->$methodGet()),
]);
} | php | protected function showMessage(OutputInterface $output, $instance, $message)
{
$methodGet = $this->adapter->getDisplayNameMethod();
$output->writeln([
'',
sprintf($message, strtolower($this->adapter->getShortName()), $instance->$methodGet()),
]);
} | Show the message in the console output.
@param OutputInterface $output The console output
@param object $instance The object instance
@param string $message The displayed message | https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Command/Base.php#L123-L131 |
phramework/phramework | src/Extensions/Translation.php | Translation.getTranslated | public function getTranslated($key, $parameters = null, $fallback_value = null)
{
$translated = null;
//if translations is set for this key
if (!isset($this->strings[$key])) {
//Track not found strings
if ($this->track_missing_keys) {
$this->add_key($key);
}
//use $fallback_value is provided else use the key
$translated = ($fallback_value ? $fallback_value : $key);
} else {
$translated = $this->strings[$key];
}
if ($parameters) {
$translated = \Phramework\Models\language::template($translated, $parameters);
}
return $translated;
} | php | public function getTranslated($key, $parameters = null, $fallback_value = null)
{
$translated = null;
//if translations is set for this key
if (!isset($this->strings[$key])) {
//Track not found strings
if ($this->track_missing_keys) {
$this->add_key($key);
}
//use $fallback_value is provided else use the key
$translated = ($fallback_value ? $fallback_value : $key);
} else {
$translated = $this->strings[$key];
}
if ($parameters) {
$translated = \Phramework\Models\language::template($translated, $parameters);
}
return $translated;
} | Translate a string
@param string $key
@param array|NULL $parameters
@param string $fallback_value
@return string Returns the translated string | https://github.com/phramework/phramework/blob/40041d1ef23b1f8cdbd26fb112448d6a3dbef012/src/Extensions/Translation.php#L53-L75 |
Boolive/Core | events/Events.php | Events.trigger | static function trigger($event, $params = [], $all = true)
{
$result = [];
if (isset(self::$handlers[$event])) {
foreach (self::$handlers[$event] as $key => $handler) {
if (isset($handler[0]) && (empty($handler[0]) || mb_strpos($handler[0], '/') !== false)) {
$out = call_user_func_array([\boolive\core\data\Data::read($handler[0]), $handler[1]], $params);
} else {
$out = call_user_func_array($handler, $params);
}
if ($out === false){
if (!$all) return $out;
}else{
$result[$key] = $out;
}
}
}
if (count($result) ==0 && !$all){
return null;
}
return $result;
} | php | static function trigger($event, $params = [], $all = true)
{
$result = [];
if (isset(self::$handlers[$event])) {
foreach (self::$handlers[$event] as $key => $handler) {
if (isset($handler[0]) && (empty($handler[0]) || mb_strpos($handler[0], '/') !== false)) {
$out = call_user_func_array([\boolive\core\data\Data::read($handler[0]), $handler[1]], $params);
} else {
$out = call_user_func_array($handler, $params);
}
if ($out === false){
if (!$all) return $out;
}else{
$result[$key] = $out;
}
}
}
if (count($result) ==0 && !$all){
return null;
}
return $result;
} | Генерация события
@param string $event Имя события
@param array|mixed $params Параметры события
@param bool $all
@return mixed Объект события с результатами его обработки | https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/events/Events.php#L45-L66 |
hal-platform/hal-core | src/Repository/TargetRepository.php | TargetRepository.getGroupedTargets | public function getGroupedTargets(?Application $application = null): array
{
$environments = $this->getEntityManager()
->getRepository(Environment::class)
->findAll();
if ($application) {
$findBy = ['application' => $application];
} else {
$findBy = [];
}
$targets = $this->findBy($findBy);
usort($environments, $this->environmentSorter());
usort($targets, $this->targetSorter());
$sorted = [];
foreach ($environments as $environment) {
$sorted[$environment->id()] = [
'environment' => $environment,
'targets' => [],
];
}
foreach ($targets as $target) {
$id = $target->environment()->id();
$sorted[$id]['targets'][] = $target;
}
return array_filter($sorted, function ($e) {
return count($e['targets']) !== 0;
});
} | php | public function getGroupedTargets(?Application $application = null): array
{
$environments = $this->getEntityManager()
->getRepository(Environment::class)
->findAll();
if ($application) {
$findBy = ['application' => $application];
} else {
$findBy = [];
}
$targets = $this->findBy($findBy);
usort($environments, $this->environmentSorter());
usort($targets, $this->targetSorter());
$sorted = [];
foreach ($environments as $environment) {
$sorted[$environment->id()] = [
'environment' => $environment,
'targets' => [],
];
}
foreach ($targets as $target) {
$id = $target->environment()->id();
$sorted[$id]['targets'][] = $target;
}
return array_filter($sorted, function ($e) {
return count($e['targets']) !== 0;
});
} | Get all targets sorted into environments.
@param Application|null $application
@return array | https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Repository/TargetRepository.php#L50-L83 |
ajaxtown/eaglehorn_framework | src/Eaglehorn/Template.php | Template.render | public function render()
{
$template_name = $this->base->load->template[0];
$template_file = configItem('site')['templatedir'] . $template_name . '.tpl';
if (file_exists($template_file)) {
$template = $this->twig->loadTemplate($template_name . '.tpl');
$template_data = array();
if (isset($this->base->load->template[1]) && is_array($this->base->load->template[1]))
{
$template_data = $this->base->load->template[1];
foreach($template_data as $key => $value)
{
$file = configItem('site')['viewdir'] . $value;
if (file_exists($file) && is_file($file))
{
$template_data[$key] = $this->base->getFileOutput($file);
$this->base->logger->info("View parsed - $file");
}
}
}
$this->template_markup = $template->render($template_data);
if(sizeof($this->injections) > 0)
{
$this->_applyInjections();
}
echo $this->template_markup;
} else {
//log error
}
} | php | public function render()
{
$template_name = $this->base->load->template[0];
$template_file = configItem('site')['templatedir'] . $template_name . '.tpl';
if (file_exists($template_file)) {
$template = $this->twig->loadTemplate($template_name . '.tpl');
$template_data = array();
if (isset($this->base->load->template[1]) && is_array($this->base->load->template[1]))
{
$template_data = $this->base->load->template[1];
foreach($template_data as $key => $value)
{
$file = configItem('site')['viewdir'] . $value;
if (file_exists($file) && is_file($file))
{
$template_data[$key] = $this->base->getFileOutput($file);
$this->base->logger->info("View parsed - $file");
}
}
}
$this->template_markup = $template->render($template_data);
if(sizeof($this->injections) > 0)
{
$this->_applyInjections();
}
echo $this->template_markup;
} else {
//log error
}
} | Render the template | https://github.com/ajaxtown/eaglehorn_framework/blob/5e2a1456ff6c65b3925f1219f115d8a919930f52/src/Eaglehorn/Template.php#L93-L132 |
ajaxtown/eaglehorn_framework | src/Eaglehorn/Template.php | Template._applyInjections | private function _applyInjections()
{
foreach ($this->injections as $head)
{
$tags = $this->_getInjectionString($head);
}
$this->template_markup = str_replace('</head>', $tags, $this->template_markup);
} | php | private function _applyInjections()
{
foreach ($this->injections as $head)
{
$tags = $this->_getInjectionString($head);
}
$this->template_markup = str_replace('</head>', $tags, $this->template_markup);
} | Insert the stored CSS links, JS, files and Meta into the HEAD | https://github.com/ajaxtown/eaglehorn_framework/blob/5e2a1456ff6c65b3925f1219f115d8a919930f52/src/Eaglehorn/Template.php#L137-L146 |
MDooley47/laravel-urlvalidator | src/UrlValidator.php | UrlValidator.match | public static function match($url, $options)
{
if (!is_array($options)) {
$tmpString = $options;
$options = null;
$options['host'] = $tmpString;
}
// build the rules
$rules = '';
foreach ($options as $key => $value) {
switch (Str::lower($key)) {
case 'scheme':
$rules .= "|scheme:${value}";
break;
case 'user':
$rules .= "|user:${value}";
break;
case 'pass':
$rules .= "|pass:${value}";
break;
case 'host':
$rules .= "|host:${value}";
break;
case 'subdomain':
$rules .= "|subdomain:${value}";
break;
case 'domain':
$rules .= "|domain:${value}";
break;
case 'tld':
$rules .= "|tld:${value}";
break;
case 'port':
$rules .= "|port:${value}";
break;
case 'path':
$rules .= "|path:${value}";
break;
case 'query':
$rules .= "|query:${value}";
break;
case 'fragment':
$rules .= "|fragment:${value}";
break;
}
}
$validate = Validator::make(['url' => $url], [
'url' => 'required|url'.$rules,
]);
return $validate->passes();
} | php | public static function match($url, $options)
{
if (!is_array($options)) {
$tmpString = $options;
$options = null;
$options['host'] = $tmpString;
}
// build the rules
$rules = '';
foreach ($options as $key => $value) {
switch (Str::lower($key)) {
case 'scheme':
$rules .= "|scheme:${value}";
break;
case 'user':
$rules .= "|user:${value}";
break;
case 'pass':
$rules .= "|pass:${value}";
break;
case 'host':
$rules .= "|host:${value}";
break;
case 'subdomain':
$rules .= "|subdomain:${value}";
break;
case 'domain':
$rules .= "|domain:${value}";
break;
case 'tld':
$rules .= "|tld:${value}";
break;
case 'port':
$rules .= "|port:${value}";
break;
case 'path':
$rules .= "|path:${value}";
break;
case 'query':
$rules .= "|query:${value}";
break;
case 'fragment':
$rules .= "|fragment:${value}";
break;
}
}
$validate = Validator::make(['url' => $url], [
'url' => 'required|url'.$rules,
]);
return $validate->passes();
} | @param string $url
@param array|string $options
@return bool | https://github.com/MDooley47/laravel-urlvalidator/blob/e35863a5ed70e010e316916c503b90adf4f0115c/src/UrlValidator.php#L16-L69 |
wigedev/farm | src/FormBuilder/FormElement.php | FormElement.addClass | public function addClass(string $value) : self
{
$class = trim($this->attributes['class']);
$this->attributes['class'] = trim($class . ' ' . trim($value));
return $this;
} | php | public function addClass(string $value) : self
{
$class = trim($this->attributes['class']);
$this->attributes['class'] = trim($class . ' ' . trim($value));
return $this;
} | Add the specified class to the class attribute for the form field.
@param string $value A class to add
@return self | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement.php#L161-L166 |
wigedev/farm | src/FormBuilder/FormElement.php | FormElement.setValidator | public function setValidator(string $validator_class_name, array $constraints = []) : self
{
$this->validator = $validator_class_name;
$this->constraints = $constraints;
return $this;
} | php | public function setValidator(string $validator_class_name, array $constraints = []) : self
{
$this->validator = $validator_class_name;
$this->constraints = $constraints;
return $this;
} | Sets a validator for the field
@param string $validator_class_name The name of the validation class
@param array $constraints Optional constraints
@return self | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement.php#L189-L194 |
wigedev/farm | src/FormBuilder/FormElement.php | FormElement.setRequired | public function setRequired(bool $required) : self
{
$required = (bool)$required;
$this->required = $required;
return $this;
} | php | public function setRequired(bool $required) : self
{
$required = (bool)$required;
$this->required = $required;
return $this;
} | Set if the field is required.
@param bool $required True if this field is required.
@return self | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement.php#L203-L208 |
wigedev/farm | src/FormBuilder/FormElement.php | FormElement.setDefaultValue | public function setDefaultValue($value) : self
{
$this->default_value = $value;
// If valid input was entered already, check if this value is different.
if ($this->is_valid) {
$this->is_changed = ($this->default_value == $this->user_value);
}
return $this;
} | php | public function setDefaultValue($value) : self
{
$this->default_value = $value;
// If valid input was entered already, check if this value is different.
if ($this->is_valid) {
$this->is_changed = ($this->default_value == $this->user_value);
}
return $this;
} | Sets the default or database value for the
@param mixed $value The value of the form field.
@return self | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement.php#L277-L285 |
wigedev/farm | src/FormBuilder/FormElement.php | FormElement.getSelectName | public function getSelectName() : ?string
{
if (null !== $this->select_name) {
return $this->select_name . ' as ' . $this->getDBName();
}
if (null !== $this->db_name) {
return $this->db_name;
}
return $this->attributes['name'];
} | php | public function getSelectName() : ?string
{
if (null !== $this->select_name) {
return $this->select_name . ' as ' . $this->getDBName();
}
if (null !== $this->db_name) {
return $this->db_name;
}
return $this->attributes['name'];
} | Returns the db select name of the field. If none is set, returns the db_name of the field, if that is not set,
returns the base name of the field.
@return null|string | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement.php#L335-L344 |
wigedev/farm | src/FormBuilder/FormElement.php | FormElement.setUserValue | public function setUserValue(string $value) : self
{
$this->user_value = $value;
$this->is_valid = null;
return $this;
} | php | public function setUserValue(string $value) : self
{
$this->user_value = $value;
$this->is_valid = null;
return $this;
} | Sets a user value to be validated
@param mixed $value
@return self | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement.php#L363-L368 |
wigedev/farm | src/FormBuilder/FormElement.php | FormElement.getValue | public function getValue()
{
if (null == $this->is_valid && null != $this->user_value) {
$this->validate();
}
if (null !== $this->user_value && $this->is_valid) {
if ('' === $this->user_value && true === $this->null_on_empty) {
return null;
}
return $this->user_value;
} else {
if ('' === $this->default_value && true === $this->null_on_empty) {
return null;
}
return $this->default_value;
}
} | php | public function getValue()
{
if (null == $this->is_valid && null != $this->user_value) {
$this->validate();
}
if (null !== $this->user_value && $this->is_valid) {
if ('' === $this->user_value && true === $this->null_on_empty) {
return null;
}
return $this->user_value;
} else {
if ('' === $this->default_value && true === $this->null_on_empty) {
return null;
}
return $this->default_value;
}
} | Gets the value of the field, either the user set value if valid and set, or the object value.
@return mixed | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement.php#L375-L391 |
wigedev/farm | src/FormBuilder/FormElement.php | FormElement.getUserValue | public function getUserValue()
{
if (null == $this->is_valid) {
$this->validate();
}
if (null !== $this->user_value && $this->is_valid) {
if ('' === $this->user_value && true === $this->null_on_empty) {
return null;
}
return $this->user_value;
} else {
return '';
}
} | php | public function getUserValue()
{
if (null == $this->is_valid) {
$this->validate();
}
if (null !== $this->user_value && $this->is_valid) {
if ('' === $this->user_value && true === $this->null_on_empty) {
return null;
}
return $this->user_value;
} else {
return '';
}
} | Get the user set value, if valid.
@return mixed | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement.php#L408-L421 |
wigedev/farm | src/FormBuilder/FormElement.php | FormElement.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) {
if ('' === $this->user_value && false === $this->required) {
$this->is_valid = true;
return;
} elseif ('' === $this->user_value && true === $this->required) {
$this->is_valid = false;
return;
}
try {
$validator = $this->validator;
$result = $validator::quickValidate($this->user_value, $this->constraints);
$this->user_value = $result;
$this->is_valid = true;
} catch (InvalidInputException $e) {
$this->user_value = null;
$this->is_valid = false;
$this->error = $e->getMessage();
}
} 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) {
if ('' === $this->user_value && false === $this->required) {
$this->is_valid = true;
return;
} elseif ('' === $this->user_value && true === $this->required) {
$this->is_valid = false;
return;
}
try {
$validator = $this->validator;
$result = $validator::quickValidate($this->user_value, $this->constraints);
$this->user_value = $result;
$this->is_valid = true;
} catch (InvalidInputException $e) {
$this->user_value = null;
$this->is_valid = false;
$this->error = $e->getMessage();
}
} 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.
TODO: Refactor | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement.php#L437-L471 |
wigedev/farm | src/FormBuilder/FormElement.php | FormElement.setError | public function setError(?string $message = null) : void
{
$this->is_valid = false;
$this->error = (null === $message) ? $this->default_error : $message;
} | php | public function setError(?string $message = null) : void
{
$this->is_valid = false;
$this->error = (null === $message) ? $this->default_error : $message;
} | Allows other systems such as the form's validator, to set this element as invalid. If no error message is
specified, the default error message will be set.
@param string|null $message | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement.php#L527-L531 |
wigedev/farm | src/FormBuilder/FormElement.php | FormElement.commit | public function commit() : void
{
if (null === $this->is_valid) {
$this->validate();
}
if ($this->is_valid && $this->user_value != null) {
$this->default_value = $this->user_value;
}
$this->user_value = null;
$this->is_valid = null;
$this->is_changed = false;
} | php | public function commit() : void
{
if (null === $this->is_valid) {
$this->validate();
}
if ($this->is_valid && $this->user_value != null) {
$this->default_value = $this->user_value;
}
$this->user_value = null;
$this->is_valid = null;
$this->is_changed = false;
} | After the form is saved, use commit to "save" the input values. This replaces the default value with the input
value, and resets isValid to null and isChanged to false. | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement.php#L537-L548 |
wigedev/farm | src/FormBuilder/FormElement.php | FormElement.outputElement | public function outputElement() : string
{
$attributes = [];
foreach ($this->attributes as $name => $value) {
if ('value' === $name) {
$value = $this->getValue();
}
$attributes[] = $name . '="' . $value . '"';
}
return '<input ' . implode(' ', $attributes) . ' />';
} | php | public function outputElement() : string
{
$attributes = [];
foreach ($this->attributes as $name => $value) {
if ('value' === $name) {
$value = $this->getValue();
}
$attributes[] = $name . '="' . $value . '"';
}
return '<input ' . implode(' ', $attributes) . ' />';
} | Returns the form element as an HTML tag
@return string | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement.php#L582-L592 |
stackpr/quipxml | src/Xml/QuipXmlElement.php | QuipXmlElement.before | public function before($content) {
if (FALSE === (bool) $this) {
return $this;
}
$me = $this->dom();
$parent = $this->xparent()->dom();
$new = $this->_contentToDom($content);
$parent->insertBefore($new, $me);
return $this;
} | php | public function before($content) {
if (FALSE === (bool) $this) {
return $this;
}
$me = $this->dom();
$parent = $this->xparent()->dom();
$new = $this->_contentToDom($content);
$parent->insertBefore($new, $me);
return $this;
} | Add the content before this node.
@param mixed $content
@return \QuipXml\Xml\QuipXmlElement | https://github.com/stackpr/quipxml/blob/472e0d98a90aa0a283aac933158d830311480ff8/src/Xml/QuipXmlElement.php#L63-L72 |
stackpr/quipxml | src/Xml/QuipXmlElement.php | QuipXmlElement.after | public function after($content) {
if (FALSE === (bool) $this) {
return $this;
}
$me = $this->dom();
$parent = $this->xparent()->dom();
$new = $this->_contentToDom($content);
if (isset($me->nextSibling)) {
$parent->insertBefore($new, $me->nextSibling);
}
else {
$parent->appendChild($new);
}
return $this;
} | php | public function after($content) {
if (FALSE === (bool) $this) {
return $this;
}
$me = $this->dom();
$parent = $this->xparent()->dom();
$new = $this->_contentToDom($content);
if (isset($me->nextSibling)) {
$parent->insertBefore($new, $me->nextSibling);
}
else {
$parent->appendChild($new);
}
return $this;
} | Add the content after this node.
@param mixed $content
@return \QuipXml\Xml\QuipXmlElement | https://github.com/stackpr/quipxml/blob/472e0d98a90aa0a283aac933158d830311480ff8/src/Xml/QuipXmlElement.php#L79-L93 |
stackpr/quipxml | src/Xml/QuipXmlElement.php | QuipXmlElement.xpath | public function xpath($path) {
$results = parent::xpath($path);
if (empty($results)) {
return $this->_getEmptyElement();
}
return new QuipXmlElementIterator(new \ArrayIterator($results));
} | php | public function xpath($path) {
$results = parent::xpath($path);
if (empty($results)) {
return $this->_getEmptyElement();
}
return new QuipXmlElementIterator(new \ArrayIterator($results));
} | Wrap the xpath results in a Quip iterator.
@see SimpleXMLElement::xpath()
@return \QuipXml\Xml\QuipXmlElementIterator | https://github.com/stackpr/quipxml/blob/472e0d98a90aa0a283aac933158d830311480ff8/src/Xml/QuipXmlElement.php#L325-L331 |
jelix/castor | lib/Castor/CastorCore.php | CastorCore.append | public function append($name, $value = null)
{
if (is_array($name)) {
foreach ($name as $key => $val) {
if (isset($this->_vars[$key])) {
$this->_vars[$key] .= $val;
} else {
$this->_vars[$key] = $val;
}
}
} else {
if (isset($this->_vars[$name])) {
$this->_vars[$name] .= $value;
} else {
$this->_vars[$name] = $value;
}
}
} | php | public function append($name, $value = null)
{
if (is_array($name)) {
foreach ($name as $key => $val) {
if (isset($this->_vars[$key])) {
$this->_vars[$key] .= $val;
} else {
$this->_vars[$key] = $val;
}
}
} else {
if (isset($this->_vars[$name])) {
$this->_vars[$name] .= $value;
} else {
$this->_vars[$name] = $value;
}
}
} | concat a value in with a value of an existing template variable.
@param string|array $name the variable name, or an associative array 'name'=>'value'
@param mixed $value the value (or null if $name is an array) | https://github.com/jelix/castor/blob/113aacc4c65766816bb11e263e44da12ec645d6e/lib/Castor/CastorCore.php#L86-L103 |
jelix/castor | lib/Castor/CastorCore.php | CastorCore.meta | public function meta($tpl, $outputtype = '', $trusted = true)
{
if (in_array($tpl, $this->processedMeta)) {
// we want to process meta only one time, when a template is included
// several time in an other template, or, more important, when a template
// is included in a recursive manner (in this case, it did cause infinite loop, see #1396).
return $this->_meta;
}
$this->processedMeta[] = $tpl;
$md = $this->getTemplate($tpl, $outputtype, $trusted);
$fct = 'template_meta_'.$md;
$fct($this);
return $this->_meta;
} | php | public function meta($tpl, $outputtype = '', $trusted = true)
{
if (in_array($tpl, $this->processedMeta)) {
// we want to process meta only one time, when a template is included
// several time in an other template, or, more important, when a template
// is included in a recursive manner (in this case, it did cause infinite loop, see #1396).
return $this->_meta;
}
$this->processedMeta[] = $tpl;
$md = $this->getTemplate($tpl, $outputtype, $trusted);
$fct = 'template_meta_'.$md;
$fct($this);
return $this->_meta;
} | process all meta instruction of a template.
@param string $tpl template selector
@param string $outputtype the type of output (html, text etc..)
@param bool $trusted says if the template file is trusted or not | https://github.com/jelix/castor/blob/113aacc4c65766816bb11e263e44da12ec645d6e/lib/Castor/CastorCore.php#L173-L188 |
jelix/castor | lib/Castor/CastorCore.php | CastorCore.display | public function display($tpl, $outputtype = '', $trusted = true)
{
$previousTpl = $this->_templateName;
$this->_templateName = $tpl;
$this->recursiveTpl[] = $tpl;
$md = $this->getTemplate($tpl, $outputtype, $trusted);
$fct = 'template_'.$md;
$fct($this);
array_pop($this->recursiveTpl);
$this->_templateName = $previousTpl;
} | php | public function display($tpl, $outputtype = '', $trusted = true)
{
$previousTpl = $this->_templateName;
$this->_templateName = $tpl;
$this->recursiveTpl[] = $tpl;
$md = $this->getTemplate($tpl, $outputtype, $trusted);
$fct = 'template_'.$md;
$fct($this);
array_pop($this->recursiveTpl);
$this->_templateName = $previousTpl;
} | display the generated content from the given template.
@param string $tpl template selector
@param string $outputtype the type of output (html, text etc..)
@param bool $trusted says if the template file is trusted or not | https://github.com/jelix/castor/blob/113aacc4c65766816bb11e263e44da12ec645d6e/lib/Castor/CastorCore.php#L197-L208 |
jelix/castor | lib/Castor/CastorCore.php | CastorCore.fetchFromString | public function fetchFromString($tpl, $outputtype = '', $trusted = true, $callMeta = true)
{
$content = '';
ob_start();
try {
$cachePath = $this->getCachePath().'virtual/';
$previousTpl = $this->_templateName;
$md = 'virtual_'.md5($tpl).($trusted ? '_t' : '');
$this->_templateName = $md;
if ($outputtype == '') {
$outputtype = 'html';
}
$cachePath .= $outputtype.'_'.$this->_templateName.'.php';
$mustCompile = $this->compilationNeeded($cachePath);
if ($mustCompile && !function_exists('template_'.$md)) {
$compiler = $this->getCompiler();
$compiler->outputType = $outputtype;
$compiler->trusted = $trusted;
$compiler->compileString($tpl,
$cachePath,
$this->userModifiers,
$this->userFunctions,
$md);
}
require_once $cachePath;
if ($callMeta) {
$fct = 'template_meta_'.$md;
$fct($this);
}
$fct = 'template_'.$md;
$fct($this);
$content = ob_get_clean();
$this->_templateName = $previousTpl;
} catch (exception $e) {
ob_end_clean();
throw $e;
}
return $content;
} | php | public function fetchFromString($tpl, $outputtype = '', $trusted = true, $callMeta = true)
{
$content = '';
ob_start();
try {
$cachePath = $this->getCachePath().'virtual/';
$previousTpl = $this->_templateName;
$md = 'virtual_'.md5($tpl).($trusted ? '_t' : '');
$this->_templateName = $md;
if ($outputtype == '') {
$outputtype = 'html';
}
$cachePath .= $outputtype.'_'.$this->_templateName.'.php';
$mustCompile = $this->compilationNeeded($cachePath);
if ($mustCompile && !function_exists('template_'.$md)) {
$compiler = $this->getCompiler();
$compiler->outputType = $outputtype;
$compiler->trusted = $trusted;
$compiler->compileString($tpl,
$cachePath,
$this->userModifiers,
$this->userFunctions,
$md);
}
require_once $cachePath;
if ($callMeta) {
$fct = 'template_meta_'.$md;
$fct($this);
}
$fct = 'template_'.$md;
$fct($this);
$content = ob_get_clean();
$this->_templateName = $previousTpl;
} catch (exception $e) {
ob_end_clean();
throw $e;
}
return $content;
} | Return the generated content from the given string template (virtual).
@param string $tpl template content
@param string $outputtype the type of output (html, text etc..)
@param bool $trusted says if the template file is trusted or not
@param bool $callMeta false if meta should not be called
@return string the generated content | https://github.com/jelix/castor/blob/113aacc4c65766816bb11e263e44da12ec645d6e/lib/Castor/CastorCore.php#L290-L335 |
fnayou/instapush-php | src/Api/EventsApi.php | EventsApi.add | public function add(Event $event)
{
$this->doPost('/events/add', $event->toArray());
/** @var \Fnayou\InstapushPHP\Model\Events $events */
$events = $this->list();
return $events->last();
} | php | public function add(Event $event)
{
$this->doPost('/events/add', $event->toArray());
/** @var \Fnayou\InstapushPHP\Model\Events $events */
$events = $this->list();
return $events->last();
} | @param \Fnayou\InstapushPHP\Model\Event $event
@return \Fnayou\InstapushPHP\Model\Event | https://github.com/fnayou/instapush-php/blob/fa7bd9091cf4dee767449412dc10911f4afbdf24/src/Api/EventsApi.php#L41-L49 |
kleijnweb/php-api-middleware | src/ParameterHydrator.php | ParameterHydrator.process | public function process(ServerRequestInterface $request, DelegateInterface $delegate)
{
$operation = $this->getOperation($request);
foreach ($operation->getParameters() as $parameter) {
$name = $parameter->getName();
$request = $request->withAttribute(
$name,
$this->processorBuilder
->build($this->getOperation($request)->getParameter($name)->getSchema())
->hydrate($request->getAttribute($name))
);
}
return $delegate->process($request);
} | php | public function process(ServerRequestInterface $request, DelegateInterface $delegate)
{
$operation = $this->getOperation($request);
foreach ($operation->getParameters() as $parameter) {
$name = $parameter->getName();
$request = $request->withAttribute(
$name,
$this->processorBuilder
->build($this->getOperation($request)->getParameter($name)->getSchema())
->hydrate($request->getAttribute($name))
);
}
return $delegate->process($request);
} | Process a server request and return a response.
@param ServerRequestInterface $request
@param DelegateInterface $delegate
@return ResponseInterface | https://github.com/kleijnweb/php-api-middleware/blob/e9e74706c3b30a0e06c7f0f7e2a3a43ef17e6df4/src/ParameterHydrator.php#L40-L55 |
newup/core | src/Console/Commands/About.php | About.handle | public function handle()
{
$this->info('NewUp version ' . $this->laravel->version());
$this->line('http://newup.io' . PHP_EOL);
$this->line('Configuration loaded from: '.$this->normalizePath(get_user_config_path()).PHP_EOL);
$this->comment('NewUp is a simple command line utility, built on Laravel\'s Artisan, to quickly generate packages compatible with all of PHP.');
$this->comment('Check out the source code at github.com/newup/newup' . PHP_EOL);
$this->line('Thank you for using NewUp!');
} | php | public function handle()
{
$this->info('NewUp version ' . $this->laravel->version());
$this->line('http://newup.io' . PHP_EOL);
$this->line('Configuration loaded from: '.$this->normalizePath(get_user_config_path()).PHP_EOL);
$this->comment('NewUp is a simple command line utility, built on Laravel\'s Artisan, to quickly generate packages compatible with all of PHP.');
$this->comment('Check out the source code at github.com/newup/newup' . PHP_EOL);
$this->line('Thank you for using NewUp!');
} | Execute the console command.
@return mixed | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Console/Commands/About.php#L32-L40 |
3ev/wordpress-core | src/Tev/Field/Model/RepeaterField.php | RepeaterField.current | public function current()
{
return new FieldGroup(
$this->base['sub_fields'],
$this->base['value'][$this->position],
$this,
$this->fieldFactory
);
} | php | public function current()
{
return new FieldGroup(
$this->base['sub_fields'],
$this->base['value'][$this->position],
$this,
$this->fieldFactory
);
} | Get the current repeater item.
@return \Tev\Field\Util\FieldGroup | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Field/Model/RepeaterField.php#L74-L82 |
3ev/wordpress-core | src/Tev/Field/Model/RepeaterField.php | RepeaterField.valid | public function valid()
{
return isset($this->base['value'][$this->position]) && is_array($this->base['value'][$this->position]);
} | php | public function valid()
{
return isset($this->base['value'][$this->position]) && is_array($this->base['value'][$this->position]);
} | Check if current position is valid.
@return boolean | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Field/Model/RepeaterField.php#L119-L122 |
3ev/wordpress-core | src/Tev/Field/Model/RepeaterField.php | RepeaterField.offsetExists | public function offsetExists($offset)
{
return isset($this->base['value'][$offset]) && is_array($this->base['value'][$offset]);
} | php | public function offsetExists($offset)
{
return isset($this->base['value'][$offset]) && is_array($this->base['value'][$offset]);
} | Required for `\ArrayAccess`.
@param mixed $offset Array offset
@return boolean | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Field/Model/RepeaterField.php#L130-L133 |
3ev/wordpress-core | src/Tev/Field/Model/RepeaterField.php | RepeaterField.offsetGet | public function offsetGet($offset)
{
if (isset($this->base['value'][$offset]) && is_array($this->base['value'][$offset])) {
return new FieldGroup(
$this->base['sub_fields'],
$this->base['value'][$offset],
$this,
$this->fieldFactory
);
}
return null;
} | php | public function offsetGet($offset)
{
if (isset($this->base['value'][$offset]) && is_array($this->base['value'][$offset])) {
return new FieldGroup(
$this->base['sub_fields'],
$this->base['value'][$offset],
$this,
$this->fieldFactory
);
}
return null;
} | Required for `\ArrayAccess`.
@param mixed $offset Array offset
@return mixed | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Field/Model/RepeaterField.php#L141-L153 |
dreamfactorysoftware/df-rackspace | src/Models/OpenStackConfig.php | OpenStackConfig.getConfigSchema | public static function getConfigSchema()
{
$model = new static;
$schema = $model->getTableSchema();
if ($schema) {
$out = [];
foreach ($schema->columns as $name => $column) {
/** @var ColumnSchema $column */
if (('service_id' === $name) ||
'api_key' === $name ||
'storage_type' === $name ||
$column->autoIncrement
) {
continue;
}
$temp = $column->toArray();
static::prepareConfigSchemaField($temp);
$out[] = $temp;
}
return $out;
}
return null;
} | php | public static function getConfigSchema()
{
$model = new static;
$schema = $model->getTableSchema();
if ($schema) {
$out = [];
foreach ($schema->columns as $name => $column) {
/** @var ColumnSchema $column */
if (('service_id' === $name) ||
'api_key' === $name ||
'storage_type' === $name ||
$column->autoIncrement
) {
continue;
}
$temp = $column->toArray();
static::prepareConfigSchemaField($temp);
$out[] = $temp;
}
return $out;
}
return null;
} | {@inheritdoc} | https://github.com/dreamfactorysoftware/df-rackspace/blob/fad0bf9e6165cd868308d054dde7d0766dd8380a/src/Models/OpenStackConfig.php#L41-L67 |
asaritech/ukey1-php-sdk | src/Ukey1/Endpoints/Authentication/User.php | User.execute | public function execute()
{
if ($this->executed) {
return;
}
if (!$this->accessToken) {
throw new EndpointException("No access token was provided");
}
if (!$this->valid()) {
throw new EndpointException("Access token expired");
}
$request = new Request(Request::GET);
$request->setHost($this->app->getHost())
->setEndpoint(self::ENDPOINT)
->setCredentials($this->app->getAppId(), $this->app->getSecretKey())
->setAccessToken($this->accessToken);
$result = $request->send();
$this->resultRaw = $result->getBody();
$this->resultData = $result->getData();
$this->executed = true;
} | php | public function execute()
{
if ($this->executed) {
return;
}
if (!$this->accessToken) {
throw new EndpointException("No access token was provided");
}
if (!$this->valid()) {
throw new EndpointException("Access token expired");
}
$request = new Request(Request::GET);
$request->setHost($this->app->getHost())
->setEndpoint(self::ENDPOINT)
->setCredentials($this->app->getAppId(), $this->app->getSecretKey())
->setAccessToken($this->accessToken);
$result = $request->send();
$this->resultRaw = $result->getBody();
$this->resultData = $result->getData();
$this->executed = true;
} | Executes an API request
@throws \Ukey1\Exceptions\EndpointException | https://github.com/asaritech/ukey1-php-sdk/blob/a4a306b9c71db8644dfd85e0e231f2b2b21bdd3a/src/Ukey1/Endpoints/Authentication/User.php#L104-L129 |
asaritech/ukey1-php-sdk | src/Ukey1/Endpoints/Authentication/User.php | User.jwt | private function jwt()
{
if (!$this->jwt) {
if (!$this->accessToken) {
throw new EndpointException("No access token was provided");
}
$this->jwt = (new Parser())->parse($this->accessToken);
$this->checkSignature();
}
} | php | private function jwt()
{
if (!$this->jwt) {
if (!$this->accessToken) {
throw new EndpointException("No access token was provided");
}
$this->jwt = (new Parser())->parse($this->accessToken);
$this->checkSignature();
}
} | Create JWT object from access token string
@throws EndpointException | https://github.com/asaritech/ukey1-php-sdk/blob/a4a306b9c71db8644dfd85e0e231f2b2b21bdd3a/src/Ukey1/Endpoints/Authentication/User.php#L148-L158 |
asaritech/ukey1-php-sdk | src/Ukey1/Endpoints/Authentication/User.php | User.checkSignature | private function checkSignature()
{
$signer = new Sha512();
$keychain = new Keychain();
if (!$this->jwt->verify($signer, $keychain->getPublicKey($this->app->getSecretKey()))) {
throw new EndpointException("Access token verification failed");
}
} | php | private function checkSignature()
{
$signer = new Sha512();
$keychain = new Keychain();
if (!$this->jwt->verify($signer, $keychain->getPublicKey($this->app->getSecretKey()))) {
throw new EndpointException("Access token verification failed");
}
} | Signature verification
@throws EndpointException | https://github.com/asaritech/ukey1-php-sdk/blob/a4a306b9c71db8644dfd85e0e231f2b2b21bdd3a/src/Ukey1/Endpoints/Authentication/User.php#L165-L173 |
asaritech/ukey1-php-sdk | src/Ukey1/Endpoints/Authentication/User.php | User.getId | public function getId()
{
$this->jwt();
$exist = $this->jwt->hasClaim("user");
if (!$exist) {
throw new EndpointException("Invalid access token");
}
$claim = $this->jwt->getClaim("user");
if ($claim->id) {
return $claim->id;
} else {
throw new EndpointException("Invalid access token");
}
} | php | public function getId()
{
$this->jwt();
$exist = $this->jwt->hasClaim("user");
if (!$exist) {
throw new EndpointException("Invalid access token");
}
$claim = $this->jwt->getClaim("user");
if ($claim->id) {
return $claim->id;
} else {
throw new EndpointException("Invalid access token");
}
} | Return user ID (parsed from access token)
@return string | https://github.com/asaritech/ukey1-php-sdk/blob/a4a306b9c71db8644dfd85e0e231f2b2b21bdd3a/src/Ukey1/Endpoints/Authentication/User.php#L214-L231 |
asaritech/ukey1-php-sdk | src/Ukey1/Endpoints/Authentication/User.php | User.valid | public function valid()
{
$this->jwt();
$data = new ValidationData();
if ($this->leeway != 0) {
$data->setCurrentTime(time() + $this->leeway);
}
return $this->jwt->validate($data);
} | php | public function valid()
{
$this->jwt();
$data = new ValidationData();
if ($this->leeway != 0) {
$data->setCurrentTime(time() + $this->leeway);
}
return $this->jwt->validate($data);
} | Return if access token is valid
@return bool | https://github.com/asaritech/ukey1-php-sdk/blob/a4a306b9c71db8644dfd85e0e231f2b2b21bdd3a/src/Ukey1/Endpoints/Authentication/User.php#L238-L249 |
DimNS/SimpleCSRF | src/SimpleCSRF.php | SimpleCSRF.getToken | public function getToken()
{
if (isset($_SESSION[$this->session_name])) {
return $_SESSION[$this->session_name];
} else {
$token = uniqid($this->randomString());
$_SESSION[$this->session_name] = $token;
return $token;
}
} | php | public function getToken()
{
if (isset($_SESSION[$this->session_name])) {
return $_SESSION[$this->session_name];
} else {
$token = uniqid($this->randomString());
$_SESSION[$this->session_name] = $token;
return $token;
}
} | Getting a token
@return string Return result
@version v2.0.0
@author Dmitrii Shcherbakov <[email protected]> | https://github.com/DimNS/SimpleCSRF/blob/8bd8fe2e9fe8aa90334b88f8fa398fcf3817ba45/src/SimpleCSRF.php#L49-L58 |
DimNS/SimpleCSRF | src/SimpleCSRF.php | SimpleCSRF.validateToken | public function validateToken($token)
{
if (isset($_SESSION[$this->session_name])) {
if ($_SESSION[$this->session_name] === $token) {
return true;
} else {
return false;
}
} else {
return false;
}
} | php | public function validateToken($token)
{
if (isset($_SESSION[$this->session_name])) {
if ($_SESSION[$this->session_name] === $token) {
return true;
} else {
return false;
}
} else {
return false;
}
} | Checking the token
@param string $token The token to check
@return boolean Return result
@version v2.0.0
@author Dmitrii Shcherbakov <[email protected]> | https://github.com/DimNS/SimpleCSRF/blob/8bd8fe2e9fe8aa90334b88f8fa398fcf3817ba45/src/SimpleCSRF.php#L70-L81 |
DimNS/SimpleCSRF | src/SimpleCSRF.php | SimpleCSRF.randomString | private function randomString()
{
$chars = 'qazxswedcvfrtgbnhyujmkiolp1234567890QAZXSWEDCVFRTGBNHYUJMKIOLP';
$max = $this->length_random_string;
$size = strlen($chars) - 1;
$string = '';
while ($max--) {
$string .= $chars[mt_rand(0, $size)];
}
return $string;
} | php | private function randomString()
{
$chars = 'qazxswedcvfrtgbnhyujmkiolp1234567890QAZXSWEDCVFRTGBNHYUJMKIOLP';
$max = $this->length_random_string;
$size = strlen($chars) - 1;
$string = '';
while ($max--) {
$string .= $chars[mt_rand(0, $size)];
}
return $string;
} | Generate a random string
@return string Return result
@version v2.0.0
@author Dmitrii Shcherbakov <[email protected]> | https://github.com/DimNS/SimpleCSRF/blob/8bd8fe2e9fe8aa90334b88f8fa398fcf3817ba45/src/SimpleCSRF.php#L91-L103 |
emeric0101/PHPEntityManagerRest.Server | src/Service/Auth.php | Auth.createTable | private function createTable($rights) {
$table = [];
foreach ($rights as $flag => $right) {
$table[$flag] = new RightGroup($flag);
}
foreach ($rights as $flag => $right) {
$this->parseRightGroup($right, $flag, $table);
}
return $table;
} | php | private function createTable($rights) {
$table = [];
foreach ($rights as $flag => $right) {
$table[$flag] = new RightGroup($flag);
}
foreach ($rights as $flag => $right) {
$this->parseRightGroup($right, $flag, $table);
}
return $table;
} | Create the right table from the Config | https://github.com/emeric0101/PHPEntityManagerRest.Server/blob/532db4f89c99b5775cbc1bcf7e0fd02c7a1c1bd5/src/Service/Auth.php#L67-L77 |
davin-bao/php-git | src/Controllers/AssetController.php | AssetController.js | public function js($name){
$content = $this->dumpAssetsToString('js', $name);
$response = new Response(
$content, 200, array(
'Content-Type' => 'text/javascript',
)
);
return $this->cacheResponse($response);
} | php | public function js($name){
$content = $this->dumpAssetsToString('js', $name);
$response = new Response(
$content, 200, array(
'Content-Type' => 'text/javascript',
)
);
return $this->cacheResponse($response);
} | Return the javascript for the PhpGit
@return \Symfony\Component\HttpFoundation\Response | https://github.com/davin-bao/php-git/blob/9ae1997dc07978a3e647d44cba433d6638474c5c/src/Controllers/AssetController.php#L19-L30 |
davin-bao/php-git | src/Controllers/AssetController.php | AssetController.css | public function css($name) {
$content = $this->dumpAssetsToString('css', $name);
$response = new Response(
$content, 200, array(
'Content-Type' => 'text/css',
)
);
return $this->cacheResponse($response);
} | php | public function css($name) {
$content = $this->dumpAssetsToString('css', $name);
$response = new Response(
$content, 200, array(
'Content-Type' => 'text/css',
)
);
return $this->cacheResponse($response);
} | Return the stylesheets for the PhpGit
@return \Symfony\Component\HttpFoundation\Response | https://github.com/davin-bao/php-git/blob/9ae1997dc07978a3e647d44cba433d6638474c5c/src/Controllers/AssetController.php#L37-L48 |
slickframework/form | src/Renderer/AbstractRenderer.php | AbstractRenderer.getEngine | public function getEngine()
{
if (null === $this->engine) {
$this->setEngine(TemplateFactory::getEngine());
}
return $this->engine;
} | php | public function getEngine()
{
if (null === $this->engine) {
$this->setEngine(TemplateFactory::getEngine());
}
return $this->engine;
} | Returns the current template engine
If no template is provided a new one is created with default settings.
@return EngineInterface | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Renderer/AbstractRenderer.php#L74-L80 |
slickframework/form | src/Renderer/AbstractRenderer.php | AbstractRenderer.getAttributes | public function getAttributes()
{
$result = [];
foreach ($this->element->getAttributes() as $attribute => $value) {
if (null === $value) {
$result[] = $attribute;
continue;
}
$result[] = "{$attribute}=\"{$value}\"";
}
return implode(' ', $result);
} | php | public function getAttributes()
{
$result = [];
foreach ($this->element->getAttributes() as $attribute => $value) {
if (null === $value) {
$result[] = $attribute;
continue;
}
$result[] = "{$attribute}=\"{$value}\"";
}
return implode(' ', $result);
} | Returns the elements's attributes as a string
@return string | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Renderer/AbstractRenderer.php#L100-L112 |
borobudur-php/borobudur | src/Borobudur/Component/Ddd/ModelMapperTrait.php | ModelMapperTrait.fill | protected function fill(Model $model, object $data): Model
{
$mapper = new ObjectMapper();
return $mapper->map($model)->fill($data);
} | php | protected function fill(Model $model, object $data): Model
{
$mapper = new ObjectMapper();
return $mapper->map($model)->fill($data);
} | Fill the model with given data.
@param Model $model
@param object $data
@return Model|mixed | https://github.com/borobudur-php/borobudur/blob/6ab0d97e1819ba0b96dc4c3bca3a7c9b1217bd44/src/Borobudur/Component/Ddd/ModelMapperTrait.php#L32-L37 |
borobudur-php/borobudur | src/Borobudur/Component/Ddd/ModelMapperTrait.php | ModelMapperTrait.setId | protected function setId(Identifier $id, Model $model): void
{
$prop = new ReflectionProperty(get_class($model), 'id');
$prop->setAccessible(true);
$prop->setValue($model, $id);
} | php | protected function setId(Identifier $id, Model $model): void
{
$prop = new ReflectionProperty(get_class($model), 'id');
$prop->setAccessible(true);
$prop->setValue($model, $id);
} | Set the protected id value.
@param Identifier $id
@param Model $model | https://github.com/borobudur-php/borobudur/blob/6ab0d97e1819ba0b96dc4c3bca3a7c9b1217bd44/src/Borobudur/Component/Ddd/ModelMapperTrait.php#L45-L50 |
phpalchemy/phpalchemy | Alchemy/Component/UI/Parser.php | Parser.parse | public function parse()
{
if (!is_file($this->file)) {
throw new \Exception(sprintf(
'Template "%s" file doesn\'t exist!', $this->file
));
}
$fp = fopen($this->file, 'r');
$lineCount = 0;
$nextToken = '';
$block = '';
$currentValue = '';
$stringComposing = false;
$skipMultilineComment = false;
while (($line = fgets($fp)) !== false) {
$lineCount++;
if ($stringComposing) {
if (substr(ltrim($line), 0, 3) === '>>>') {
$this->blocks[$block][$name] = trim($value);
//$block = '';
$value = '';
$stringComposing = false;
} else {
// $line = trim($line);
// if (substr($value, -1) != '>' && ! empty($line)) {
// $line = " " . $line;
// }
//$value .= substr($value, -1) == '>' ? trim($line) : " " . trim($line);
$value .= $line;
}
continue;
}
$line = trim($line);
if (substr($line, 0, 1) === '#' || $line === '' || substr($line, 0, 2) === '//') {
continue; // skip single comments or empty lines
} elseif (substr($line, 0, 2) === '/*') { // start multiline comment
if (strpos($line, '*/') === false) {
$skipMultilineComment = true; // activate multiline comments skipping
} else {
continue; // just skip this line, it has the form: /* ... */
}
} elseif (strpos($line, '*/') !== false) { // end multiline comment
$skipMultilineComment = false;
continue; // just skip the end multiline comment
}
if ($skipMultilineComment) {
continue; //skip multiline comments segment
}
$kwPattern = '^@(?<keyword>\w+)';
if (! preg_match('/'.$kwPattern.'.*/', $line, $matches)) {
throw new \Exception(sprintf(
'Parse Error: Unknow keyword, lines must starts with a valid keyword, near: %s, on line %s',
$line, $lineCount
));
}
//var_dump($matches);
$keyword = $matches['keyword'];
switch ($keyword) {
case Parser::T_DEF:
$pattern = '/'.$kwPattern.'\s+(?<type>[\w]+)\s+(?<name>[\w.]+)\s+(?<value>.+)/';
if (!preg_match($pattern, $line, $matches)) {
throw new \Exception(sprintf(
"Syntax Error: near: '%s', on line %s.\n" .
"Syntax should be: @def <type> <name> <value>",
$line, $lineCount
));
}
$keyword = $matches['keyword'];
$type = $matches['type'];
$name = $matches['name'];
$value = $matches['value'];
$tmp = explode('.', $name);
$defName = $tmp[0];
$defProp = isset($tmp[1]) ? $tmp[1] : '';
switch ($type) {
case Parser::T_GLOBAL:
case Parser::T_ITERATOR:
case Parser::T_SETCONF:
if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
$value = trim($value, '"');
} elseif (substr($value, 0, 1) == "'" && substr($value, -1) == "'") {
$value = trim($value, "'");
}
if ($value === '\n' || $value === '\r\n') {
$value = "\n";
}
$value = self::castValue($value);
if (empty($defProp)) {
$this->defs[$type][$defName] = $value;
} else {
$this->defs[$type][$defName][$defProp] = $value;
}
break;
default:
throw new \Exception(sprintf(
'Parse Error: unknow definition type: "%s" on line %s.', $type, $lineCount
));
}
break;
case Parser::T_BLOCK:
$pattern = '/'.$kwPattern.'\s+(?<block>[\w]+)/';
if (!preg_match($pattern, $line, $matches)) {
throw new Exception(sprintf(
"Parse Error: Syntax error near: %s, on line %s.\n." .
"Syntax should be: @def <type> <name> <value>",
substr($line, 0, 20).'...', $lineCount
));
}
//var_dump($matches);
$block = $matches['block'];
if (!empty($nextToken)) {
throw new \Exception(sprintf(
'Parse Error: expected: @"%s", given: @"%s"', $nextToken, Parser::T_BLOCK
));
}
$nextToken = Parser::T_END;
break;
case Parser::T_END:
if (empty($nextToken)) {
throw new \Exception(sprintf(
'Parse Error: close keyword: @"%s" given, but any block was started.', Parser::T_BLOCK
));
}
if ($nextToken !== Parser::T_END) {
throw new \Exception(sprintf(
'Parse Error: expected: @"%s", given: @"%s"', $nextToken, Parser::T_END
));
}
$nextToken = '';
break;
case Parser::T_VAR:
$pattern = '/'.$kwPattern.'\s+(?<name>[\w]+)\s+(?<value>.+)/';
if (!preg_match($pattern, $line, $matches)) {
throw new Exception(sprintf(
"Parse Error: Syntax error near: %s, on line %s.\n." .
"Syntax should be: @var <name> <value>\n or \n" .
"@var <name> <<<\nsome large string\nmultiline...\n>>>\n\n",
substr($line, 0, 20).'...', $lineCount
));
}
//print_r($matches);
$keyword = $matches['keyword'];
$name = $matches['name'];
$value = $matches['value'];
if (substr($value, 0, 3) === '<<<' && $value !== '<<<') {
throw new \Exception(sprintf(
"Syntax Error: multiline string must starts on new line after open braces <<<\n" .
"near: '%s', on line %s", $line, $lineCount
));
}
if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
$value = trim($value, '"');
} elseif (substr($value, 0, 1) == "'" && substr($value, -1) == "'") {
$value = trim($value, "'");
}
if ($value !== '<<<') {
$this->blocks[$block][$name] = self::castValue($value);
} else {
$value = '';
$stringComposing = true;
}
break;
default:
throw new \Exception(sprintf(
'Parse Error: Unknown definition type: %s, on line %s', $type, $lineCount
));
}
}
if ($stringComposing) {
throw new \Exception(sprintf(
"Parse Error: Multiline string closing braces are missing '>>>',\nfor @block: '%s', @var: '%s' " .
"until end of file.", $block, $name
));
}
} | php | public function parse()
{
if (!is_file($this->file)) {
throw new \Exception(sprintf(
'Template "%s" file doesn\'t exist!', $this->file
));
}
$fp = fopen($this->file, 'r');
$lineCount = 0;
$nextToken = '';
$block = '';
$currentValue = '';
$stringComposing = false;
$skipMultilineComment = false;
while (($line = fgets($fp)) !== false) {
$lineCount++;
if ($stringComposing) {
if (substr(ltrim($line), 0, 3) === '>>>') {
$this->blocks[$block][$name] = trim($value);
//$block = '';
$value = '';
$stringComposing = false;
} else {
// $line = trim($line);
// if (substr($value, -1) != '>' && ! empty($line)) {
// $line = " " . $line;
// }
//$value .= substr($value, -1) == '>' ? trim($line) : " " . trim($line);
$value .= $line;
}
continue;
}
$line = trim($line);
if (substr($line, 0, 1) === '#' || $line === '' || substr($line, 0, 2) === '//') {
continue; // skip single comments or empty lines
} elseif (substr($line, 0, 2) === '/*') { // start multiline comment
if (strpos($line, '*/') === false) {
$skipMultilineComment = true; // activate multiline comments skipping
} else {
continue; // just skip this line, it has the form: /* ... */
}
} elseif (strpos($line, '*/') !== false) { // end multiline comment
$skipMultilineComment = false;
continue; // just skip the end multiline comment
}
if ($skipMultilineComment) {
continue; //skip multiline comments segment
}
$kwPattern = '^@(?<keyword>\w+)';
if (! preg_match('/'.$kwPattern.'.*/', $line, $matches)) {
throw new \Exception(sprintf(
'Parse Error: Unknow keyword, lines must starts with a valid keyword, near: %s, on line %s',
$line, $lineCount
));
}
//var_dump($matches);
$keyword = $matches['keyword'];
switch ($keyword) {
case Parser::T_DEF:
$pattern = '/'.$kwPattern.'\s+(?<type>[\w]+)\s+(?<name>[\w.]+)\s+(?<value>.+)/';
if (!preg_match($pattern, $line, $matches)) {
throw new \Exception(sprintf(
"Syntax Error: near: '%s', on line %s.\n" .
"Syntax should be: @def <type> <name> <value>",
$line, $lineCount
));
}
$keyword = $matches['keyword'];
$type = $matches['type'];
$name = $matches['name'];
$value = $matches['value'];
$tmp = explode('.', $name);
$defName = $tmp[0];
$defProp = isset($tmp[1]) ? $tmp[1] : '';
switch ($type) {
case Parser::T_GLOBAL:
case Parser::T_ITERATOR:
case Parser::T_SETCONF:
if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
$value = trim($value, '"');
} elseif (substr($value, 0, 1) == "'" && substr($value, -1) == "'") {
$value = trim($value, "'");
}
if ($value === '\n' || $value === '\r\n') {
$value = "\n";
}
$value = self::castValue($value);
if (empty($defProp)) {
$this->defs[$type][$defName] = $value;
} else {
$this->defs[$type][$defName][$defProp] = $value;
}
break;
default:
throw new \Exception(sprintf(
'Parse Error: unknow definition type: "%s" on line %s.', $type, $lineCount
));
}
break;
case Parser::T_BLOCK:
$pattern = '/'.$kwPattern.'\s+(?<block>[\w]+)/';
if (!preg_match($pattern, $line, $matches)) {
throw new Exception(sprintf(
"Parse Error: Syntax error near: %s, on line %s.\n." .
"Syntax should be: @def <type> <name> <value>",
substr($line, 0, 20).'...', $lineCount
));
}
//var_dump($matches);
$block = $matches['block'];
if (!empty($nextToken)) {
throw new \Exception(sprintf(
'Parse Error: expected: @"%s", given: @"%s"', $nextToken, Parser::T_BLOCK
));
}
$nextToken = Parser::T_END;
break;
case Parser::T_END:
if (empty($nextToken)) {
throw new \Exception(sprintf(
'Parse Error: close keyword: @"%s" given, but any block was started.', Parser::T_BLOCK
));
}
if ($nextToken !== Parser::T_END) {
throw new \Exception(sprintf(
'Parse Error: expected: @"%s", given: @"%s"', $nextToken, Parser::T_END
));
}
$nextToken = '';
break;
case Parser::T_VAR:
$pattern = '/'.$kwPattern.'\s+(?<name>[\w]+)\s+(?<value>.+)/';
if (!preg_match($pattern, $line, $matches)) {
throw new Exception(sprintf(
"Parse Error: Syntax error near: %s, on line %s.\n." .
"Syntax should be: @var <name> <value>\n or \n" .
"@var <name> <<<\nsome large string\nmultiline...\n>>>\n\n",
substr($line, 0, 20).'...', $lineCount
));
}
//print_r($matches);
$keyword = $matches['keyword'];
$name = $matches['name'];
$value = $matches['value'];
if (substr($value, 0, 3) === '<<<' && $value !== '<<<') {
throw new \Exception(sprintf(
"Syntax Error: multiline string must starts on new line after open braces <<<\n" .
"near: '%s', on line %s", $line, $lineCount
));
}
if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
$value = trim($value, '"');
} elseif (substr($value, 0, 1) == "'" && substr($value, -1) == "'") {
$value = trim($value, "'");
}
if ($value !== '<<<') {
$this->blocks[$block][$name] = self::castValue($value);
} else {
$value = '';
$stringComposing = true;
}
break;
default:
throw new \Exception(sprintf(
'Parse Error: Unknown definition type: %s, on line %s', $type, $lineCount
));
}
}
if ($stringComposing) {
throw new \Exception(sprintf(
"Parse Error: Multiline string closing braces are missing '>>>',\nfor @block: '%s', @var: '%s' " .
"until end of file.", $block, $name
));
}
} | /*
PRIVATE/PROTECTED METHODS | https://github.com/phpalchemy/phpalchemy/blob/5b7e9b13acfda38c61b2da2639e8a56f298dc32e/Alchemy/Component/UI/Parser.php#L155-L360 |
schpill/thin | src/Mail/Mandrill.php | Mandrill.send | public function send(Swift_Mime_Message $message, &$failedRecipients = null)
{
$message->setSender(
Config::get('mailer.global.address', 'mailer@' . SITE_NAME . '.com'),
Config::get('mailer.global.sender', SITE_NAME)
);
$headers = $message->getHeaders();
$headers->addTextHeader('X-Mailer', Config::get('mailer.app.version', SITE_NAME . ' Mailer v1.2'));
$headers->addTextHeader('X-MC-Track', Config::get('mailer.global.track', 'clicks_textonly'));
$message = (string) $message;
$message = str_replace('swift', SITE_NAME, $message);
// $res = $client->post('https://mandrillapp.com/api/1.0/messages/send-raw.json', [
// 'body' => [
// 'key' => $this->key,
// 'raw_message' => (string) $message,
// 'async' => true,
// ],
// ]);
$arguments = [
'body' => [
'key' => $this->key,
'raw_message' => (string) $message,
'async' => true,
],
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://mandrillapp.com/api/1.0/messages/send-raw.json');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
'key' => $this->key,
'raw_message' => (string) $message,
'async' => true
)));
$response = curl_exec($ch);
// catch errors
if (curl_errno($ch)) {
#$errors = curl_error($ch);
curl_close($ch);
// return false
return false;
} else {
curl_close($ch);
// return array
return json_decode($response, true);
}
} | php | public function send(Swift_Mime_Message $message, &$failedRecipients = null)
{
$message->setSender(
Config::get('mailer.global.address', 'mailer@' . SITE_NAME . '.com'),
Config::get('mailer.global.sender', SITE_NAME)
);
$headers = $message->getHeaders();
$headers->addTextHeader('X-Mailer', Config::get('mailer.app.version', SITE_NAME . ' Mailer v1.2'));
$headers->addTextHeader('X-MC-Track', Config::get('mailer.global.track', 'clicks_textonly'));
$message = (string) $message;
$message = str_replace('swift', SITE_NAME, $message);
// $res = $client->post('https://mandrillapp.com/api/1.0/messages/send-raw.json', [
// 'body' => [
// 'key' => $this->key,
// 'raw_message' => (string) $message,
// 'async' => true,
// ],
// ]);
$arguments = [
'body' => [
'key' => $this->key,
'raw_message' => (string) $message,
'async' => true,
],
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://mandrillapp.com/api/1.0/messages/send-raw.json');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
'key' => $this->key,
'raw_message' => (string) $message,
'async' => true
)));
$response = curl_exec($ch);
// catch errors
if (curl_errno($ch)) {
#$errors = curl_error($ch);
curl_close($ch);
// return false
return false;
} else {
curl_close($ch);
// return array
return json_decode($response, true);
}
} | {@inheritdoc} | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Mail/Mandrill.php#L57-L112 |
interactivesolutions/honeycomb-scripts | src/app/providers/HCScriptsServiceProvider.php | HCScriptsServiceProvider.registerProviders | public function registerProviders()
{
if ($this->app->environment() !== 'production')
{
$this->app->register(GeneratorsServiceProvider::class);
$this->app->register(MigrationsGeneratorServiceProvider::class);
}
} | php | public function registerProviders()
{
if ($this->app->environment() !== 'production')
{
$this->app->register(GeneratorsServiceProvider::class);
$this->app->register(MigrationsGeneratorServiceProvider::class);
}
} | Register the application services.
@return void | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/providers/HCScriptsServiceProvider.php#L39-L46 |
comoyi/redis | src/Redis/RedisSlave.php | RedisSlave.connect | public function connect() {
$this->handler = new Redis();
$this->handler->connect($this->configs['host'], $this->configs['port']);
} | php | public function connect() {
$this->handler = new Redis();
$this->handler->connect($this->configs['host'], $this->configs['port']);
} | 连接 | https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisSlave.php#L59-L62 |
IftekherSunny/Planet-Framework | src/Sun/Console/Application.php | Application.bootCommand | protected function bootCommand()
{
foreach ($this->commands as $command) {
$this->add($this->app->make($command));
}
} | php | protected function bootCommand()
{
foreach ($this->commands as $command) {
$this->add($this->app->make($command));
}
} | Resolve all dependencies | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Console/Application.php#L48-L53 |
IftekherSunny/Planet-Framework | src/Sun/Console/Application.php | Application.bootPHPMig | protected function bootPHPMig()
{
foreach($this->getPhpMigCommands() as $command) {
$command->setName('migration:'.$command->getName());
$this->add($command);
}
} | php | protected function bootPHPMig()
{
foreach($this->getPhpMigCommands() as $command) {
$command->setName('migration:'.$command->getName());
$this->add($command);
}
} | Bootstrap PHP Mig | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Console/Application.php#L58-L64 |
IftekherSunny/Planet-Framework | src/Sun/Console/Application.php | Application.getPhpMigCommands | protected function getPhpMigCommands()
{
return [
new Command\CheckCommand(),
new Command\DownCommand(),
new Command\GenerateCommand(),
new Command\MigrateCommand(),
new Command\RedoCommand(),
new Command\RollbackCommand(),
new Command\StatusCommand(),
new Command\UpCommand(),
];
} | php | protected function getPhpMigCommands()
{
return [
new Command\CheckCommand(),
new Command\DownCommand(),
new Command\GenerateCommand(),
new Command\MigrateCommand(),
new Command\RedoCommand(),
new Command\RollbackCommand(),
new Command\StatusCommand(),
new Command\UpCommand(),
];
} | Get PHP Mig console commands
@return array | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Console/Application.php#L71-L83 |
spiral/views | src/ViewCache.php | ViewCache.resetPath | public function resetPath(string $path)
{
foreach ($this->cache as &$cache) {
unset($cache[$path], $cache);
}
} | php | public function resetPath(string $path)
{
foreach ($this->cache as &$cache) {
unset($cache[$path], $cache);
}
} | Reset view cache from all the contexts.
@param string $path | https://github.com/spiral/views/blob/0e35697204dfffabf71546d20e89f14b50414a9a/src/ViewCache.php#L37-L42 |
spiral/views | src/ViewCache.php | ViewCache.get | public function get(ContextInterface $context, string $path): ViewInterface
{
if (!$this->has($context, $path)) {
throw new CacheException("No cache is available for {$path}.");
}
return $this->cache[$context->getID()][$path];
} | php | public function get(ContextInterface $context, string $path): ViewInterface
{
if (!$this->has($context, $path)) {
throw new CacheException("No cache is available for {$path}.");
}
return $this->cache[$context->getID()][$path];
} | @param ContextInterface $context
@param string $path
@return ViewInterface
@throws CacheException | https://github.com/spiral/views/blob/0e35697204dfffabf71546d20e89f14b50414a9a/src/ViewCache.php#L71-L78 |
m6w6/pq-gateway | lib/pq/Gateway/Rowset.php | Rowset.create | function create($txn = true) {
if ($txn && !($txn instanceof pq\Transaction)) {
$txn = $this->table->getConnection()->startTransaction();
}
try {
foreach ($this->rows as $row) {
$row->create();
}
} catch (\Exception $e) {
if ($txn) {
$txn->rollback();
}
throw $e;
}
if ($txn) {
$txn->commit();
}
return $this;
} | php | function create($txn = true) {
if ($txn && !($txn instanceof pq\Transaction)) {
$txn = $this->table->getConnection()->startTransaction();
}
try {
foreach ($this->rows as $row) {
$row->create();
}
} catch (\Exception $e) {
if ($txn) {
$txn->rollback();
}
throw $e;
}
if ($txn) {
$txn->commit();
}
return $this;
} | Create all rows of this rowset
@param mixed $txn
@return \pq\Gateway\Rowset
@throws Exception | https://github.com/m6w6/pq-gateway/blob/58233722a06fd742f531f8f012ea540b309303da/lib/pq/Gateway/Rowset.php#L106-L124 |
m6w6/pq-gateway | lib/pq/Gateway/Rowset.php | Rowset.filter | function filter(callable $cb) {
$rowset = clone $this;
$rowset->index = 0;
$rowset->rows = array_filter($this->rows, $cb);
return $rowset;
} | php | function filter(callable $cb) {
$rowset = clone $this;
$rowset->index = 0;
$rowset->rows = array_filter($this->rows, $cb);
return $rowset;
} | Filter by callback
@param callable $cb
@return \pq\Gateway\Rowset | https://github.com/m6w6/pq-gateway/blob/58233722a06fd742f531f8f012ea540b309303da/lib/pq/Gateway/Rowset.php#L274-L279 |
ruvents/ruwork-synchronizer | ContextBuilder.php | ContextBuilder.createContext | public function createContext(): ContextInterface
{
return new Context(
$this->types,
$this->cacheFactory,
new ImmutableEventDispatcher($this->eventDispatcher),
$this->attributes
);
} | php | public function createContext(): ContextInterface
{
return new Context(
$this->types,
$this->cacheFactory,
new ImmutableEventDispatcher($this->eventDispatcher),
$this->attributes
);
} | {@inheritdoc} | https://github.com/ruvents/ruwork-synchronizer/blob/68aa35d48f04634828e76eb2a49e504985da92a9/ContextBuilder.php#L62-L70 |
thienhungho/yii2-contact-management | src/modules/ContactManage/controllers/ContactController.php | ContactController.actionIndex | public function actionIndex()
{
$searchModel = new ContactSearch();
$dataProvider = $searchModel->search(request()->queryParams);
$dataProvider->sort->defaultOrder = ['id' => SORT_DESC];
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
} | php | public function actionIndex()
{
$searchModel = new ContactSearch();
$dataProvider = $searchModel->search(request()->queryParams);
$dataProvider->sort->defaultOrder = ['id' => SORT_DESC];
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
} | Lists all Contact models.
@return mixed | https://github.com/thienhungho/yii2-contact-management/blob/652d7b0ee628eb924e197ad956ce3c6045b878eb/src/modules/ContactManage/controllers/ContactController.php#L33-L43 |
thienhungho/yii2-contact-management | src/modules/ContactManage/controllers/ContactController.php | ContactController.findModel | protected function findModel($id)
{
if (($model = Contact::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException(t('app', 'The requested page does not exist.'));
}
} | php | protected function findModel($id)
{
if (($model = Contact::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException(t('app', 'The requested page does not exist.'));
}
} | Finds the Contact model based on its primary key value.
If the model is not found, a 404 HTTP exception will be thrown.
@param integer $id
@return Contact the loaded model
@throws NotFoundHttpException if the model cannot be found | https://github.com/thienhungho/yii2-contact-management/blob/652d7b0ee628eb924e197ad956ce3c6045b878eb/src/modules/ContactManage/controllers/ContactController.php#L174-L181 |
matryoshka-model/matryoshka | library/ModelEvent.php | ModelEvent.setTarget | public function setTarget($target)
{
if (!$target instanceof ModelInterface) {
throw new Exception\InvalidArgumentException(sprintf(
'"%s" works only with ModelInterface targets',
__CLASS__
));
}
return parent::setTarget($target);
} | php | public function setTarget($target)
{
if (!$target instanceof ModelInterface) {
throw new Exception\InvalidArgumentException(sprintf(
'"%s" works only with ModelInterface targets',
__CLASS__
));
}
return parent::setTarget($target);
} | {@inheritdoc}
@throws Exception\InvalidArgumentException | https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/ModelEvent.php#L56-L65 |
matryoshka-model/matryoshka | library/ModelEvent.php | ModelEvent.setParam | public function setParam($name, $value)
{
if (in_array($name, $this->specializedParams)) {
$this->{'set'.$name}($value);
} else {
parent::setParam($name, $value);
}
return $this;
} | php | public function setParam($name, $value)
{
if (in_array($name, $this->specializedParams)) {
$this->{'set'.$name}($value);
} else {
parent::setParam($name, $value);
}
return $this;
} | {@inheritdoc} | https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/ModelEvent.php#L142-L150 |
matryoshka-model/matryoshka | library/ModelEvent.php | ModelEvent.setParams | public function setParams($params)
{
parent::setParams($params);
$isObject = is_object($this->params);
foreach ($this->specializedParams as $param) {
if ($isObject) {
if (isset($params->{$param})) {
$method = 'set' . $param;
$this->$method($params->{$param});
}
unset($this->params->{$param});
} else {
if (isset($params[$param])) {
$method = 'set' . $param;
$this->$method($params[$param]);
}
unset($this->params[$param]);
}
}
return $this;
} | php | public function setParams($params)
{
parent::setParams($params);
$isObject = is_object($this->params);
foreach ($this->specializedParams as $param) {
if ($isObject) {
if (isset($params->{$param})) {
$method = 'set' . $param;
$this->$method($params->{$param});
}
unset($this->params->{$param});
} else {
if (isset($params[$param])) {
$method = 'set' . $param;
$this->$method($params[$param]);
}
unset($this->params[$param]);
}
}
return $this;
} | {@inheritdoc} | https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/ModelEvent.php#L155-L175 |
matryoshka-model/matryoshka | library/ModelEvent.php | ModelEvent.getParam | public function getParam($name, $default = null)
{
if (in_array($name, $this->specializedParams)) {
return $this->{'get'.$name}();
}
return parent::getParam($name, $default);
} | php | public function getParam($name, $default = null)
{
if (in_array($name, $this->specializedParams)) {
return $this->{'get'.$name}();
}
return parent::getParam($name, $default);
} | {@inheritdoc} | https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/ModelEvent.php#L180-L186 |
matryoshka-model/matryoshka | library/ModelEvent.php | ModelEvent.getParams | public function getParams()
{
$params = parent::getParams();
$isObject = is_object($params);
foreach ($this->specializedParams as $param) {
if ($isObject) {
$params->{$param} = $this->{'get'.$param}();
} else {
$params[$param] = $this->{'get'.$param}();
}
}
return $params;
} | php | public function getParams()
{
$params = parent::getParams();
$isObject = is_object($params);
foreach ($this->specializedParams as $param) {
if ($isObject) {
$params->{$param} = $this->{'get'.$param}();
} else {
$params[$param] = $this->{'get'.$param}();
}
}
return $params;
} | {@inheritdoc} | https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/ModelEvent.php#L191-L203 |
schpill/thin | src/Queuespl.php | Queuespl.insert | public function insert($data, $priority = 1)
{
$priority = (int) $priority;
$this->items[] = array(
'data' => $data,
'priority' => $priority,
);
$this->getQueue()->insert($data, $priority);
return $this;
} | php | public function insert($data, $priority = 1)
{
$priority = (int) $priority;
$this->items[] = array(
'data' => $data,
'priority' => $priority,
);
$this->getQueue()->insert($data, $priority);
return $this;
} | Insert an item into the queue
Priority defaults to 1 (low priority) if none provided.
@param mixed $data
@param int $priority
@return Queue | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Queuespl.php#L56-L66 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.