sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
private function getColumnTypes(): void { $rows = DataLayer::getAllTableColumns(); foreach ($rows as $row) { $key = '@'.$row['table_name'].'.'.$row['column_name'].'%type@'; $key = strtoupper($key); $value = $row['column_type']; if (isset($row['character_set_name'])) $value .= ' character set '.$row['character_set_name']; $this->replacePairs[$key] = $value; } $this->io->text(sprintf('Selected %d column types for substitution', sizeof($rows))); }
Selects schema, table, column names and the column type from MySQL and saves them as replace pairs.
entailment
private function getConstants(): void { // If myTargetConfigFilename is not set return immediately. if (!isset($this->constantClassName)) return; $reflection = new \ReflectionClass($this->constantClassName); $constants = $reflection->getConstants(); foreach ($constants as $name => $value) { if (!is_numeric($value)) $value = "'".$value."'"; $this->replacePairs['@'.$name.'@'] = $value; } $this->io->text(sprintf('Read %d constants for substitution from <fso>%s</fso>', sizeof($constants), OutputFormatter::escape($reflection->getFileName()))); }
Reads constants set the PHP configuration file and adds them to the replace pairs.
entailment
private function getDuplicates(): array { // First pass make lookup table by method_name. $lookup = []; foreach ($this->sources as $source) { if (isset($source['method_name'])) { if (!isset($lookup[$source['method_name']])) { $lookup[$source['method_name']] = []; } $lookup[$source['method_name']][] = $source; } } // Second pass find duplicate sources. $duplicates_sources = []; $duplicates_methods = []; foreach ($this->sources as $source) { if (sizeof($lookup[$source['method_name']])>1) { $duplicates_sources[$source['path_name']] = $source; $duplicates_methods[$source['method_name']] = $lookup[$source['method_name']]; } } return [$duplicates_sources, $duplicates_methods]; }
Returns all elements in {@link $sources} with duplicate method names. @return array[]
entailment
private function getOldStoredRoutinesInfo(): void { $this->rdbmsOldMetadata = []; $routines = DataLayer::getRoutines(); foreach ($routines as $routine) { $this->rdbmsOldMetadata[$routine['routine_name']] = $routine; } }
Retrieves information about all stored routines in the current schema.
entailment
private function loadAll(): void { $this->findSourceFiles(); $this->detectNameConflicts(); $this->getColumnTypes(); $this->readStoredRoutineMetadata(); $this->getConstants(); $this->getOldStoredRoutinesInfo(); $this->getCorrectSqlMode(); $this->loadStoredRoutines(); // Drop obsolete stored routines. $this->dropObsoleteRoutines(); // Remove metadata of stored routines that have been removed. $this->removeObsoleteMetadata(); $this->io->writeln(''); // Write the metadata to file. $this->writeStoredRoutineMetadata(); }
Loads all stored routines into MySQL.
entailment
private function loadList(array $fileNames): void { $this->findSourceFilesFromList($fileNames); $this->detectNameConflicts(); $this->getColumnTypes(); $this->readStoredRoutineMetadata(); $this->getConstants(); $this->getOldStoredRoutinesInfo(); $this->getCorrectSqlMode(); $this->loadStoredRoutines(); // Write the metadata to file. $this->writeStoredRoutineMetadata(); }
Loads all stored routines in a list into MySQL. @param string[] $fileNames The list of files to be loaded.
entailment
private function loadStoredRoutines(): void { // Log an empty line. $this->io->writeln(''); // Sort the sources by routine name. usort($this->sources, function ($a, $b) { return strcmp($a['routine_name'], $b['routine_name']); }); // Process all sources. foreach ($this->sources as $filename) { $routineName = $filename['routine_name']; $helper = new RoutineLoaderHelper($this->io, $filename['path_name'], $this->phpStratumMetadata[$routineName] ?? null, $this->replacePairs, $this->rdbmsOldMetadata[$routineName] ?? null, $this->sqlMode, $this->characterSet, $this->collate); try { $this->phpStratumMetadata[$routineName] = $helper->loadStoredRoutine(); } catch (RoutineLoaderException $e) { $messages = [$e->getMessage(), sprintf("Failed to load file '%s'", $filename['path_name'])]; $this->io->error($messages); $this->errorFilenames[] = $filename['path_name']; unset($this->phpStratumMetadata[$routineName]); } catch (DataLayerException $e) { if ($e->isQueryError()) { // Exception is caused by a SQL error. Log the message and the SQL statement with highlighting the error. $this->io->error($e->getShortMessage()); $this->io->text($e->getMarkedQuery()); } else { $this->io->error($e->getMessage()); } } } }
Loads all stored routines.
entailment
private function logOverviewErrors(): void { if (!empty($this->errorFilenames)) { $this->io->warning('Routines in the files below are not loaded:'); $this->io->listing($this->errorFilenames); } }
Logs the source files that were not successfully loaded into MySQL.
entailment
private function methodName(string $routineName): ?string { if ($this->nameMangler!==null) { /** @var NameMangler $mangler */ $mangler = $this->nameMangler; return $mangler::getMethodName($routineName); } return null; }
Returns the method name in the wrapper for a stored routine. Returns null when name mangler is not set. @param string $routineName The name of the routine. @return null|string
entailment
private function readStoredRoutineMetadata(): void { if (file_exists($this->phpStratumMetadataFilename)) { $this->phpStratumMetadata = (array)json_decode(file_get_contents($this->phpStratumMetadataFilename), true); if (json_last_error()!=JSON_ERROR_NONE) { throw new RuntimeException("Error decoding JSON: '%s'.", json_last_error_msg()); } } }
Reads the metadata of stored routines from the metadata file.
entailment
private function removeObsoleteMetadata(): void { // 1 pass through $mySources make new array with routine_name is key. $clean = []; foreach ($this->sources as $source) { $routine_name = $source['routine_name']; if (isset($this->phpStratumMetadata[$routine_name])) { $clean[$routine_name] = $this->phpStratumMetadata[$routine_name]; } } $this->phpStratumMetadata = $clean; }
Removes obsolete entries from the metadata of all stored routines.
entailment
private function writeStoredRoutineMetadata(): void { $json_data = json_encode($this->phpStratumMetadata, JSON_PRETTY_PRINT); if (json_last_error()!=JSON_ERROR_NONE) { throw new RuntimeException("Error of encoding to JSON: '%s'.", json_last_error_msg()); } // Save the metadata. $this->writeTwoPhases($this->phpStratumMetadataFilename, $json_data); }
Writes the metadata of all stored routines to the metadata file.
entailment
public function offsetGet($offset) { if (isset($this->data[$offset])) { return $this->data[$offset]; } return false; }
Get. @param string $offset @return mixed
entailment
public static function canComment($hook, $type, $permission, $params) { $entity = elgg_extract('entity', $params); if (!$entity instanceof Comment) { return $permission; } if ($entity->getDepthToOriginalContainer() >= (int) elgg_get_plugin_setting('max_comment_depth', 'hypeInteractions')) { return false; } }
Disallows commenting on comments once a certain depth has been reached @param string $hook "permissions_check:comment" @param string $type "object" @param bool $permission Current permission @param array $params Hook params @param bool
entailment
public static function canEditAnnotation($hook, $type, $permission, $params) { $annotation = elgg_extract('annotation', $params); $user = elgg_extract('user', $params); if ($annotation instanceof ElggAnnotation && $annotation->name == 'likes') { // only owners of original annotation (or users who can edit these owners) $ann_owner = $annotation->getOwnerEntity(); return ($ann_owner && $ann_owner->canEdit($user->guid)); } return $permission; }
Fixes editing permissions on likes @param string $hook "permissions_check" @param string $type "annotation" @param bool $permission Current permission @param array $params Hook params @return boolean
entailment
public function disabled() { $this->attributes->addAttributeClass('disabled'); if ($this->childNodes->first() instanceof Item) { $this->childNodes->first()->disabled(); } }
Item::disabled
entailment
public function render() { $output[] = $this->open(); if ( ! empty($this->heading)) { $output[] = $this->heading . PHP_EOL; } if ( ! empty($this->paragraph)) { if ($this->textContent->count()) { foreach ($this->textContent as $textContent) { $this->paragraph->textContent->push($textContent); } } $output[] = $this->paragraph . PHP_EOL; } elseif ($this->textContent->count()) { $output[] = implode('', $this->textContent->getArrayCopy()); } if ($this->hasChildNodes()) { foreach ($this->childNodes as $childNode) { $output[] = $childNode . PHP_EOL; } } $output[] = $this->close(); return implode('', $output); }
Item::render @return string
entailment
public function store($offset, $value) { $element = new Element('meta'); if ($offset === 'http-equiv') { $element->attributes[ 'http-equiv' ] = $value[ 'property' ]; $element->attributes[ 'content' ] = $value[ 'content' ]; parent::store(camelcase('http_equiv_' . $value[ 'property' ]), $element); } else { $element->attributes[ 'name' ] = $offset; if (is_array($value)) { if (is_numeric(key($value))) { $element->attributes[ 'content' ] = implode(', ', $value); } else { $newValue = []; foreach ($value as $key => $val) { $newValue[] = $key . '=' . $val; } $element->attributes[ 'content' ] = implode(', ', $newValue); } } else { $element->attributes[ 'content' ] = $value; } if (in_array($offset, ['description']) and $this->opengraph instanceof Meta\Opengraph) { $this->opengraph->setObject($element->attributes[ 'name' ], $element->attributes[ 'content' ]); } parent::store(camelcase($offset), $element); } }
Meta::store @param string $offset @param mixed $value
entailment
public function transform() { $object = $this->resource; $data = $object instanceof Collection || $object instanceof AbstractPaginator ? $object->map([$this, 'transformResource'])->toArray() : $this->transformResource($object); if ($object instanceof AbstractPaginator) { $this->withMeta(array_merge( $this->getExtra('meta', []), Arr::except($object->toArray(), ['data']) )); } $data = array_filter(compact('data') + $this->extras); ksort($data); return $data; }
Get a displayable API output for the given object. @return array
entailment
public function toResponse($status = 200, array $headers = [], $options = 0) { return new JsonResponse($this->transform(), $status, $headers, $options); }
Get the instance as a json response object. @param int $status @param array $headers @param int $options @return \Illuminate\Http\JsonResponse
entailment
public static function riverMenuSetup($hook, $type, $return, $params) { if (!elgg_is_logged_in()) { return $return; } $remove = array('comment'); foreach ($return as $key => $item) { if ($item instanceof ElggMenuItem&& in_array($item->getName(), $remove)) { unset($return[$key]); } } return $return; }
Filters river menu @param string $hook "register" @param string $type "menu:river" @param array $return Menu items @param array $params Hook params @return array
entailment
public static function interactionsMenuSetup($hook, $type, $menu, $params) { $entity = elgg_extract('entity', $params, false); /* @var ElggEntity $entity */ if (!elgg_instanceof($entity)) { return $menu; } $active_tab = elgg_extract('active_tab', $params); // Commenting $comments_count = $entity->countComments(); $can_comment = $entity->canComment(); if ($can_comment) { $menu[] = ElggMenuItem::factory(array( 'name' => 'comments', 'text' => ($entity instanceof Comment) ? elgg_echo('interactions:reply:create') : elgg_echo('interactions:comment:create'), 'href' => "stream/comments/$entity->guid", 'priority' => 200, 'data-trait' => 'comments', 'item_class' => 'interactions-action', )); } if ($can_comment || $comments_count) { $menu[] = ElggMenuItem::factory(array( 'name' => 'comments:badge', 'text' => elgg_view('framework/interactions/elements/badge', array( 'entity' => $entity, 'icon' => 'comments', 'type' => 'comments', 'count' => $comments_count, )), 'href' => "stream/comments/$entity->guid", 'selected' => ($active_tab == 'comments'), 'priority' => 100, 'data-trait' => 'comments', 'item_class' => 'interactions-tab', )); } if (elgg_is_active_plugin('likes')) { // Liking and unliking $likes_count = $entity->countAnnotations('likes'); $can_like = $entity->canAnnotate(0, 'likes'); $does_like = elgg_annotation_exists($entity->guid, 'likes'); if ($can_like) { $before_text = elgg_echo('interactions:likes:before'); $after_text = elgg_echo('interactions:likes:after'); $menu[] = ElggMenuItem::factory(array( 'name' => 'likes', 'text' => ($does_like) ? $after_text : $before_text, 'href' => "action/stream/like?guid=$entity->guid", 'is_action' => true, 'priority' => 400, 'link_class' => 'interactions-state-toggler', 'item_class' => 'interactions-action', // Attrs for JS toggle 'data-guid' => $entity->guid, 'data-trait' => 'likes', 'data-state' => ($does_like) ? 'after' : 'before', )); } if ($can_like || $likes_count) { $menu[] = ElggMenuItem::factory(array( 'name' => 'likes:badge', 'text' => elgg_view('framework/interactions/elements/badge', array( 'entity' => $entity, 'icon' => 'likes', 'type' => 'likes', 'count' => $likes_count, )), 'href' => "stream/likes/$entity->guid", 'selected' => ($active_tab == 'likes'), 'data-trait' => 'likes', 'priority' => 300, 'item_class' => 'interactions-tab', )); } } return $menu; }
Setups entity interactions menu @param string $hook "register" @param string $type "menu:interactions" @param array $menu Menu @param array $params Hook parameters @uses $params['entity'] An entity that we are interacting with @uses $params['active_tab'] Currently active tab, default to 'comments' @return array
entailment
public static function entityMenuSetup($hook, $type, $menu, $params) { $entity = elgg_extract('entity', $params); if (!$entity instanceof Comment) { return; } if ($entity->canEdit()) { $menu[] = ElggMenuItem::factory(array( 'name' => 'edit', 'text' => elgg_echo('edit'), 'href' => "stream/edit/$entity->guid", 'priority' => 800, 'item_class' => 'interactions-edit', 'data' => [ 'icon' => 'pencil', ] )); } if ($entity->canDelete()) { $menu[] = ElggMenuItem::factory(array( 'name' => 'delete', 'text' => elgg_echo('delete'), 'href' => "action/comment/delete?guid=$entity->guid", 'is_action' => true, 'priority' => 900, 'confirm' => true, 'item_class' => 'interactions-delete', 'data' => [ 'icon' => 'delete', ] )); } return $menu; }
Setups comment menu @param string $hook "register" @param string $type "menu:interactions" @param array $menu Menu @param array $params Hook parameters @return array
entailment
public function register(Application $app) { $app[Controller::INDEX] = $app->share(function () use ($app) { return new Controller\IndexController($app[UseCase::LOGIN]); }); $app[Controller::ACCOUNT] = $app->share(function () use ($app) { return new Controller\AccountController($app[UseCase::REGISTRATION], $app[Repository::USER]); }); $app[Controller::CITY] = $app->share(function () use ($app) { return new Controller\CityController( $app[UseCase::LIST_DIRECTIONS], $app[Repository::USER], $app[Repository::CITY]); }); }
Registers services on the given app. This method should only be used to configure services and parameters. It should not get services. @param Application $app An Application instance
entailment
public function write($session_id, $session_data) { return $this->memcached->set($session_id, $session_data, $this->expire); }
Write session data to storage. http://php.net/manual/en/sessionhandler.write.php. @param string $session_id @param string $session_data @return bool
entailment
public function destroy($session_id) { if ($this->memcached->delete($session_id)) { return true; } if ($this->memcached->getResultCode() === 16) { return true; } return false; }
Destroy session data. http://php.net/manual/en/sessionhandler.destroy.php. @param string $session_id @return bool
entailment
public function add(array $item) { $item = array_merge([ 'id' => null, 'sku' => null, 'quantity' => 1, 'price' => 0, 'discount' => 0, 'name' => null, 'options' => [], ], $item); // set sku $sku = empty($item[ 'sku' ]) ? $item[ 'id' ] : $item[ 'sku' ]; // set sub-total $item[ 'subTotal' ][ 'price' ] = $item[ 'price' ] * $item[ 'quantity' ]; $item[ 'subTotal' ][ 'discount' ] = 0; if (is_numeric($item[ 'discount' ])) { $item[ 'subTotal' ][ 'discount' ] = $item[ 'subTotal' ][ 'price' ] - $item[ 'discount' ]; } elseif (is_string($item[ 'discount' ]) && strpos($item[ 'discount' ], '+') !== false) { $discounts = explode('+', $item[ 'discount' ]); if (count($discounts)) { $item[ 'subTotal' ][ 'discount' ] = $item[ 'subTotal' ][ 'price' ] * (intval(reset($discounts)) / 100); foreach (array_slice($discounts, 1) as $discount) { $item[ 'subTotal' ][ 'discount' ] += $item[ 'subTotal' ][ 'discount' ] * (intval($discount) / 100); } } } elseif (is_string($item[ 'discount' ]) && strpos($item[ 'discount' ], '%') !== false) { $item[ 'subTotal' ][ 'discount' ] = $item[ 'subTotal' ][ 'price' ] * (intval($item[ 'discount' ]) / 100); } $item[ 'subTotal' ][ 'weight' ] = $item[ 'weight' ] * $item[ 'quantity' ]; $this->storage[ $sku ] = $item; }
Cart::add @param array $item
entailment
public function update($sku, array $item) { if ($this->offsetExists($sku)) { $item = array_merge($this->offsetGet($sku), $item); // update sub-total $item[ 'subTotal' ][ 'price' ] = $item[ 'price' ] * $item[ 'quantity' ]; $item[ 'subTotal' ][ 'weight' ] = $item[ 'weight' ] * $item[ 'quantity' ]; $this->storage[ $sku ] = $item; return true; } return false; }
Cart::update @param string $sku @param array $item @return bool
entailment
public function getTotalWeight() { $totalWeight = 0; if ($this->count()) { foreach ($this->storage as $id => $item) { if (isset($item[ 'subTotal' ][ 'weight' ])) { $totalWeight += (int)$item[ 'weight' ]; } } } return $totalWeight; }
Cart::getTotalWeight @return int
entailment
public function getTotalPrice() { $totalPrice = 0; if ($this->count()) { foreach ($this->storage as $id => $item) { if (isset($item[ 'subTotal' ][ 'price' ])) { $totalPrice += (int)$item[ 'price' ]; } } } return $totalPrice; }
Cart::getTotalPrice @return int
entailment
public function contextOutline() { $this->attributes->replaceAttributeClass($this->contextualClassPrefix . '-', $this->contextualClassPrefix . '-outline-'); $this->setContextualClassPrefix($this->contextualClassPrefix . '-outline'); return $this; }
ContextualClassSetterTrait::contextOutline @return static
entailment
public function setContextualClassSuffix($suffix) { $this->attributes->removeAttributeClass([ $this->contextualClassPrefix . '-' . 'default', $this->contextualClassPrefix . '-' . 'primary', $this->contextualClassPrefix . '-' . 'secondary', $this->contextualClassPrefix . '-' . 'success', $this->contextualClassPrefix . '-' . 'info', $this->contextualClassPrefix . '-' . 'warning', $this->contextualClassPrefix . '-' . 'danger', $this->contextualClassPrefix . '-' . 'neutral', ]); $this->attributes->addAttributeClass($this->contextualClassPrefix . '-' . $suffix); return $this; }
ContextualClassSetterTrait::setContextualClassSuffix @param string $suffix @return static
entailment
protected function generateBody(array $params, array $columns): void { $uniqueColumns = $this->checkUniqueKeys($columns); $limit = ($uniqueColumns==null); $this->codeStore->append(sprintf('delete from %s', $this->tableName)); $this->codeStore->append('where'); $first = true; foreach ($params as $column) { if ($first) { $format = sprintf("%%%ds %%s = p_%%s", 1); $this->codeStore->appendToLastLine(sprintf($format, '', $column['column_name'], $column['column_name'])); } else { $format = sprintf("and%%%ds %%s = p_%%s", 3); $this->codeStore->append(sprintf($format, '', $column['column_name'], $column['column_name'])); } $first = false; } if ($limit) { $this->codeStore->append('limit 0,1'); } $this->codeStore->append(';'); }
Generate body part. @param array[] $columns Columns from table. @param array[] $params Params for where block.
entailment
public function createHelp($text = null, $tagName = 'span') { $help = new Group\Help($tagName); if (isset($text)) { $help->textContent->push($text); } $this->childNodes->push($help); return $this->help = $this->childNodes->last(); }
Group::createHelp @param string|null $text @param string $tagName @return \O2System\Framework\Libraries\Ui\Components\Form\Group\Help
entailment
public function render() { if ($this->help instanceof Group\Help) { foreach ($this->childNodes as $childNode) { if ($childNode instanceof Elements\Input or $childNode instanceof Elements\Checkbox or $childNode instanceof Elements\Select or $childNode instanceof Elements\Textarea ) { if (false !== ($attributeId = $childNode->attributes->getAttributeId())) { $this->help->attributes->setAttributeId('help-' . $attributeId); $childNode->attributes->addAttribute('aria-describedby', 'help-' . $attributeId); } } } } return parent::render(); }
Group::render @return string
entailment
public function createTokenResponse( ServerRequestInterface $request, Client $client = null, TokenOwnerInterface $owner = null ): ResponseInterface { $postParams = $request->getParsedBody(); $refreshToken = $postParams['refresh_token'] ?? null; if (null === $refreshToken) { throw OAuth2Exception::invalidRequest('Refresh token is missing'); } // We can fetch the actual token, and validate it /** @var RefreshToken $refreshToken */ $refreshToken = $this->refreshTokenService->getToken((string) $refreshToken); if (null === $refreshToken || $refreshToken->isExpired()) { throw OAuth2Exception::invalidGrant('Refresh token is expired'); } // We can now create a new access token! First, we need to make some checks on the asked scopes, // because according to the spec, a refresh token can create an access token with an equal or lesser // scope, but not more $scope = $postParams['scope'] ?? null; $scopes = is_string($scope) ? explode(' ', $scope) : $refreshToken->getScopes(); if (! $refreshToken->matchScopes($scopes)) { throw OAuth2Exception::invalidScope( 'The scope of the new access token exceeds the scope(s) of the refresh token' ); } $owner = $refreshToken->getOwner(); $accessToken = $this->accessTokenService->createToken($owner, $client, $scopes); // We may want to revoke the old refresh token if ($this->serverOptions->getRotateRefreshTokens()) { if ($this->serverOptions->getRevokeRotatedRefreshTokens()) { $this->refreshTokenService->deleteToken($refreshToken); } $refreshToken = $this->refreshTokenService->createToken($owner, $client, $scopes); } // We can generate the response! return $this->prepareTokenResponse($accessToken, $refreshToken, true); }
{@inheritdoc}
entailment
protected function connect(array $settings): void { $host = $this->getSetting($settings, true, 'database', 'host'); $user = $this->getSetting($settings, true, 'database', 'user'); $password = $this->getSetting($settings, true, 'database', 'password'); $database = $this->getSetting($settings, true, 'database', 'database'); MetadataDataLayer::setIo($this->io); MetadataDataLayer::connect($host, $user, $password, $database); }
Connects to a MySQL instance. @param array $settings The settings from the configuration file.
entailment
public static function createNewAccessToken( int $ttl, TokenOwnerInterface $owner = null, Client $client = null, $scopes = null ): AccessToken { return static::createNew($ttl, $owner, $client, $scopes); }
Create a new AccessToken @param string|string[]|Scope[]|null $scopes
entailment
public function createCard($contextualClass = Card::DEFAULT_CONTEXT, $inverse = false) { $card = new Card($contextualClass, $inverse); $this->childNodes->push($card); return $this->childNodes->last(); }
Group::createCard @param string $contextualClass @param bool $inverse @return Card
entailment
public function createInput(array $attributes = []) { $field = new Form\Elements\Input(); if (count($attributes)) { foreach ($attributes as $name => $value) { $field->attributes->addAttribute($name, $value); if ($name === 'name') { $this->entity->setEntityName('input-' . $value); if ( ! array_key_exists('id', $attributes)) { $field->attributes->setAttributeId('input-' . $value); } } } } return $this->input = $field; }
Group::createInput @param array $attributes @return \O2System\Framework\Libraries\Ui\Components\Form\Elements\Input
entailment
public function createSelect(array $options = [], $selected = null, array $attributes = []) { $field = new Form\Elements\Select(); if (count($options)) { $field->createOptions($options, $selected); } if (count($attributes)) { foreach ($attributes as $name => $value) { $field->attributes->addAttribute($name, $value); if ($name === 'name') { $this->entity->setEntityName('input-' . $value); if ( ! array_key_exists('id', $attributes)) { $field->attributes->setAttributeId('input-' . $value); } } } } return $this->input = $field; }
Group::createSelect @param array $options @param string|null $selected @param array $attributes @return \O2System\Framework\Libraries\Ui\Components\Form\Elements\Select
entailment
public function createAddon($node = null, $position = Group\AddOn::ADDON_LEFT) { $addOn = new Group\AddOn($position); if (isset($node)) { if ($node instanceof Element) { $addOn->childNodes->push($node); } else { $addOn->textContent->push($node); } } $this->addOns->push($addOn); return $this->addOns->last(); }
Group::createAddon @param Element|string|null $node @param int $position @return mixed
entailment
public function render() { $addOnsLeft = []; $addOnsRight = []; if ($this->addOns->count()) { foreach ($this->addOns as $addOn) { if ($addOn->position === Group\AddOn::ADDON_LEFT) { $addOnsLeft[] = $addOn; } else { $addOnsRight[] = $addOn; } } } $output[] = $this->open(); // AddOn Left if (count($addOnsLeft)) { $prependContainer = new Element('div'); $prependContainer->attributes->addAttributeClass('input-group-prepend'); foreach ($addOnsLeft as $addOn) { $prependContainer->childNodes->push($addOn); } $output[] = $prependContainer; } // Input $output[] = $this->input; // AddOn Right if (count($addOnsRight)) { $appendContainer = new Element('div'); $appendContainer->attributes->addAttributeClass('input-group-prepend'); foreach ($addOnsRight as $addOn) { $appendContainer->childNodes->push($addOn); } $output[] = $appendContainer; } if ($this->hasChildNodes()) { foreach ($this->childNodes as $childNode) { if ($childNode instanceof Components\Dropdown) { $childNode->attributes->removeAttributeClass('dropdown'); $childNode->attributes->addAttributeClass('input-group-btn'); $childNode->toggle->tagName = 'a'; $childNode->toggle->attributes->removeAttribute('type'); } $output[] = $childNode; } } if ($this->hasTextContent()) { $output[] = implode(PHP_EOL, $this->textContent->getArrayCopy()); } $output[] = $this->close(); return implode(PHP_EOL, $output); }
Group::render @return string
entailment
public function floatLeft($size = null) { if (empty($size)) { $this->attributes->addAttributeClass('float-left'); } elseif (in_array($size, ['xs', 'sm', 'md', 'lg', 'xl'])) { $this->attributes->addAttributeClass('float-' . $size . '-left'); } return $this; }
FloatUtilitiesTrait::floatLeft @param string|null $size @return static
entailment
public function floatRight($size = null) { if (empty($size)) { $this->attributes->addAttributeClass('float-right'); } elseif (in_array($size, ['xs', 'sm', 'md', 'lg', 'xl'])) { $this->attributes->addAttributeClass('float-' . $size . '-right'); } return $this; }
FloatUtilitiesTrait::floatRight @param string|null $size @return static
entailment
public function floatNone($size = null) { if (empty($size)) { $this->attributes->addAttributeClass('float-none'); } elseif (in_array($size, ['xs', 'sm', 'md', 'lg', 'xl'])) { $this->attributes->addAttributeClass('float-' . $size . '-none'); } return $this; }
FloatUtilitiesTrait::floatNone @param string|null $size @return static
entailment
public function createHeader($text, $tagName = 'h6') { $header = new Element($tagName); $header->attributes->addAttributeClass('dropdown-header'); $header->textContent->push($text); $this->childNodes->push($header); return $this->childNodes->last(); }
Menu::createHeader @param string $text @param string $tagName @return Element
entailment
public function createItem($label = null, $href = null) { $link = new Link($label, $href); $link->attributes->addAttributeClass('dropdown-item'); $this->childNodes->push($link); return $this->childNodes->last(); }
Menu::createItem @param string|null $label @param string|null $href @return Link
entailment
public function createDivider() { $element = new Element('div'); $element->attributes->addAttributeClass('dropdown-divider'); $this->childNodes->push($element); return $this->childNodes->last(); }
Menu::createDivider @return Element
entailment
public function map(array $options, Banner $banner) { $bannerOptions = get_object_vars($banner); $validatedOptions = array(); foreach ($bannerOptions as $name => $value) { $validatedOptions[$name] = empty($options[$name]) ? $value : $options[$name]; } return $validatedOptions; }
Map additional options used by Banner object. @param array $options @param \EzSystems\PrivacyCookieBundle\Banner\Banner $banner @return array
entailment
private function registerApiMiddleware() { /** @var \Illuminate\Contracts\Config\Repository $config */ $config = $this->app['config']; foreach ($config->get('api-helper.middleware', []) as $name => $class) { $this->aliasMiddleware($name, $class); }; }
Register the API route Middleware.
entailment
public function &__get($property) { $get[ $property ] = false; // CodeIgniter property aliasing if ($property === 'load') { $property = 'loader'; } if (services()->has($property)) { return services()->get($property); } elseif (o2system()->__isset($property)) { return o2system()->__get($property); } elseif ($property === 'model') { return models('controller'); } return $get[ $property ]; }
Commander::__get @param string $property @return mixed|\O2System\Framework\Containers\Models|\O2System\Framework\Models\NoSql\Model|\O2System\Framework\Models\Sql\Model
entailment
public function getResult() { if ($this->map->currentModel->row instanceof Sql\DataObjects\Result\Row) { $criteria = $this->map->currentModel->row->offsetGet($this->map->currentForeignKey); $field = $this->map->referenceTable . '.' . $this->map->referencePrimaryKey; if ($result = $this->map->referenceModel->find($criteria, $field, 1)) { return $result; } } return false; }
BelongsTo::getResult @return array|bool|\O2System\Framework\Models\Sql\DataObjects\Result\Row
entailment
protected function prepareTokenResponse( AccessToken $accessToken, RefreshToken $refreshToken = null, bool $useRefreshTokenScopes = false ): ResponseInterface { $owner = $accessToken->getOwner(); $scopes = $useRefreshTokenScopes ? $refreshToken->getScopes() : $accessToken->getScopes(); $responseBody = [ 'access_token' => $accessToken->getToken(), 'token_type' => 'Bearer', 'expires_in' => $accessToken->getExpiresIn(), 'scope' => implode(' ', $scopes), 'owner_id' => $owner ? $owner->getTokenOwnerId() : null, ]; if (null !== $refreshToken) { $responseBody['refresh_token'] = $refreshToken->getToken(); } return new Response\JsonResponse(array_filter($responseBody)); }
Prepare the actual HttpResponse for the token
entailment
protected static function parseButton(ButtonInterface $button, array $args) { $button->setActive(ArrayHelper::get($args, "active", false)); $button->setBlock(ArrayHelper::get($args, "block", false)); $button->setContent(ArrayHelper::get($args, "content")); $button->setDisabled(ArrayHelper::get($args, "disabled", false)); $button->setSize(ArrayHelper::get($args, "size")); $button->setTitle(ArrayHelper::get($args, "title")); return $button; }
Parses a button. @param ButtonInterface $button The button. @param array $args The arguments. @return ButtonInterface Returns the button.
entailment
public function setName($name) { $xName = explode(' ', $name); $firstName = $xName[ 0 ]; array_shift($xName); $lastName = implode(' ', $xName); $this->setObject('first_name', $firstName); $this->setObject('last_name', $lastName); return $this; }
Profile::setName @param string $name @return static
entailment
public function setGender($gender) { $gender = strtolower($gender); if (in_array($gender, ['male', 'female'])) { $this->setObject('gender', $gender); } return $this; }
Profile::setGender @param string $gender @return static
entailment
public function execute() { parent::execute(); if (empty($this->optionFilename)) { output()->write( (new Format()) ->setContextualClass(Format::DANGER) ->setString(language()->getLine('CLI_MAKE_WIDGET_E_NAME')) ->setNewLinesAfter(1) ); exit(EXIT_ERROR); } if (strpos($this->optionPath, 'Widgets') === false) { $widgetPath = $this->optionPath . 'Widgets' . DIRECTORY_SEPARATOR . $this->optionFilename . DIRECTORY_SEPARATOR; } else { $widgetPath = $this->optionPath . $this->optionFilename . DIRECTORY_SEPARATOR; } if ( ! is_dir($widgetPath)) { mkdir($widgetPath, 0777, true); } else { output()->write( (new Format()) ->setContextualClass(Format::DANGER) ->setString(language()->getLine('CLI_MAKE_WIDGET_E_EXISTS', [$widgetPath])) ->setNewLinesAfter(1) ); exit(EXIT_ERROR); } $jsonProperties[ 'name' ] = readable( pathinfo($widgetPath, PATHINFO_FILENAME), true ); if (empty($this->namespace)) { @list($moduleDirectory, $moduleName) = explode('Widgets', dirname($widgetPath)); $namespace = loader()->getDirNamespace($moduleDirectory) . 'Widgets' . '\\' . prepare_class_name( $this->optionFilename ) . '\\'; } else { $namespace = prepare_class_name($this->namespace); $jsonProperties[ 'namespace' ] = rtrim($namespace, '\\') . '\\'; } $jsonProperties[ 'created' ] = date('d M Y'); loader()->addNamespace($namespace, $widgetPath); $fileContent = json_encode($jsonProperties, JSON_PRETTY_PRINT); $filePath = $widgetPath . 'widget.json'; file_put_contents($filePath, $fileContent); $this->optionPath = $widgetPath; $this->optionFilename = prepare_filename($this->optionFilename) . '.php'; (new Presenter()) ->optionPath($this->optionPath) ->optionFilename($this->optionFilename); if (is_dir($widgetPath)) { output()->write( (new Format()) ->setContextualClass(Format::SUCCESS) ->setString(language()->getLine('CLI_MAKE_WIDGET_S_MAKE', [$widgetPath])) ->setNewLinesAfter(1) ); exit(EXIT_SUCCESS); } }
Widget::execute
entailment
final protected function fetchSubModels() { $reflection = new \ReflectionClass(get_called_class()); // Define called model class filepath $filePath = $reflection->getFileName(); // Define filename for used as subdirectory name $filename = pathinfo($filePath, PATHINFO_FILENAME); // Get model class directory name $dirName = dirname($filePath) . DIRECTORY_SEPARATOR; // Get sub models or siblings models if ($filename === 'Model' || $filename === modules()->top()->getDirName()) { $subModelsDirName = dirname($dirName) . DIRECTORY_SEPARATOR . 'Models' . DIRECTORY_SEPARATOR; if (is_dir($subModelsDirName)) { $subModelPath = $subModelsDirName; } } elseif (is_dir($subModelsDirName = $dirName . $filename . DIRECTORY_SEPARATOR)) { $subModelPath = $subModelsDirName; } if (isset($subModelPath)) { loader()->addNamespace($reflection->name, $subModelPath); foreach (glob($subModelPath . '*.php') as $filepath) { if ($filepath === $filePath) { continue; } $this->validSubModels[ camelcase(pathinfo($filepath, PATHINFO_FILENAME)) ] = $filepath; } } }
AbstractModel::fetchSubModels @access protected @final this method cannot be overwritten. @return void @throws \ReflectionException
entailment
final protected function hasSubModel($model) { if (array_key_exists($model, $this->validSubModels)) { return (bool)is_file($this->validSubModels[ $model ]); } return false; }
------------------------------------------------------------------------
entailment
public function createInput(array $attributes = []) { $field = new Components\Form\Elements\Input(); if (count($attributes)) { foreach ($attributes as $name => $value) { $field->attributes->addAttribute($name, $value); if ($name === 'name') { $this->entity->setEntityName('input-' . $value); if ( ! array_key_exists('id', $attributes)) { $field->attributes->setAttributeId('input-' . $value); } } } } $this->childNodes->push($field); return $this->childNodes->last(); }
Form::createInput @param array $attributes @return Components\Form\Elements\Input
entailment
public function createButton($label, array $attributes = []) { $button = new Components\Form\Elements\Button($label); if ( ! array_key_exists('class', $attributes)) { $button->attributes->addAttributeClass(['btn', 'my-2', 'my-sm-0']); } if (count($attributes)) { foreach ($attributes as $name => $value) { $button->attributes->addAttribute($name, $value); } } $this->childNodes->push($button); return $this->childNodes->last(); }
From::createButton @param string $label @param array $attributes @return Components\Form\Elements\Button
entailment
protected function getSyntaxHighlighterConfig() { $provider = $this->get(SyntaxHighlighterStringsProvider::SERVICE_NAME); $config = new SyntaxHighlighterConfig(); $config->setStrings($provider->getSyntaxHighlighterStrings()); return $config; }
Get the Syntax Highlighter config. @return SyntaxHighlighterConfig Returns the SyntaxHighlighter config.
entailment
public static function renderType(ButtonInterface $button) { return null !== $button->getType() ? $button->getPrefix() . $button->getType() : null; }
Render a type. @param ButtonInterface $button The button. @return string|null Returns the rendered type.
entailment
public static function setup_theme() { global $pagenow; if ( ( is_admin() && 'themes.php' == $pagenow ) || ! self::can_switch_themes() ) { return; } self::check_reset(); self::load_cookie(); if ( empty( self::$theme ) ) { return; } add_filter( 'pre_option_template', array( self::$theme, 'get_template' ) ); add_filter( 'pre_option_stylesheet', array( self::$theme, 'get_stylesheet' ) ); add_filter( 'pre_option_stylesheet_root', array( self::$theme, 'get_theme_root' ) ); $parent = self::$theme->parent(); add_filter( 'pre_option_template_root', array( empty( $parent ) ? self::$theme : $parent, 'get_theme_root' ) ); add_filter( 'pre_option_current_theme', '__return_false' ); }
Loads cookie and sets up theme filters.
entailment
public static function check_reset() { if ( ! empty( filter_input( INPUT_GET, 'tts_reset' ) ) ) { setcookie( self::get_cookie_name(), '', 1 ); nocache_headers(); wp_safe_redirect( home_url() ); die; } }
Clear theme choice if reset variable is present in request.
entailment
public static function load_cookie() { $theme_name = filter_input( INPUT_COOKIE, self::get_cookie_name() ); if ( ! $theme_name ) { return; } $theme = wp_get_theme( $theme_name ); if ( $theme->exists() && $theme->get( 'Name' ) !== get_option( 'current_theme' ) && $theme->is_allowed() ) { self::$theme = $theme; } }
Sets if cookie is defined to non-default theme.
entailment
public static function get_allowed_themes() { static $themes; if ( isset( $themes ) ) { return $themes; } $wp_themes = wp_get_themes( array( 'allowed' => true ) ); /** @var WP_Theme $theme */ foreach ( $wp_themes as $theme ) { // Make keys names (rather than slugs) for backwards compat. $themes[ $theme->get( 'Name' ) ] = $theme; } $themes = apply_filters( 'tts_allowed_themes', $themes ); return $themes; }
Retrieves allowed themes. @return WP_Theme[]
entailment
public static function init() { if ( self::can_switch_themes() ) { add_action( 'admin_bar_menu', array( __CLASS__, 'admin_bar_menu' ), 90 ); add_action( 'wp_ajax_tts_set_theme', array( __CLASS__, 'set_theme' ) ); } load_plugin_textdomain( 'toolbar-theme-switcher', false, dirname( dirname( plugin_basename( __FILE__ ) ) ) . '/lang' ); }
Sets up hooks that doesn't need to happen early.
entailment
public static function admin_bar_menu( $wp_admin_bar ) { $themes = self::get_allowed_themes(); $current = empty( self::$theme ) ? wp_get_theme() : self::$theme; unset( $themes[ $current->get( 'Name' ) ] ); uksort( $themes, array( __CLASS__, 'sort_core_themes' ) ); $title = apply_filters( 'tts_root_title', sprintf( __( 'Theme: %s', 'toolbar-theme-switcher' ), $current->display( 'Name' ) ) ); $wp_admin_bar->add_menu( array( 'id' => 'toolbar_theme_switcher', 'title' => $title, 'href' => admin_url( 'themes.php' ), ) ); $ajax_url = admin_url( 'admin-ajax.php' ); foreach ( $themes as $theme ) { $href = add_query_arg( array( 'action' => 'tts_set_theme', 'theme' => urlencode( $theme->get_stylesheet() ), ), $ajax_url ); $wp_admin_bar->add_menu( array( 'id' => $theme['Stylesheet'], 'title' => $theme->display( 'Name' ), 'href' => $href, 'parent' => 'toolbar_theme_switcher', ) ); } }
Creates menu in toolbar. @param WP_Admin_Bar $wp_admin_bar Admin bar instance.
entailment
public static function sort_core_themes( $theme_a, $theme_b ) { static $twenties = array( 'Twenty Ten', 'Twenty Eleven', 'Twenty Twelve', 'Twenty Thirteen', 'Twenty Fourteen', 'Twenty Fifteen', 'Twenty Sixteen', 'Twenty Seventeen', 'Twenty Eighteen', 'Twenty Nineteen', 'Twenty Twenty', ); if ( 0 === strpos( $theme_a, 'Twenty' ) && 0 === strpos( $theme_b, 'Twenty' ) ) { $index_a = array_search( $theme_a, $twenties, true ); $index_b = array_search( $theme_b, $twenties, true ); if ( false !== $index_a && false !== $index_b ) { return ( $index_a < $index_b ) ? - 1 : 1; } } return strcasecmp( $theme_a, $theme_b ); }
Callback to sort theme array with core themes in numerical order by year. @param string $theme_a First theme name. @param string $theme_b Second theme name. @return int
entailment
public static function set_theme() { $stylesheet = filter_input( INPUT_GET, 'theme' ); $theme = wp_get_theme( $stylesheet ); if ( $theme->exists() && $theme->is_allowed() ) { setcookie( self::get_cookie_name(), $theme->get_stylesheet(), strtotime( '+1 year' ), COOKIEPATH ); } wp_safe_redirect( wp_get_referer() ); die; }
Saves selected theme in cookie if valid.
entailment
public static function get_theme_field( $field_name, $default = false ) { if ( ! empty( self::$theme ) ) { return self::$theme->get( $field_name ); } return $default; }
Returns field from theme data if cookie is set to valid theme. @param string $field_name @param mixed $default @deprecated :2.0 @return mixed
entailment
public function render() { if ($this->attributes->hasAttribute('class') === false) { $this->attributes->addAttributeClass('col'); } return parent::render(); }
Column::render @return string
entailment
public function getGrant(string $grantType): GrantInterface { if ($this->hasGrant($grantType)) { return $this->grants[$grantType]; } // If we reach here... then no grant was found. Not good! throw OAuth2Exception::unsupportedGrantType(sprintf( 'Grant type "%s" is not supported by this server', $grantType )); }
Get the grant by its name @throws OAuth2Exception (unsupported_grant_type) When grant type is not registered
entailment
public function getResponseType(string $responseType): GrantInterface { if ($this->hasResponseType($responseType)) { return $this->responseTypes[$responseType]; } // If we reach here... then no grant was found. Not good! throw OAuth2Exception::unsupportedResponseType(sprintf( 'Response type "%s" is not supported by this server', $responseType )); }
Get the response type by its name @throws OAuth2Exception (unsupported_grant_type) When response type is not registered
entailment
private function getClient(ServerRequestInterface $request, bool $allowPublicClients) { list($id, $secret) = $this->extractClientCredentials($request); // If the grant type we are issuing does not allow public clients, and that the secret is // missing, then we have an error... if (! $allowPublicClients && ! $secret) { throw OAuth2Exception::invalidClient('Client secret is missing'); } // If we allow public clients and no client id was set, we can return null if ($allowPublicClients && ! $id) { return null; } $client = $this->clientService->getClient($id); // We delegate all the checks to the client service if (null === $client || (! $allowPublicClients && ! $client->authenticate($secret))) { throw OAuth2Exception::invalidClient('Client authentication failed'); } return $client; }
Get the client (after authenticating it) According to the spec (http://tools.ietf.org/html/rfc6749#section-2.3), for public clients we do not need to authenticate them @return Client|null @throws OAuth2Exception (invalid_client) When a client secret is missing or client authentication failed
entailment
private function createResponseFromOAuthException(OAuth2Exception $exception): ResponseInterface { $payload = [ 'error' => $exception->getCode(), 'error_description' => $exception->getMessage(), ]; return new Response\JsonResponse($payload, 400); }
Create a response from the exception, using the format of the spec @link http://tools.ietf.org/html/rfc6749#section-5.2
entailment
private function extractClientCredentials(ServerRequestInterface $request): array { // We first try to get the Authorization header, as this is the recommended way according to the spec if ($request->hasHeader('Authorization')) { // The value is "Basic xxx", we are interested in the last part $parts = explode(' ', $request->getHeaderLine('Authorization')); $value = base64_decode(end($parts)); list($id, $secret) = explode(':', $value); } else { $postParams = $request->getParsedBody(); $id = $postParams['client_id'] ?? null; $secret = $postParams['client_secret'] ?? null; } return [$id, $secret]; }
Extract the client credentials from Authorization header or POST data
entailment
public function createToken($owner, $client, array $scopes = []): AccessToken { if (empty($scopes)) { $scopes = $this->scopeService->getDefaultScopes(); } else { $this->validateTokenScopes($scopes); } do { $token = AccessToken::createNewAccessToken( $this->serverOptions->getAccessTokenTtl(), $owner, $client, $scopes ); } while ($this->tokenRepository->tokenExists($token->getToken())); return $this->tokenRepository->save($token); }
Create a new token (and generate the token) @param TokenOwnerInterface $owner @param Client $client @param string[]|Scope[] $scopes @return AccessToken @throws OAuth2Exception
entailment
protected function bootstrapGrid($lg, $md, $sm, $xs, $recopy, $prefix) { $found = null; $values = [&$lg, &$md, &$sm, &$xs]; foreach ($values as &$current) { if (1 <= $current && $current <= 12) { $found = $current; } if (null === $current && true === $recopy && null !== $found) { $current = $found; } } $columns = []; $columns[] = GridHelper::getCSSClassname("lg", $lg, $prefix, 1, 12); $columns[] = GridHelper::getCSSClassname("md", $md, $prefix, 1, 12);; $columns[] = GridHelper::getCSSClassname("sm", $sm, $prefix, 1, 12);; $columns[] = GridHelper::getCSSClassname("xs", $xs, $prefix, 1, 12);; return trim(implode(" ", $columns)); }
Displays a Bootstrap grid. @param string $lg The large column size. @param string $md The medium column size. @param string $sm The small column size. @param string $xs The extra-small column size. @param string $recopy Recopy ? @param string $prefix The column prefix. @return string Returns the Bootstrap grid.
entailment
public function execute() { $options = input()->get(); if (empty($options)) { $_GET[ 'host' ] = 'localhost'; $_GET[ 'port' ] = 8000; } parent::execute(); output()->write( (new Format()) ->setContextualClass(Format::SUCCESS) ->setString(language()->getLine('CLI_SERVE_STARTED', [$this->optionHost, $this->optionPort])) ->setNewLinesAfter(1) ); $_SERVER[ 'DOCUMENT_ROOT' ] = PATH_PUBLIC; output()->write( (new Format()) ->setContextualClass(Format::INFO) ->setString(language()->getLine('CLI_SERVE_DOC_ROOT', [$_SERVER[ 'DOCUMENT_ROOT' ]])) ->setNewLinesAfter(1) ); output()->write( (new Format()) ->setContextualClass(Format::WARNING) ->setString(language()->getLine('CLI_SERVE_STOP')) ->setNewLinesAfter(1) ); /* * Call PHP's built-in webserver, making sure to set our * base path to the public folder, and to use the rewrite file * to ensure our environment is set and it simulates basic mod_rewrite. */ passthru('php -S ' . $this->optionHost . ':' . $this->optionPort . ' -t ' . str_replace('\\', DIRECTORY_SEPARATOR, DIR_PUBLIC) . ' ' . PATH_ROOT . 'server.php' ); }
Serve::execute
entailment
public function getDigitalOcean($file = self::DEFAULT_CREDENTIALS_FILE) { if (!file_exists($file)) { throw new \RuntimeException(sprintf('Impossible to get credentials informations in %s', $file)); } $credentials = Yaml::parse($file); return new DigitalOcean(new Credentials($credentials['CLIENT_ID'], $credentials['API_KEY'])); }
Returns an instance of DigitalOcean @param string $file The file with credentials. @return DigitalOcean An instance of DigitalOcean @throws \RuntimeException
entailment
private static function getLeadingDir(string $pattern): string { $dir = $pattern; $pos = strpos($dir, '*'); if ($pos!==false) $dir = substr($dir, 0, $pos); $pos = strpos($dir, '?'); if ($pos!==false) $dir = substr($dir, 0, $pos); $pos = strrpos($dir, '/'); if ($pos!==false) { $dir = substr($dir, 0, $pos); } else { $dir = '.'; } return $dir; }
Returns the leading directory without wild cards of a pattern. @param string $pattern The pattern. @return string
entailment
public function findSources(string $sources): array { $patterns = $this->sourcesToPatterns($sources); $sources = []; foreach ($patterns as $pattern) { $tmp = $this->findSourcesInPattern($pattern); $sources = array_merge($sources, $tmp); } $sources = array_unique($sources); sort($sources); return $sources; }
Finds sources of stored routines. @param string $sources The value of the sources parameter. @return string[]
entailment
private function findSourcesInPattern(string $pattern): array { $sources = []; $directory = new RecursiveDirectoryIterator(self::getLeadingDir($pattern)); $directory->setFlags(RecursiveDirectoryIterator::FOLLOW_SYMLINKS); $files = new RecursiveIteratorIterator($directory); foreach ($files as $fullPath => $file) { // If the file is a source file with stored routine add it to my sources. if ($file->isFile() && SelectorHelper::matchPath($pattern, $fullPath)) { $sources[] = $fullPath; } } return $sources; }
Finds sources of stored routines in a pattern. @param string $pattern The pattern of the sources. @return string[]
entailment
private function readPatterns(string $filename): array { $path = $this->basedir.'/'.$filename; $lines = explode(PHP_EOL, file_get_contents($path)); $patterns = []; foreach ($lines as $line) { $line = trim($line); if ($line<>'') { $patterns[] = $line; } } return $patterns; }
Reads a list of patterns from a file. @param string $filename The name of the file with a list of patterns. @return string[]
entailment
private function sourcesToPatterns(string $sources): array { if (substr($sources, 0, 5)=='file:') { $patterns = $this->readPatterns(substr($sources, 5)); } else { $patterns = [$sources]; } return $patterns; }
Converts the sources parameter to a list a patterns. @param string $sources The value of the sources parameter. @return string[]
entailment
protected function bootstrapButtonGroup($class, $role, array $buttons) { $attributes = []; $attributes["class"] = $class; $attributes["role"] = $role; $innerHTML = "\n" . implode("\n", $buttons) . "\n"; return static::coreHTMLElement("div", $innerHTML, $attributes); }
Displays a Bootstrap button group. @param string $class The class. @param string $role The role. @param array $buttons The buttons. @return string Returns the Bootstrap button group.
entailment
public static function createNewAuthorizationCode( int $ttl, string $redirectUri = null, TokenOwnerInterface $owner = null, Client $client = null, $scopes = null ): AuthorizationCode { $token = static::createNew($ttl, $owner, $client, $scopes); $token->redirectUri = $redirectUri ?? ''; return $token; }
Create a new AuthorizationCode @param int $ttl @param string $redirectUri @param TokenOwnerInterface $owner @param Client $client @param string|string[]|Scope[]|null $scopes @return AuthorizationCode
entailment
public function &__get($property) { $get[ $property ] = false; if (property_exists($this, $property)) { return $this->{$property}; } return $get[ $property ]; }
View::__get @param string $property @return bool Returns FALSE when property is not set.
entailment
public function with($vars, $value = null) { if (is_string($vars)) { $vars = [$vars => $value]; } presenter()->merge($vars); return $this; }
View::with @param mixed $vars @param mixed $value @return static
entailment
public function modal($filename, array $vars = []) { if (presenter()->theme->hasLayout('modal')) { if (presenter()->theme->hasLayout('modal')) { presenter()->theme->setLayout('modal'); echo $this->load($filename, $vars, true); exit(EXIT_SUCCESS); } } if ($content = $this->load($filename, $vars, true)) { echo $content; exit(EXIT_SUCCESS); } }
View::modal @param string $filename @param array $vars
entailment
public function load($filename, array $vars = [], $return = false) { if ($filename instanceof \SplFileInfo) { return $this->page($filename->getRealPath(), array_merge($vars, $filename->getVars())); } if (strpos($filename, 'Pages') !== false) { return $this->page($filename, $vars, $return); } presenter()->merge($vars); if (false !== ($filePath = $this->getFilePath($filename))) { // Load Assets presenter()->assets->addFilePath(dirname($filePath) . DIRECTORY_SEPARATOR); presenter()->assets->loadCss(pathinfo($filePath, PATHINFO_FILENAME)); presenter()->assets->loadJs(pathinfo($filePath, PATHINFO_FILENAME)); if ($return === false) { if (presenter()->partials->hasPartial('content') === false) { if (is_ajax()) { parser()->loadFile($filePath); $content = parser()->parse(presenter()->getArrayCopy()); presenter()->partials->addPartial('content', $content); } else { presenter()->partials->addPartial('content', $filePath); } } else { presenter()->partials->addPartial(pathinfo($filePath, PATHINFO_FILENAME), $filePath); } } else { parser()->loadFile($filePath); return parser()->parse(presenter()->getArrayCopy()); } } else { $vars = presenter()->getArrayCopy(); extract($vars); $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); $error = new ErrorException( 'E_VIEW_NOT_FOUND', 0, @$backtrace[ 0 ][ 'file' ], @$backtrace[ 0 ][ 'line' ], [trim($filename)] ); unset($backtrace); ob_start(); include output()->getFilePath('error'); $content = ob_get_contents(); ob_end_clean(); if ($return === false) { if (presenter()->partials->hasPartial('content') === false) { presenter()->addPartial('content', $content); } else { presenter()->addPartial(pathinfo($filePath, PATHINFO_FILENAME), $content); } } else { return $content; } } }
View::load @param string $filename @param array $vars @param bool $return @return false|string
entailment
public function page($filename, array $vars = [], $return = false) { if ( ! is_file($filename)) { $pageDirectories = modules()->getResourcesDirs('pages'); foreach ($pageDirectories as $pageDirectory) { if (is_file($pageFilePath = $pageDirectory . $filename . '.phtml')) { $filename = $pageFilePath; break; } } } if (count($vars)) { presenter()->merge($vars); } presenter()->merge(presenter()->page->getVars()); if ($return === false) { if (presenter()->partials->hasPartial('content') === false) { presenter()->partials->addPartial('content', $filename); } else { presenter()->partials->addPartial(pathinfo($filename, PATHINFO_FILENAME), $filename); } } elseif (parser()->loadFile($filename)) { return parser()->parse(presenter()->getArrayCopy()); } }
View::page @param string $filename @param array $vars @param bool $return @return bool|string Returns FALSE if failed.
entailment
public function getFilePath($filename) { $filename = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $filename); if (is_file($filename)) { return realpath($filename); } else { $viewsDirectories = array_merge([ PATH_KERNEL . 'Views' . DIRECTORY_SEPARATOR, PATH_FRAMEWORK . 'Views' . DIRECTORY_SEPARATOR, ], $this->filePaths); $viewsDirectories = array_unique($viewsDirectories); $viewsDirectories = array_reverse($viewsDirectories); $controllerSubDir = services('controller')->getParameter() . DIRECTORY_SEPARATOR; foreach ($viewsDirectories as $viewsDirectory) { $filename = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $filename); // Find specific view file for mobile version if (services('userAgent')->isMobile()) { // Find without controller parameter as sub directory if (is_file($filePath = $viewsDirectory . $filename . '.mobile.phtml')) { return realpath($filePath); break; } // Find without controller parameter as sub directory if (is_file($filePath = $viewsDirectory . $controllerSubDir . $filename . '.mobile.phtml')) { return realpath($filePath); break; } } // Find without controller parameter as sub directory if (is_file($filePath = $viewsDirectory . $filename . '.phtml')) { return realpath($filePath); break; } // Find without controller parameter as sub directory if (is_file($filePath = $viewsDirectory . $controllerSubDir . $filename . '.phtml')) { return realpath($filePath); break; } } } return false; }
View::getFilePath @param string $filename @return bool|string
entailment
public function render(array $options = []) { if (profiler() !== false) { profiler()->watch('Starting View Rendering'); } parser()->loadVars(presenter()->getArrayCopy()); if (presenter()->page->file instanceof \SplFileInfo) { if (false === ($pagePresets = presenter()->page->getPresets())) { if (presenter()->page->file->getFilename() === 'index') { $title = presenter()->page->file->getDirectoryInfo()->getDirName(); } else { $titles[] = presenter()->page->file->getDirectoryInfo()->getDirName(); $titles[] = presenter()->page->file->getFilename(); $title = implode(' - ', array_unique($titles)); } $pagePresets = new SplArrayObject([ 'title' => readable($title, true), 'access' => 'public', ]); } /** * Sets Page Theme */ if ($pagePresets->offsetExists('theme')) { presenter()->setTheme($pagePresets->theme); } elseif (false !== ($theme = presenter()->getConfig('theme'))) { if (modules()->top()->hasTheme($theme)) { presenter()->setTheme($theme); } } /** * Sets Page Layout */ if (presenter()->theme !== false) { if ($pagePresets->offsetExists('layout')) { presenter()->theme->setLayout($pagePresets->layout); } /** * Autoload Theme Assets */ presenter()->theme->load(); if (false !== ($modulePresets = modules()->top()->getPresets())) { /** * Autoload Module Assets */ if ($modulePresets->offsetExists('assets')) { presenter()->assets->autoload($modulePresets->assets); } /** * Sets Module Meta */ if ($modulePresets->offsetExists('title')) { presenter()->meta->title->append(language()->getLine($modulePresets->title)); } if ($modulePresets->offsetExists('pageTitle')) { presenter()->meta->title->replace(language()->getLine($modulePresets->pageTitle)); } if ($modulePresets->offsetExists('browserTitle')) { presenter()->meta->title->replace(language()->getLine($modulePresets->browserTitle)); } if ($modulePresets->offsetExists('meta')) { foreach ($modulePresets->meta as $name => $content) { presenter()->meta->store($name, $content); } } } $moduleAssets = [ 'app', 'module', modules()->top()->getParameter(), ]; // Autoload Assets presenter()->assets->loadCss($moduleAssets); presenter()->assets->loadJs($moduleAssets); /** * Autoload Page Assets */ if ($pagePresets->offsetExists('assets')) { presenter()->assets->autoload($pagePresets->assets); } if (presenter()->page->file instanceof \SplFileInfo) { $pageDir = presenter()->page->file->getRealPath(); $pageDir = str_replace('.' . pathinfo($pageDir, PATHINFO_EXTENSION), '', $pageDir); $pageDirParts = explode('pages' . DIRECTORY_SEPARATOR, str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $pageDir)); $pageDir = end($pageDirParts); presenter()->assets->addFilePath(reset($pageDirParts) . 'pages' . DIRECTORY_SEPARATOR); $pageDir = rtrim($pageDir, DIRECTORY_SEPARATOR); $pageDirParts = explode(DIRECTORY_SEPARATOR, $pageDir); $totalParts = count($pageDirParts); for ($i = 0; $i < $totalParts; $i++) { $pageAssets[] = implode(DIRECTORY_SEPARATOR, array_slice($pageDirParts, 0, ($totalParts - $i))); } $pageAssets[] = implode(DIRECTORY_SEPARATOR, [end($pageAssets), end($pageAssets)]); // Autoload Assets presenter()->assets->loadCss($pageAssets); presenter()->assets->loadJs($pageAssets); } /** * Sets Page Meta */ if ($pagePresets->offsetExists('title')) { presenter()->meta->title->append(language()->getLine($pagePresets->title)); } if ($pagePresets->offsetExists('pageTitle')) { presenter()->meta->title->replace(language()->getLine($pagePresets->pageTitle)); } if ($pagePresets->offsetExists('browserTitle')) { presenter()->meta->title->replace(language()->getLine($pagePresets->browserTitle)); } if ($pagePresets->offsetExists('meta')) { foreach ($pagePresets->meta as $name => $content) { presenter()->meta->store($name, $content); } } if (false !== ($layout = presenter()->theme->getLayout())) { parser()->loadFile($layout->getRealPath()); $htmlOutput = parser()->parse(); $htmlOutput = presenter()->assets->parseSourceCode($htmlOutput); $this->document->loadHTML($htmlOutput); } } else { output()->sendError(204, language()->getLine('E_THEME_NOT_FOUND', [$theme])); } } elseif (presenter()->theme instanceof Theme) { /** * Autoload Theme Assets */ presenter()->theme->load(); if (false !== ($modulePresets = modules()->top()->getPresets())) { /** * Autoload Module Assets */ if ($modulePresets->offsetExists('assets')) { presenter()->assets->autoload($modulePresets->assets); } /** * Sets Module Meta */ if ($modulePresets->offsetExists('title')) { presenter()->meta->title->append(language()->getLine($modulePresets->title)); } if ($modulePresets->offsetExists('pageTitle')) { presenter()->meta->title->replace(language()->getLine($modulePresets->pageTitle)); } if ($modulePresets->offsetExists('browserTitle')) { presenter()->meta->title->replace(language()->getLine($modulePresets->browserTitle)); } if ($modulePresets->offsetExists('meta')) { foreach ($modulePresets->meta as $name => $content) { presenter()->meta->store($name, $content); } } } $moduleAssets = [ 'app', 'module', modules()->top()->getParameter(), ]; // Autoload Assets presenter()->assets->loadCss($moduleAssets); presenter()->assets->loadJs($moduleAssets); /** * Autoload Controller Assets */ $controllerFilename = str_replace([modules()->top()->getDir('Controllers'), '.php'], '', controller()->getFileInfo()->getRealPath()); $controllerFilename = dash($controllerFilename); $controllerAssets[] = $controllerFilename; $controllerAssets[] = implode('/', [ $controllerFilename, controller()->getRequestMethod(), ]); presenter()->assets->loadCss($controllerAssets); presenter()->assets->loadJs($controllerAssets); if (false !== ($layout = presenter()->theme->getLayout())) { parser()->loadFile($layout->getRealPath()); $htmlOutput = parser()->parse(); $htmlOutput = presenter()->assets->parseSourceCode($htmlOutput); $this->document->loadHTML($htmlOutput); } } elseif (false !== ($theme = presenter()->getConfig('theme'))) { if (modules()->top()->hasTheme($theme)) { presenter()->setTheme($theme); /** * Autoload Theme Assets */ presenter()->theme->load(); if (false !== ($modulePresets = modules()->top()->getPresets())) { /** * Autoload Module Assets */ if ($modulePresets->offsetExists('assets')) { presenter()->assets->autoload($modulePresets->assets); } /** * Sets Module Meta */ if ($modulePresets->offsetExists('title')) { presenter()->meta->title->append(language()->getLine($modulePresets->title)); } if ($modulePresets->offsetExists('pageTitle')) { presenter()->meta->title->replace(language()->getLine($modulePresets->pageTitle)); } if ($modulePresets->offsetExists('browserTitle')) { presenter()->meta->title->replace(language()->getLine($modulePresets->browserTitle)); } if ($modulePresets->offsetExists('meta')) { foreach ($modulePresets->meta as $name => $content) { presenter()->meta->store($name, $content); } } } $moduleAssets = [ 'app', 'module', modules()->top()->getParameter(), ]; // Autoload Assets presenter()->assets->loadCss($moduleAssets); presenter()->assets->loadJs($moduleAssets); /** * Autoload Controller Assets */ $controllerFilename = str_replace([modules()->top()->getDir('Controllers'), '.php'], '', controller()->getFileInfo()->getRealPath()); $controllerFilename = dash($controllerFilename); $controllerAssets[] = $controllerFilename; $controllerAssets[] = implode('/', [ $controllerFilename, controller()->getRequestMethod(), ]); if (false !== ($layout = presenter()->theme->getLayout())) { parser()->loadFile($layout->getRealPath()); $htmlOutput = parser()->parse(); $htmlOutput = presenter()->assets->parseSourceCode($htmlOutput); $this->document->loadHTML($htmlOutput); } } else { output()->sendError(204, language()->getLine('E_THEME_NOT_FOUND', [$theme])); } } else { $this->document->find('body')->append(presenter()->partials->__get('content')); } /** * Set Document Meta Title */ if (presenter()->meta->title instanceof Meta\Title) { $this->document->title->text(presenter()->meta->title->__toString()); } /** * Injecting Meta Opengraph */ if (presenter()->meta->opengraph instanceof Meta\Opengraph) { // set opengraph title if (presenter()->meta->title instanceof Meta\Title) { presenter()->meta->opengraph->setTitle(presenter()->meta->title->__toString()); } // set opengraph site name if (presenter()->exists('siteName')) { presenter()->meta->opengraph->setSiteName(presenter()->offsetGet('siteName')); } if (presenter()->meta->opengraph->count()) { $htmlElement = $this->document->getElementsByTagName('html')->item(0); $htmlElement->setAttribute('prefix', 'og: ' . presenter()->meta->opengraph->prefix); if (presenter()->meta->opengraph->exists('og:type') === false) { presenter()->meta->opengraph->setType('website'); } $opengraph = presenter()->meta->opengraph->getArrayCopy(); foreach ($opengraph as $tag) { $this->document->metaNodes->createElement($tag->attributes->getArrayCopy()); } } } if (presenter()->meta->count()) { $meta = presenter()->meta->getArrayCopy(); foreach ($meta as $tag) { $this->document->metaNodes->createElement($tag->attributes->getArrayCopy()); } } /** * Inject body attributes */ $body = $this->document->getElementsByTagName('body'); $body->item(0)->setAttribute('module', modules()->top()->getParameter()); /** * Injecting Single Sign-On (SSO) iFrame */ if (services()->has('user')) { $iframe = services()->get('user')->getIframeCode(); if ( ! empty($iframe)) { $this->document->find('body')->append($iframe); } } if (input()->env('DEBUG_STAGE') === 'DEVELOPER' and presenter()->getConfig('debugToolBar') === true and services()->has('profiler') ) { $this->document->find('body')->append((new Toolbar())->__toString()); } /** * Injecting Progressive Web Application (PWA) Manifest */ $this->document->linkNodes->createElement([ 'rel' => 'manifest', 'href' => '/manifest.json', ]); $htmlOutput = $this->document->saveHTML(); // Uglify Output if ($this->config->output[ 'uglify' ] === true) { $htmlOutput = preg_replace( [ '/\>[^\S ]+/s', // strip whitespaces after tags, except space '/[^\S ]+\</s', // strip whitespaces before tags, except space '/(\s)+/s', // shorten multiple whitespace sequences '/<!--(.|\s)*?-->/', // Remove HTML comments '/<!--(.*)-->/Uis', "/[[:blank:]]+/", ], [ '>', '<', '\\1', '', '', ' ', ], str_replace(["\n", "\r", "\t"], '', $htmlOutput)); } // Beautify Output if ($this->config->output[ 'beautify' ] === true) { $beautifier = new Html\Dom\Beautifier(); $htmlOutput = $beautifier->format($htmlOutput); } if (profiler() !== false) { profiler()->watch('Ending View Rendering'); } return $htmlOutput; }
View::render @param array $options @return string
entailment
public static function getCSSClassname($size, $value, $suffix, $min = 1, $max = 12) { if ($value < $min || $max < $value) { return null; } $sizes = ["lg", "md", "sm", "xs"]; $suffixes = ["offset", "pull", "push", ""]; if (false === in_array($size, $sizes) || false === in_array($suffix, $suffixes)) { return null; } if ("" !== $suffix) { $suffix .= "-"; } return implode("-", ["col", $size, $suffix . $value]); }
Get a CSS classname. @param string $size The size. @param int $value The value. @param string $suffix The suffix. @param int $min The min value. @param int $max The max value. @return string|null Returns the CSS classname.
entailment
public static function getInstance() { if (is_null(self::$_instance)) { $id_cache = is_memcache_available() ? new Memcache() : new FileCache(); self::$_instance = new self($id_cache); } return self::$_instance; }
Returns a singleton @return self
entailment
public function getGuidFromRiverId($river_id = 0) { $river_id = (int) $river_id; $guid = $this->id_cache->get($river_id); if ($guid) { return $guid; } $objects = elgg_get_entities_from_metadata([ 'types' => RiverObject::TYPE, 'subtypes' => [RiverObject::SUBTYPE, 'hjstream'], 'metadata_name_value_pairs' => [ 'name' => 'river_id', 'value' => $river_id, ], 'limit' => 1, 'callback' => false, ]); $guid = ($objects) ? $objects[0]->guid : false; if ($guid) { $this->id_cache->put($river_id, $guid); return $guid; } return false; }
Return value of the entity guid that corresponds to river_id @param int $river_id River item ID @return int|false
entailment