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
yii2lab/yii2-rbac
src/domain/repositories/traits/AssignmentTrait.php
AssignmentTrait.assign
public function assign($role, $userId) { $userId = $this->getId($userId); $entity = \App::$domain->account->login->oneById($userId); $assignEntity = $this->forgeEntity([ 'user_id' => $userId, 'item_name' => $role, ]); $this->insert($assignEntity); return AssignmentHelper::forge($userId, $role); }
php
public function assign($role, $userId) { $userId = $this->getId($userId); $entity = \App::$domain->account->login->oneById($userId); $assignEntity = $this->forgeEntity([ 'user_id' => $userId, 'item_name' => $role, ]); $this->insert($assignEntity); return AssignmentHelper::forge($userId, $role); }
Assigns a role to a user. @param Role|Permission $role @param string|int $userId the user ID (see [[\yii\web\User::id]]) @return Assignment the role assignment information. @throws \Exception if the role has already been assigned to the user
https://github.com/yii2lab/yii2-rbac/blob/e72ac0359af660690c161451f864208b2d20919d/src/domain/repositories/traits/AssignmentTrait.php#L131-L141
yii2lab/yii2-rbac
src/domain/repositories/traits/AssignmentTrait.php
AssignmentTrait.revoke
public function revoke($role, $userId) { $userId = $this->getId($userId); $entity = \App::$domain->account->login->oneById($userId); $this->model->deleteAll(['user_id' => $userId, 'item_name' => $role]); }
php
public function revoke($role, $userId) { $userId = $this->getId($userId); $entity = \App::$domain->account->login->oneById($userId); $this->model->deleteAll(['user_id' => $userId, 'item_name' => $role]); }
Revokes a role from a user. @param Role|Permission $role @param string|int $userId the user ID (see [[\yii\web\User::id]]) @return bool whether the revoking is successful
https://github.com/yii2lab/yii2-rbac/blob/e72ac0359af660690c161451f864208b2d20919d/src/domain/repositories/traits/AssignmentTrait.php#L151-L155
cyberspectrum/i18n-contao
src/Mapping/Terminal42ChangeLanguage/MapBuilder.php
MapBuilder.getMappingFor
public function getMappingFor(string $tables, string $sourceLanguage, string $targetLanguage): MappingInterface { switch ($tables) { case 'tl_page': return $this->getPageMap($sourceLanguage, $targetLanguage); case 'tl_article': return $this->getArticleMap($sourceLanguage, $targetLanguage); case 'tl_article.tl_content': return $this->getArticleContentMap($sourceLanguage, $targetLanguage); default: } throw new \InvalidArgumentException('Unknown table ' . $tables); }
php
public function getMappingFor(string $tables, string $sourceLanguage, string $targetLanguage): MappingInterface { switch ($tables) { case 'tl_page': return $this->getPageMap($sourceLanguage, $targetLanguage); case 'tl_article': return $this->getArticleMap($sourceLanguage, $targetLanguage); case 'tl_article.tl_content': return $this->getArticleContentMap($sourceLanguage, $targetLanguage); default: } throw new \InvalidArgumentException('Unknown table ' . $tables); }
{@inheritDoc} @throws \InvalidArgumentException When the table is unknown.
https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Mapping/Terminal42ChangeLanguage/MapBuilder.php#L87-L99
cyberspectrum/i18n-contao
src/Mapping/Terminal42ChangeLanguage/MapBuilder.php
MapBuilder.supports
public function supports(string $tablePath, string $sourceLanguage, string $targetLanguage): bool { return \in_array($tablePath, ['tl_page', 'tl_article', 'tl_article.tl_content']) && $this->supportsLanguage($sourceLanguage) && $this->supportsLanguage($targetLanguage); }
php
public function supports(string $tablePath, string $sourceLanguage, string $targetLanguage): bool { return \in_array($tablePath, ['tl_page', 'tl_article', 'tl_article.tl_content']) && $this->supportsLanguage($sourceLanguage) && $this->supportsLanguage($targetLanguage); }
{@inheritDoc}
https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Mapping/Terminal42ChangeLanguage/MapBuilder.php#L104-L109
cyberspectrum/i18n-contao
src/Mapping/Terminal42ChangeLanguage/MapBuilder.php
MapBuilder.getSupportedLanguages
public function getSupportedLanguages(): array { if (null === $this->supportedLanguages) { $this->supportedLanguages = array_map(function (array $row) { return $row['language']; }, $this->database->getRootPages()); } return $this->supportedLanguages; }
php
public function getSupportedLanguages(): array { if (null === $this->supportedLanguages) { $this->supportedLanguages = array_map(function (array $row) { return $row['language']; }, $this->database->getRootPages()); } return $this->supportedLanguages; }
{@inheritDoc}
https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Mapping/Terminal42ChangeLanguage/MapBuilder.php#L114-L123
cyberspectrum/i18n-contao
src/Mapping/Terminal42ChangeLanguage/MapBuilder.php
MapBuilder.getPageMap
private function getPageMap(string $sourceLanguage, string $targetLanguage): PageMap { if (!array_key_exists($key = $sourceLanguage . '->' . $targetLanguage, $this->pageMaps)) { return $this->pageMaps[$key] = new PageMap( $sourceLanguage, $targetLanguage, $this->database, $this->logger ); } return $this->pageMaps[$key]; }
php
private function getPageMap(string $sourceLanguage, string $targetLanguage): PageMap { if (!array_key_exists($key = $sourceLanguage . '->' . $targetLanguage, $this->pageMaps)) { return $this->pageMaps[$key] = new PageMap( $sourceLanguage, $targetLanguage, $this->database, $this->logger ); } return $this->pageMaps[$key]; }
Retrieve pageMap. @param string $sourceLanguage The source language. @param string $targetLanguage The target language. @return PageMap
https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Mapping/Terminal42ChangeLanguage/MapBuilder.php#L133-L145
cyberspectrum/i18n-contao
src/Mapping/Terminal42ChangeLanguage/MapBuilder.php
MapBuilder.getArticleMap
private function getArticleMap(string $sourceLanguage, string $targetLanguage): ArticleMap { if (!array_key_exists($key = $sourceLanguage . '->' . $targetLanguage, $this->articleMaps)) { return $this->articleMaps[$key] = new ArticleMap( $this->getPageMap($sourceLanguage, $targetLanguage), $this->logger ); } return $this->articleMaps[$key]; }
php
private function getArticleMap(string $sourceLanguage, string $targetLanguage): ArticleMap { if (!array_key_exists($key = $sourceLanguage . '->' . $targetLanguage, $this->articleMaps)) { return $this->articleMaps[$key] = new ArticleMap( $this->getPageMap($sourceLanguage, $targetLanguage), $this->logger ); } return $this->articleMaps[$key]; }
Retrieve article map. @param string $sourceLanguage The source language. @param string $targetLanguage The target language. @return ArticleMap
https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Mapping/Terminal42ChangeLanguage/MapBuilder.php#L155-L165
cyberspectrum/i18n-contao
src/Mapping/Terminal42ChangeLanguage/MapBuilder.php
MapBuilder.getArticleContentMap
private function getArticleContentMap(string $sourceLanguage, string $targetLanguage): ArticleContentMap { if (!array_key_exists($key = $sourceLanguage . '->' . $targetLanguage, $this->articleContentMaps)) { return $this->articleContentMaps[$key] = new ArticleContentMap( $this->getArticleMap($sourceLanguage, $targetLanguage), $this->logger ); } return $this->articleContentMaps[$key]; }
php
private function getArticleContentMap(string $sourceLanguage, string $targetLanguage): ArticleContentMap { if (!array_key_exists($key = $sourceLanguage . '->' . $targetLanguage, $this->articleContentMaps)) { return $this->articleContentMaps[$key] = new ArticleContentMap( $this->getArticleMap($sourceLanguage, $targetLanguage), $this->logger ); } return $this->articleContentMaps[$key]; }
Retrieve article content map. @param string $sourceLanguage The source language. @param string $targetLanguage The target language. @return ArticleContentMap
https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Mapping/Terminal42ChangeLanguage/MapBuilder.php#L175-L185
3ev/wordpress-core
src/Tev/Field/Model/TaxonomyField.php
TaxonomyField.getValue
public function getValue() { $terms = $this->base['value']; if (is_array($terms)) { $ret = array(); foreach ($terms as $t) { $ret[] = $this->termFactory->create($t, $this->taxonomy()); } return $ret; } elseif (is_object($terms)) { return $this->termFactory->create($terms, $this->taxonomy()); } else { if ($this->base['multiple'] || $this->base['field_type'] === 'multi_select' || $this->base['field_type'] === 'checkbox') { return array(); } else { return null; } } }
php
public function getValue() { $terms = $this->base['value']; if (is_array($terms)) { $ret = array(); foreach ($terms as $t) { $ret[] = $this->termFactory->create($t, $this->taxonomy()); } return $ret; } elseif (is_object($terms)) { return $this->termFactory->create($terms, $this->taxonomy()); } else { if ($this->base['multiple'] || $this->base['field_type'] === 'multi_select' || $this->base['field_type'] === 'checkbox') { return array(); } else { return null; } } }
Get Term or array of Terms. @return \Tev\Term\Model\Term|\Tev\Term\Model\Term[]|null
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Field/Model/TaxonomyField.php#L59-L80
3ev/wordpress-core
src/Tev/Field/Model/TaxonomyField.php
TaxonomyField.taxonomy
public function taxonomy() { if ($this->_taxonomy === null) { $this->_taxonomy = $this->taxonomyFactory->create($this->base['taxonomy']); } return $this->_taxonomy; }
php
public function taxonomy() { if ($this->_taxonomy === null) { $this->_taxonomy = $this->taxonomyFactory->create($this->base['taxonomy']); } return $this->_taxonomy; }
Get Term Taxonomy. @return \Tev\Taxonomy\Model\Taxonomy
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Field/Model/TaxonomyField.php#L87-L94
as3io/symfony-data-importer
src/Import/Persister.php
Persister.getWriteMode
final public function getWriteMode() { switch ($this->getDataMode()) { case Configuration::DATA_MODE_WIPE: case Configuration::DATA_MODE_PROGRESSIVE: $this->setWriteMode(static::WRITE_MODE_INSERT); break; default: $this->setWriteMode(static::WRITE_MODE_UPSERT); } return $this->writeMode; }
php
final public function getWriteMode() { switch ($this->getDataMode()) { case Configuration::DATA_MODE_WIPE: case Configuration::DATA_MODE_PROGRESSIVE: $this->setWriteMode(static::WRITE_MODE_INSERT); break; default: $this->setWriteMode(static::WRITE_MODE_UPSERT); } return $this->writeMode; }
Returns the current write mode @return string
https://github.com/as3io/symfony-data-importer/blob/33383e38f20f6b7a4b83da619bd028ac84ced579/src/Import/Persister.php#L128-L139
as3io/symfony-data-importer
src/Import/Persister.php
Persister.insert
final public function insert($typeKey, array $item) { $item = $this->sanitizeModel($typeKey, $item); switch ($this->getWriteMode()) { case static::WRITE_MODE_INSERT: $items = $this->appendIds($typeKey, [$item]); $item = $this->doInsert($typeKey, $items[0]); break; case static::WRITE_MODE_UPSERT: $item = $this->doUpsert($typeKey, $item); break; case static::WRITE_MODE_UPDATE: $item = $this->doUpdate($typeKey, $item); break; default: throw new Exception\WriteModeException(sprintf('Unsupported write mode `%s`!', $this->getWriteMode())); } return $item; }
php
final public function insert($typeKey, array $item) { $item = $this->sanitizeModel($typeKey, $item); switch ($this->getWriteMode()) { case static::WRITE_MODE_INSERT: $items = $this->appendIds($typeKey, [$item]); $item = $this->doInsert($typeKey, $items[0]); break; case static::WRITE_MODE_UPSERT: $item = $this->doUpsert($typeKey, $item); break; case static::WRITE_MODE_UPDATE: $item = $this->doUpdate($typeKey, $item); break; default: throw new Exception\WriteModeException(sprintf('Unsupported write mode `%s`!', $this->getWriteMode())); } return $item; }
{@inheritdoc}
https://github.com/as3io/symfony-data-importer/blob/33383e38f20f6b7a4b83da619bd028ac84ced579/src/Import/Persister.php#L144-L162
as3io/symfony-data-importer
src/Import/Persister.php
Persister.batchInsert
final public function batchInsert($typeKey, array $items) { if (empty($items)) { throw new \InvalidArgumentException('Nothing to insert!'); } $items = array_map(function($item) use($typeKey, $items) { return $this->sanitizeModel($typeKey, $item); }, $items); switch ($mode = $this->getWriteMode()) { case static::WRITE_MODE_INSERT: $items = $this->appendIds($typeKey, $items); $items = $this->doBatchInsert($typeKey, $items); break; case static::WRITE_MODE_UPSERT: $items = $this->doBatchUpsert($typeKey, $items); break; case static::WRITE_MODE_UPDATE: $items = $this->doBatchUpdate($typeKey, $items); break; default: throw new Exception\WriteModeException(sprintf('Unsupported write mode `%s`!', $this->getWriteMode())); } return $items; }
php
final public function batchInsert($typeKey, array $items) { if (empty($items)) { throw new \InvalidArgumentException('Nothing to insert!'); } $items = array_map(function($item) use($typeKey, $items) { return $this->sanitizeModel($typeKey, $item); }, $items); switch ($mode = $this->getWriteMode()) { case static::WRITE_MODE_INSERT: $items = $this->appendIds($typeKey, $items); $items = $this->doBatchInsert($typeKey, $items); break; case static::WRITE_MODE_UPSERT: $items = $this->doBatchUpsert($typeKey, $items); break; case static::WRITE_MODE_UPDATE: $items = $this->doBatchUpdate($typeKey, $items); break; default: throw new Exception\WriteModeException(sprintf('Unsupported write mode `%s`!', $this->getWriteMode())); } return $items; }
{@inheritdoc}
https://github.com/as3io/symfony-data-importer/blob/33383e38f20f6b7a4b83da619bd028ac84ced579/src/Import/Persister.php#L167-L188
as3io/symfony-data-importer
src/Import/Persister.php
Persister.batchUpdate
final public function batchUpdate($scn, array $criteria, array $update) { return $this->getCollectionForModel($scn)->update($criteria, $update, ['multiple' => true]); }
php
final public function batchUpdate($scn, array $criteria, array $update) { return $this->getCollectionForModel($scn)->update($criteria, $update, ['multiple' => true]); }
Performs a batch update @param string $scn @param array $criteria The targeting parameters @param array $update The modifications to make to the targeted documents
https://github.com/as3io/symfony-data-importer/blob/33383e38f20f6b7a4b83da619bd028ac84ced579/src/Import/Persister.php#L197-L200
as3io/symfony-data-importer
src/Import/Persister.php
Persister.doUpsert
final protected function doUpsert($scn, array $kvs) { $upsertKey = isset($kvs['external']) ? 'external' : 'legacy'; $upsertNs = 'legacy' === $upsertKey ? 'source' : 'namespace'; $upsertId = 'legacy' === $upsertKey ? 'id' : 'identifier'; $update = ['$set' => $kvs]; if (!isset($kvs[$upsertKey][$upsertId]) || !isset($kvs[$upsertKey][$upsertNs])) { throw new Exception\UpsertException(sprintf('%s.%s or %s.%s was not specified, cannot upsert!', $upsertKey, $upsertId, $upsertKey, $upsertNs)); } if (!isset($kvs['_id'])) { $id = $this->generateId($scn); if (null !== $id) { $update['$setOnInsert'] = ['_id' => $id]; } } $query = [ sprintf('%s.%s', $upsertKey, $upsertId) => $kvs[$upsertKey][$upsertId], sprintf('%s.%s', $upsertKey, $upsertNs) => $kvs[$upsertKey][$upsertNs], ]; $r = $this->getCollectionForModel($scn)->update($query, $update, ['upsert' => true]); if (true === $r['updatedExisting']) { $id = $this->getCollectionForModel($scn)->findOne($query, ['_id'])['_id']; $kvs['_id'] = $id; } else { if (!isset($kvs['_id'])) { $kvs['_id'] = $r['upserted']; } } return $kvs; }
php
final protected function doUpsert($scn, array $kvs) { $upsertKey = isset($kvs['external']) ? 'external' : 'legacy'; $upsertNs = 'legacy' === $upsertKey ? 'source' : 'namespace'; $upsertId = 'legacy' === $upsertKey ? 'id' : 'identifier'; $update = ['$set' => $kvs]; if (!isset($kvs[$upsertKey][$upsertId]) || !isset($kvs[$upsertKey][$upsertNs])) { throw new Exception\UpsertException(sprintf('%s.%s or %s.%s was not specified, cannot upsert!', $upsertKey, $upsertId, $upsertKey, $upsertNs)); } if (!isset($kvs['_id'])) { $id = $this->generateId($scn); if (null !== $id) { $update['$setOnInsert'] = ['_id' => $id]; } } $query = [ sprintf('%s.%s', $upsertKey, $upsertId) => $kvs[$upsertKey][$upsertId], sprintf('%s.%s', $upsertKey, $upsertNs) => $kvs[$upsertKey][$upsertNs], ]; $r = $this->getCollectionForModel($scn)->update($query, $update, ['upsert' => true]); if (true === $r['updatedExisting']) { $id = $this->getCollectionForModel($scn)->findOne($query, ['_id'])['_id']; $kvs['_id'] = $id; } else { if (!isset($kvs['_id'])) { $kvs['_id'] = $r['upserted']; } } return $kvs; }
Handles a single document upsert @param string $scn The model type @param array $kvs The model's keyValues. @return array The upserted modelValues
https://github.com/as3io/symfony-data-importer/blob/33383e38f20f6b7a4b83da619bd028ac84ced579/src/Import/Persister.php#L259-L293
as3io/symfony-data-importer
src/Import/Persister.php
Persister.setWriteMode
final protected function setWriteMode($mode) { if (!in_array($mode, [static::WRITE_MODE_INSERT, static::WRITE_MODE_UPSERT, static::WRITE_MODE_UPDATE])) { throw new \InvalidArgumentException(sprintf('Passed write mode "%s" is invalid!', $mode)); } $this->writeMode = $mode; }
php
final protected function setWriteMode($mode) { if (!in_array($mode, [static::WRITE_MODE_INSERT, static::WRITE_MODE_UPSERT, static::WRITE_MODE_UPDATE])) { throw new \InvalidArgumentException(sprintf('Passed write mode "%s" is invalid!', $mode)); } $this->writeMode = $mode; }
Sets the current write mode @param string $mode The write mode to use.
https://github.com/as3io/symfony-data-importer/blob/33383e38f20f6b7a4b83da619bd028ac84ced579/src/Import/Persister.php#L311-L317
Phpillip/phpillip
src/EventListener/ContentConverterListener.php
ContentConverterListener.onKernelController
public function onKernelController(FilterControllerEvent $event) { $request = $event->getRequest(); $route = $this->routes->get($request->attributes->get('_route')); if ($route && $route->hasContent()) { $this->populateContent($route, $request); } }
php
public function onKernelController(FilterControllerEvent $event) { $request = $event->getRequest(); $route = $this->routes->get($request->attributes->get('_route')); if ($route && $route->hasContent()) { $this->populateContent($route, $request); } }
Handler Kernel Controller events @param FilterControllerEvent $event
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/EventListener/ContentConverterListener.php#L60-L68
Phpillip/phpillip
src/EventListener/ContentConverterListener.php
ContentConverterListener.populateContent
protected function populateContent(Route $route, Request $request) { $content = $route->getContent(); $name = $content; if ($route->isList()) { $name .= 's'; $value = $this->repository->getContents($content, $route->getIndexBy(), $route->getOrder()); if ($route->isPaginated()) { $paginator = new Paginator($value, $route->getPerPage()); $value = $paginator->get($request->attributes->get('page')); $request->attributes->set('paginator', $paginator); } } else { $value = $this->repository->getContent($content, $request->attributes->get($content)); } $request->attributes->set($name, $value); }
php
protected function populateContent(Route $route, Request $request) { $content = $route->getContent(); $name = $content; if ($route->isList()) { $name .= 's'; $value = $this->repository->getContents($content, $route->getIndexBy(), $route->getOrder()); if ($route->isPaginated()) { $paginator = new Paginator($value, $route->getPerPage()); $value = $paginator->get($request->attributes->get('page')); $request->attributes->set('paginator', $paginator); } } else { $value = $this->repository->getContent($content, $request->attributes->get($content)); } $request->attributes->set($name, $value); }
Populate content for the request @param Route $route @param Request $request
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/EventListener/ContentConverterListener.php#L76-L95
tarsana/syntax
src/ObjectSyntax.php
ObjectSyntax.fields
public function fields($value = null) { if (null === $value) { return $this->fields; } $this->fields = $value; return $this; }
php
public function fields($value = null) { if (null === $value) { return $this->fields; } $this->fields = $value; return $this; }
Fields getter and setter. @param array $value @return mixed
https://github.com/tarsana/syntax/blob/fd3f8a25e3be0e391c8fd486ccfcffe913ade534/src/ObjectSyntax.php#L81-L88
tarsana/syntax
src/ObjectSyntax.php
ObjectSyntax.field
public function field(string $name, Syntax $value = null) { if ($value === null) { $names = explode('.', $name); $syntax = $this; foreach ($names as $field) { while (method_exists($syntax, 'syntax')) { $syntax = $syntax->syntax(); } if ($syntax instanceof ObjectSyntax && array_key_exists($field, $syntax->fields)) { $syntax = $syntax->fields[$field]; } else { throw new \InvalidArgumentException("field '{$name}' not found"); } } return $syntax; } $this->fields[$name] = $value; return $this; }
php
public function field(string $name, Syntax $value = null) { if ($value === null) { $names = explode('.', $name); $syntax = $this; foreach ($names as $field) { while (method_exists($syntax, 'syntax')) { $syntax = $syntax->syntax(); } if ($syntax instanceof ObjectSyntax && array_key_exists($field, $syntax->fields)) { $syntax = $syntax->fields[$field]; } else { throw new \InvalidArgumentException("field '{$name}' not found"); } } return $syntax; } $this->fields[$name] = $value; return $this; }
Setter and getter of a specific field. @param string $name @param Tarsana\Syntax\Syntax|null $value @return Tarsana\Syntax\Syntax|self @throws InvalidArgumentException
https://github.com/tarsana/syntax/blob/fd3f8a25e3be0e391c8fd486ccfcffe913ade534/src/ObjectSyntax.php#L99-L119
tarsana/syntax
src/ObjectSyntax.php
ObjectSyntax.clearValues
protected function clearValues() { $this->values = []; foreach ($this->fields as $name => $syntax) { $this->values[$name] = (object) [ 'value' => null, 'error' => static::MISSING_FIELD ]; } }
php
protected function clearValues() { $this->values = []; foreach ($this->fields as $name => $syntax) { $this->values[$name] = (object) [ 'value' => null, 'error' => static::MISSING_FIELD ]; } }
Clears the parsed values. @return void
https://github.com/tarsana/syntax/blob/fd3f8a25e3be0e391c8fd486ccfcffe913ade534/src/ObjectSyntax.php#L152-L161
tarsana/syntax
src/ObjectSyntax.php
ObjectSyntax.parse
public function parse(string $text) : \stdClass { $items = Text::split($text, $this->separator); $itemsCount = count($items); $itemIndex = 0; $names = array_keys($this->fields); $namesCount = count($names); $nameIndex = 0; $index = 0; $separatorLength = strlen($this->separator); $itemsLeft = false; $this->clearValues(); try { while ($itemIndex < $itemsCount && $nameIndex < $namesCount) { $syntax = $this->fields[$names[$nameIndex]]; $this->values[$names[$nameIndex]]->value = $syntax->parse($items[$itemIndex]); $this->values[$names[$nameIndex]]->error = null; $index += strlen($items[$itemIndex]) + $separatorLength; $nameIndex ++; $itemIndex ++; if ($syntax instanceof OptionalSyntax && !$syntax->success()) { $itemIndex --; } } // if items are left if ($itemIndex < $itemsCount) $itemsLeft = true; // if fields are left while ($nameIndex < $namesCount) { $syntax = $this->fields[$names[$nameIndex]]; $this->values[$names[$nameIndex]]->value = $syntax->parse(''); $this->values[$names[$nameIndex]]->error = null; $nameIndex ++; } } catch (ParseException $e) { if ($itemIndex < $itemsCount) { $this->values[$names[$nameIndex]]->error = static::INVALID_FIELD; $error = "Unable to parse the item '{$items[$itemIndex]}' for field '{$names[$nameIndex]}'"; $extra = [ 'type' => 'invalid-field', 'field' => $names[$nameIndex], 'text' => $items[$itemIndex] ]; } else { $this->values[$names[$nameIndex]]->error = static::MISSING_FIELD; $error = "No item left for field '{$names[$nameIndex]}'"; $extra = [ 'type' => 'missing-field', 'field' => $names[$nameIndex], 'position' => $e->position() ]; } throw new ParseException($this, $text, $index + $e->position(), $error, $extra, $e); } if ($itemsLeft) { $extra = [ 'type' => 'additional-items', 'items' => array_slice($items, $itemIndex) ]; throw new ParseException($this, $text, $index - $separatorLength, "Additional items with no corresponding fields", $extra); } return (object) array_map(function(\stdClass $field) { return $field->value; }, $this->values); }
php
public function parse(string $text) : \stdClass { $items = Text::split($text, $this->separator); $itemsCount = count($items); $itemIndex = 0; $names = array_keys($this->fields); $namesCount = count($names); $nameIndex = 0; $index = 0; $separatorLength = strlen($this->separator); $itemsLeft = false; $this->clearValues(); try { while ($itemIndex < $itemsCount && $nameIndex < $namesCount) { $syntax = $this->fields[$names[$nameIndex]]; $this->values[$names[$nameIndex]]->value = $syntax->parse($items[$itemIndex]); $this->values[$names[$nameIndex]]->error = null; $index += strlen($items[$itemIndex]) + $separatorLength; $nameIndex ++; $itemIndex ++; if ($syntax instanceof OptionalSyntax && !$syntax->success()) { $itemIndex --; } } // if items are left if ($itemIndex < $itemsCount) $itemsLeft = true; // if fields are left while ($nameIndex < $namesCount) { $syntax = $this->fields[$names[$nameIndex]]; $this->values[$names[$nameIndex]]->value = $syntax->parse(''); $this->values[$names[$nameIndex]]->error = null; $nameIndex ++; } } catch (ParseException $e) { if ($itemIndex < $itemsCount) { $this->values[$names[$nameIndex]]->error = static::INVALID_FIELD; $error = "Unable to parse the item '{$items[$itemIndex]}' for field '{$names[$nameIndex]}'"; $extra = [ 'type' => 'invalid-field', 'field' => $names[$nameIndex], 'text' => $items[$itemIndex] ]; } else { $this->values[$names[$nameIndex]]->error = static::MISSING_FIELD; $error = "No item left for field '{$names[$nameIndex]}'"; $extra = [ 'type' => 'missing-field', 'field' => $names[$nameIndex], 'position' => $e->position() ]; } throw new ParseException($this, $text, $index + $e->position(), $error, $extra, $e); } if ($itemsLeft) { $extra = [ 'type' => 'additional-items', 'items' => array_slice($items, $itemIndex) ]; throw new ParseException($this, $text, $index - $separatorLength, "Additional items with no corresponding fields", $extra); } return (object) array_map(function(\stdClass $field) { return $field->value; }, $this->values); }
Transforms a string to an object based on the fields or throws a ParseException. @param string $text the string to parse @return object @throws Tarsana\Syntax\Exceptions\ParseException
https://github.com/tarsana/syntax/blob/fd3f8a25e3be0e391c8fd486ccfcffe913ade534/src/ObjectSyntax.php#L172-L239
tarsana/syntax
src/ObjectSyntax.php
ObjectSyntax.dump
public function dump($value) : string { $value = (array) $value; $result = []; $current = ''; $missingField = false; try { foreach ($this->fields as $name => $syntax) { $current = $name; if (!array_key_exists($name, $value)) { $missingField = true; break; } $result[] = $syntax->dump($value[$name]); } } catch (DumpException $e) { throw new DumpException($this, $value, "Unable to dump the field '{$current}'", [], $e); } if ($missingField) throw new DumpException($this, $value, "Missing field '{$name}'"); return Text::join($result, $this->separator); }
php
public function dump($value) : string { $value = (array) $value; $result = []; $current = ''; $missingField = false; try { foreach ($this->fields as $name => $syntax) { $current = $name; if (!array_key_exists($name, $value)) { $missingField = true; break; } $result[] = $syntax->dump($value[$name]); } } catch (DumpException $e) { throw new DumpException($this, $value, "Unable to dump the field '{$current}'", [], $e); } if ($missingField) throw new DumpException($this, $value, "Missing field '{$name}'"); return Text::join($result, $this->separator); }
Transforms an object to a string based on the fields or throws a DumpException. @param mixed $value @return string @throws Tarsana\Syntax\Exceptions\DumpException
https://github.com/tarsana/syntax/blob/fd3f8a25e3be0e391c8fd486ccfcffe913ade534/src/ObjectSyntax.php#L250-L273
valu-digital/valuso
src/ValuSo/Feature/OptionsTrait.php
OptionsTrait.setOptions
public function setOptions($options) { if (!is_array($options) && !$options instanceof \Traversable) { throw new \InvalidArgumentException(sprintf( 'Parameter provided to %s must be an array or Traversable', __METHOD__ )); } foreach ($options as $key => $value){ $this->setOption($key, $value); } return $this; }
php
public function setOptions($options) { if (!is_array($options) && !$options instanceof \Traversable) { throw new \InvalidArgumentException(sprintf( 'Parameter provided to %s must be an array or Traversable', __METHOD__ )); } foreach ($options as $key => $value){ $this->setOption($key, $value); } return $this; }
Set service options from array or traversable object @param array|Traversable $options @return \stdClass @ValuSo\Exclude
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Feature/OptionsTrait.php#L22-L36
valu-digital/valuso
src/ValuSo/Feature/OptionsTrait.php
OptionsTrait.getOptions
public function getOptions() { if(!$this->options){ if (isset($this->optionsClass)) { $this->options = new $this->optionsClass(array()); } else { $this->options = new Options(array()); } } return $this->options; }
php
public function getOptions() { if(!$this->options){ if (isset($this->optionsClass)) { $this->options = new $this->optionsClass(array()); } else { $this->options = new Options(array()); } } return $this->options; }
Retrieve service options @return \Zend\Stdlib\ParameterObjectInterface @ValuSo\Exclude
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Feature/OptionsTrait.php#L45-L56
valu-digital/valuso
src/ValuSo/Feature/OptionsTrait.php
OptionsTrait.getOption
public function getOption($key, $default = null) { if ($this->hasOption($key)) { return $this->getOptions()->__get($key); } return $default; }
php
public function getOption($key, $default = null) { if ($this->hasOption($key)) { return $this->getOptions()->__get($key); } return $default; }
Retrieve a single option @param string $key @return mixed @ValuSo\Exclude
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Feature/OptionsTrait.php#L94-L101
valu-digital/valuso
src/ValuSo/Feature/OptionsTrait.php
OptionsTrait.setConfig
public function setConfig($config) { if(is_string($config)){ if (file_exists($config)) { $config = \Zend\Config\Factory::fromFile($config); } else { throw new \InvalidArgumentException( sprintf('Unable to read configurations from file %s',$config)); } } if(!is_array($config) && !($config instanceof \Traversable)){ throw new \InvalidArgumentException( sprintf('Config must be an array, Traversable object or filename; %s received', is_object($config) ? get_class($config) : gettype($config))); } $this->setOptions($config); }
php
public function setConfig($config) { if(is_string($config)){ if (file_exists($config)) { $config = \Zend\Config\Factory::fromFile($config); } else { throw new \InvalidArgumentException( sprintf('Unable to read configurations from file %s',$config)); } } if(!is_array($config) && !($config instanceof \Traversable)){ throw new \InvalidArgumentException( sprintf('Config must be an array, Traversable object or filename; %s received', is_object($config) ? get_class($config) : gettype($config))); } $this->setOptions($config); }
Set options as config file, array or traversable object @param string|array|\Traversable $config @ValuSo\Exclude
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Feature/OptionsTrait.php#L124-L142
LoggerEssentials/LoggerEssentials
src/Wrappers/BufferedLogger.php
BufferedLogger.log
public function log($level, $message, array $context = array()) { $this->entries[] = array($level, $message, $context); if($this->maxEntries > -1 && count($this->entries) >= $this->maxEntries) { $this->flush(); } }
php
public function log($level, $message, array $context = array()) { $this->entries[] = array($level, $message, $context); if($this->maxEntries > -1 && count($this->entries) >= $this->maxEntries) { $this->flush(); } }
Logs with an arbitrary level. @param mixed $level @param string $message @param array $context @return void
https://github.com/LoggerEssentials/LoggerEssentials/blob/f32f9b865eacfccced90697f3eb69dc4ad80dc96/src/Wrappers/BufferedLogger.php#L73-L78
JDGrimes/wp-filesystem-mock
src/wp-mock-filesystem.php
WP_Mock_Filesystem.normalize_path
protected function normalize_path( $path ) { $path = str_replace( '\\', '/', $path ); $path = preg_replace( '|/+|','/', $path ); return rtrim( $path, '/' ); }
php
protected function normalize_path( $path ) { $path = str_replace( '\\', '/', $path ); $path = preg_replace( '|/+|','/', $path ); return rtrim( $path, '/' ); }
Normalize a path. @since 0.1.0 @param string $path The path to normalize. @return string The normalized path.
https://github.com/JDGrimes/wp-filesystem-mock/blob/986df3bfeb1554ae19856537dfeb558037275c25/src/wp-mock-filesystem.php#L53-L59
JDGrimes/wp-filesystem-mock
src/wp-mock-filesystem.php
WP_Mock_Filesystem.get_file
protected function get_file( $file ) { $path_parts = $this->parse_path( $file ); if ( '' === $path_parts[0] ) { $file = $this->root; unset( $path_parts[0] ); } else { $file = $this->cwd; } foreach ( $path_parts as $part ) { if ( '' === $part ) { continue; } if ( 'dir' !== $file->type || false === isset( $file->contents->$part ) ) { return false; } $file = $file->contents->$part; } return $file; }
php
protected function get_file( $file ) { $path_parts = $this->parse_path( $file ); if ( '' === $path_parts[0] ) { $file = $this->root; unset( $path_parts[0] ); } else { $file = $this->cwd; } foreach ( $path_parts as $part ) { if ( '' === $part ) { continue; } if ( 'dir' !== $file->type || false === isset( $file->contents->$part ) ) { return false; } $file = $file->contents->$part; } return $file; }
Get the data for a file. @since 0.1.0 @param string $file The file to retrieve. @return object|false The file data, or false if it does't exist.
https://github.com/JDGrimes/wp-filesystem-mock/blob/986df3bfeb1554ae19856537dfeb558037275c25/src/wp-mock-filesystem.php#L84-L109
JDGrimes/wp-filesystem-mock
src/wp-mock-filesystem.php
WP_Mock_Filesystem.get_default_atts
protected function get_default_atts( $atts ) { if ( false === isset( $atts['type'] ) ) { $atts['type'] = 'file'; } if ( 'file' === $atts['type'] ) { $defaults = array( 'contents' => '', 'mode' => 0644, 'size' => 0, ); } elseif ( 'dir' === $atts['type'] ) { $defaults = array( 'contents' => new stdClass(), 'mode' => 0755 ); } else { $defaults = array(); } $atts = array_merge( array( 'atime' => time(), 'mtime' => time(), 'owner' => '', 'group' => '', ) , $defaults , $atts ); if ( ! empty( $atts['contents'] ) && 'file' === $atts['type'] ) { $atts['size'] = mb_strlen( $atts['contents'], '8bit' ); } return (object) $atts; }
php
protected function get_default_atts( $atts ) { if ( false === isset( $atts['type'] ) ) { $atts['type'] = 'file'; } if ( 'file' === $atts['type'] ) { $defaults = array( 'contents' => '', 'mode' => 0644, 'size' => 0, ); } elseif ( 'dir' === $atts['type'] ) { $defaults = array( 'contents' => new stdClass(), 'mode' => 0755 ); } else { $defaults = array(); } $atts = array_merge( array( 'atime' => time(), 'mtime' => time(), 'owner' => '', 'group' => '', ) , $defaults , $atts ); if ( ! empty( $atts['contents'] ) && 'file' === $atts['type'] ) { $atts['size'] = mb_strlen( $atts['contents'], '8bit' ); } return (object) $atts; }
Get the default attributes for a file. @since 0.1.0 @param string $atts @return object The attributes.
https://github.com/JDGrimes/wp-filesystem-mock/blob/986df3bfeb1554ae19856537dfeb558037275c25/src/wp-mock-filesystem.php#L120-L150
JDGrimes/wp-filesystem-mock
src/wp-mock-filesystem.php
WP_Mock_Filesystem.add_file
public function add_file( $file, array $atts = array() ) { $parent = $this->get_file( dirname( $file ) ); $filename = basename( $file ); if ( false === $parent || true === isset( $parent->contents->$filename ) ) { return false; } $parent->contents->$filename = $this->get_default_atts( $atts ); return true; }
php
public function add_file( $file, array $atts = array() ) { $parent = $this->get_file( dirname( $file ) ); $filename = basename( $file ); if ( false === $parent || true === isset( $parent->contents->$filename ) ) { return false; } $parent->contents->$filename = $this->get_default_atts( $atts ); return true; }
Create a file or directory. @since 0.1.0 @param string $file The path of the file/directory to create. @param array $atts The attributes of the file/directory. @return bool True if the file was added, false otherwise.
https://github.com/JDGrimes/wp-filesystem-mock/blob/986df3bfeb1554ae19856537dfeb558037275c25/src/wp-mock-filesystem.php#L175-L187
JDGrimes/wp-filesystem-mock
src/wp-mock-filesystem.php
WP_Mock_Filesystem.mkdir_p
public function mkdir_p( $file, array $atts = array() ) { $dir_levels = $this->parse_path( $file ); $path = ''; $atts['type'] = 'dir'; foreach ( $dir_levels as $level ) { $path .= '/' . $level; if ( $this->exists( $path ) ) { continue; } if ( ! $this->add_file( $path, $atts ) ) { return false; } } return true; }
php
public function mkdir_p( $file, array $atts = array() ) { $dir_levels = $this->parse_path( $file ); $path = ''; $atts['type'] = 'dir'; foreach ( $dir_levels as $level ) { $path .= '/' . $level; if ( $this->exists( $path ) ) { continue; } if ( ! $this->add_file( $path, $atts ) ) { return false; } } return true; }
Create a deep directory. @since 0.1.0 @param string $file The path of the file/directory to create. @param array $atts The attributes of the file/directory. @return bool True if the file was added, false otherwise.
https://github.com/JDGrimes/wp-filesystem-mock/blob/986df3bfeb1554ae19856537dfeb558037275c25/src/wp-mock-filesystem.php#L199-L220
JDGrimes/wp-filesystem-mock
src/wp-mock-filesystem.php
WP_Mock_Filesystem.get_file_attr
public function get_file_attr( $file, $attr, $type = null ) { $file_atts = $this->get_file( $file ); if ( false === $file_atts || false === isset( $file_atts->$attr ) ) { return false; } if ( isset( $type ) && $type !== $file_atts->type ) { return false; } return $file_atts->$attr; }
php
public function get_file_attr( $file, $attr, $type = null ) { $file_atts = $this->get_file( $file ); if ( false === $file_atts || false === isset( $file_atts->$attr ) ) { return false; } if ( isset( $type ) && $type !== $file_atts->type ) { return false; } return $file_atts->$attr; }
Get a piece of information about a file. @since 0.1.0 @param string $file The path to the file/directory. @param string $attr The file attribute to get. @param string $type The type of file this is expected to be. @return mixed The value of this attribute, or false on failure.
https://github.com/JDGrimes/wp-filesystem-mock/blob/986df3bfeb1554ae19856537dfeb558037275c25/src/wp-mock-filesystem.php#L246-L259
JDGrimes/wp-filesystem-mock
src/wp-mock-filesystem.php
WP_Mock_Filesystem.set_file_attr
public function set_file_attr( $file, $attr, $value, $recursive = false ) { $file_atts = $this->get_file( $file ); if ( false === $file_atts ) { return false; } if ( 'contents' === $attr ) { if ( 'file' === $file_atts->type ) { $file_atts->size = mb_strlen( $value, '8bit' ); } else { return false; } } if ( true === $recursive ) { $this->set_file_attr_recursive( $file_atts, $attr, $value ); } $file_atts->$attr = $value; return true; }
php
public function set_file_attr( $file, $attr, $value, $recursive = false ) { $file_atts = $this->get_file( $file ); if ( false === $file_atts ) { return false; } if ( 'contents' === $attr ) { if ( 'file' === $file_atts->type ) { $file_atts->size = mb_strlen( $value, '8bit' ); } else { return false; } } if ( true === $recursive ) { $this->set_file_attr_recursive( $file_atts, $attr, $value ); } $file_atts->$attr = $value; return true; }
Set the value of file attribute. @since 0.1.0 @param string $file The path of the file/directory. @param string $attr The attribute to set. @param mixed $value The new value for this attribute. @param bool $recursive Whether to set the value recursively. @return bool True if the attribute value was set, false otherwise.
https://github.com/JDGrimes/wp-filesystem-mock/blob/986df3bfeb1554ae19856537dfeb558037275c25/src/wp-mock-filesystem.php#L273-L296
JDGrimes/wp-filesystem-mock
src/wp-mock-filesystem.php
WP_Mock_Filesystem.set_file_attr_recursive
protected function set_file_attr_recursive( $file, $attr, $value ) { if ( 'dir' === $file->type ) { foreach ( $file->contents as $sub => $atts ) { $this->set_file_attr_recursive( $atts, $attr, $value ); } } $file->$attr = $value; }
php
protected function set_file_attr_recursive( $file, $attr, $value ) { if ( 'dir' === $file->type ) { foreach ( $file->contents as $sub => $atts ) { $this->set_file_attr_recursive( $atts, $attr, $value ); } } $file->$attr = $value; }
Set the value of file attribute recursively. @since 0.1.0 @param object $file The file data. @param string $attr The attribute to set. @param mixed $value The new value for this attribute. @return bool True if the attribute value was set, false otherwise.
https://github.com/JDGrimes/wp-filesystem-mock/blob/986df3bfeb1554ae19856537dfeb558037275c25/src/wp-mock-filesystem.php#L309-L319
JDGrimes/wp-filesystem-mock
src/wp-mock-filesystem.php
WP_Mock_Filesystem.set_cwd
public function set_cwd( $cwd ) { $file = $this->get_file( $cwd ); if ( false === $file || 'dir' !== $file->type ) { return false; } $this->cwd = $this->normalize_path( $cwd ); if ( empty( $this->cwd ) ) { $this->cwd = '/'; } return true; }
php
public function set_cwd( $cwd ) { $file = $this->get_file( $cwd ); if ( false === $file || 'dir' !== $file->type ) { return false; } $this->cwd = $this->normalize_path( $cwd ); if ( empty( $this->cwd ) ) { $this->cwd = '/'; } return true; }
Set the current working directory. @since 0.1.0 @param string $cwd The path to the new working directory. @return bool True if the current working directory was set, false otherwise.
https://github.com/JDGrimes/wp-filesystem-mock/blob/986df3bfeb1554ae19856537dfeb558037275c25/src/wp-mock-filesystem.php#L341-L356
JDGrimes/wp-filesystem-mock
src/wp-mock-filesystem.php
WP_Mock_Filesystem.copy
public function copy( $source, $destination ) { $source = $this->get_file( $source ); if ( false === $source ) { return false; } $destination_parent = $this->get_file( dirname( $destination ) ); $filename = basename( $destination ); if ( false === $destination_parent ) { return false; } $destination_parent->contents->$filename = clone $source; return true; }
php
public function copy( $source, $destination ) { $source = $this->get_file( $source ); if ( false === $source ) { return false; } $destination_parent = $this->get_file( dirname( $destination ) ); $filename = basename( $destination ); if ( false === $destination_parent ) { return false; } $destination_parent->contents->$filename = clone $source; return true; }
Copy a file or directory. The destination will be overwritten if it already exists. @since 0.1.0 @param string $source The source path. @param string $destination The destination path. @return bool True if the file was copied, false otherwise.
https://github.com/JDGrimes/wp-filesystem-mock/blob/986df3bfeb1554ae19856537dfeb558037275c25/src/wp-mock-filesystem.php#L370-L388
JDGrimes/wp-filesystem-mock
src/wp-mock-filesystem.php
WP_Mock_Filesystem.move
public function move( $source, $destination ) { if ( false === $this->copy( $source, $destination ) ) { return false; } $this->delete( $source ); return true; }
php
public function move( $source, $destination ) { if ( false === $this->copy( $source, $destination ) ) { return false; } $this->delete( $source ); return true; }
Move a file or directory. @since 0.1.0 @param string $source The source path. @param string $destination The destination path. @return bool True if the file was moved, false otherwise.
https://github.com/JDGrimes/wp-filesystem-mock/blob/986df3bfeb1554ae19856537dfeb558037275c25/src/wp-mock-filesystem.php#L400-L409
JDGrimes/wp-filesystem-mock
src/wp-mock-filesystem.php
WP_Mock_Filesystem.delete
public function delete( $file ) { $parent = $this->get_file( dirname( $file ) ); $filename = basename( $file ); if ( false === $parent || 'dir' !== $parent->type || false === isset( $parent->contents->$filename ) ) { return false; } unset( $parent->contents->$filename ); return true; }
php
public function delete( $file ) { $parent = $this->get_file( dirname( $file ) ); $filename = basename( $file ); if ( false === $parent || 'dir' !== $parent->type || false === isset( $parent->contents->$filename ) ) { return false; } unset( $parent->contents->$filename ); return true; }
Delete a file or directory. @since 0.1.0 @param string $file The path of the file/directory to delete. @return bool True if the file was deleted, false otherwise.
https://github.com/JDGrimes/wp-filesystem-mock/blob/986df3bfeb1554ae19856537dfeb558037275c25/src/wp-mock-filesystem.php#L420-L437
phPoirot/AuthSystem
Authenticate/RepoIdentityCredential/IdentityCredentialDigestFile.php
IdentityCredentialDigestFile.doFindIdentityMatch
protected function doFindIdentityMatch(array $credentials) { ErrorStack::handleError(E_WARNING); // { $hFile = fopen($this->getPwdFilePath(), 'r'); $error = ErrorStack::handleDone(); // } if ($hFile === false) throw new \RuntimeException("Cannot open '{$this->getPwdFilePath()}' for reading", 0, $error); $username = $this->getUsername(); $password = $this->getPassword(); if (!isset($username)) throw new exMissingCredential('Adapter Credential not contains Username.'); $realm = $this->getRealm(); $id = "$username:$realm"; while (($line = fgets($hFile)) !== false) { $line = trim($line); if (substr($line, 0, strlen($id)) !== $id) ## try next (user:realm) not match continue; if (!isset($password)) { // just username match, digest http authorization need secret key (A1) $identity = new IdentityHttpDigest; $identity->setUsername($username); $a1Hash = substr($line, strlen($id)+1 /* +1 for : */); if (strlen($a1Hash) !== 32) continue; // it seems invalid a1hash just continue; if match others. $identity->setA1(strtolower($a1Hash)); return $identity; } if (isset($password) ## 32 for md5 length && strtolower(substr($line, -32)) === strtolower(md5("$username:$realm:$password")) ) { ## user/pass credential match $identity = new IdentityUsername; $identity->setUsername($username); return $identity; } } return false; }
php
protected function doFindIdentityMatch(array $credentials) { ErrorStack::handleError(E_WARNING); // { $hFile = fopen($this->getPwdFilePath(), 'r'); $error = ErrorStack::handleDone(); // } if ($hFile === false) throw new \RuntimeException("Cannot open '{$this->getPwdFilePath()}' for reading", 0, $error); $username = $this->getUsername(); $password = $this->getPassword(); if (!isset($username)) throw new exMissingCredential('Adapter Credential not contains Username.'); $realm = $this->getRealm(); $id = "$username:$realm"; while (($line = fgets($hFile)) !== false) { $line = trim($line); if (substr($line, 0, strlen($id)) !== $id) ## try next (user:realm) not match continue; if (!isset($password)) { // just username match, digest http authorization need secret key (A1) $identity = new IdentityHttpDigest; $identity->setUsername($username); $a1Hash = substr($line, strlen($id)+1 /* +1 for : */); if (strlen($a1Hash) !== 32) continue; // it seems invalid a1hash just continue; if match others. $identity->setA1(strtolower($a1Hash)); return $identity; } if (isset($password) ## 32 for md5 length && strtolower(substr($line, -32)) === strtolower(md5("$username:$realm:$password")) ) { ## user/pass credential match $identity = new IdentityUsername; $identity->setUsername($username); return $identity; } } return false; }
Do Match Identity With Given Options/Credential - match against username:realm; used on http digest authorization to retrieve A1. A1 = md5(username:realm:password) @param array $credentials Include Credential Data @return iIdentity|false
https://github.com/phPoirot/AuthSystem/blob/bb8d02f72a7c2686d7d453021143361fa704a5a6/Authenticate/RepoIdentityCredential/IdentityCredentialDigestFile.php#L43-L93
IftekherSunny/Planet-Framework
src/Sun/Application.php
Application.group
public function group(array $routeOption = [], $callback) { if (isset($routeOption['namespace'])) { $this->namespace = '\\' . $routeOption['namespace'] . '\\'; } (isset($routeOption['prefix'])) ? $this->prefix = '/' . $routeOption['prefix'] : $this->prefix = ''; (isset($routeOption['filter'])) ? $this->filter = ['filter' => $routeOption['filter']] : $this->filter = []; call_user_func_array($callback, $routeOption); $this->prefix = ''; $this->filter = []; }
php
public function group(array $routeOption = [], $callback) { if (isset($routeOption['namespace'])) { $this->namespace = '\\' . $routeOption['namespace'] . '\\'; } (isset($routeOption['prefix'])) ? $this->prefix = '/' . $routeOption['prefix'] : $this->prefix = ''; (isset($routeOption['filter'])) ? $this->filter = ['filter' => $routeOption['filter']] : $this->filter = []; call_user_func_array($callback, $routeOption); $this->prefix = ''; $this->filter = []; }
Route GROUP @param array $routeOption @param callback $callback
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Application.php#L90-L105
IftekherSunny/Planet-Framework
src/Sun/Application.php
Application.get
public function get($uri, $pattern, array $options = []) { $options = array_merge($options, $this->filter); if (is_callable($pattern)) { $this->route->add('GET', $this->prefix . $uri, $pattern, $options); } else { $this->route->add('GET', $this->prefix . $uri, $this->namespace . $pattern, $options); } }
php
public function get($uri, $pattern, array $options = []) { $options = array_merge($options, $this->filter); if (is_callable($pattern)) { $this->route->add('GET', $this->prefix . $uri, $pattern, $options); } else { $this->route->add('GET', $this->prefix . $uri, $this->namespace . $pattern, $options); } }
Route GET @param string $uri @param string $pattern @param array $options
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Application.php#L114-L123
IftekherSunny/Planet-Framework
src/Sun/Application.php
Application.any
public function any($uri, $pattern, array $options = []) { $patterns = explode('@', $pattern); $controller = $patterns[0]; $method = ucfirst($patterns[1]); $this->get($uri, "$controller@get$method", $options); $this->post($uri, "$controller@post$method", $options); }
php
public function any($uri, $pattern, array $options = []) { $patterns = explode('@', $pattern); $controller = $patterns[0]; $method = ucfirst($patterns[1]); $this->get($uri, "$controller@get$method", $options); $this->post($uri, "$controller@post$method", $options); }
Route ANY @param string $uri @param string $pattern @param array $options
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Application.php#L204-L212
IftekherSunny/Planet-Framework
src/Sun/Application.php
Application.resource
public function resource($uri, $controller, array $options = []) { $this->get($uri, "$controller@index", $options); $this->post($uri, "$controller@store", $options); $this->get("$uri/{placeholder}", "$controller@show", $options); $this->put("$uri/{placeholder}", "$controller@update", $options); $this->delete("$uri/{placeholder}", "$controller@delete", $options); }
php
public function resource($uri, $controller, array $options = []) { $this->get($uri, "$controller@index", $options); $this->post($uri, "$controller@store", $options); $this->get("$uri/{placeholder}", "$controller@show", $options); $this->put("$uri/{placeholder}", "$controller@update", $options); $this->delete("$uri/{placeholder}", "$controller@delete", $options); }
Route RESOURCE @param string $uri @param string $controller @param array $options
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Application.php#L221-L228
IftekherSunny/Planet-Framework
src/Sun/Application.php
Application.run
public function run() { $this->make('Sun\Bootstrap\Provider')->registerRoute(); $this->route->register(); $httpMethod = $this->make('Sun\Contracts\Http\Request')->method(); $uri = $this->make('Sun\Contracts\Routing\UrlGenerator')->getUri(); $data = $this->route->dispatch($httpMethod, $uri); $this->make('Sun\Bootstrap\Provider')->dispatch(); $this->make('Sun\Contracts\Http\Response')->html($data); }
php
public function run() { $this->make('Sun\Bootstrap\Provider')->registerRoute(); $this->route->register(); $httpMethod = $this->make('Sun\Contracts\Http\Request')->method(); $uri = $this->make('Sun\Contracts\Routing\UrlGenerator')->getUri(); $data = $this->route->dispatch($httpMethod, $uri); $this->make('Sun\Bootstrap\Provider')->dispatch(); $this->make('Sun\Contracts\Http\Response')->html($data); }
To run application
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Application.php#L233-L248
IftekherSunny/Planet-Framework
src/Sun/Application.php
Application.base_path
public function base_path($path = null) { return empty($path) ? $this->path : $this->path . $path; }
php
public function base_path($path = null) { return empty($path) ? $this->path : $this->path . $path; }
To get application base directory path @param null $path @return string
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Application.php#L257-L260
IftekherSunny/Planet-Framework
src/Sun/Application.php
Application.app_path
public function app_path($path = null) { return empty($path) ? $this->base_path() . DIRECTORY_SEPARATOR . 'app' : $this->base_path() . 'app' . $path; }
php
public function app_path($path = null) { return empty($path) ? $this->base_path() . DIRECTORY_SEPARATOR . 'app' : $this->base_path() . 'app' . $path; }
To get application app directory path @param null $path @return string
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Application.php#L269-L272
IftekherSunny/Planet-Framework
src/Sun/Application.php
Application.loadAlien
public function loadAlien() { $alien = $this->config->getAlien(); foreach ($alien as $alias => $namespace) { class_alias($namespace, $alias); } }
php
public function loadAlien() { $alien = $this->config->getAlien(); foreach ($alien as $alias => $namespace) { class_alias($namespace, $alias); } }
To load alien
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Application.php#L347-L354
IftekherSunny/Planet-Framework
src/Sun/Application.php
Application.bootDatabase
protected function bootDatabase() { $this->database = $this->make('Sun\Contracts\Database\Database'); $this->database->boot(); $this->db = $this->database->getCapsuleInstance(); }
php
protected function bootDatabase() { $this->database = $this->make('Sun\Contracts\Database\Database'); $this->database->boot(); $this->db = $this->database->getCapsuleInstance(); }
To boot database configuration
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Application.php#L359-L366
IftekherSunny/Planet-Framework
src/Sun/Application.php
Application.getNamespace
public function getNamespace() { if(!is_null($this->appNamespace)) { return $this->appNamespace; } $composer = json_decode(file_get_contents(base_path().'/composer.json')); foreach($composer->autoload->{"psr-4"} as $namespace => $path) { if(realpath(app_path()) === realpath(base_path(). '/' .$path)) { return $this->appNamespace = $namespace; } } throw new Exception("Namespace detect problem."); }
php
public function getNamespace() { if(!is_null($this->appNamespace)) { return $this->appNamespace; } $composer = json_decode(file_get_contents(base_path().'/composer.json')); foreach($composer->autoload->{"psr-4"} as $namespace => $path) { if(realpath(app_path()) === realpath(base_path(). '/' .$path)) { return $this->appNamespace = $namespace; } } throw new Exception("Namespace detect problem."); }
To get application namespace @return string @throws Exception
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Application.php#L400-L415
IftekherSunny/Planet-Framework
src/Sun/Application.php
Application.booting
protected function booting() { $this->setInstance(); $this->bind('Sun\Contracts\Container\Container', $this->getContainer()); $this->bind('Sun\Contracts\Application', $this); $this->config = $this->make('Sun\Support\Config'); }
php
protected function booting() { $this->setInstance(); $this->bind('Sun\Contracts\Container\Container', $this->getContainer()); $this->bind('Sun\Contracts\Application', $this); $this->config = $this->make('Sun\Support\Config'); }
Booting application
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Application.php#L420-L429
IftekherSunny/Planet-Framework
src/Sun/Application.php
Application.bootstrap
protected function bootstrap() { $this->make('Sun\Bootstrap\Application')->bootstrap(); $this->make('Sun\Bootstrap\HandleExceptions')->bootstrap(); $this->make('Sun\Bootstrap\Route')->bootstrap(); $this->make('Sun\Bootstrap\Provider')->bootstrap(); $this->route = $this->make('Sun\Contracts\Routing\Route'); }
php
protected function bootstrap() { $this->make('Sun\Bootstrap\Application')->bootstrap(); $this->make('Sun\Bootstrap\HandleExceptions')->bootstrap(); $this->make('Sun\Bootstrap\Route')->bootstrap(); $this->make('Sun\Bootstrap\Provider')->bootstrap(); $this->route = $this->make('Sun\Contracts\Routing\Route'); }
Bootstrap application required class
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Application.php#L434-L445
IftekherSunny/Planet-Framework
src/Sun/Application.php
Application.registerBindings
protected function registerBindings() { $binding = config('binding')?: []; foreach($binding as $contract => $implementation) { $this->bind($contract, $implementation); } }
php
protected function registerBindings() { $binding = config('binding')?: []; foreach($binding as $contract => $implementation) { $this->bind($contract, $implementation); } }
To register all bindings
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Application.php#L450-L457
IftekherSunny/Planet-Framework
src/Sun/Application.php
Application.config
public function config($location) { $keys = explode('.', $location); $filename = 'get' . strtoupper(array_shift($keys)); $location = implode('.', $keys); if(empty($location)) { return $this->config->{$filename}(); } return $this->config->{$filename}($location); }
php
public function config($location) { $keys = explode('.', $location); $filename = 'get' . strtoupper(array_shift($keys)); $location = implode('.', $keys); if(empty($location)) { return $this->config->{$filename}(); } return $this->config->{$filename}($location); }
To get configuration @param string $location @return mixed
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Application.php#L466-L479
AcaiFramework/Bartender
src/Bartender.php
Bartender.run
public static function run ($args) { //Initialize colors Bartender::setup(); //Start on a new line Bartender::printColored("\n", "white"); //Show all commands if (count($args) == 1) { Bartender::printColored("Commands avaible:", "purple"); Bartender::newLine(); foreach (Bartender::$commands as $key => $value) { Bartender::printColored($key, "green"); Bartender::newLine(); $value = "Acai\Core\Commands\\".$value; $value::description(); Bartender::newLine(); Bartender::newLine(); } } //Show command specific help else { //Gather $caller = array_shift($args); $command = array_shift($args); $action = (count($args) > 0)? array_shift($args):""; if (isset(Bartender::$commands[$command])) { $command = "Acai\Core\Commands\\".Bartender::$commands[$command]; $command::action($action); $command::arguments($args); $command::run(); } else { Bartender::printColored("Command not found", "white", "red"); } } Bartender::printColored("", "white", "black"); }
php
public static function run ($args) { //Initialize colors Bartender::setup(); //Start on a new line Bartender::printColored("\n", "white"); //Show all commands if (count($args) == 1) { Bartender::printColored("Commands avaible:", "purple"); Bartender::newLine(); foreach (Bartender::$commands as $key => $value) { Bartender::printColored($key, "green"); Bartender::newLine(); $value = "Acai\Core\Commands\\".$value; $value::description(); Bartender::newLine(); Bartender::newLine(); } } //Show command specific help else { //Gather $caller = array_shift($args); $command = array_shift($args); $action = (count($args) > 0)? array_shift($args):""; if (isset(Bartender::$commands[$command])) { $command = "Acai\Core\Commands\\".Bartender::$commands[$command]; $command::action($action); $command::arguments($args); $command::run(); } else { Bartender::printColored("Command not found", "white", "red"); } } Bartender::printColored("", "white", "black"); }
///////////////////////////////////////////////////////////////////////////////////////////////////////
https://github.com/AcaiFramework/Bartender/blob/e3959f4c0c4f89aad33e5cf2213452c80dfe3486/src/Bartender.php#L28-L68
AcaiFramework/Bartender
src/Bartender.php
Bartender.printColored
public static function printColored ($string, $foreground_color = null, $background_color = null) { $colored_string = ""; // Check if given foreground color found if (isset(Bartender::$foreground_colors[$foreground_color])) { $colored_string .= "\033[" . Bartender::$foreground_colors[$foreground_color] . "m"; } // Check if given background color found if (isset(Bartender::$background_colors[$background_color])) { $colored_string .= "\033[" . Bartender::$background_colors[$background_color] . "m"; } // Add string and end coloring $colored_string .= $string; echo $colored_string; }
php
public static function printColored ($string, $foreground_color = null, $background_color = null) { $colored_string = ""; // Check if given foreground color found if (isset(Bartender::$foreground_colors[$foreground_color])) { $colored_string .= "\033[" . Bartender::$foreground_colors[$foreground_color] . "m"; } // Check if given background color found if (isset(Bartender::$background_colors[$background_color])) { $colored_string .= "\033[" . Bartender::$background_colors[$background_color] . "m"; } // Add string and end coloring $colored_string .= $string; echo $colored_string; }
Returns colored string
https://github.com/AcaiFramework/Bartender/blob/e3959f4c0c4f89aad33e5cf2213452c80dfe3486/src/Bartender.php#L119-L135
stonedz/pff2
src/Core/HookManager.php
HookManager.registerHook
public function registerHook(IHookProvider $prov, $moduleName, $loadBefore = null) { $found = false; if(is_a($prov, '\\pff\\Iface\\IBeforeHook')) { $found = $this->addHook($this->_beforeController, $prov, $moduleName, $loadBefore); } if(is_a($prov, '\\pff\\Iface\\IAfterHook')) { $found = $this->addHook($this->_afterController, $prov, $moduleName, $loadBefore); } if(is_a($prov, '\\pff\\Iface\\IBeforeSystemHook')) { $found = $this->addHook($this->_beforeSystem, $prov, $moduleName, $loadBefore); } if(is_a($prov, '\\pff\\Iface\\IBeforeViewHook')) { $found = $this->addHook($this->_beforeView, $prov, $moduleName, $loadBefore); } if(is_a($prov, '\\pff\\Iface\\IAfterViewHook')) { $found = $this->addHook($this->_afterView, $prov, $moduleName, $loadBefore); } if(!$found) { throw new HookException("Cannot add given class as a hook provider: ". get_class($prov)); } }
php
public function registerHook(IHookProvider $prov, $moduleName, $loadBefore = null) { $found = false; if(is_a($prov, '\\pff\\Iface\\IBeforeHook')) { $found = $this->addHook($this->_beforeController, $prov, $moduleName, $loadBefore); } if(is_a($prov, '\\pff\\Iface\\IAfterHook')) { $found = $this->addHook($this->_afterController, $prov, $moduleName, $loadBefore); } if(is_a($prov, '\\pff\\Iface\\IBeforeSystemHook')) { $found = $this->addHook($this->_beforeSystem, $prov, $moduleName, $loadBefore); } if(is_a($prov, '\\pff\\Iface\\IBeforeViewHook')) { $found = $this->addHook($this->_beforeView, $prov, $moduleName, $loadBefore); } if(is_a($prov, '\\pff\\Iface\\IAfterViewHook')) { $found = $this->addHook($this->_afterView, $prov, $moduleName, $loadBefore); } if(!$found) { throw new HookException("Cannot add given class as a hook provider: ". get_class($prov)); } }
Registers a hook provider @param IHookProvider $prov Hook provider (module) @param string $moduleName Name of the module @param string|null $loadBefore Hook must be run before specified module name @throws HookException
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/Core/HookManager.php#L72-L98
stonedz/pff2
src/Core/HookManager.php
HookManager.runBeforeSystem
public function runBeforeSystem() { if($this->_beforeSystem !== null) { foreach($this->_beforeSystem as $hookProvider) { $hookProvider->doBeforeSystem(); } } }
php
public function runBeforeSystem() { if($this->_beforeSystem !== null) { foreach($this->_beforeSystem as $hookProvider) { $hookProvider->doBeforeSystem(); } } }
Executes the registered methods (before the system) @return void
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/Core/HookManager.php#L130-L136
stonedz/pff2
src/Core/HookManager.php
HookManager.runBefore
public function runBefore() { if($this->_beforeController !== null) { foreach($this->_beforeController as $hookProvider) { $hookProvider->doBefore(); } } }
php
public function runBefore() { if($this->_beforeController !== null) { foreach($this->_beforeController as $hookProvider) { $hookProvider->doBefore(); } } }
Executes the registered methods (before the controller) @return void
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/Core/HookManager.php#L143-L149
stonedz/pff2
src/Core/HookManager.php
HookManager.runAfter
public function runAfter() { if($this->_afterController !== null) { foreach($this->_afterController as $hookProvider) { $hookProvider->doAfter(); } } }
php
public function runAfter() { if($this->_afterController !== null) { foreach($this->_afterController as $hookProvider) { $hookProvider->doAfter(); } } }
Executes the registered methods (after the controller) @return void
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/Core/HookManager.php#L156-L162
stonedz/pff2
src/Core/HookManager.php
HookManager.runBeforeView
public function runBeforeView($context = null) { if($this->_beforeView !== null) { foreach($this->_beforeView as $hookProvider) { $hookProvider->doBeforeView($context); } } }
php
public function runBeforeView($context = null) { if($this->_beforeView !== null) { foreach($this->_beforeView as $hookProvider) { $hookProvider->doBeforeView($context); } } }
Executes the registered methods (before the View) @return void
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/Core/HookManager.php#L169-L175
stonedz/pff2
src/Core/HookManager.php
HookManager.runAfterView
public function runAfterView() { if($this->_afterView !== null) { foreach($this->_afterView as $hookProvider) { $hookProvider->doAfterView(); } } }
php
public function runAfterView() { if($this->_afterView !== null) { foreach($this->_afterView as $hookProvider) { $hookProvider->doAfterView(); } } }
Executes the registered methods (after the View) @return void
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/Core/HookManager.php#L182-L188
ekyna/AdminBundle
Twig/AdminExtension.php
AdminExtension.renderResourceButton
public function renderResourceButton($resource, $action = 'view', array $options = [], array $attributes = []) { if ($this->helper->isGranted($resource, $action)) { $options = array_merge($this->getButtonOptions($action), $options); $label = null; if (array_key_exists('label', $options)) { $label = $options['label']; unset($options['label']); } elseif (array_key_exists('short', $options)) { if ($options['short']) { $label = 'ekyna_core.button.' . $action; } unset($options['short']); } if (null === $label) { $config = $this->helper->getRegistry()->findConfiguration($resource); $label = sprintf('%s.button.%s', $config->getId(), $action); } if (!array_key_exists('path', $options)) { $options['path'] = $this->helper->generateResourcePath($resource, $action); } if (!array_key_exists('type', $options)) { $options['type'] = 'link'; } return $this->ui->renderButton( $label, $options, $attributes ); } return ''; }
php
public function renderResourceButton($resource, $action = 'view', array $options = [], array $attributes = []) { if ($this->helper->isGranted($resource, $action)) { $options = array_merge($this->getButtonOptions($action), $options); $label = null; if (array_key_exists('label', $options)) { $label = $options['label']; unset($options['label']); } elseif (array_key_exists('short', $options)) { if ($options['short']) { $label = 'ekyna_core.button.' . $action; } unset($options['short']); } if (null === $label) { $config = $this->helper->getRegistry()->findConfiguration($resource); $label = sprintf('%s.button.%s', $config->getId(), $action); } if (!array_key_exists('path', $options)) { $options['path'] = $this->helper->generateResourcePath($resource, $action); } if (!array_key_exists('type', $options)) { $options['type'] = 'link'; } return $this->ui->renderButton( $label, $options, $attributes ); } return ''; }
Renders a resource action button. @param mixed $resource @param string $action @param array $options @param array $attributes @return string
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Twig/AdminExtension.php#L69-L104
cityware/city-format
src/Rtf.php
Rtf.isPlainText
function isPlainText($s) { $arrfailAt = array("*", "fonttbl", "colortbl", "datastore", "themedata"); for ($i = 0; $i < count($arrfailAt); $i++) { if (!empty($s[$arrfailAt[$i]])) { return false; } } return true; }
php
function isPlainText($s) { $arrfailAt = array("*", "fonttbl", "colortbl", "datastore", "themedata"); for ($i = 0; $i < count($arrfailAt); $i++) { if (!empty($s[$arrfailAt[$i]])) { return false; } } return true; }
For example, there may be a description of font or color palette etc.
https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Rtf.php#L23-L31
gintonicweb/admin-theme
src/View/Helper/IconsHelper.php
IconsHelper.actions
public function actions($actions) { $substitutes = $this->config('substitutes'); foreach ($actions as $name => $config) { if (array_key_exists($name, $substitutes)) { $actions[$name]['title'] = '<i class="' . $substitutes[$name] . '"></i>'; } } return $actions; }
php
public function actions($actions) { $substitutes = $this->config('substitutes'); foreach ($actions as $name => $config) { if (array_key_exists($name, $substitutes)) { $actions[$name]['title'] = '<i class="' . $substitutes[$name] . '"></i>'; } } return $actions; }
This method replaces a string by an action icon. Mainly used for action icons
https://github.com/gintonicweb/admin-theme/blob/35a3c685c2d4e462ffea022d3d89c2c0ed7104a1/src/View/Helper/IconsHelper.php#L24-L35
leprephp/routing
src/Route.php
Route.allowMethod
public function allowMethod(string $method): Route { if (!in_array($method, self::$supportedMethods)) { throw new UnsupportedMethodException($method); } $this->methods[] = $method; return $this; }
php
public function allowMethod(string $method): Route { if (!in_array($method, self::$supportedMethods)) { throw new UnsupportedMethodException($method); } $this->methods[] = $method; return $this; }
Allows an HTTP method. @param string $method The HTTP method to allow @return $this @throws UnsupportedMethodException If the method is not supported
https://github.com/leprephp/routing/blob/c76beb1d6629896be956f4e2ee76dc0e9a6ed0f1/src/Route.php#L98-L107
leprephp/routing
src/Route.php
Route.allowMethods
public function allowMethods(array $methods = []): Route { $this->methods = []; foreach ($methods as $method) { $this->allowMethod($method); } return $this; }
php
public function allowMethods(array $methods = []): Route { $this->methods = []; foreach ($methods as $method) { $this->allowMethod($method); } return $this; }
Allows a list of HTTP methods. @param string[] $methods The HTTP methods list to allow @return $this @throws UnsupportedMethodException If at least one of the methods is not supported
https://github.com/leprephp/routing/blob/c76beb1d6629896be956f4e2ee76dc0e9a6ed0f1/src/Route.php#L116-L124
leprephp/routing
src/Route.php
Route.getName
public function getName(): string { if ($this->name === null) { $this->name = $this->path; } return $this->name; }
php
public function getName(): string { if ($this->name === null) { $this->name = $this->path; } return $this->name; }
Returns the name of the route. @return string
https://github.com/leprephp/routing/blob/c76beb1d6629896be956f4e2ee76dc0e9a6ed0f1/src/Route.php#L154-L161
4devs/serializer
OptionRegistry.php
OptionRegistry.getOption
public function getOption($name, $type = null) { $type = $type ?: $this->getTypeByName($name); if (!isset($this->options[$name]) && class_exists($name)) { $name = array_search($name, $this->mapping[$type]) ?: $name; } if (!isset($this->options[$name])) { $option = $this->createOption($name, $type); $name = $option->getName(); $this->options[$name] = $option; if (!isset($this->mapping[$type][$name])) { $this->mapping[$type][$name] = get_class($option); } } return $this->options[$name]; }
php
public function getOption($name, $type = null) { $type = $type ?: $this->getTypeByName($name); if (!isset($this->options[$name]) && class_exists($name)) { $name = array_search($name, $this->mapping[$type]) ?: $name; } if (!isset($this->options[$name])) { $option = $this->createOption($name, $type); $name = $option->getName(); $this->options[$name] = $option; if (!isset($this->mapping[$type][$name])) { $this->mapping[$type][$name] = get_class($option); } } return $this->options[$name]; }
@param string $name class or name @param string|null $type @throws OptionNotFoundException @return OptionInterface
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/OptionRegistry.php#L103-L119
4devs/serializer
OptionRegistry.php
OptionRegistry.addOption
public function addOption(OptionInterface $option, $name = null) { $this->options[$name ?: $option->getName()] = $option; if ($option instanceof OptionRegistryAwareInterface) { $option->setOptionRegistry($this); } return $this; }
php
public function addOption(OptionInterface $option, $name = null) { $this->options[$name ?: $option->getName()] = $option; if ($option instanceof OptionRegistryAwareInterface) { $option->setOptionRegistry($this); } return $this; }
@param OptionInterface $option @param string|null $name @return $this
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/OptionRegistry.php#L139-L147
4devs/serializer
OptionRegistry.php
OptionRegistry.createOption
private function createOption($name, $type) { if (isset($this->mapping[$type][$name])) { $class = $this->mapping[$type][$name]; $option = new $class(); } elseif (class_exists($name)) { $option = new $name(); } else { throw new OptionNotFoundException($name, $type); } if ($option instanceof OptionRegistryAwareInterface) { $option->setOptionRegistry($this); } return $option; }
php
private function createOption($name, $type) { if (isset($this->mapping[$type][$name])) { $class = $this->mapping[$type][$name]; $option = new $class(); } elseif (class_exists($name)) { $option = new $name(); } else { throw new OptionNotFoundException($name, $type); } if ($option instanceof OptionRegistryAwareInterface) { $option->setOptionRegistry($this); } return $option; }
@param string $name @throws OptionNotFoundException @return OptionInterface
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/OptionRegistry.php#L156-L172
keeko/framework
src/foundation/AbstractModule.php
AbstractModule.getFilesPath
public function getFilesPath() { $repo = $this->getServiceContainer()->getResourceRepository(); if (!$repo->contains($this->getFilesPuliPath())) { $dir = new Directory($repo->get('/files')->getFilesystemPath()); $path = $dir->toPath()->append('managed/' . $this->model->getName()); $dir = new Directory($path); $dir->make(); } $dir = new Directory($repo->get($this->getFilesPuliPath())->getFilesystemPath()); return $dir->toPath(); }
php
public function getFilesPath() { $repo = $this->getServiceContainer()->getResourceRepository(); if (!$repo->contains($this->getFilesPuliPath())) { $dir = new Directory($repo->get('/files')->getFilesystemPath()); $path = $dir->toPath()->append('managed/' . $this->model->getName()); $dir = new Directory($path); $dir->make(); } $dir = new Directory($repo->get($this->getFilesPuliPath())->getFilesystemPath()); return $dir->toPath(); }
Returns the path for managed files for this module @return Path
https://github.com/keeko/framework/blob/a2c5d76a4ab7bd658e81d88fb3c98eee115c06ac/src/foundation/AbstractModule.php#L111-L122
keeko/framework
src/foundation/AbstractModule.php
AbstractModule.getFilesUrl
public function getFilesUrl($suffix = '') { $generator = $this->getServiceContainer()->getUrlGenerator(); return $generator->generateUrl($this->getFilesPuliPath() . '/' . $suffix); }
php
public function getFilesUrl($suffix = '') { $generator = $this->getServiceContainer()->getUrlGenerator(); return $generator->generateUrl($this->getFilesPuliPath() . '/' . $suffix); }
Returns the url for a managed file @param string $suffix @return string
https://github.com/keeko/framework/blob/a2c5d76a4ab7bd658e81d88fb3c98eee115c06ac/src/foundation/AbstractModule.php#L130-L133
keeko/framework
src/foundation/AbstractModule.php
AbstractModule.getPreferences
public function getPreferences() { if ($this->preferences === null) { $this->preferences = $this->service->getPreferenceLoader()->getModulePreferences($this->model->getId()); } return $this->preferences; }
php
public function getPreferences() { if ($this->preferences === null) { $this->preferences = $this->service->getPreferenceLoader()->getModulePreferences($this->model->getId()); } return $this->preferences; }
Returns the module's preferences @return Preferences
https://github.com/keeko/framework/blob/a2c5d76a4ab7bd658e81d88fb3c98eee115c06ac/src/foundation/AbstractModule.php#L140-L146
keeko/framework
src/foundation/AbstractModule.php
AbstractModule.getActionModel
public function getActionModel($actionName) { if (isset($this->actions[$actionName])) { return $this->actions[$actionName]['model']; } return mull; }
php
public function getActionModel($actionName) { if (isset($this->actions[$actionName])) { return $this->actions[$actionName]['model']; } return mull; }
Returns the model for the given action name @param string $actionName @return Action
https://github.com/keeko/framework/blob/a2c5d76a4ab7bd658e81d88fb3c98eee115c06ac/src/foundation/AbstractModule.php#L175-L181
keeko/framework
src/foundation/AbstractModule.php
AbstractModule.loadAction
public function loadAction($nameOrAction, $format = null) { $model = null; if ($nameOrAction instanceof Action) { $model = $nameOrAction; $actionName = $nameOrAction->getName(); } else { $actionName = $nameOrAction; } if (!isset($this->actions[$actionName])) { throw new ModuleException(sprintf('Action (%s) not found in Module (%s)', $actionName, $this->model->getName())); } if ($model === null) { $model = $this->actions[$actionName]['model']; } /* @var $action ActionSchema */ $action = $this->actions[$actionName]['action']; // check permission if (!$this->service->getFirewall()->hasActionPermission($model)) { throw new PermissionDeniedException(sprintf('Can\'t access Action (%s) in Module (%s)', $actionName, $this->model->getName())); } // check if a response is given if ($format !== null) { if (!$action->hasResponder($format)) { throw new ModuleException(sprintf('No Responder (%s) given for Action (%s) in Module (%s)', $format, $actionName, $this->model->getName())); } $responseClass = $action->getResponder($format); if (!class_exists($responseClass)) { throw new ModuleException(sprintf('Responder (%s) not found in Module (%s)', $responseClass, $this->model->getName())); } $responder = new $responseClass($this); } else { $responder = new NullResponder($this); } // gets the action class $className = $model->getClassName(); if (!class_exists($className)) { throw new ModuleException(sprintf('Action (%s) not found in Module (%s)', $className, $this->model->getName())); } $class = new $className($model, $this, $responder); // locales // ------------ $localeService = $this->getServiceContainer()->getLocaleService(); // load module l10n $file = sprintf('/%s/locales/{locale}/translations.json', $this->package->getFullName()); $localeService->loadLocaleFile($file, $class->getCanonicalName()); // // load additional l10n files // foreach ($action->getL10n() as $file) { // $file = sprintf('/%s/locales/{locale}/%s', $this->package->getFullName(), $file); // $localeService->loadLocaleFile($file, $class->getCanonicalName()); // } // // load action l10n // $file = sprintf('/%s/locales/{locale}/actions/%s', $this->package->getFullName(), $actionName); // $localeService->loadLocaleFile($file, $class->getCanonicalName()); // assets // ------------ $app = $this->getServiceContainer()->getKernel()->getApplication(); $page = $app->getPage(); // scripts foreach ($action->getScripts() as $script) { $page->addScript($script); } // styles foreach ($action->getStyles() as $style) { $page->addStyle($style); } return $class; }
php
public function loadAction($nameOrAction, $format = null) { $model = null; if ($nameOrAction instanceof Action) { $model = $nameOrAction; $actionName = $nameOrAction->getName(); } else { $actionName = $nameOrAction; } if (!isset($this->actions[$actionName])) { throw new ModuleException(sprintf('Action (%s) not found in Module (%s)', $actionName, $this->model->getName())); } if ($model === null) { $model = $this->actions[$actionName]['model']; } /* @var $action ActionSchema */ $action = $this->actions[$actionName]['action']; // check permission if (!$this->service->getFirewall()->hasActionPermission($model)) { throw new PermissionDeniedException(sprintf('Can\'t access Action (%s) in Module (%s)', $actionName, $this->model->getName())); } // check if a response is given if ($format !== null) { if (!$action->hasResponder($format)) { throw new ModuleException(sprintf('No Responder (%s) given for Action (%s) in Module (%s)', $format, $actionName, $this->model->getName())); } $responseClass = $action->getResponder($format); if (!class_exists($responseClass)) { throw new ModuleException(sprintf('Responder (%s) not found in Module (%s)', $responseClass, $this->model->getName())); } $responder = new $responseClass($this); } else { $responder = new NullResponder($this); } // gets the action class $className = $model->getClassName(); if (!class_exists($className)) { throw new ModuleException(sprintf('Action (%s) not found in Module (%s)', $className, $this->model->getName())); } $class = new $className($model, $this, $responder); // locales // ------------ $localeService = $this->getServiceContainer()->getLocaleService(); // load module l10n $file = sprintf('/%s/locales/{locale}/translations.json', $this->package->getFullName()); $localeService->loadLocaleFile($file, $class->getCanonicalName()); // // load additional l10n files // foreach ($action->getL10n() as $file) { // $file = sprintf('/%s/locales/{locale}/%s', $this->package->getFullName(), $file); // $localeService->loadLocaleFile($file, $class->getCanonicalName()); // } // // load action l10n // $file = sprintf('/%s/locales/{locale}/actions/%s', $this->package->getFullName(), $actionName); // $localeService->loadLocaleFile($file, $class->getCanonicalName()); // assets // ------------ $app = $this->getServiceContainer()->getKernel()->getApplication(); $page = $app->getPage(); // scripts foreach ($action->getScripts() as $script) { $page->addScript($script); } // styles foreach ($action->getStyles() as $style) { $page->addStyle($style); } return $class; }
Loads the given action @param Action|string $actionName @param string $format the response type (e.g. html, json, ...) @return AbstractAction
https://github.com/keeko/framework/blob/a2c5d76a4ab7bd658e81d88fb3c98eee115c06ac/src/foundation/AbstractModule.php#L190-L277
keeko/framework
src/foundation/AbstractModule.php
AbstractModule.hasPermission
public function hasPermission($action, User $user = null) { return $this->getServiceContainer()->getFirewall()->hasPermission($this->getName(), $action, $user); }
php
public function hasPermission($action, User $user = null) { return $this->getServiceContainer()->getFirewall()->hasPermission($this->getName(), $action, $user); }
Shortcut for getting permission on the given action in this module @param string $action @param User $user
https://github.com/keeko/framework/blob/a2c5d76a4ab7bd658e81d88fb3c98eee115c06ac/src/foundation/AbstractModule.php#L285-L287
songshenzong/http-client
src/Response.php
Response.unserialize
public function unserialize($serialized = null) { if ($this->response) { return Strings::unserialize((string) $this->response->getBody()); } return null; }
php
public function unserialize($serialized = null) { if ($this->response) { return Strings::unserialize((string) $this->response->getBody()); } return null; }
@param null $serialized @return mixed
https://github.com/songshenzong/http-client/blob/480c11398f37d188817fd9dda196c8dda15d53c2/src/Response.php#L92-L99
songshenzong/http-client
src/Response.php
Response.serialize
public function serialize() { if ($this->response) { return serialize((string) $this->response->getBody()); } return serialize(null); }
php
public function serialize() { if ($this->response) { return serialize((string) $this->response->getBody()); } return serialize(null); }
String representation of object @return string
https://github.com/songshenzong/http-client/blob/480c11398f37d188817fd9dda196c8dda15d53c2/src/Response.php#L106-L113
galileo/GalileoSettingBundle
Features/Context/Features/GetSettingContext.php
GetSettingContext.youTryToGetSettingWithinSection
public function youTryToGetSettingWithinSection($setting, $section) { $this->responseValue = $this->settingService->section($section)->get($setting, 'null'); }
php
public function youTryToGetSettingWithinSection($setting, $section) { $this->responseValue = $this->settingService->section($section)->get($setting, 'null'); }
@When you try to get :setting within :section @param string $setting @param string $section
https://github.com/galileo/GalileoSettingBundle/blob/a5755ca898a145bb749f6f951ff815a5b00f9acc/Features/Context/Features/GetSettingContext.php#L44-L47
phramework/phramework
src/Viewers/JSON.php
JSON.view
public function view($parameters) { if (!headers_sent()) { header('Content-Type: application/json;charset=utf-8'); } //If JSONP requested (if callback is requested though GET) if (($callback = \Phramework\Phramework::getCallback())) { echo $callback; echo '(['; echo json_encode($parameters); echo '])'; } else { echo json_encode($parameters); } }
php
public function view($parameters) { if (!headers_sent()) { header('Content-Type: application/json;charset=utf-8'); } //If JSONP requested (if callback is requested though GET) if (($callback = \Phramework\Phramework::getCallback())) { echo $callback; echo '(['; echo json_encode($parameters); echo '])'; } else { echo json_encode($parameters); } }
Display output @param array $parameters Output parameters to display
https://github.com/phramework/phramework/blob/40041d1ef23b1f8cdbd26fb112448d6a3dbef012/src/Viewers/JSON.php#L18-L33
luoxiaojun1992/lb_framework
components/db/mysql/Connection.php
Connection.getMasterConnection
protected function getMasterConnection() { $db_config = $this->containers['config']->get('mysql'); $master_db_config = $db_config['master']; $this->_master_db = isset($master_db_config['dbname']) ? $master_db_config['dbname'] : ''; $this->_master_host = isset($master_db_config['host']) ? $master_db_config['host'] : ''; $this->_master_username = isset($master_db_config['username']) ? $master_db_config['username'] : ''; $this->_master_password = isset($master_db_config['password']) ? $master_db_config['password'] : ''; $this->_master_options = isset($master_db_config['options']) ? $master_db_config['options'] : []; $this->getDsn(self::CONN_TYPE_MASTER); $this->getConnection(self::CONN_TYPE_MASTER); }
php
protected function getMasterConnection() { $db_config = $this->containers['config']->get('mysql'); $master_db_config = $db_config['master']; $this->_master_db = isset($master_db_config['dbname']) ? $master_db_config['dbname'] : ''; $this->_master_host = isset($master_db_config['host']) ? $master_db_config['host'] : ''; $this->_master_username = isset($master_db_config['username']) ? $master_db_config['username'] : ''; $this->_master_password = isset($master_db_config['password']) ? $master_db_config['password'] : ''; $this->_master_options = isset($master_db_config['options']) ? $master_db_config['options'] : []; $this->getDsn(self::CONN_TYPE_MASTER); $this->getConnection(self::CONN_TYPE_MASTER); }
Establish master node mysql connection
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/db/mysql/Connection.php#L92-L103
luoxiaojun1992/lb_framework
components/db/mysql/Connection.php
Connection.getSlaveConnection
protected function getSlaveConnection($server_hosts = []) { $db_config = $this->containers['config']->get('mysql'); $slave_config = $db_config['slaves']; if (!$server_hosts) { foreach ($slave_config as $key => $config) { $server_hosts[$key] = $config['host']; } } if ($server_hosts) { // 一致性HASH $target_host = LoadBalancer::getTargetHost($server_hosts); foreach ($server_hosts as $key => $server_host) { if ($server_host == $target_host) { $slave_target_num = $key; $target_slave_config = $slave_config[$slave_target_num]; $this->_slave_db = $target_slave_config['dbname'] ?? ''; $this->_slave_host = $target_slave_config['host'] ?? ''; $this->_slave_username = $target_slave_config['username'] ?? ''; $this->_slave_password = $target_slave_config['password'] ?? ''; $this->_slave_options = $target_slave_config['options'] ?? []; $this->getDsn(self::CONN_TYPE_SLAVE); try { $this->getConnection(self::CONN_TYPE_SLAVE); } catch (\PDOException $e) { unset($server_hosts[$slave_target_num]); $this->getSlaveConnection($server_hosts); } break; } } } }
php
protected function getSlaveConnection($server_hosts = []) { $db_config = $this->containers['config']->get('mysql'); $slave_config = $db_config['slaves']; if (!$server_hosts) { foreach ($slave_config as $key => $config) { $server_hosts[$key] = $config['host']; } } if ($server_hosts) { // 一致性HASH $target_host = LoadBalancer::getTargetHost($server_hosts); foreach ($server_hosts as $key => $server_host) { if ($server_host == $target_host) { $slave_target_num = $key; $target_slave_config = $slave_config[$slave_target_num]; $this->_slave_db = $target_slave_config['dbname'] ?? ''; $this->_slave_host = $target_slave_config['host'] ?? ''; $this->_slave_username = $target_slave_config['username'] ?? ''; $this->_slave_password = $target_slave_config['password'] ?? ''; $this->_slave_options = $target_slave_config['options'] ?? []; $this->getDsn(self::CONN_TYPE_SLAVE); try { $this->getConnection(self::CONN_TYPE_SLAVE); } catch (\PDOException $e) { unset($server_hosts[$slave_target_num]); $this->getSlaveConnection($server_hosts); } break; } } } }
Establish slave node mysql connection @param array $server_hosts
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/db/mysql/Connection.php#L110-L142
luoxiaojun1992/lb_framework
components/db/mysql/Connection.php
Connection.getExtraConnection
protected function getExtraConnection($conn) { $dbConfigs = $this->containers['config']->get('mysql'); $dbConfig = $dbConfigs[$conn]; $this->extraConfigs[$conn]['_db'] = $dbConfig['dbname'] ?? ''; $this->extraConfigs[$conn]['_host'] = $dbConfig['host'] ?? ''; $this->extraConfigs[$conn]['_username'] = $dbConfig['username'] ?? ''; $this->extraConfigs[$conn]['_password'] = $dbConfig['password'] ?? ''; $this->extraConfigs[$conn]['_options'] = $dbConfig['options'] ?? ''; $this->getDsn($conn); $this->getConnection($conn); }
php
protected function getExtraConnection($conn) { $dbConfigs = $this->containers['config']->get('mysql'); $dbConfig = $dbConfigs[$conn]; $this->extraConfigs[$conn]['_db'] = $dbConfig['dbname'] ?? ''; $this->extraConfigs[$conn]['_host'] = $dbConfig['host'] ?? ''; $this->extraConfigs[$conn]['_username'] = $dbConfig['username'] ?? ''; $this->extraConfigs[$conn]['_password'] = $dbConfig['password'] ?? ''; $this->extraConfigs[$conn]['_options'] = $dbConfig['options'] ?? ''; $this->getDsn($conn); $this->getConnection($conn); }
Establish extra mysql connection @param $conn
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/db/mysql/Connection.php#L149-L160
luoxiaojun1992/lb_framework
components/db/mysql/Connection.php
Connection.getDsn
protected function getDsn($node_type) { switch ($node_type) { case self::CONN_TYPE_MASTER: $this->_master_dsn = sprintf($this->dsn_format, static::DB_TYPE, $this->_master_host, $this->_master_db); break; case self::CONN_TYPE_SLAVE: $this->_slave_dsn = sprintf($this->dsn_format, static::DB_TYPE, $this->_slave_host, $this->_slave_db); break; default: if (in_array($node_type, $this->extraConfigs)) { $extraConfig = $this->extraConfigs[$node_type]; $this->extraDsns[$node_type] = sprintf($this->dsn_format, static::DB_TYPE, $extraConfig['_host'], $extraConfig['_db']); } else { $this->_master_dsn = sprintf($this->dsn_format, static::DB_TYPE, $this->_master_host, $this->_master_db); } } }
php
protected function getDsn($node_type) { switch ($node_type) { case self::CONN_TYPE_MASTER: $this->_master_dsn = sprintf($this->dsn_format, static::DB_TYPE, $this->_master_host, $this->_master_db); break; case self::CONN_TYPE_SLAVE: $this->_slave_dsn = sprintf($this->dsn_format, static::DB_TYPE, $this->_slave_host, $this->_slave_db); break; default: if (in_array($node_type, $this->extraConfigs)) { $extraConfig = $this->extraConfigs[$node_type]; $this->extraDsns[$node_type] = sprintf($this->dsn_format, static::DB_TYPE, $extraConfig['_host'], $extraConfig['_db']); } else { $this->_master_dsn = sprintf($this->dsn_format, static::DB_TYPE, $this->_master_host, $this->_master_db); } } }
Generate dsn @param $node_type
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/db/mysql/Connection.php#L167-L184
luoxiaojun1992/lb_framework
components/db/mysql/Connection.php
Connection.getConnection
protected function getConnection($node_type) { switch ($node_type) { case self::CONN_TYPE_MASTER: $this->write_conn = new \PDO($this->_master_dsn, $this->_master_username, $this->_master_password, $this->_master_options); break; case self::CONN_TYPE_SLAVE: $this->read_conn = new \PDO($this->_slave_dsn, $this->_slave_username, $this->_slave_password, $this->_slave_options); break; default: if (in_array($node_type, $this->extraConfigs) && in_array($node_type, $this->extraDsns)) { $extraConfig = $this->extraConfigs[$node_type]; $this->extraConns[$node_type] = new \PDO($this->extraDsns[$node_type], $extraConfig['_username'], $extraConfig['_password'], $extraConfig['_options']); } else { $this->write_conn = new \PDO($this->_master_dsn, $this->_master_username, $this->_master_password, $this->_master_options); } } }
php
protected function getConnection($node_type) { switch ($node_type) { case self::CONN_TYPE_MASTER: $this->write_conn = new \PDO($this->_master_dsn, $this->_master_username, $this->_master_password, $this->_master_options); break; case self::CONN_TYPE_SLAVE: $this->read_conn = new \PDO($this->_slave_dsn, $this->_slave_username, $this->_slave_password, $this->_slave_options); break; default: if (in_array($node_type, $this->extraConfigs) && in_array($node_type, $this->extraDsns)) { $extraConfig = $this->extraConfigs[$node_type]; $this->extraConns[$node_type] = new \PDO($this->extraDsns[$node_type], $extraConfig['_username'], $extraConfig['_password'], $extraConfig['_options']); } else { $this->write_conn = new \PDO($this->_master_dsn, $this->_master_username, $this->_master_password, $this->_master_options); } } }
Establish mysql connection @param $node_type
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/db/mysql/Connection.php#L191-L208
denkfabrik-neueMedien/silverstripe-siteinfo
src/extension/SiteInfoController.php
SiteInfoController.CountryNice
public function CountryNice() { // $config = SiteConfig::current_site_config(); return Zend_Locale::getTranslation($config->Country, "territory", i18n::get_locale()); }
php
public function CountryNice() { // $config = SiteConfig::current_site_config(); return Zend_Locale::getTranslation($config->Country, "territory", i18n::get_locale()); }
Get the full translated country name @return false|string
https://github.com/denkfabrik-neueMedien/silverstripe-siteinfo/blob/cd59ea0cf5c13678ff8efd93028d35c726670c25/src/extension/SiteInfoController.php#L49-L54
bennybi/yii2-cza-base
behaviors/TranslationBehavior.php
TranslationBehavior.saveTranslation
public function saveTranslation($language, $data, $formName = null) { $model = $this->getTranslationModel($language); $model->load($data, $formName); $dirty = $model->getDirtyAttributes(); if (empty($dirty)) { return true; // we do not need to save anything } /** @var \yii\db\ActiveQuery $relation */ $relation = $this->owner->getRelation($this->relation); $model->{key($relation->link)} = $this->owner->getPrimaryKey(); // $result = $model->save(); // if (!$result) { // Yii::info(\yii\helpers\VarDumper::dumpAsString($model->getErrors())); // } // return $result; return $model->save(); }
php
public function saveTranslation($language, $data, $formName = null) { $model = $this->getTranslationModel($language); $model->load($data, $formName); $dirty = $model->getDirtyAttributes(); if (empty($dirty)) { return true; // we do not need to save anything } /** @var \yii\db\ActiveQuery $relation */ $relation = $this->owner->getRelation($this->relation); $model->{key($relation->link)} = $this->owner->getPrimaryKey(); // $result = $model->save(); // if (!$result) { // Yii::info(\yii\helpers\VarDumper::dumpAsString($model->getErrors())); // } // return $result; return $model->save(); }
Saves current translation model @return bool
https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/behaviors/TranslationBehavior.php#L163-L182
bennybi/yii2-cza-base
behaviors/TranslationBehavior.php
TranslationBehavior.getTranslationModel
public function getTranslationModel($language = null) { if ($language === null) { $language = $this->getLanguage(); } if (!isset($this->_models[$language])) { $this->_models[$language] = $this->loadTranslation($language); } return $this->_models[$language]; }
php
public function getTranslationModel($language = null) { if ($language === null) { $language = $this->getLanguage(); } if (!isset($this->_models[$language])) { $this->_models[$language] = $this->loadTranslation($language); } return $this->_models[$language]; }
Returns a related translation model @param string|null $language the language to return. If null, current sys language @return ActiveRecord
https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/behaviors/TranslationBehavior.php#L191-L199
bennybi/yii2-cza-base
behaviors/TranslationBehavior.php
TranslationBehavior.loadTranslation
private function loadTranslation($language) { $translation = null; /** @var \yii\db\ActiveQuery $relation */ $relation = $this->owner->getRelation($this->relation); /** @var ActiveRecord $class */ $class = $relation->modelClass; $language = strtolower($language); if ($this->owner->getPrimarykey()) { $translation = $class::findOne( [$this->languageField => $language, key($relation->link) => $this->owner->getPrimarykey()] ); } if ($translation === null) { $translation = new $class; $translation->{key($relation->link)} = $this->owner->getPrimaryKey(); $translation->{$this->languageField} = $language; } return $translation; }
php
private function loadTranslation($language) { $translation = null; /** @var \yii\db\ActiveQuery $relation */ $relation = $this->owner->getRelation($this->relation); /** @var ActiveRecord $class */ $class = $relation->modelClass; $language = strtolower($language); if ($this->owner->getPrimarykey()) { $translation = $class::findOne( [$this->languageField => $language, key($relation->link) => $this->owner->getPrimarykey()] ); } if ($translation === null) { $translation = new $class; $translation->{key($relation->link)} = $this->owner->getPrimaryKey(); $translation->{$this->languageField} = $language; } return $translation; }
Loads a specific translation model @param string $language the language to return @return null|\yii\db\ActiveQuery|static
https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/behaviors/TranslationBehavior.php#L227-L245
jtallant/skimpy-engine
src/Skimpy.php
Skimpy.findBy
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) { return $this->contentRepository->findBy($criteria, $orderBy, $limit, $offset); }
php
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) { return $this->contentRepository->findBy($criteria, $orderBy, $limit, $offset); }
Finds objects by a set of criteria. @param array $criteria @param array|null $orderBy @param int|null $limit @param int|null $offset @return array
https://github.com/jtallant/skimpy-engine/blob/2fce5bc16f8745e54fd66a1c291fcea47fc1b4b2/src/Skimpy.php#L51-L54
jtallant/skimpy-engine
src/Skimpy.php
Skimpy.getArchive
public function getArchive($taxonomySlug, $termSlug) { $taxonomy = $this->taxonomyRepository->findOneBy(['uri' => $taxonomySlug]); $term = $this->termRepository->findOneBy(['taxonomy' => $taxonomy, 'slug' => $termSlug]); return [ 'taxonomy' => $taxonomy, 'term' => $term, 'items' => $term->getContentItems()->toArray(), ]; }
php
public function getArchive($taxonomySlug, $termSlug) { $taxonomy = $this->taxonomyRepository->findOneBy(['uri' => $taxonomySlug]); $term = $this->termRepository->findOneBy(['taxonomy' => $taxonomy, 'slug' => $termSlug]); return [ 'taxonomy' => $taxonomy, 'term' => $term, 'items' => $term->getContentItems()->toArray(), ]; }
@param string $taxonomySlug category, tag, product-type, etc @param string $termSlug web-development, unix, etc @return array
https://github.com/jtallant/skimpy-engine/blob/2fce5bc16f8745e54fd66a1c291fcea47fc1b4b2/src/Skimpy.php#L62-L72
jtallant/skimpy-engine
src/Skimpy.php
Skimpy.getTerm
protected function getTerm($taxonomySlug, $termSlug) { $taxonomy = $this->taxonomyRepository->findOneBy(['uri' => $taxonomySlug]); return $this->termRepository->findOneBy( [ 'taxonomy' => $taxonomy, 'slug' => $termSlug, ] ); }
php
protected function getTerm($taxonomySlug, $termSlug) { $taxonomy = $this->taxonomyRepository->findOneBy(['uri' => $taxonomySlug]); return $this->termRepository->findOneBy( [ 'taxonomy' => $taxonomy, 'slug' => $termSlug, ] ); }
@param string $taxonomySlug 'category' @param string $termSlug 'unix' @return Term|null
https://github.com/jtallant/skimpy-engine/blob/2fce5bc16f8745e54fd66a1c291fcea47fc1b4b2/src/Skimpy.php#L80-L90
borobudur-php/borobudur
src/Borobudur/Component/Mapper/ObjectMapper.php
ObjectMapper.fill
public function fill($data) { if (!$this->object) { throw new InvalidArgumentException( 'There are no object to be mapped' ); } if (!is_object($data)) { throw new InvalidArgumentException('Data should be an object'); } $data = $this->extractData($data); $allowed = $this->extractAllowedAttributes($this->class); foreach ($this->class->getProperties() as $property) { $name = $property->getName(); if (!in_array($name, $allowed, true) || !array_key_exists( $name, $data ) ) { continue; } $property->setAccessible(true); $property->setValue($this->object, $data[$name]); } return $this->object; }
php
public function fill($data) { if (!$this->object) { throw new InvalidArgumentException( 'There are no object to be mapped' ); } if (!is_object($data)) { throw new InvalidArgumentException('Data should be an object'); } $data = $this->extractData($data); $allowed = $this->extractAllowedAttributes($this->class); foreach ($this->class->getProperties() as $property) { $name = $property->getName(); if (!in_array($name, $allowed, true) || !array_key_exists( $name, $data ) ) { continue; } $property->setAccessible(true); $property->setValue($this->object, $data[$name]); } return $this->object; }
Fill object from object @param object $data @return object
https://github.com/borobudur-php/borobudur/blob/6ab0d97e1819ba0b96dc4c3bca3a7c9b1217bd44/src/Borobudur/Component/Mapper/ObjectMapper.php#L71-L102
borobudur-php/borobudur
src/Borobudur/Component/Mapper/ObjectMapper.php
ObjectMapper.map
public function map($object): MapperInterface { if (!$object && !is_object($object)) { throw new InvalidArgumentException('There is object to be mapped'); } $this->object = $object; $this->class = new ReflectionClass(get_class($object)); return $this; }
php
public function map($object): MapperInterface { if (!$object && !is_object($object)) { throw new InvalidArgumentException('There is object to be mapped'); } $this->object = $object; $this->class = new ReflectionClass(get_class($object)); return $this; }
{@inheritdoc}
https://github.com/borobudur-php/borobudur/blob/6ab0d97e1819ba0b96dc4c3bca3a7c9b1217bd44/src/Borobudur/Component/Mapper/ObjectMapper.php#L107-L117
borobudur-php/borobudur
src/Borobudur/Component/Mapper/ObjectMapper.php
ObjectMapper.extractAllowedAttributes
private function extractAllowedAttributes(ReflectionClass $reflection): array { $allowed = []; foreach ( $reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method ) { if (!$this->isGetMethod($method)) { continue; } $name = $this->getAttributeName($method); if ($this->isExclude($name)) { continue; } $allowed[] = $name; } return $allowed; }
php
private function extractAllowedAttributes(ReflectionClass $reflection): array { $allowed = []; foreach ( $reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method ) { if (!$this->isGetMethod($method)) { continue; } $name = $this->getAttributeName($method); if ($this->isExclude($name)) { continue; } $allowed[] = $name; } return $allowed; }
Extract allowed attributes. @param ReflectionClass $reflection @return array
https://github.com/borobudur-php/borobudur/blob/6ab0d97e1819ba0b96dc4c3bca3a7c9b1217bd44/src/Borobudur/Component/Mapper/ObjectMapper.php#L126-L145
borobudur-php/borobudur
src/Borobudur/Component/Mapper/ObjectMapper.php
ObjectMapper.isExclude
private function isExclude(string $key): bool { if (!empty($this->excludes) && in_array($key, $this->excludes, true)) { return true; } if (!empty($this->only) && !in_array($key, $this->only, true)) { return true; } return false; }
php
private function isExclude(string $key): bool { if (!empty($this->excludes) && in_array($key, $this->excludes, true)) { return true; } if (!empty($this->only) && !in_array($key, $this->only, true)) { return true; } return false; }
Check whether current key is excluded. @param string $key @return bool
https://github.com/borobudur-php/borobudur/blob/6ab0d97e1819ba0b96dc4c3bca3a7c9b1217bd44/src/Borobudur/Component/Mapper/ObjectMapper.php#L154-L165
borobudur-php/borobudur
src/Borobudur/Component/Mapper/ObjectMapper.php
ObjectMapper.extractData
private function extractData(object $data): array { if ($data instanceof \stdClass) { return (array) $data; } $extracted = []; $reflection = new \ReflectionObject($data); foreach ( $reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method ) { if (!$this->isGetMethod($method)) { continue; } $extracted[$this->getAttributeName($method)] = $method->invoke( $data ); } return $extracted; }
php
private function extractData(object $data): array { if ($data instanceof \stdClass) { return (array) $data; } $extracted = []; $reflection = new \ReflectionObject($data); foreach ( $reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method ) { if (!$this->isGetMethod($method)) { continue; } $extracted[$this->getAttributeName($method)] = $method->invoke( $data ); } return $extracted; }
Extract the object data to array. @param object $data @return array
https://github.com/borobudur-php/borobudur/blob/6ab0d97e1819ba0b96dc4c3bca3a7c9b1217bd44/src/Borobudur/Component/Mapper/ObjectMapper.php#L174-L195
borobudur-php/borobudur
src/Borobudur/Component/Mapper/ObjectMapper.php
ObjectMapper.getAttributeName
private function getAttributeName(ReflectionMethod $method): string { return lcfirst( substr($method->name, 0 === strpos($method->name, 'is') ? 2 : 3) ); }
php
private function getAttributeName(ReflectionMethod $method): string { return lcfirst( substr($method->name, 0 === strpos($method->name, 'is') ? 2 : 3) ); }
Get the attribute name from method. @param ReflectionMethod $method @return string
https://github.com/borobudur-php/borobudur/blob/6ab0d97e1819ba0b96dc4c3bca3a7c9b1217bd44/src/Borobudur/Component/Mapper/ObjectMapper.php#L225-L230