sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function toArray(): array { return [ 'name' => $this->name, 'method' => $this->method, 'url' => $this->url, 'model' => $this->model, 'view' => $this->view, 'controller' => $this->controller, 'action' => $this->action, 'default' => $this->default, 'param' => $this->param, 'callback' => $this->callback ]; }
Return route array. @return array
entailment
private function protect(Authentication $authentication, int $httpResponseCode = 403): void { if (($this->authentication = $authentication->isLogged()) === false) { \http_response_code($httpResponseCode); throw new AuthenticationException(''); } }
Allow access to controller class or methods only if logged. Return a status code, useful with AJAX requests. @param Authentication $authentication @param int $httpResponseCode @return void @throws AuthenticationException if not authenticated.
entailment
private function protectWithRedirect(Authentication $authentication, string $location): void { if (($this->authentication = $authentication->isLogged()) === false) { \header('Location: '.$location); throw new AuthenticationException(''); } }
Allow access to controller class or methods only if logged and do a redirection. @param Authentication $authentication @param string $location @return void @throws AuthenticationException
entailment
public function bootstrapFormButtonDefaultFunction(array $args = []) { $cancelButton = $this->bootstrapFormButtonCancelFunction(["href" => ArrayHelper::get($args, "cancel_href")]); $submitButton = $this->bootstrapFormButtonSubmitFunction(); // Return the HTML. return implode(" ", [$cancelButton, $submitButton]); }
Displays a Bootstrap form buttons "default". @param array $args The arguments. @return string Returns the Bootstrap form button "Default".
entailment
public function bootstrapFormButtonSubmitFunction() { $txt = $this->getTranslator()->trans("label.submit", [], "WBWBootstrapBundle"); $but = $this->getButtonTwigExtension()->bootstrapButtonPrimaryFunction(["content" => $txt, "title" => $txt, "icon" => "g:ok"]); return $this->getButtonTwigExtension()->bootstrapButtonSubmitFilter($but); }
Displays a Bootstrap form button "submit". @return string Returns the Bootstrap form button "Submit".
entailment
public function getMultiple(array $keys, $default = null): array { $arrayResult = []; foreach ($keys as $key) { $arrayResult[$key] = $this->get($key, $default); } return $arrayResult; }
Obtains multiple cache items by their unique keys. @param array $keys A list of keys that can obtained in a single operation. @param mixed $default Default value to return for keys that do not exist. @return array A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value.
entailment
public function validate(string $requestUri, string $requestMethod): bool { $route = $this->findRoute($this->filterUri($requestUri), $requestMethod); if ($route instanceof Route) { $this->buildValidRoute($route); return true; } $this->buildErrorRoute(); return false; }
Evaluate request uri. @param string $requestUri @param string $requestMethod @return bool
entailment
private function findRoute(string $uri, string $method): RouteInterface { $matches = []; $route = new NullRoute(); foreach ($this->routes as $value) { $urlMatch = \preg_match('`^'.\preg_replace($this->matchTypes, $this->types, $value->url).'/?$`', $uri, $matches); $methodMatch = \strpos($value->method, $method); if ($urlMatch && $methodMatch !== false) { $route = clone $value; $this->routeMatches = $matches; break; } } return $route; }
Find if provided route match with one of registered routes. @param string $uri @param string $method @return RouteInterface
entailment
private function buildValidRoute(Route $route): void { //add to route array the passed uri for param check when call $matches = $this->routeMatches; //route match and there is a subpattern with action if (\count($matches) > 1) { //assume that subpattern rapresent action $route->action = $matches[1]; //url clean $route->url = \preg_replace('`\([0-9A-Za-z\|]++\)`', $matches[1], $route->url); } $route->param = $this->buildParam($route); $this->route = $route; }
Build a valid route. @param Route $route @return void
entailment
private function buildParam(Route $route): array { $param = []; $url = \explode('/', $route->url); $matches = \explode('/', $this->routeMatches[0]); $rawParam = \array_diff($matches, $url); foreach ($rawParam as $key => $value) { $paramName = \strtr($url[$key], ['[' => '', ']' => '']); $param[$paramName] = $value; } return $param; }
Try to find parameters in a valid route and return it. @param Route $route @return array
entailment
private function buildErrorRoute(): void { //check if there is a declared route for errors, if no exit with false if (($key = \array_search($this->badRoute, \array_column($this->routes->getArrayCopy(), 'name'), true)) === false) { $this->route = new NullRoute(); return; } //build and store route for errors $this->route = $this->routes[$key]; }
Actions for error route. @return void
entailment
private function filterUri(string $passedUri): string { //sanitize url $url = \filter_var($passedUri, FILTER_SANITIZE_URL); //check for rewrite mode $url = \str_replace($this->rewriteModeOffRouter, '', $url); //remove basepath $url = \substr($url, \strlen($this->basePath)); //remove doubled slash $url = \str_replace('//', '/', $url); return (\substr($url, 0, 1) === '/') ? $url : '/'.$url; }
Analize current uri, sanitize and return it. @param string $passedUri @return string
entailment
public function transform(ApiRequest $request, ApiResponse $response, array $context = []): ApiResponse { if (isset($context['exception'])) { // Convert exception to json $content = Json::encode($this->extractException($request, $response, $context)); if ($context['exception'] instanceof ClientErrorException || $context['exception'] instanceof ServerErrorException) { $response = $response->withStatus($context['exception']->getCode()); } else { $response = $response->withStatus(500); } } else { // Convert data to array to json $content = Json::encode($this->extractData($request, $response, $context)); } $response->getBody()->write($content); // Setup content type return $response ->withHeader('Content-Type', 'application/json'); }
Encode given data for response @param mixed[] $context
entailment
public function start(): void { if (\session_status() !== PHP_SESSION_ACTIVE) { //prepare the session start \session_name($this->name); //start session \session_start([ 'cookie_path' => $this->cookiePath, 'cookie_domain' => $this->cookieDomain, 'cookie_lifetime' => $this->expire, 'cookie_secure' => $this->cookieSecure, 'cookie_httponly' => $this->cookieHttpOnly ]); //link session super global to $data property $this->data = &$_SESSION; } //refresh session $this->refresh(); }
Start session. @return void
entailment
private function refresh(): void { $time = \time(); if (isset($this->data['time']) && $this->data['time'] <= ($time - $this->expire)) { //delete session data $this->data = []; //regenerate session $this->regenerate(); } $this->setSessionData($time); }
Refresh session. @return void
entailment
private function setSessionData(int $time): void { $this->id = \session_id(); $this->data['time'] = $time; $this->data['expire'] = $this->expire; $this->status = \session_status(); }
Set Session Data. @param int $time @return void
entailment
public function destroy(): void { //delete session data $this->data = []; $this->id = ''; //destroy cookie \setcookie($this->name, 'NothingToSeeHere.', \time()); //call session destroy \session_destroy(); //update status $this->status = \session_status(); }
Destroy session. @return void
entailment
protected function notifyDanger($content) { $notification = NotificationFactory::newDangerNotification($content); return $this->notify(NotificationEvents::NOTIFICATION_DANGER, $notification); }
Notify "danger". @param string $content The content. @return Event Returns the event.
entailment
protected function notifyInfo($content) { $notification = NotificationFactory::newInfoNotification($content); return $this->notify(NotificationEvents::NOTIFICATION_INFO, $notification); }
Notify "info". @param string $content The content. @return Event Returns the event.
entailment
protected function notifySuccess($content) { $notification = NotificationFactory::newSuccessNotification($content); return $this->notify(NotificationEvents::NOTIFICATION_SUCCESS, $notification); }
Notify "success". @param string $content The content. @return Event Returns the event.
entailment
protected function notifyWarning($content) { $notification = NotificationFactory::newWarningNotification($content); return $this->notify(NotificationEvents::NOTIFICATION_WARNING, $notification); }
Notify "warning". @param string $content The content. @return Event Returns the event.
entailment
public static function getGlyphiconBreadcrumbNodes() { $breadcrumbNodes = []; $breadcrumbNodes[] = new BreadcrumbNode("label.edit_profile", "g:user", "fos_user_profile_edit", NavigationInterface::NAVIGATION_MATCHER_ROUTER); $breadcrumbNodes[] = new BreadcrumbNode("label.show_profile", "g:user", "fos_user_profile_show", NavigationInterface::NAVIGATION_MATCHER_ROUTER); $breadcrumbNodes[] = new BreadcrumbNode("label.change_password", "g:lock", "fos_user_change_password", NavigationInterface::NAVIGATION_MATCHER_ROUTER); return $breadcrumbNodes; }
Get a FOSUser breadcrumb node with Glyphicon icons. @return BreadcrumbNode[] Returns the FOSUser breadcrumb node.
entailment
public function setPosition($position) { if (in_array($position, [self::ADDON_LEFT, self::ADDON_RIGHT])) { $this->position = $position; } return $this; }
AddOn::setPosition @param $position @return static
entailment
public function render() { if ($this->hasChildNodes()) { if ($this->childNodes->first() instanceof Button) { $this->attributes->removeAttributeClass('input-group-text'); } } return parent::render(); }
AddOn::render @return string
entailment
public static function renderIcon(Environment $twigEnvironment, $name, $style = null) { // Determines the handler. $handler = explode(":", $name); if (1 === count($handler)) { array_unshift($handler, "g"); } if (2 !== count($handler)) { return ""; } // Swith into handler. switch ($handler[0]) { case "b": // Bootstrap case "g": // Glyphicon $output = (new GlyphiconTwigExtension($twigEnvironment))->renderIcon($handler[1], $style); break; default: $output = parent::renderIcon($twigEnvironment, $name, $style); break; } return $output; }
Render an icon. @param Environment $twigEnvironment The twig environment. @param string $name The icon name. @param string $style The icon style. @return string Returns a rendered icon.
entailment
protected function bootstrapGlyphicon($name, $style) { $attributes = []; $attributes["class"][] = "glyphicon"; $attributes["class"][] = null !== $name ? "glyphicon-" . $name : null; $attributes["aria-hidden"] = "true"; $attributes["style"] = $style; return static::coreHTMLElement("span", null, $attributes); }
Displays a Bootstrap glyphicon. @param string $name The name. @return string Returns the Bootstrap glyphicon.
entailment
public function showPrivacyCookieBanner( Twig_Environment $twigEnvironment, $policyPageUrl = null, array $options = array() ) { $options['policyPageUrl'] = $policyPageUrl; return $twigEnvironment->render( 'EzSystemsPrivacyCookieBundle::privacycookie.html.twig', $this->bannerOptions->map($options, $this->banner) ); }
Renders cookie privacy banner snippet code. This helper should be included at the end of template before the body ending tag. @param \Twig_Environment $twigEnvironment @param string $policyPageUrl cookie policy page address (not required, no policy link will be shown) @param array $options override default options @return string
entailment
public function loadFile($filename, $subDir = null) { if (is_file($filename)) { $this->javascripts->append($filename); } else { $extension = pathinfo($filename, PATHINFO_EXTENSION); if (empty($extension)) { if (input()->env('DEBUG_STAGE') === 'PRODUCTION') { if (false !== ($filePath = $this->getFilePath($filename . '.min.js'))) { $this->javascripts->append($filePath); } } else { if (false !== ($filePath = $this->getFilePath($filename . '.js', $subDir))) { $this->javascripts->append($filePath); } } } elseif (false !== ($filePath = $this->getFilePath($filename, $subDir))) { $this->javascripts->append($filePath); } } }
Body::loadFile @param string $filename @param string|null $subDir @return void
entailment
protected function bootstrapButton(ButtonInterface $button, $icon) { $attributes = []; $attributes["class"] = ["btn", ButtonRenderer::renderType($button)]; $attributes["class"][] = ButtonRenderer::renderBlock($button); $attributes["class"][] = ButtonRenderer::renderSize($button); $attributes["class"][] = ButtonRenderer::renderActive($button); $attributes["title"] = ButtonRenderer::renderTitle($button); $attributes["type"] = "button"; $attributes["data-toggle"] = ButtonRenderer::renderDataToggle($button); $attributes["data-placement"] = ButtonRenderer::renderDataPLacement($button); $attributes["disabled"] = ButtonRenderer::renderDisabled($button); $glyphicon = null !== $icon ? RendererTwigExtension::renderIcon($this->getTwigEnvironment(), $icon) : ""; $innerHTML = ButtonRenderer::renderContent($button); return static::coreHTMLElement("button", implode(" ", [$glyphicon, $innerHTML]), $attributes); }
Displays a Bootstrap button. @param ButtonInterface $button The button. @param string $icon The icon. @return string Returns the Bootstrap button.
entailment
public function register(Application $app) { $app[Service::PASSWORD_HASH] = $app->share(function () use ($app) { return new Service\DefaultPasswordHashService(); }); }
Registers services on the given app. This method should only be used to configure services and parameters. It should not get services.
entailment
public function stream_close() { if ($this->data == null) { return; } $this->stream_flush(); $this->data = null; $this->path = null; $this->save = false; $this->dirty = null; $this->metadata = array(); }
Close the stream
entailment
protected function bootstrapNavs(array $items, $class, $stacked) { $attributes = []; $attributes["class"][] = "nav"; $attributes["class"][] = $class; $attributes["class"][] = true === $stacked ? "nav-stacked" : null; $innerHTML = []; foreach ($items as $current) { $innerHTML[] = $this->bootstrapNav($current); } return static::coreHTMLElement("ul", "\n" . implode("\n", $innerHTML) . "\n", $attributes); }
Displays a Bootstrap navs. @param array $items The items. @param string $class The class. @param bool $stacked Stacked ? @return string Returns the Bootstrap nav.
entailment
public function setObject($property, $content) { $property = $this->namespace . ':' . $property; $element = new Element('meta'); $element->attributes[ 'name' ] = $property; $element->attributes[ 'content' ] = (is_array($content) ? implode(', ', $content) : trim($content)); $this->store($property, $element); return $this; }
AbstractNamespace::setObject @param string $property @param string $content @return static
entailment
public function createGroup($label) { $group = new Select\Group(); $group->textContent->push($label); $this->childNodes->push($group); return $this->childNodes->last(); }
Select::createGroup @param string $label @return Select\Group
entailment
public function setTitle($text, $tagName = 'h5', array $attributes = []) { $this->dialog->content->header->tagName = $tagName; $this->dialog->content->header->textContent->push($text); if (count($this->attributes)) { foreach ($attributes as $name => $value) { $this->dialog->content->header->attributes->addAttribute($name, $value); } } return $this; }
Modal::setTitle @param string $text @param string $tagName @param array $attributes @return static
entailment
public function register(Application $app) { $app[Validator::LOGIN] = $app->share(function () use ($app) { return new Validator\SymfonyLoginValidator($app['validator']); }); $app[Validator::REGISTRATION] = $app->share(function () use ($app) { return new Validator\SymfonyRegistrationValidator($app['validator']); }); }
Registers services on the given app. This method should only be used to configure services and parameters. It should not get services.
entailment
public function createImage($src, $alt = null) { return $this->image = new Card\Image($src, $alt); }
Card::createImage @param string $src @param string|null $alt @return \O2System\Framework\Libraries\Ui\Components\Card\Image
entailment
public function createRibbon( $ribbon, $contextualClass = Card\Ribbon::DEFAULT_CONTEXT, $position = Card\Ribbon::LEFT_RIBBON ) { if ($ribbon instanceof Card\Ribbon) { $ribbon->position = $position; } elseif (is_string($ribbon)) { $ribbon = new Card\Ribbon($ribbon, $contextualClass, $position); } $this->ribbons->push($ribbon); return $this->ribbons->last(); }
Card::createRibbon @param Card\Ribbon|string $ribbon @param string $contextualClass @param int $position @return Card\Ribbon
entailment
public function createHeader() { $this->childNodes->prepend(new Card\Header()); return $this->header = $this->childNodes->first(); }
Card::createHeader @return Card\Header
entailment
public function createBody() { $this->childNodes->push(new Card\Body()); return $this->body = $this->childNodes->last(); }
Card::createBody @return Card\Body
entailment
public function createFooter() { $this->childNodes->push(new Card\Footer()); return $this->footer = $this->childNodes->last(); }
Card::createFooter @return Card\Footer
entailment
public function render() { $output[] = $this->open(); // Render header and image if ($this->header->hasTextContent() || $this->header->hasChildNodes()) { $output[] = $this->header; if ($this->image instanceof Card\Image || $this->image instanceof Card\Carousel ) { $this->image->attributes->removeAttributeClass('card-img-top'); } } elseif ($this->image instanceof Card\Image || $this->image instanceof Card\Carousel ) { $this->image->attributes->addAttributeClass('card-img-top'); } // Render ribbons if ($this->ribbons->count()) { $ribbonsLeft = []; $ribbonsRight = []; foreach ($this->ribbons as $ribbon) { if ($ribbon->position === Card\Ribbon::LEFT_RIBBON) { $ribbonsLeft[] = $ribbon; } elseif ($ribbon->position === Card\Ribbon::RIGHT_RIBBON) { $ribbonsRight[] = $ribbon; } } $ribbonContainer = new Element('div'); $ribbonContainer->attributes->addAttributeClass('card-ribbon'); if (count($ribbonsLeft)) { $ribbonLeftContainer = new Element('div'); $ribbonLeftContainer->attributes->addAttributeClass(['card-ribbon-container', 'left']); foreach ($ribbonsLeft as $ribbonLeft) { $ribbonLeftContainer->childNodes->push($ribbonLeft); } $ribbonContainer->childNodes->push($ribbonLeftContainer); } if (count($ribbonsRight)) { $ribbonRightContainer = new Element('div'); $ribbonRightContainer->attributes->addAttributeClass(['card-ribbon-container', 'right']); foreach ($ribbonsRight as $ribbonRight) { $ribbonRightContainer->childNodes->push($ribbonRight); } $ribbonContainer->childNodes->push($ribbonRightContainer); } $output[] = $ribbonContainer; } // Render images if ($this->image instanceof Card\Image || $this->image instanceof Card\Carousel ) { $output[] = $this->image; } // Render badges if ($this->badges->count()) { $badgesLeft = []; $badgesRight = []; $badgesInline = []; foreach ($this->badges as $badge) { if ($badge->position === Card\Badge::LEFT_BADGE) { $badgesLeft[] = $badge; } elseif ($badge->position === Card\Badge::RIGHT_BADGE) { $badgesRight[] = $badge; } elseif ($badge->position === Card\Badge::INLINE_BADGE) { $badgesInline[] = $badge; } } $badgeContainer = new Element('div'); $badgeContainer->attributes->addAttributeClass('card-badge'); if (count($badgesLeft)) { $badgeLeftContainer = new Element('div'); $badgeLeftContainer->attributes->addAttributeClass(['card-badge-container', 'left']); foreach ($badgesLeft as $badgeLeft) { $badgeLeftContainer->childNodes->push($badgeLeft); } $badgeContainer->childNodes->push($badgeLeftContainer); } if (count($badgesRight)) { $badgeRightContainer = new Element('div'); $badgeRightContainer->attributes->addAttributeClass(['card-badge-container', 'right']); foreach ($badgesRight as $badgeRight) { $badgeRightContainer->childNodes->push($badgeRight); } $badgeContainer->childNodes->push($badgeRightContainer); } if (count($badgesInline)) { $badgeInlineContainer = new Element('div'); $badgeInlineContainer->attributes->addAttributeClass(['card-badge-container', 'inline']); foreach ($badgesInline as $badgeInline) { $badgeInlineContainer->childNodes->push($badgeInline); } $badgeContainer->childNodes->push($badgeInlineContainer); } $output[] = $badgeContainer; } // Render body if ($this->hasChildNodes()) { $output[] = implode(PHP_EOL, $this->childNodes->getArrayCopy()); } if ($this->hasTextContent()) { $output[] = implode(PHP_EOL, $this->textContent->getArrayCopy()); } // Render footer if ($this->footer->hasTextContent() || $this->footer->hasChildNodes()) { $output[] = $this->footer; } $output[] = $this->close(); return implode(PHP_EOL, $output); }
Card::render @return string
entailment
public function getResource(): object { return new ExtendedPDO( $this->options['dsn'], $this->options['user'], $this->options['password'], $this->options['options'] ); }
Get Resource. @return object
entailment
private function askForCreateSP(string $spType, string $tableName): void { $question = sprintf('Create SP for <dbo>%s</dbo> ? (default Yes): ', $spType); $question = new ConfirmationQuestion($question, true); if ($this->helper->ask($this->input, $this->output, $question)) { $defaultSpName = strtolower(sprintf('%s_%s', $tableName, $spType)); $fileName = sprintf('%s/%s.psql', $this->sourceDirectory, $defaultSpName); $question = new Question(sprintf('Please enter filename (%s): ', $fileName), $fileName); $spName = $this->helper->ask($this->input, $this->output, $question); if ($spName!==$fileName) { $spName = strtolower($spName); $fileName = sprintf('%s/%s.psql', $this->sourceDirectory, $spName); } else { $spName = $defaultSpName; } if (file_exists($fileName)) { $this->io->writeln(sprintf('File <fso>%s</fso> already exists', $fileName)); $question = 'Overwrite it ? (default No): '; $question = new ConfirmationQuestion($question, false); if ($this->helper->ask($this->input, $this->output, $question)) { $code = $this->generateSP($tableName, $spType, $spName); $this->writeTwoPhases($fileName, $code); } } else { $code = $this->generateSP($tableName, $spType, $spName); $this->writeTwoPhases($fileName, $code); } } }
Asking function for create or not stored procedure. @param string $spType Stored procedure type {insert|update|delete|select}. @param string $tableName The table name.
entailment
private function generateSP(string $tableName, string $spType, string $spName): string { switch ($spType) { case 'UPDATE': $routine = new UpdateRoutine($this->input, $this->output, $this->helper, $spType, $spName, $tableName, $this->dataSchema); break; case 'DELETE': $routine = new DeleteRoutine($this->input, $this->output, $this->helper, $spType, $spName, $tableName, $this->dataSchema); break; case 'SELECT': $routine = new SelectRoutine($this->input, $this->output, $this->helper, $spType, $spName, $tableName, $this->dataSchema); break; case 'INSERT': $routine = new InsertRoutine($this->input, $this->output, $this->helper, $spType, $spName, $tableName, $this->dataSchema); break; default: throw new FallenException("Unknown type '%s'", $spType); } return $routine->getCode(); }
Generate code for stored routine. @param string $tableName The table name. @param string $spType Stored routine type {insert|update|delete|select}. @param string $spName Stored routine name. @return string
entailment
private function printAllTables(array $tableList): void { if ($this->input->getOption('tables')) { $tableData = array_chunk($tableList, 4); $array = []; foreach ($tableData as $parts) { $partsArray = []; foreach ($parts as $part) { $partsArray[] = $part['table_name']; } $array[] = $partsArray; } $table = new Table($this->output); $table->setRows($array); $table->render(); } }
Check option -t for show all tables. @param array[] $tableList All existing tables from data schema.
entailment
private function startAsking(array $tableList): void { $question = new Question('Please enter <note>TABLE NAME</note>: '); $tableName = $this->helper->ask($this->input, $this->output, $question); $key = StaticDataLayer::searchInRowSet('table_name', $tableName, $tableList); if (!isset($key)) { $this->io->logNote("Table '%s' not exist.", $tableName); } else { $this->askForCreateSP('INSERT', $tableName); $this->askForCreateSP('UPDATE', $tableName); $this->askForCreateSP('DELETE', $tableName); $this->askForCreateSP('SELECT', $tableName); } }
Main function for asking. @param array[] $tableList All existing tables from data schema.
entailment
public function image($large, $small = null) { $this->image = [ 'smallImageUrl' => $small ?? $large, 'largeImageUrl' => $large, ]; return $this; }
Set the card image. @param $large @param null $small @return $this
entailment
public static function createNewScope( int $id, string $name, string $description = null, bool $isDefault = false ): Scope { $scope = new static(); $scope->id = $id; $scope->name = $name; $scope->description = $description; $scope->isDefault = $isDefault; return $scope; }
Create a new Scope
entailment
public function login(string $userName, string $password, string $storedUserName = '', string $storedPassword = '', int $storedId): bool { if ($userName === $storedUserName && $this->password->verify($password, $storedPassword)) { //write valid login on session $this->session->loginTime = \time(); $this->session->login = [ 'login' => true, 'user_id' => $storedId, 'user_name' => $storedUserName, ]; //update login data $this->data = $this->session->login; //regenerate session id $this->session->regenerate(); $this->logged = true; return true; } return false; }
Try to attemp login with the informations passed by param. <pre><code class="php">$user = ''; //user from login page form $password = ''; //password from login page form $storedUser = ''; //user from stored informations $storedPassword = ''; //password hash from stored informations $storedId = ''; //user id from stored informations $auth = new Authentication($session, $password); $auth->login($user, $password, $storedUser, $storedPassword, $storedId); //other operation after login </code></pre> @param string $userName User name from browser input. @param string $password Password from browser input. @param string $storedUserName User name from persistent storage. @param string $storedPassword Password from persistent storage. @param int $storedId User id from persistent storage. @return bool True for successful login, false if login fails.
entailment
public function logout(): bool { //remove login data from session unset($this->session->login, $this->session->loginTime); //regenerate session id $this->session->regenerate(); $this->logged = false; return true; }
Do logout and delete login information from session. <pre><code class="php">$auth = new Authentication($session, $password); $auth->logout(); </code></pre> @return bool True if logout is done.
entailment
private function refresh(): bool { //check for login data on in current session if (empty($this->session->login)) { return false; } //take time $time = \time(); //check if login expired if (($this->session->loginTime + $this->session->expire) < $time) { return false; } //update login data $this->session->loginTime = $time; $this->data = $this->session->login; return true; }
Check if user is logged, get login data from session and update it. @return bool True if refresh is done false if no.
entailment
public function register(Application $app) { $app[Repository::USER] = $app->share(function () use ($app) { return new Repository\DBALUserRepository($app['db']); }); $app[Repository::CITY] = $app->share(function()use($app){ return new MockCityRepository(); }); $app[Repository::DIRECTION] = $app->share(function()use($app){ return new Repository\ConfigDirectionsRepository($app['directions']); }); }
Registers services on the given app. This method should only be used to configure services and parameters. It should not get services.
entailment
public function callPoolOffset($method, array $args = []) { $poolOffset = $this->poolOffset; if ( ! $this->exists($poolOffset)) { $poolOffset = 'default'; } $itemPool = $this->getItemPool($poolOffset); if ($itemPool instanceof AbstractItemPool) { if (method_exists($itemPool, $method)) { return call_user_func_array([&$itemPool, $method], $args); } } return false; }
Cache::callPoolOffset @param string $method @param array $args @return bool|mixed
entailment
public function get($key, $default = null) { if ($this->hasItem($key)) { $item = $this->getItem($key); return $item->get(); } return $default; }
Cache::get Fetches a value from the cache. @param string $key The unique key of this item in the cache. @param mixed $default Default value to return if the key does not exist. @return mixed The value of the item from the cache, or $default in case of cache miss. @throws \Psr\SimpleCache\InvalidArgumentException @throws \Exception MUST be thrown if the $key string is not a legal value.
entailment
public function getItem($key) { if (false !== ($cacheItem = $this->callPoolOffset('getItem', [$key]))) { return $cacheItem; } return new Item(null, null); }
Cache::getItem Returns a Cache Item representing the specified key. This method must always return a CacheItemInterface object, even in case of a cache miss. It MUST NOT return null. @param string $key The key for which to return the corresponding Cache Item. @throws InvalidArgumentException @throws \Exception If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException MUST be thrown. @return CacheItemInterface The corresponding Cache Item.
entailment
public function set($key, $value, $ttl = null) { return $this->save(new Item($key, $value, $ttl)); }
Cache::set Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time. @param string $key The key of the item to store. @param mixed $value The value of the item to store, must be serializable. @param null|int|\DateInterval $ttl Optional. The TTL value of this item. If no value is sent and the driver supports TTL then the library may set a default value for it or let the driver take care of that. @return bool True on success and false on failure. @throws \Psr\SimpleCache\InvalidArgumentException @throws \Exception MUST be thrown if the $key string is not a legal value.
entailment
public function registerClient(string $name, array $redirectUris): array { do { $client = Client::createNewClient($name, $redirectUris); } while ($this->clientRepository->idExists($client->getId())); $secret = $client->generateSecret(); $client = $this->clientRepository->save($client); return [$client, $secret]; }
Register a new client and generate a strong secret Please note that the secret must be really kept secret, as it is used for some grant type to authorize the client. It is returned as a result of this method, as it's already encrypted in the client object @param string $name @param array $redirectUris @return array [$client, $secret]
entailment
public function sendError($code, $message = null) { if ($this->ajaxOnly === false) { output()->setContentType('application/json'); } if (is_array($code)) { if (is_numeric(key($code))) { $message = reset($code); $code = key($code); } elseif (isset($code[ 'code' ])) { $code = $code[ 'code' ]; $message = $code[ 'message' ]; } } output()->sendError($code, $message); }
------------------------------------------------------------------------
entailment
public function sendPayload($data, $longPooling = false) { if ($longPooling === false) { if ($this->ajaxOnly) { if (is_ajax()) { output()->send($data); } else { output()->sendError(403); } } else { output()->send($data); } } elseif (is_ajax()) { /** * Server-side file. * This file is an infinitive loop. Seriously. * It gets the cache created timestamp, checks if this is larger than the timestamp of the * AJAX-submitted timestamp (time of last ajax request), and if so, it sends back a JSON with the data from * data.txt (and a timestamp). If not, it waits for one seconds and then start the next while step. * * Note: This returns a JSON, containing the content of data.txt and the timestamp of the last data.txt change. * This timestamp is used by the client's JavaScript for the next request, so THIS server-side script here only * serves new content after the last file change. Sounds weird, but try it out, you'll get into it really fast! */ // set php runtime to unlimited set_time_limit(0); $longPoolingCacheKey = 'long-pooling-' . session()->get('id'); $longPoolingCacheData = null; if ( ! cache()->hasItem($longPoolingCacheKey)) { cache()->save(new Item($longPoolingCacheKey, $data)); } // main loop while (true) { // if ajax request has send a timestamp, then $lastCallTimestamp = timestamp, else $last_call = null $lastCallTimestamp = (int)input()->getPost('last_call_timestamp'); // PHP caches file data, like requesting the size of a file, by default. clearstatcache() clears that cache clearstatcache(); if (cache()->hasItem($longPoolingCacheKey)) { $longPoolingCacheData = cache()->getItem($longPoolingCacheKey); } // get timestamp of when file has been changed the last time $longPoolingCacheMetadata = $longPoolingCacheData->getMetadata(); // if no timestamp delivered via ajax or data.txt has been changed SINCE last ajax timestamp if ($lastCallTimestamp == null || $longPoolingCacheMetadata[ 'ctime' ] > $lastCallTimestamp) { output()->send([ 'timestamp' => $longPoolingCacheMetadata, 'data' => $data, ]); } else { // wait for 1 sec (not very sexy as this blocks the PHP/Apache process, but that's how it goes) sleep(1); continue; } } } else { output()->sendError(501); } }
Restful::sendPayload @param mixed $data The payload data to-be send. @param bool $longPooling Long pooling flag mode. @throws \Exception
entailment
public function setConfig(array $config) { $this->config = array_merge($this->config, $config); if ($this->config[ 'responsive' ]) { $this->responsive(); } return $this; }
Table::setConfig Set table configuration. @param array $config @return static
entailment
public function setColumns(array $columns) { $defaultColumn = [ 'field' => 'label', 'label' => 'Label', 'attr' => [ 'name' => '', 'id' => '', 'class' => '', 'width' => '', 'style' => '', ], 'format' => 'txt', 'show' => true, 'sorting' => true, 'hiding' => true, 'options' => false, 'nested' => false, ]; $this->setPrependColumns(); foreach ($columns as $key => $column) { $column = array_merge($defaultColumn, $column); $this->columns[ $key ] = $column; } $this->setAppendColumns(); return $this; }
Table::setColumns @param array $columns @return static
entailment
protected function setPrependColumns() { $prependColumns = [ 'numbering' => [ 'field' => 'numbering', 'label' => '#', 'attr' => [ 'width' => '5%', ], 'format' => 'number', 'show' => true, 'sorting' => true, 'hiding' => false, 'options' => false, 'nested' => false, 'content' => '', ], 'id' => [ 'field' => 'id', 'label' => 'ID', 'attr' => [ 'class' => 'text-right', 'width' => '3%', ], 'format' => 'txt', 'show' => true, 'sorting' => true, 'hiding' => true, 'options' => false, 'nested' => false, ], 'checkbox' => [ 'field' => 'id', 'label' => new Ui\Components\Form\Elements\Checkbox([ 'data-toggle' => 'table-crud-checkbox', ]), 'attr' => [ 'width' => '2%', ], 'format' => 'checkbox', 'show' => true, 'sorting' => false, 'hiding' => false, 'options' => false, 'nested' => false, ], 'images' => [ 'field' => 'images', 'label' => null, 'attr' => [ 'width' => '5%', ], 'format' => 'image', 'show' => true, 'sorting' => false, 'hiding' => true, 'options' => false, 'nested' => false, ], ]; foreach ($prependColumns as $key => $column) { if ($this->config[ $key ] === true) { $this->columns[ $key ] = $column; } } }
Table::setPrependColumns
entailment
protected function setAppendColumns() { $appendColumns = [ 'ordering' => [ 'field' => 'ordering', 'label' => '', 'attr' => [ 'class' => 'width-fit', 'width' => '1%', ], 'format' => 'ordering', 'show' => true, 'sorting' => false, 'filtering' => false, 'hiding' => false, 'options' => true, 'nested' => false, ], 'status' => [ 'field' => 'record_status', 'label' => 'TABLE_LABEL_STATUS', 'format' => 'status', 'show' => false, 'sorting' => false, 'hiding' => true, 'grouping' => true, 'options' => true, 'nested' => false, ], 'createTimestamp' => [ 'field' => 'record_create_timestamp', 'label' => 'TABLE_LABEL_CREATED_DATE', 'format' => 'date', 'show' => false, 'hidden' => true, 'sorting' => true, 'hiding' => true, 'grouping' => false, 'options' => true, 'nested' => false, ], 'updateTimestamp' => [ 'field' => 'record_update_timestamp', 'label' => 'TABLE_LABEL_UPDATED_DATE', 'format' => 'date', 'show' => false, 'hidden' => true, 'sorting' => true, 'grouping' => false, 'hiding' => true, 'options' => true, 'nested' => false, ], 'actions' => [ 'field' => null, 'label' => null, 'format' => 'actions', 'show' => true, 'sorting' => false, 'hiding' => false, 'grouping' => false, 'options' => false, 'nested' => false, ], ]; foreach ($appendColumns as $key => $column) { if ($this->config[ $key ] === true) { $this->columns[ $key ] = $column; } } }
Table::setAppendColumns
entailment
public function render() { if ($this->config[ 'ordering' ]) { $this->attributes->addAttributeClass('table-ordering'); } // Render header $tr = $this->header->createRow(); foreach ($this->columns as $key => $column) { $th = $tr->createColumn('th'); $column[ 'attr' ][ 'data-column' ] = $key; foreach ($column[ 'attr' ] as $name => $value) { if ( ! empty($value)) { $th->attributes->addAttribute($name, $value); } } if ($column[ 'sorting' ] === true) { $icon = new Ui\Contents\Icon('fa fa-sort'); $icon->attributes->addAttributeClass(['text-muted', 'float-right', 'mt-1']); $th->attributes->addAttributeClass('col-sortable'); $th->attributes->addAttribute('data-toggle', 'sort'); $th->childNodes->push($icon); } if ($column[ 'show' ] === false) { $th->attributes->addAttributeClass('hidden'); } $th->textContent->push(language()->getLine($column[ 'label' ])); } // Render tbody if ($this->rows->count() > 0) { $totalEntries = $this->rows->count(); $totalRows = $this->rows->countAll(); $currentPage = input()->get('page') ? input()->get('page') : 1; $startNumber = $currentPage == 1 ? 1 : $currentPage * $this->config[ 'entries' ][ 'minimum' ]; $totalPages = round($totalRows / $this->config[ 'entries' ][ 'minimum' ]); $totalPages = $totalPages == 0 && $totalRows > 0 ? 1 : $totalPages; $i = $startNumber; foreach ($this->rows as $row) { $row->numbering = $i; $tr = $this->body->createRow(); $tr->attributes->addAttribute('data-id', $row->id); foreach ($this->columns as $key => $column) { $column[ 'key' ] = $key; $td = $tr->createColumn(); $column[ 'attr' ][ 'data-column' ] = $key; foreach ($column[ 'attr' ] as $name => $value) { if ( ! empty($value)) { $td->attributes->addAttribute($name, $value); } } if ($column[ 'show' ] === false) { $td->attributes->addAttributeClass('hidden'); } $td->attributes->addAttributeClass('col-body-' . $key); $this->renderBodyColumn($td, $column, $row); } $i++; } } else { $totalEntries = 0; $totalRows = 0; $currentPage = 1; $startNumber = 0; $totalPages = 0; } $showEntries = input()->get('entries') ? input()->get('entries') : $this->config[ 'entries' ][ 'minimum' ]; // Build table card $card = new Ui\Components\Card(); $card->attributes->addAttribute('data-role', 'table-crud'); $card->attributes->addAttributeClass('card-table'); // Build table header tools $tools = new Element('div', 'cardHeaderTools'); $tools->attributes->addAttributeClass(['card-tools', 'float-left']); $buttons = new Ui\Components\Buttons\Group(); foreach ($this->tools as $key => $tool) { if ($tool[ 'show' ] === false) { continue; } if ($tool[ 'label' ] === true) { $button = $buttons->createButton(language()->getLine('TABLE_BUTTON_' . strtoupper($key))); if ( ! empty($tool[ 'icon' ])) { $button->setIcon($tool[ 'icon' ]); } } else { $button = $buttons->createButton(new Ui\Contents\Icon($tool[ 'icon' ])); $button->attributes->addAttribute('data-toggle', 'tooltip'); $button->attributes->addAttribute('title', language()->getLine('TABLE_BUTTON_' . strtoupper($key))); } if ( ! empty($tool[ 'href' ])) { $tool[ 'data-url' ] = $tool[ 'href' ]; } if (isset($tool[ 'attr' ])) { foreach ($tool[ 'attr' ] as $name => $value) { $button->attributes->addAttribute($name, $value); } } $button->setContextualClass($tool[ 'contextual' ]); $button->smallSize(); $button->attributes->addAttribute('data-action', $key); } $tools->childNodes->push($buttons); $card->header->childNodes->push($tools); // Build table header options $options = new Element('div', 'cardHeaderOptions'); $options->attributes->addAttributeClass(['card-options', 'float-right']); $buttons = new Ui\Components\Buttons\Group(); foreach ($this->options as $key => $option) { if ($option[ 'show' ] === false) { continue; } if ($option[ 'label' ] === true) { $button = $buttons->createButton(language()->getLine('TABLE_BUTTON_' . strtoupper($key))); if ( ! empty($option[ 'icon' ])) { $button->setIcon($option[ 'icon' ]); } } else { $button = $buttons->createButton(new Ui\Contents\Icon($option[ 'icon' ])); $button->attributes->addAttribute('data-toggle', 'tooltip'); $button->attributes->addAttribute('title', language()->getLine('TABLE_BUTTON_' . strtoupper($key))); } if ( ! empty($option[ 'href' ])) { $option[ 'data-url' ] = $option[ 'href' ]; } if (isset($option[ 'attr' ])) { foreach ($option[ 'attr' ] as $name => $value) { $button->attributes->addAttribute($name, $value); } } $button->setContextualClass($option[ 'contextual' ]); $button->smallSize(); $button->attributes->addAttribute('data-action', $key); } $options->childNodes->push($buttons); $card->header->childNodes->push($options); // Build table body $cardBody = $card->createBody(); $cardBodyRow = $cardBody->createRow(); $columnSearch = $cardBodyRow->createColumn(['class' => 'col-md-4']); $columnShow = $cardBodyRow->createColumn(['class' => 'col-md-8']); // Search $search = new Ui\Components\Form\Elements\Input([ 'name' => 'query', 'data-role' => 'table-crud-search', 'placeholder' => language()->getLine('TABLE_LABEL_SEARCH'), 'value' => input()->get('query'), ]); $columnSearch->childNodes->push($search); // Show $inputGroup = new Ui\Components\Form\Input\Group(); $addOn = new Ui\Components\Form\Input\Group\AddOn(); $addOn->textContent->push(language()->getLine('TABLE_LABEL_SHOW')); $inputGroup->childNodes->push($addOn); $options = []; foreach (range((int)$this->config[ 'entries' ][ 'minimum' ], (int)$this->config[ 'entries' ][ 'maximum' ], (int)$this->config[ 'entries' ][ 'step' ]) as $entries ) { $options[ $entries ] = $entries; } $columnsDropdown = new Ui\Components\Dropdown(language()->getLine('TABLE_LABEL_COLUMNS')); $columnsDropdown->attributes->addAttribute('data-role', 'table-crud-columns'); foreach ($this->columns as $key => $column) { if ($column[ 'hiding' ] === false) { continue; } $label = new Ui\Components\Form\Elements\Label(); $label->attributes->addAttributeClass('form-check-label'); $label->textContent->push(language()->getLine($column[ 'label' ])); $checkbox = new Ui\Components\Form\Elements\Input([ 'type' => 'checkbox', 'class' => 'form-check-input', 'data-toggle' => 'table-crud-columns', 'data-column' => $key, ]); $checkbox->attributes->removeAttributeClass('form-control'); if ($column[ 'show' ] === true) { $checkbox->attributes->addAttribute('checked', 'checked'); } $label->childNodes->push($checkbox); $columnsDropdown->menu->createItem($label); } $inputGroup->childNodes->push($columnsDropdown); $select = new Ui\Components\Form\Elements\Select(); $select->attributes->addAttribute('name', 'entries'); $select->createOptions($options, $showEntries); $inputGroup->childNodes->push($select); $addOn = new Ui\Components\Form\Input\Group\AddOn(); $addOn->textContent->push(language()->getLine('TABLE_LABEL_PAGE', [ $startNumber, $totalEntries, $totalRows, $currentPage, $totalPages, ])); $inputGroup->childNodes->push($addOn); $input = new Ui\Components\Form\Elements\Input([ 'name' => 'page', 'placeholder' => language()->getLine('TABLE_LABEL_GOTO'), ]); $inputGroup->childNodes->push($input); $pagination = new Ui\Components\Pagination($totalRows, $showEntries); $inputGroup->childNodes->push($pagination); $columnShow->childNodes->push($inputGroup); $card->textContent->push(parent::render()); return $card->render(); }
Table::render @return string
entailment
protected function renderBodyColumn($td, array $column, Result\Row $row) { switch ($column[ 'format' ]) { default: if (is_callable($column[ 'format' ])) { if (is_array($column[ 'field' ])) { foreach ($column[ 'field' ] as $field) { $args[ $field ] = $row->offsetGet($field); } $textContent = call_user_func_array($column[ 'format' ], $args); } elseif ($row->offsetExists($column[ 'field' ])) { $textContent = call_user_func_array($column[ 'format' ], [$row->offsetGet($column[ 'field' ])]); } $td->textContent->push($textContent); } elseif (strpos($column[ 'format' ], '{{') !== false) { $textContent = str_replace(['{{', '}}'], '', $column[ 'format' ]); if (is_array($column[ 'field' ])) { foreach ($column[ 'field' ] as $field) { if ($row->offsetExists($field)) { $textContent = str_replace('$' . $field, $row->offsetGet($field), $textContent); } else { $textContent = str_replace('$' . $field, '', $textContent); } } } elseif ($row->offsetExists($column[ 'field' ])) { $textContent = str_replace('$' . $column[ 'field' ], $row->offsetGet($column[ 'field' ]), $textContent); } $td->textContent->push($textContent); } break; case 'checkbox': $checkbox = new Ui\Components\Form\Elements\Checkbox([ 'data-role' => 'table-crud-checkbox', ]); $td->childNodes->push($checkbox); break; case 'number': case 'txt': case 'text': case 'price': case 'number': if ($row->offsetExists($column[ 'field' ])) { $td->textContent->push($row->offsetGet($column[ 'field' ])); } break; case 'date': if ($row->offsetExists($column[ 'field' ])) { print_out('date'); } break; case 'status': if ($row->offsetExists($column[ 'field' ])) { $options = [ 'PUBLISH' => 'success', 'UNPUBLISH' => 'warning', 'DRAFT' => 'default', 'ARCHIVE' => 'info', 'DELETE' => 'danger', ]; $badge = new Ui\Components\Badge( language()->getLine('TABLE_OPTION_' . $row->offsetGet($column[ 'field' ])), $options[ $row->offsetGet($column[ 'field' ]) ] ); $td->childNodes->push($badge); } break; case 'actions': $buttons = new Ui\Components\Buttons\Group(); foreach ($this->actions as $key => $action) { if ($action[ 'show' ] === false) { continue; } if ($action[ 'label' ] === true) { $button = $buttons->createButton(language()->getLine('TABLE_BUTTON_' . strtoupper($key))); if ( ! empty($action[ 'icon' ])) { $button->setIcon($action[ 'icon' ]); } } else { $button = $buttons->createButton(new Ui\Contents\Icon($action[ 'icon' ])); $button->attributes->addAttribute('data-toggle', 'tooltip'); $button->attributes->addAttribute('title', language()->getLine('TABLE_BUTTON_' . strtoupper($key))); } if (isset($action[ 'attr' ])) { foreach ($action[ 'attr' ] as $name => $value) { $button->attributes->addAttribute($name, $value); } } $button->setContextualClass($action[ 'contextual' ]); $button->smallSize(); $button->attributes->addAttribute('data-action', $key); } $td->childNodes->push($buttons); break; } }
Table::renderBodyColumn @param Element $td @param array $column @param \O2System\Database\DataObjects\Result\Row $row
entailment
public function &__get($property) { $get[ $property ] = false; if (services()->has($property)) { $get[ $property ] = services()->get($property); } elseif (array_key_exists($property, $this->validSubModels)) { $get[ $property ] = $this->loadSubModel($property); } elseif (o2system()->__isset($property)) { $get[ $property ] = o2system()->__get($property); } return $get[ $property ]; }
------------------------------------------------------------------------
entailment
final protected function loadSubModel($model) { if (is_file($this->validSubModels[ $model ])) { $className = '\\' . get_called_class() . '\\' . ucfirst($model); $className = str_replace('\Base\\Model', '\Models', $className); if (class_exists($className)) { $this->{$model} = new $className(); } } return $this->{$model}; }
------------------------------------------------------------------------
entailment
public function setClass($className) { $this->attributes->removeAttributeClass($this->iconPrefixClass . '-*'); $this->attributes->addAttributeClass($this->iconPrefixClass . '-' . $className); return $this; }
AbstractIcon::setClass @param string $className @return static
entailment
public function setHeading($text, $level = 3) { $this->heading = new Heading($text, $level); $this->heading->entity->setEntityName($text); return $this; }
HeadingSetterTrait::setHeading @param string $text @param int $level @return static
entailment
public function languages() { $languages = []; foreach ($this->language->getRegistry() as $language) { $languages[ $language->getParameter() ] = $language->getProperties()->name; } return $languages; }
Options::languages @return array
entailment
public function load() { if ($this->getPresets()->offsetExists('assets')) { presenter()->assets->autoload($this->getPresets()->offsetGet('assets')); } presenter()->assets->loadCss('theme'); presenter()->assets->loadJs('theme'); // Autoload default theme layout $this->loadLayout(); return $this; }
Theme::load @return static
entailment
public function hasLayout($layout) { $extensions = ['.php', '.phtml', '.html', '.tpl']; if (isset($this->presets[ 'extensions' ])) { array_unshift($partialsExtensions, $this->presets[ 'extension' ]); } elseif (isset($this->presets[ 'extension' ])) { array_unshift($extensions, $this->presets[ 'extension' ]); } $found = false; foreach ($extensions as $extension) { $extension = trim($extension, '.'); if ($layout === 'theme') { $layoutFilePath = $this->getRealPath() . 'theme.' . $extension; } else { $layoutFilePath = $this->getRealPath() . 'layouts' . DIRECTORY_SEPARATOR . dash($layout) . DIRECTORY_SEPARATOR . 'layout.' . $extension; } if (is_file($layoutFilePath)) { $found = true; break; } } return (bool) $found; }
Theme::hasLayout @return bool
entailment
public function setLayout($layout) { $extensions = ['.php', '.phtml', '.html', '.tpl']; if (isset($this->presets[ 'extensions' ])) { array_unshift($partialsExtensions, $this->presets[ 'extension' ]); } elseif (isset($this->presets[ 'extension' ])) { array_unshift($extensions, $this->presets[ 'extension' ]); } foreach ($extensions as $extension) { $extension = trim($extension, '.'); if ($layout === 'theme') { $layoutFilePath = $this->getRealPath() . 'theme.' . $extension; } else { $layoutFilePath = $this->getRealPath() . 'layouts' . DIRECTORY_SEPARATOR . dash($layout) . DIRECTORY_SEPARATOR . 'layout.' . $extension; } if (is_file($layoutFilePath)) { $this->layout = new Theme\Layout($layoutFilePath); //$this->loadLayout(); break; } } return $this; }
Theme::setLayout @param string $layout @return static
entailment
protected function loadLayout() { if ($this->layout instanceof Theme\Layout) { // add theme layout public directory loader()->addPublicDir($this->layout->getPath() . 'assets'); presenter()->assets->autoload( [ 'css' => ['layout'], 'js' => ['layout'], ] ); $partials = $this->layout->getPartials()->getArrayCopy(); foreach ($partials as $offset => $partial) { if ($partial instanceof SplFileInfo) { presenter()->partials->addPartial($offset, $partial->getPathName()); } } } return $this; }
Theme::loadLayout @return static
entailment
protected function bootstrapImage($src, $alt, $width, $height, $class, $usemap) { $template = "<img %attributes%/>"; $attributes = []; $attributes["src"] = $src; $attributes["alt"] = $alt; $attributes["width"] = $width; $attributes["height"] = $height; $attributes["class"] = $class; $attributes["usemap"] = $usemap; return StringHelper::replace($template, ["%attributes%"], [StringHelper::parseArray($attributes)]); }
Displays a Bootstrap image. @param string $src The source @param string $alt The alternative text. @param string $width The width. @param string $height The height. @param string $class The class. @param string $usemap The usemap. @return string Returns the Bootstrap image.
entailment
public function createOptions(array $options, $selected = null) { foreach ($options as $label => $value) { $option = $this->createOption($label, $value); if (is_array($selected) && in_array($value, $selected)) { $option->selected(); } elseif ($selected === $value) { $option->selected(); } } return $this; }
OptionCreateTrait::createOptions @param array $options @param string|null $selected @return static
entailment
public function createOption($label, $value = null, $selected = false) { $option = new Option(); $option->textContent->push($label); if (isset($value)) { $option->attributes->addAttribute('value', $value); } if ($selected) { $option->selected(); } $this->childNodes->push($option); return $this->childNodes->last(); }
OptionCreateTrait::createOption @param string $label @param string|null $value @param bool $selected @return Option
entailment
public function render() { if ( ! $this->footer->hasChildNodes() && ! $this->footer->hasTextContent() && ! $this->footer->hasButtons()) { $this->childNodes->pop(); } return parent::render(); }
Content::render @return string
entailment
public function register() { parent::register(); $this->registerConfig(); $this->singleton(Contracts\Http\JsonResponse::class, Http\JsonResponder::class); }
Register the service provider.
entailment
public function bootstrapNavsPills(array $args = []) { return $this->bootstrapNavs(ArrayHelper::get($args, "items", []), "nav-pills", ArrayHelper::get($args, "stacked", false)); }
Displays a Bootstrap navs "Pills". @param array $args The arguments. @return string Returns the Bootstrap nav "Pills".
entailment
public function getFilterOptions(array $options = array()) { $options['types'] = $this->comment->getType(); $options['subtypes'] = array($this->comment->getSubtype(), 'hjcomment'); $options['container_guids'] = $this->comment->container_guid; if (!isset($options['order_by'])) { $options['order_by'] = 'e.guid ASC'; } return $options; }
Get options for {@link elgg_get_entities()} @param array $options Default options array @return array
entailment
public function getOffset($limit = self::LIMIT, $order = 'desc') { if ($limit === 0) { return 0; } if ($order == 'asc' || $order == 'time_created::asc') { $before = $this->getCommentsBefore(array('count' => true, 'offset' => 0)); } else { $before = $this->getCommentsAfter(array('count' => true, 'offset' => 0)); } return floor($before / $limit) * $limit; }
Calculate a page offset to the given comment @param int $limit Items per page @param int $order Ordering @return int
entailment
public function delete($recursive = true) { $success = 0; $count = $this->getCount(); $comments = $this->getAll()->setIncrementOffset(false); foreach ($comments as $comment) { if ($comment->delete($recursive)) { $success++; } } return ($success == $count); }
Delete all comments in a thread @param bool $recursive Delete recursively @return bool
entailment
public function getAll($getter = 'elgg_get_entities_from_metadata', $options = array()) { $options['limit'] = 0; $options = $this->getFilterOptions($options); return new ElggBatch($getter, $options); }
Get all comments as batch @param string $getter Callable getter @param array $options Getter options @return ElggBatch
entailment
public function getCommentsBefore(array $options = array()) { $options['wheres'][] = " e.time_created < {$this->comment->time_created} "; $options['order_by'] = 'e.time_created ASC'; $comments = elgg_get_entities_from_metadata($this->getFilterOptions($options)); if (is_array($comments)) { return array_reverse($comments); } return $comments; }
Get preceding comments @param array $options Additional options @return mixed
entailment
public function setImage($src, $alt = null) { $this->image = new Element('img'); if (strpos($src, 'holder.js') !== false) { $parts = explode('/', $src); $size = end($parts); $this->image->attributes->addAttribute('data-src', $src); $alt = empty($alt) ? $size : $alt; } else { $this->image->attributes->addAttribute('src', $src); } $this->image->attributes->addAttribute('alt', $alt); return $this; }
ImageSetterTrait::setImage @param string $src @param string|null $alt @return static
entailment
public function transform(ApiRequest $request, ApiResponse $response, array $context = []): ApiResponse { if (isset($context['exception'])) { return $this->transformException($context['exception'], $request, $response); } return $this->transformResponse($request, $response); }
Encode given data for response @param mixed[] $context
entailment
public function authenticate($username, $password) { if ($user = $this->find($username)) { if ($user->account) { if ($this->passwordVerify($password, $user->account->password)) { if ($this->passwordRehash($password)) { $user->account->update([ 'id' => $user->id, 'password' => $this->passwordHash($password), ]); } $account = $user->account->getArrayCopy(); } } elseif ($this->passwordVerify($password, $user->password)) { $account = $user->getArrayCopy(); } if (isset($account)) { foreach ($account as $key => $value) { if (strpos($key, 'record') !== false) { unset($account[ $key ]); } elseif (in_array($key, ['password', 'pin', 'token', 'sso', 'id_sys_user', 'id_sys_module', 'id_sys_module_role'])) { unset($account[ $key ]); } } $this->login($account); return true; } } return false; }
User::authenticate @param string $username @param string $password @return bool
entailment
public function find($username) { $column = 'username'; if (is_numeric($username)) { $column = 'id'; } elseif (filter_var($username, FILTER_VALIDATE_EMAIL)) { $column = 'email'; } elseif (preg_match($this->config[ 'msisdnRegex' ], $username)) { $column = 'msisdn'; } if ($user = models('users')->findWhere([$column => $username], 1)) { return $user; } return false; }
User::find @param string $username @return bool|mixed|\O2System\Database\DataObjects\Result|\O2System\Framework\Models\Sql\DataObjects\Result
entailment
public function loggedIn() { if (parent::loggedIn()) { $account = new Account($_SESSION[ 'account' ]); if ($user = models('users')->findWhere(['username' => $account->username], 1)) { // Store Account Profile if ($profile = $user->profile) { $account->store('profile', $profile); } // Store Account Role if ($role = $user->role) { $account->store('role', new Role([ 'label' => $role->label, 'description' => $role->description, 'code' => $role->code, 'authorities' => $role->authorities, ])); } } // Store Globals Account globals()->store('account', $account); // Store Presenter Account if (services()->has('view')) { presenter()->store('account', $account); } return true; } return false; }
User::loggedIn @return bool @throws \Psr\Cache\InvalidArgumentException
entailment
public function forceLogin($username, $column = 'username') { if (is_numeric($username)) { $column = 'id'; } elseif (filter_var($username, FILTER_VALIDATE_EMAIL)) { $column = 'email'; } elseif (preg_match($this->config[ 'msisdnRegex' ], $username)) { $column = 'msisdn'; } elseif (strpos($username, 'token-') !== false) { $username = str_replace('token-', '', $username); $column = 'token'; } elseif (strpos($username, 'sso-') !== false) { $username = str_replace('sso-', '', $username); $column = 'sso'; } if ($account = models('users')->findWhere([$column => $username], 1)) { $account = $account->getArrayCopy(); foreach ($account as $key => $value) { if (strpos($key, 'record') !== false) { unset($account[ $key ]); } elseif (in_array($key, ['password', 'pin', 'token', 'sso'])) { unset($account[ $key ]); } } if ($column === 'token') { models('users')->update([ 'id' => $account[ 'id' ], 'token' => null, ]); } $this->login($account); return true; } return false; }
User::forceLogin @param string $username @param string $column @return bool
entailment
public function authorize(ServerRequest $request) { if (isset($GLOBALS[ 'account' ][ 'role' ])) { $uriSegments = $request->getUri()->getSegments()->getString(); $role = $GLOBALS[ 'account' ][ 'role' ]; if (in_array($role->code, ['DEVELOPER', 'ADMINISTRATOR'])) { globals()->store('authority', new Authority([ 'permission' => 'GRANTED', 'privileges' => '11111111', ])); return true; } elseif ($role->authorities instanceof Authorities) { if ($role->authorities->exists($uriSegments)) { $authority = $role->authorities->getAuthority($uriSegments); globals()->store('authority', $authority); return $authority->getPermission(); } globals()->store('authority', new Authority([ 'permission' => 'DENIED', 'privileges' => '00000000', ])); return false; } } return false; }
User::authorize @param \O2System\Framework\Http\Message\ServerRequest $request @return bool
entailment
public function render() { if ($this->title instanceof Element) { $this->title->attributes->addAttributeClass('card-title'); $this->childNodes->push($this->title); } if ($this->subTitle instanceof Element) { $this->subTitle->attributes->addAttributeClass('card-subtitle'); $this->childNodes->push($this->subTitle); } if ($this->paragraph instanceof Element) { $this->paragraph->attributes->addAttributeClass('card-text'); $this->childNodes->push($this->paragraph); } if ($this->links instanceof ArrayIterator) { if ($this->links->count()) { foreach ($this->links as $link) { $link->attributes->addAttributeClass('card-link'); $this->childNodes->push($link); } } } if ($this->hasChildNodes()) { $this->collapse->attributes->setAttributeId($this->attributes->getAttributeId()); $this->attributes->removeAttribute('id'); $body = new Element('div', 'body'); $body->attributes = $this->attributes; $body->textContent = $this->textContent; $body->childNodes = $this->childNodes; $this->collapse->childNodes->push($body); return $this->collapse->render(); } return ''; }
Body::render @return string
entailment
public function setNamespace(Opengraph\Abstracts\AbstractNamespace $namespace) { $this->prefix = 'http://ogp.me/ns# ' . $namespace->namespace . ": http://ogp.me/ns/$namespace->namespace#"; $this->offsetSet('type', $namespace->namespace); foreach ($namespace->getArrayCopy() as $property => $element) { parent::offsetSet($property, $element); } return $this; }
Opengraph::setNamespace @param \O2System\Framework\Http\Presenter\Meta\Opengraph\Abstracts\AbstractNamespace $namespace @return static
entailment
public function setAppId($appId) { $element = new Element('meta'); $element->attributes[ 'name' ] = 'fb:app_id'; $element->attributes[ 'content' ] = $appId; parent::offsetSet('fb:app_id', $element); return $this; }
Opengraph::setAppId @param string $appId @return static
entailment
public function setObject($property, $content) { $property = 'og:' . $property; $element = new Element('meta'); $element->attributes[ 'name' ] = $property; $element->attributes[ 'content' ] = (is_array($content) ? implode(', ', $content) : trim($content)); parent::offsetSet($property, $element); return $this; }
Opengraph::setObject @param string $property @param string $content @return static
entailment
public function setImage($image) { if (getimagesize($image)) { if (strpos($image, 'http') === false) { loader()->loadHelper('url'); $image = images_url($image); } $this->setObject('image', $image); } return $this; }
Opengraph::setImage @param $image @return static
entailment
public function setLocale($lang, $territory = null) { $lang = strtolower($lang); $this->setObject( 'locale', (isset($territory) ? $lang . '_' . strtoupper($territory) : $lang) ); return $this; }
Opengraph::setLocale @param string $lang @param string|null $territory @return static
entailment
public function setMap($latitude, $longitude) { $this->setObject('latitude', $latitude); $this->setObject('longitude', $longitude); return $this; }
Opengraph::setMap @param float $latitude @param float $longitude @return static
entailment