sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function transfert($imageId, array $parameters) { if (!array_key_exists('region_id', $parameters) || !is_int($parameters['region_id'])) { throw new \InvalidArgumentException('You need to provide an integer "region_id".'); } return $this->processQuery($this->buildQuery($imageId, ImagesActions::ACTION_TRANSFERT, $parameters)); }
Transferts a specific image to a specified region. The region_id key is required. @param integer $imageId The id of the image. @param array $parameters An array of parameters. @return StdClass @throws \InvalidArgumentException
entailment
public function route() { $segments = server_request()->getUri()->getSegments()->getParts(); array_shift($segments); $download = false; if (false !== ($key = array_search('download', $segments))) { $download = true; unset($segments[ $key ]); $segments = array_values($segments); } if (count($segments)) { $filePath = $this->directoryPath . implode(DIRECTORY_SEPARATOR, $segments); if (is_file($filePath)) { if ($download) { $downloader = new Downloader($filePath); $downloader ->speedLimit($this->speedLimit) ->resumeable($this->resumeable) ->download(); } else { $fileInfo = new SplFileInfo($filePath); header('Content-Disposition: filename=' . $fileInfo->getFilename()); header('Content-Transfer-Encoding: binary'); header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT'); header('Content-Type: ' . $fileInfo->getMime()); echo @readfile($filePath); exit(EXIT_SUCCESS); } } else { redirect_url('error/404'); } } else { redirect_url('error/403'); } }
Resources::route
entailment
public function createTitle($title) { $item = $this->list->createList($title); $item->attributes->addAttributeClass('menu-title'); return $item; }
Menu::createTitle @param string $title @return \O2System\Framework\Libraries\Ui\Contents\Lists\Item
entailment
protected function whenLoaded($relationship) { return $this->resource->relationLoaded($relationship) ? $this->resource->{$relationship} : new MissingValue; }
Retrieve a relationship if it has been loaded. @param string $relationship @return \Illuminate\Http\Resources\MissingValue|mixed
entailment
protected function whenPivotLoaded($table, $value, $default = null) { if (func_num_args() === 2) $default = new MissingValue; return $this->when( $this->pivot && ($this->pivot instanceof $table || $this->pivot->getTable() === $table), ...[$value, $default] ); }
Execute a callback if the given pivot table has been loaded. @param string $table @param mixed $value @param mixed $default @return \Illuminate\Http\Resources\MissingValue|mixed
entailment
public function resolve($request = null) { $request = $request ?: Container::getInstance()->make('request'); if ($this->resource instanceof Collection) $data = $this->resolveCollection($this->resource, $request); elseif ($this->resource instanceof AbstractPaginator) $data = $this->resolveCollection($this->resource->getCollection(), $request); else $data = $this->toArray($request); if ($data instanceof Arrayable) $data = $data->toArray(); elseif ($data instanceof JsonSerializable) $data = $data->jsonSerialize(); return $this->resolveNestedRelations((array) $data, $request); }
Resolve the resource to an array. @param \Illuminate\Http\Request|null $request @return array
entailment
protected function resolveNestedRelations($data, $request) { foreach ($data as $key => $value) { if (is_array($value)) { $data[$key] = $this->resolveNestedRelations($value, $request); } elseif ($value instanceof static) { $data[$key] = $value->resolve($request); } } return $this->filter($data); }
Resolve the nested resources to an array. @param array $data @param \Illuminate\Http\Request $request @return array
entailment
public function resolveCollection($collection, $request = null) { return $collection->map(function ($item) use ($request) { return (new static($item))->toArray($request); })->all(); }
Resolve the resource to an array. @param \Illuminate\Support\Collection $collection @param \Illuminate\Http\Request|null $request @return array
entailment
public function toResponse($request) { return ( $this->resource instanceof AbstractPaginator ? new PaginatedResourceResponse($this) : new ResourceResponse($this) )->toResponse($request); }
Create an HTTP response that represents the object. @param \Illuminate\Http\Request $request @return \Illuminate\Http\Response|mixed
entailment
protected function when($condition, $value, $default = null) { return $condition ? value($value) : (func_num_args() === 3 ? value($default) : new MissingValue); }
Retrieve a value based on a given condition. @param bool $condition @param mixed $value @param mixed $default @return \Illuminate\Http\Resources\MissingValue|mixed
entailment
protected function filter($data) { $index = -1; foreach ($data as $key => $value) { $index++; if (is_array($value)) { $data[$key] = $this->filter($value); continue; } if (is_numeric($key) && $value instanceof MergeValue) { return $this->merge($data, $index, $this->filter($value->data)); } if ( $value instanceof MissingValue || ($value instanceof self && $value->resource instanceof MissingValue) ) { unset($data[$key]); } } return $data; }
Filter the given data, removing any optional values. @param array $data @return array
entailment
protected function merge($data, $index, $merge) { if (array_values($data) === $data) { return array_merge( array_merge(array_slice($data, 0, $index, true), $merge), $this->filter(array_slice($data, $index + 1, null, true)) ); } return array_slice($data, 0, $index, true) + $merge + $this->filter(array_slice($data, $index + 1, null, true)); }
Merge the given data in at the given index. @param array $data @param int $index @param array $merge @return array
entailment
public function autoload($assets) { foreach ($assets as $position => $collections) { if (property_exists($this, $position)) { if ($collections instanceof \ArrayObject) { $collections = $collections->getArrayCopy(); } $this->{$position}->loadCollections($collections); } elseif ($position === 'packages') { $this->loadPackages($collections); } elseif ($position === 'css') { $this->loadCss($collections); } elseif ($position === 'js') { $this->loadJs($collections); } } }
Assets::autoload @param array $assets @return void
entailment
public function loadPackages($packages) { foreach ($packages as $package => $files) { if (is_string($files)) { $this->loadPackage($files); } elseif (is_array($files)) { $this->loadPackage($package, $files); } elseif (is_object($files)) { $this->loadPackage($package, get_object_vars($files)); } } }
Assets::loadPackages @param array $packages @return void
entailment
public function loadPackage($package, $subPackages = []) { $packageDir = implode(DIRECTORY_SEPARATOR, [ 'packages', $package, ]) . DIRECTORY_SEPARATOR; if (count($subPackages)) { if (array_key_exists('libraries', $subPackages)) { foreach ($subPackages[ 'libraries' ] as $subPackageFile) { $pluginDir = $packageDir . 'libraries' . DIRECTORY_SEPARATOR; $pluginName = $subPackageFile; if ($this->body->loadFile($pluginDir . $pluginName . DIRECTORY_SEPARATOR . $pluginName . '.js')) { $this->head->loadFile($pluginDir . $pluginName . DIRECTORY_SEPARATOR . $pluginName . '.css'); } else { $this->body->loadFile($pluginDir . $pluginName . '.js'); } } unset($subPackages[ 'libraries' ]); } $this->head->loadFile($packageDir . $package . '.css'); $this->body->loadFile($packageDir . $package . '.js'); foreach ($subPackages as $subPackage => $subPackageFiles) { if ($subPackage === 'theme' or $subPackage === 'themes') { if (is_string($subPackageFiles)) { $subPackageFiles = [$subPackageFiles]; } foreach ($subPackageFiles as $themeName) { $themeDir = $packageDir . 'themes' . DIRECTORY_SEPARATOR; if ($this->head->loadFile($themeDir . $themeName . DIRECTORY_SEPARATOR . $themeName . '.css')) { $this->body->loadFile($themeDir . $themeName . DIRECTORY_SEPARATOR . $themeName . '.js'); } else { $this->head->loadFile($themeDir . $themeName . '.css'); } } } elseif ($subPackage === 'plugins') { foreach ($subPackageFiles as $subPackageFile) { $pluginDir = $packageDir . 'plugins' . DIRECTORY_SEPARATOR; $pluginName = $subPackageFile; $pluginName = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $pluginName); if (strpos($pluginName, DIRECTORY_SEPARATOR) !== false) { $pluginDir .= pathinfo($pluginName, PATHINFO_DIRNAME) . DIRECTORY_SEPARATOR; $pluginName = pathinfo($pluginName, PATHINFO_BASENAME); } if ($this->body->loadFile($pluginDir . $pluginName . DIRECTORY_SEPARATOR . $pluginName . '.js')) { $this->head->loadFile($pluginDir . $pluginName . DIRECTORY_SEPARATOR . $pluginName . '.css'); } else { $this->body->loadFile($pluginDir . $pluginName . '.js'); } } } elseif ($subPackage === 'libraries') { foreach ($subPackageFiles as $subPackageFile) { $libraryDir = $packageDir . 'libraries' . DIRECTORY_SEPARATOR; $libraryName = $subPackageFile; $libraryName = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $libraryName); if (strpos($libraryName, DIRECTORY_SEPARATOR) !== false) { $libraryDir .= pathinfo($libraryName, PATHINFO_DIRNAME) . DIRECTORY_SEPARATOR; $libraryName = pathinfo($libraryName, PATHINFO_BASENAME); } if ($this->body->loadFile($libraryDir . $libraryName . DIRECTORY_SEPARATOR . $libraryName . '.js')) { $this->head->loadFile($libraryDir . $libraryName . DIRECTORY_SEPARATOR . $libraryName . '.css'); } else { $this->body->loadFile($libraryDir . $libraryName . '.js'); } } } } } else { $this->head->loadFile($packageDir . $package . '.css'); $this->body->loadFile($packageDir . $package . '.js'); } }
Assets::loadPackage @param string $package @param array $subPackages @return void
entailment
public function loadCss($files) { $files = is_string($files) ? [$files] : $files; $this->head->loadCollections(['css' => $files]); }
Assets::loadCss @param string|array $files @return void
entailment
public function loadJs($files, $position = 'body') { $files = is_string($files) ? [$files] : $files; $this->{$position}->loadCollections(['js' => $files]); }
Assets::loadJs @param string|array $files @param string $position @return void
entailment
public function loadFiles($assets) { foreach ($assets as $type => $item) { $addMethod = 'load' . ucfirst($type); if (method_exists($this, $addMethod)) { call_user_func_array([&$this, $addMethod], [$item]); } } }
Assets::loadFiles @param array $assets @return void
entailment
public function theme($path) { $path = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $path); if (is_file($filePath = PATH_THEME . $path)) { return path_to_url($filePath); } }
Assets::theme @param string $path @return string
entailment
public function file($file) { $filePaths = loader()->getPublicDirs(true); foreach ($filePaths as $filePath) { if (is_file($filePath . $file)) { return path_to_url($filePath . $file); break; } } }
Assets::file @param string $file @return string
entailment
public function image($image) { $filePaths = loader()->getPublicDirs(true); $image = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $image); foreach ($filePaths as $filePath) { $filePath .= 'img' . DIRECTORY_SEPARATOR; if (is_file($filePath . $image)) { return path_to_url($filePath . $image); break; } unset($filePath); } }
Assets::image @param string $image @return string
entailment
public function media($media) { $filePaths = loader()->getPublicDirs(true); $media = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $media); foreach ($filePaths as $filePath) { $filePath .= 'media' . DIRECTORY_SEPARATOR; if (is_file($filePath . $media)) { return path_to_url($filePath . $media); break; } unset($filePath); } }
Assets::media @param string $media @return string
entailment
public function parseSourceCode($sourceCode) { $sourceCode = str_replace( [ '"../assets/', "'../assets/", "(../assets/", ], [ '"' . base_url() . '/assets/', "'" . base_url() . '/assets/', "(" . base_url() . '/assets/', ], $sourceCode); if (presenter()->theme) { $sourceCode = str_replace( [ '"assets/', "'assets/", "(assets/", // with dot '"./assets/', "'./assets/", "(./assets/", ], [ '"' . presenter()->theme->getUrl('assets/'), "'" . presenter()->theme->getUrl('assets/'), "(" . presenter()->theme->getUrl('assets/'), // with dot '"' . presenter()->theme->getUrl('assets/'), "'" . presenter()->theme->getUrl('assets/'), "(" . presenter()->theme->getUrl('assets/'), ], $sourceCode); } // Valet path fixes if (isset($_SERVER[ 'SCRIPT_FILENAME' ])) { $valetPath = dirname($_SERVER[ 'SCRIPT_FILENAME' ]) . DIRECTORY_SEPARATOR; } else { $PATH_ROOT = $_SERVER[ 'DOCUMENT_ROOT' ]; if (isset($_SERVER[ 'PHP_SELF' ])) { $valetPath = $PATH_ROOT . dirname($_SERVER[ 'PHP_SELF' ]) . DIRECTORY_SEPARATOR; } elseif (isset($_SERVER[ 'DOCUMENT_URI' ])) { $valetPath = $PATH_ROOT . dirname($_SERVER[ 'DOCUMENT_URI' ]) . DIRECTORY_SEPARATOR; } elseif (isset($_SERVER[ 'REQUEST_URI' ])) { $valetPath = $PATH_ROOT . dirname($_SERVER[ 'REQUEST_URI' ]) . DIRECTORY_SEPARATOR; } elseif (isset($_SERVER[ 'SCRIPT_NAME' ])) { $valetPath = $PATH_ROOT . dirname($_SERVER[ 'SCRIPT_NAME' ]) . DIRECTORY_SEPARATOR; } } if (isset($valetPath)) { $sourceCode = str_replace($valetPath, '/', $sourceCode); } return $sourceCode; }
Assets::parseSourceCode @param string $sourceCode @return string
entailment
public function load($model, $offset = null) { if (is_string($model)) { if (class_exists($model)) { $service = new SplServiceRegistry($model); } } elseif ($model instanceof SplServiceRegistry) { $service = $model; } if (isset($service) && $service instanceof SplServiceRegistry) { if (profiler() !== false) { profiler()->watch('Load New Model: ' . $service->getClassName()); } $this->register($service, $offset); } }
Models::load @param object|string $model @param string|null $offset
entailment
public function register(SplServiceRegistry $service, $offset = null) { if ($service instanceof SplServiceRegistry) { $offset = isset($offset) ? $offset : camelcase($service->getParameter()); if ($service->isSubclassOf('O2System\Framework\Models\Sql\Model') || $service->isSubclassOf('O2System\Framework\Models\NoSql\Model') || $service->isSubclassOf('O2System\Framework\Models\Files\Model') ) { $this->attach($offset, $service); if (profiler() !== false) { profiler()->watch('Register New Model: ' . $service->getClassName()); } } } }
Models::register @param SplServiceRegistry $service @param string|null $offset
entailment
public function add($model, $offset = null) { if (is_object($model)) { if ( ! $model instanceof SplServiceRegistry) { $model = new SplServiceRegistry($model); } } if (profiler() !== false) { profiler()->watch('Add New Model: ' . $model->getClassName()); } $this->register($model, $offset); }
Models::add @param \O2System\Framework\Models\Sql\Model|\O2System\Framework\Models\NoSql\Model|\O2System\Framework\Models\Files\Model $model @param null $offset
entailment
public function autoload($model, $offset = null) { if (isset($offset)) { if ($this->has($offset)) { return $this->get($offset); } // Try to load if (is_string($model)) { if ($this->has($model)) { return $this->get($model); } $this->load($model, $offset); if ($this->has($offset)) { return $this->get($offset); } } } elseif (is_string($model)) { if ($this->has($model)) { return $this->get($model); } // Try to load $this->load($model, $model); if ($this->has($model)) { return $this->get($model); } } return false; }
Models::autoload @param string $model @param string|null $offset @return mixed
entailment
public function onPostBind(FormEvent $event) { $form = $event->getForm(); $request = $this->container->get('request'); if (!$request->request->has(Autocomplete::KEY_PATH)) { return; } $name = $request->request->get(Autocomplete::KEY_PATH); $parts = $this->parseNameIntoParts($name, $form->getRoot()->getName()); $field = $form->getRoot(); foreach ($parts as $part) { if (!$field->has($part)) { return; } $field = $field->get($part); } if ($field !== $form) { return; } $searchFields = $form->getConfig()->getAttribute('search-fields'); $template = $this->options['template']; $extraParams = $this->options['extra_params']; $results = $this->resultsFetcher->getPaginatedResults($request, $form->getConfig()->getAttribute('query-builder'), $searchFields); // $results still holds the total amount through (count) $ttl = count($results); $responseData = array(); $options = array('search-fields' => $searchFields, 'extra_params' => $extraParams); foreach ($results as $result) { $identifier = $this->options['identifier_propertypath'] ? $this->propertyAccessor->getValue($result, $this->options['identifier_propertypath']) : $result->getId(); $responseData[] = $this->responseFormatter->formatResultLineForAutocompleteResponse($template, $result, $options, $identifier); } throw new UnexpectedResponseException(new AutocompleteResponse($responseData, $ttl)); }
Executed on event FormEvents::POST_BIND @param FormEvent $event @throws UnexpectedResponseException to force data to be send to client
entailment
public function createLists(array $lists) { if (count($lists)) { foreach ($lists as $list) { $this->createList($list); } } return $this; }
AbstractList::createLists @param array $lists @return static
entailment
public function createList($list = null) { $node = new Item(); if ($list instanceof Item) { $node = $list; } elseif ($list instanceof Element) { $node->entity->setEntityName($list->entity->getEntityName()); $node->childNodes->push($list); } else { if (is_numeric($list)) { $node->entity->setEntityName('list-' . $list); } if (isset($list)) { $node->entity->setEntityName($list); $node->textContent->push($list); } } $this->pushChildNode($node); return $this->childNodes->last(); }
AbstractList @param Item|Element|int|string|null $list @return Item
entailment
protected function pushChildNode(Element $node) { if ($node->hasChildNodes()) { if ($node->childNodes->first() instanceof Link) { $parseUrl = parse_url($node->childNodes->first()->getAttributeHref()); $parseUrlQuery = []; if (isset($parseUrl[ 'query' ])) { parse_str($parseUrl[ 'query' ], $parseUrlQuery); } if (isset($parseUrlQuery[ 'page' ])) { if (input()->get('page') === $parseUrlQuery[ 'page' ]) { $node->attributes->addAttributeClass('active'); $node->childNodes->first()->attributes->addAttributeClass('active'); } } else { $hrefUriSegments = []; if (isset($parseUrl[ 'path' ])) { $hrefUriSegments = (new Uri\Segments($parseUrl[ 'path' ]))->getParts(); } $currentUriSegments = server_request()->getUri()->getSegments()->getParts(); $matchSegments = array_slice($currentUriSegments, 0, count($hrefUriSegments)); $stringHrefSegments = implode('/', $hrefUriSegments); $stringMatchSegments = implode('/', $matchSegments); if ($stringHrefSegments === $stringMatchSegments) { $node->attributes->addAttributeClass('active'); $node->childNodes->first()->attributes->addAttributeClass('active'); } } } } $this->childNodes->push($node); }
AbstractList::pushChildNode @param \O2System\Framework\Libraries\Ui\Element $node
entailment
public function render() { $output[] = $this->open(); if ($this->hasChildNodes()) { if ($this->inline) { $this->attributes->addAttributeClass('list-inline'); } foreach ($this->childNodes as $childNode) { if ($this->inline) { $childNode->attributes->addAttributeClass('list-inline-item'); } $output[] = $childNode; } } $output[] = $this->close(); return implode(PHP_EOL, $output); }
AbstractList::render @return string
entailment
public function items() { return [ 'home' => [ 'title' => trans('dashboard::menus.principal.home'), 'url' => '#home', 'data-scroll' => true ], 'about' => [ 'title' => trans('dashboard::menus.principal.about'), 'url' => '#about', 'data-scroll' => true ], 'team' => [ 'title' => trans('dashboard::menus.principal.team'), 'url' => '#team', 'data-scroll' => true ], 'services' => [ 'title' => trans('dashboard::menus.principal.services'), 'url' => '#services', 'data-scroll' => true ], 'platform' => [ 'title' => trans('dashboard::menus.principal.platform'), 'url' => route('auth.loginGet'), 'data-scroll' => true ], 'contact' => [ 'title' => trans('dashboard::menus.principal.contact'), 'url' => '#contact', 'data-scroll' => true ], 'facebook' => [ 'url' => '#', 'icon' => 'fa fa-facebook', ], 'twitter' => [ 'url' => '#', 'icon' => 'fa fa-twitter', ], 'google' => [ 'url' => '#', 'icon' => 'fa fa-google', ], ]; }
Specify Items Menu @return string
entailment
public function createTokenResponse( ServerRequestInterface $request, Client $client = null, TokenOwnerInterface $owner = null ): ResponseInterface { $postParams = $request->getParsedBody(); // Everything is okey, we can start tokens generation! $scope = $postParams['scope'] ?? null; $scopes = is_string($scope) ? explode(' ', $scope) : []; /** @var AccessToken $accessToken */ $accessToken = $this->accessTokenService->createToken($owner, $client, $scopes); return $this->prepareTokenResponse($accessToken); }
{@inheritdoc}
entailment
public function register(Application $app) { $app['validator'] = $app->share(function ($app) { if (isset($app['translator'])) { $r = new \ReflectionClass('Symfony\Component\Validator\Validator'); $file = dirname($r->getFilename()).'/Resources/translations/validators.'.$app['locale'].'.xlf'; if (file_exists($file)) { $app['translator']->addResource('xliff', $file, $app['locale'], 'validators'); } } $translator = isset($app['translator']) ? $app['translator'] : new IdentityTranslator(); $executionContext = new ExecutionContextFactory($translator); $metaDataFactory = new LazyLoadingMetadataFactory(); $constrainValidator = new ConstraintValidatorFactory(); return new RecursiveValidator($executionContext,$metaDataFactory,$constrainValidator); }); }
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 getDisplayName() { $name = $this->title; if (!$name) { $owner = $this->getOwnerEntity(); $name = elgg_echo('interactions:comment:subject', array($owner->name)); } return $name; }
{@inheritdoc}
entailment
public function getOriginalContainer() { $container = $this; while ($container instanceof Comment) { $container = $container->getContainerEntity(); } return ($container instanceof Comment) ? $this->getOwnerEntity() : $container; }
Get entity that the original comment was made on in a comment thread @return ElggEntity
entailment
public function getDepthToOriginalContainer() { $depth = 0; $ancestry = $this->getAncestry(); foreach ($ancestry as $a) { $ancestor = get_entity($a); if ($ancestor instanceof self) { $depth++; } } return $depth; }
Get nesting level of this comment @return int
entailment
public function getAncestry() { $ancestry = array(); $container = $this; while ($container instanceof ElggEntity) { array_unshift($ancestry, $container->guid); $container = $container->getContainerEntity(); } return $ancestry; }
Get ancestry @return int[]
entailment
public function getSubscriberFilterOptions(array $options = array()) { $defaults = array( 'type' => 'user', 'relationship' => 'subscribed', 'relationship_guid' => $this->getOriginalContainer()->guid, 'inverse_relationship' => true, ); return array_merge($defaults, $options); }
Returns getter options for comment subscribers @param array $options Additional options @return array
entailment
public function save($update_last_action = true) { $result = false; if (elgg_trigger_before_event('create', 'object', $this)) { $result = parent::save($update_last_action); if ($result) { elgg_trigger_after_event('create', 'object', $this); } } return $result; }
{@inheritdoc}
entailment
public function createBrand($label) { $brand = new Link(); $brand->attributes->addAttributeClass('navbar-brand'); $brand->setAttributeHref(base_url()); if (is_object($label)) { $brand->childNodes->push($label); } else { $brand->textContent->push($label); } $this->childNodes->unshift($brand); return $this->brand = $this->childNodes->last(); }
Navbar::createBrand @param string $label @return \O2System\Framework\Libraries\Ui\Contents\Link
entailment
public function createForm() { $this->collapse->childNodes->push(new Navbar\Form()); return $this->form = $this->collapse->childNodes->last(); }
Navbar::createForm @return \O2System\Framework\Libraries\Ui\Components\Navbar\Form
entailment
public function render() { if ($this->nav->childNodes->count() || $this->textContent->count()) { return parent::render(); } return ''; }
Navbar::render @return string
entailment
public function loadRegistry() { if (empty($this->registry)) { $cacheItemPool = cache()->getItemPool('default'); if (cache()->hasItemPool('registry')) { $cacheItemPool = cache()->getItemPool('registry'); } if ($cacheItemPool instanceof CacheItemPoolInterface) { if ($cacheItemPool->hasItem('o2languages')) { $this->registry = $cacheItemPool->getItem('o2languages')->get(); } else { $this->registry = $this->fetchRegistry(); $cacheItemPool->save(new Item('o2languages', $this->registry, false)); } } else { $this->registry = $this->fetchRegistry(); } } }
Language::loadRegistry Load language registry. @return void @throws \Psr\Cache\InvalidArgumentException
entailment
public function fetchRegistry() { $registry = []; $directory = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator(PATH_ROOT) ); $packagesIterator = new \RegexIterator($directory, '/^.+\.json$/i', \RecursiveRegexIterator::GET_MATCH); foreach ($packagesIterator as $packageJsonFiles) { foreach ($packageJsonFiles as $packageJsonFile) { $packageJsonFile = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $packageJsonFile); $packageJsonFileInfo = pathinfo($packageJsonFile); if ($packageJsonFileInfo[ 'filename' ] === 'language') { if (is_cli()) { output()->verbose( (new Format()) ->setString(language()->getLine('CLI_REGISTRY_LANGUAGE_VERB_FETCH_MANIFEST_START', [str_replace(PATH_ROOT, '/', $packageJsonFile)])) ->setNewLinesAfter(1) ); } $package = new DataStructures\Language(dirname($packageJsonFile)); if ($package->isValid()) { if (is_cli()) { output()->verbose( (new Format()) ->setContextualClass(Format::SUCCESS) ->setString(language()->getLine('CLI_REGISTRY_LANGUAGE_VERB_FETCH_MANIFEST_SUCCESS')) ->setIndent(2) ->setNewLinesAfter(1) ); } $registry[ $package->getDirName() ] = $package; } elseif (is_cli()) { output()->verbose( (new Format()) ->setContextualClass(Format::DANGER) ->setString(language()->getLine('CLI_REGISTRY_LANGUAGE_VERB_FETCH_MANIFEST_FAILED')) ->setIndent(2) ->setNewLinesAfter(1) ); } } } } ksort($registry); return $registry; }
Language::fetchRegistry Fetch language registry. @return array
entailment
public function getRegistry($package = null) { if (isset($package)) { if ($this->registered($package)) { return $this->registry[ $package ]; } return false; } return $this->registry; }
Language::getRegistry Gets language registries. @return array
entailment
public function updateRegistry() { if (is_cli()) { output()->verbose( (new Format()) ->setContextualClass(Format::WARNING) ->setString(language()->getLine('CLI_REGISTRY_LANGUAGE_VERB_UPDATE_START')) ->setNewLinesBefore(1) ->setNewLinesAfter(2) ); } $cacheItemPool = cache()->getObject('default'); if (cache()->exists('registry')) { $cacheItemPool = cache()->getObject('registry'); } if ($cacheItemPool instanceof CacheItemPoolInterface) { $this->registry = $this->fetchRegistry(); $cacheItemPool->save(new Item('o2languages', $this->registry, false)); } if (count($this->registry) and is_cli()) { output()->verbose( (new Format()) ->setContextualClass(Format::SUCCESS) ->setString(language()->getLine('CLI_REGISTRY_LANGUAGE_VERB_UPDATE_SUCCESS')) ->setNewLinesBefore(1) ->setNewLinesAfter(2) ); } elseif (is_cli()) { output()->verbose( (new Format()) ->setContextualClass(Format::DANGER) ->setString(language()->getLine('CLI_REGISTRY_LANGUAGE_VERB_UPDATE_FAILED')) ->setNewLinesBefore(1) ->setNewLinesAfter(2) ); } }
Language::updateRegistry Update language registry. @return void @throws \Exception
entailment
public function flushRegistry() { $cacheItemPool = cache()->getItemPool('default'); if (cache()->exists('registry')) { $cacheItemPool = cache()->getItemPool('registry'); } if ($cacheItemPool instanceof CacheItemPoolInterface) { $cacheItemPool->deleteItem('o2languages'); } }
Language::flushRegistry Flush language registry. @return void @throws \Psr\Cache\InvalidArgumentException
entailment
public function setSrc($src) { if (strpos($src, 'holder.js') !== false) { $parts = explode('/', $src); $size = end($parts); $this->attributes->addAttribute('data-src', $src); if ( ! $this->attributes->hasAttribute('alt')) { $this->setAlt($size); } } elseif (strpos($src, 'http')) { $this->attributes->addAttribute('src', $src); } elseif (is_file($src)) { $src = path_to_url($src); $this->attributes->addAttribute('src', $src); } return $this; }
Image::setSrc @param string $src @return static
entailment
public function getResult() { if ($this->map->currentModel->row instanceof Sql\DataObjects\Result\Row) { $criteria = $this->map->currentModel->row->offsetGet($this->map->currentPrimaryKey); $field = $this->map->currentTable . '.' . $this->map->currentPrimaryKey; $this->map->referenceModel->qb ->select([ $this->map->referenceTable . '.*', ]) ->join($this->map->currentTable, implode(' = ', [ $this->map->currentTable . '.' . $this->map->currentPrimaryKey, $this->map->intermediaryTable . '.' . $this->map->intermediaryCurrentForeignKey, ])) ->join($this->map->referenceTable, implode(' = ', [ $this->map->referenceTable . '.' . $this->map->referencePrimaryKey, $this->map->intermediaryTable . '.' . $this->map->intermediaryReferenceForeignKey, ])); if ($result = $this->map->intermediaryModel->find($criteria, $field)) { return $result; } } return false; }
BelongsToManyThrough::getResult @return array|bool|\O2System\Framework\Models\Sql\DataObjects\Result\Row
entailment
public function bootstrapBreadcrumbsFunction(array $args = [], NavigationTree $tree, Request $request) { NavigationTreeHelper::activeTree($tree, $request); return $this->bootstrapBreadcrumbs($tree); }
Displays a Bootstrap breadcrumbs. @param array $args The arguments. @param NavigationTree $tree The tree. @param Request $request The request. @return string Returns the Bootstrap breadcrumbs.
entailment
public function parseRequest(KernelMessageUri $uri = null) { $this->uri = is_null($uri) ? new KernelMessageUri() : $uri; $uriSegments = $this->uri->getSegments()->getParts(); $uriString = $this->uri->getSegments()->getString(); if ($this->uri->getSegments()->getTotalParts()) { if (strpos(end($uriSegments), '.json') !== false) { output()->setContentType('application/json'); $endSegment = str_replace('.json', '', end($uriSegments)); array_pop($uriSegments); array_push($uriSegments, $endSegment); $this->uri = $this->uri->withSegments(new KernelMessageUriSegments($uriSegments)); $uriString = $this->uri->getSegments()->getString(); } elseif (strpos(end($uriSegments), '.xml') !== false) { output()->setContentType('application/xml'); $endSegment = str_replace('.xml', '', end($uriSegments)); array_pop($uriSegments); array_push($uriSegments, $endSegment); $this->uri = $this->uri->withSegments(new KernelMessageUriSegments($uriSegments)); $uriString = $this->uri->getSegments()->getString(); } elseif (strpos(end($uriSegments), '.js') !== false) { output()->setContentType('application/x-javascript'); $endSegment = str_replace('.js', '', end($uriSegments)); array_pop($uriSegments); array_push($uriSegments, $endSegment); $this->uri = $this->uri->withSegments(new KernelMessageUriSegments($uriSegments)); $uriString = $this->uri->getSegments()->getString(); } elseif (strpos(end($uriSegments), '.css') !== false) { output()->setContentType('text/css'); $endSegment = str_replace('.css', '', end($uriSegments)); array_pop($uriSegments); array_push($uriSegments, $endSegment); $this->uri = $this->uri->withSegments(new KernelMessageUriSegments($uriSegments)); $uriString = $this->uri->getSegments()->getString(); } } else { $uriPath = urldecode( parse_url($_SERVER[ 'REQUEST_URI' ], PHP_URL_PATH) ); $uriPathParts = explode('public/', $uriPath); $uriPath = end($uriPathParts); if ($uriPath !== '/') { $uriString = $uriPath; $uriSegments = array_filter(explode('/', $uriString)); $this->uri = $this->uri->withSegments(new KernelMessageUriSegments($uriSegments)); $uriString = $this->uri->getSegments()->getString(); } } // Load app addresses config $this->addresses = config()->loadFile('addresses', true); if ($this->addresses instanceof KernelAddresses) { // Domain routing if (null !== ($domain = $this->addresses->getDomain())) { if (is_array($domain)) { $uriSegments = array_merge($domain, $uriSegments); $this->uri = $this->uri->withSegments(new KernelMessageUriSegments($uriSegments)); $uriString = $this->uri->getSegments()->getString(); $domain = reset($uriSegments); } if (false !== ($app = modules()->getApp($domain))) { $this->registerModule($app); } elseif (false !== ($module = modules()->getModule($domain))) { $this->registerModule($module); } } elseif (false !== ($subdomain = $this->uri->getSubdomain())) { if (false !== ($app = modules()->getApp($subdomain))) { $this->registerModule($app); } } } // Module routing if ($numOfUriSegments = count($uriSegments)) { if (empty($app)) { if (false !== ($module = modules()->getModule( reset($uriSegments) ))) { //array_shift($uriSegments); $this->uri = $this->uri->withSegments(new KernelMessageUriSegments($uriSegments)); $uriString = $this->uri->getSegments()->getString(); $this->registerModule($module); } } if($numOfUriSegments = count($uriSegments)) { for ($i = 0; $i <= $numOfUriSegments; $i++) { $uriRoutedSegments = array_diff($uriSegments, array_slice($uriSegments, ($numOfUriSegments - $i))); if (false !== ($module = modules()->getModule($uriRoutedSegments))) { $uriSegments = array_diff($uriSegments, $uriRoutedSegments); $this->uri = $this->uri->withSegments(new KernelMessageUriSegments($uriSegments)); $uriString = $this->uri->getSegments()->getString(); $this->registerModule($module); break; } } } } // Try to translate from uri string if (false !== ($action = $this->addresses->getTranslation($uriString))) { if ( ! $action->isValidHttpMethod(input()->server('REQUEST_METHOD')) && ! $action->isAnyHttpMethod()) { output()->sendError(405); } else { // Checks if action closure is an array if (is_array($closureSegments = $action->getClosure())) { // Closure App Routing if (false !== ($app = modules()->getModule(reset($closureSegments)))) { array_shift($closureSegments); $this->registerModule($app); } // Closure Module routing if ($numOfClosureSegments = count($closureSegments)) { for ($i = 0; $i <= $numOfClosureSegments; $i++) { $closureRoutedSegments = array_diff($closureSegments, array_slice($closureSegments, ($numOfClosureSegments - $i))); if ( ! empty($app)) { if (reset($closureSegments) !== $app->getParameter()) { array_unshift($closureRoutedSegments, $app->getParameter()); } } if (false !== ($module = modules()->getModule($closureRoutedSegments))) { $uriSegments = array_diff($closureSegments, $closureRoutedSegments); $this->uri = $this->uri->withSegments(new KernelMessageUriSegments($closureSegments)); $uriString = $this->uri->getSegments()->getString(); $this->registerModule($module); break; } } } } else { if (false !== ($parseSegments = $action->getParseUriString($uriString))) { $uriSegments = $parseSegments; } else { $uriSegments = []; } $this->uri = $this->uri->withSegments(new KernelMessageUriSegments($uriSegments)); $uriString = $this->uri->getSegments()->getString(); $this->parseAction($action, $uriSegments); if ( ! empty(services()->has('controller'))) { return true; } } } } // Try to get route from controller & page if ($numOfUriSegments = count($uriSegments)) { for ($i = 0; $i <= $numOfUriSegments; $i++) { $uriRoutedSegments = array_slice($uriSegments, 0, ($numOfUriSegments - $i)); $modules = modules()->getArrayCopy(); foreach ($modules as $module) { $controllerNamespace = $module->getNamespace() . 'Controllers\\'; if ($module->getNamespace() === 'O2System\Framework\\') { $controllerNamespace = 'O2System\Framework\Http\Controllers\\'; } /** * Try to find requested controller */ if (class_exists($controllerClassName = $controllerNamespace . implode('\\', array_map('studlycase', $uriRoutedSegments)))) { if($controllerClassName::$inherited) { $uriSegments = array_diff($uriSegments, $uriRoutedSegments); $this->setController(new KernelControllerDataStructure($controllerClassName), $uriSegments); break; } } /** * Try to find requested page */ if (false !== ($pagesDir = $module->getResourcesDir('pages', true))) { if($controllerClassName = $this->getPagesControllerClassName()) { /** * Try to find from database */ $modelClassName = str_replace('Controllers', 'Models', $controllerClassName); if (class_exists($modelClassName)) { models()->load($modelClassName, 'controller'); if (false !== ($page = models('controller')->find($uriString, 'segments'))) { if (isset($page->content)) { presenter()->partials->offsetSet('content', $page->content); $this->setController( (new KernelControllerDataStructure($controllerClassName)) ->setRequestMethod('index') ); return true; break; } } } /** * Try to find from page file */ $pageFilePath = $pagesDir . implode(DIRECTORY_SEPARATOR, array_map('dash', $uriRoutedSegments)) . '.phtml'; if (is_file($pageFilePath)) { presenter()->page->setFile($pageFilePath); } else { $pageFilePath = str_replace('.phtml', DIRECTORY_SEPARATOR . 'index.phtml', $pageFilePath); if(is_file($pageFilePath)) { presenter()->page->setFile($pageFilePath); } } if(presenter()->page->file instanceof SplFileInfo) { $this->setController( (new KernelControllerDataStructure($controllerClassName)) ->setRequestMethod('index') ); return true; break; } } } } // break the loop if the controller has been set if (services()->has('controller')) { return true; break; } } } if (class_exists($controllerClassName = modules()->top()->getDefaultControllerClassName())) { $this->setController(new KernelControllerDataStructure($controllerClassName), $uriSegments); return true; } // Let's the framework do the rest when there is no controller found // the framework will redirect to PAGE 404 }
Router::parseRequest @param KernelMessageUri|null $uri @return bool @throws \ReflectionException
entailment
final protected function getPagesControllerClassName() { $modules = modules()->getArrayCopy(); foreach($modules as $module) { $controllerClassName = $module->getNamespace() . 'Controllers\Pages'; if ($module->getNamespace() === 'O2System\Framework\\') { $controllerClassName = 'O2System\Framework\Http\Controllers\Pages'; } if(class_exists($controllerClassName)) { return $controllerClassName; break; } } if(class_exists('O2System\Framework\Http\Controllers\Pages')) { return 'O2System\Framework\Http\Controllers\Pages'; } return false; }
Router::getPagesControllerClassName @return bool|string
entailment
final public function registerModule(FrameworkModuleDataStructure $module) { // Push Subdomain App Module modules()->push($module); // Add Config FilePath config()->addFilePath($module->getRealPath()); // Reload Config config()->reload(); // Load modular addresses config if (false !== ($configDir = $module->getDir('config', true))) { unset($addresses); $reconfig = false; if (is_file( $filePath = $configDir . ucfirst( strtolower(ENVIRONMENT) ) . DIRECTORY_SEPARATOR . 'Addresses.php' )) { require($filePath); $reconfig = true; } elseif (is_file( $filePath = $configDir . 'Addresses.php' )) { require($filePath); $reconfig = true; } if ( ! $reconfig) { $controllerNamespace = $module->getNamespace() . 'Controllers\\'; $controllerClassName = $controllerNamespace . studlycase($module->getParameter()); if (class_exists($controllerClassName)) { $this->addresses->any( '/', function () use ($controllerClassName) { return new $controllerClassName(); } ); } } elseif (isset($addresses)) { $this->addresses = $addresses; } } else { $controllerNamespace = $module->getNamespace() . 'Controllers\\'; $controllerClassName = $controllerNamespace . studlycase($module->getParameter()); if (class_exists($controllerClassName)) { $this->addresses->any( '/', function () use ($controllerClassName) { return new $controllerClassName(); } ); } } }
Router::registerModule @param FrameworkModuleDataStructure $module
entailment
protected function parseAction(KernelActionDataStructure $action, array $uriSegments = []) { ob_start(); $closure = $action->getClosure(); if (empty($closure)) { $closure = ob_get_contents(); } ob_end_clean(); if ($closure instanceof Controller) { $uriSegments = empty($uriSegments) ? $action->getClosureParameters() : $uriSegments; $this->setController( (new KernelControllerDataStructure($closure)) ->setRequestMethod('index'), $uriSegments ); } elseif ($closure instanceof KernelControllerDataStructure) { $this->setController($closure, $action->getClosureParameters()); } elseif (is_array($closure)) { $this->uri = (new KernelMessageUri()) ->withSegments(new KernelMessageUriSegments('')) ->withQuery(''); $this->parseRequest($this->uri->addSegments($closure)); } else { if (class_exists($closure)) { $this->setController( (new KernelControllerDataStructure($closure)) ->setRequestMethod('index'), $uriSegments ); } elseif (preg_match("/([a-zA-Z0-9\\\]+)(@)([a-zA-Z0-9\\\]+)/", $closure, $matches)) { $this->setController( (new KernelControllerDataStructure($matches[ 1 ])) ->setRequestMethod($matches[ 3 ]), $uriSegments ); } elseif (presenter()->theme->use === true) { if ( ! presenter()->partials->offsetExists('content') && $closure !== '') { presenter()->partials->offsetSet('content', $closure); } if (presenter()->partials->offsetExists('content')) { profiler()->watch('VIEW_SERVICE_RENDER'); view()->render(); exit(EXIT_SUCCESS); } else { output()->sendError(204); exit(EXIT_ERROR); } } elseif (is_string($closure) && $closure !== '') { if (is_json($closure)) { output()->setContentType('application/json'); output()->send($closure); } else { output()->send($closure); } } elseif (is_array($closure) || is_object($closure)) { output()->send($closure); } elseif (is_numeric($closure)) { output()->sendError($closure); } else { output()->sendError(204); exit(EXIT_ERROR); } } }
Router::parseAction @param KernelActionDataStructure $action @param array $uriSegments @throws \ReflectionException
entailment
public function bootstrapDropdownButtonFunction(array $args = []) { return $this->bootstrapDropdownButton(ArrayHelper::get($args, "content"), ArrayHelper::get($args, "id"), ArrayHelper::get($args, "expanded", true), ArrayHelper::get($args, "class", "default")); }
Displays a Bootstrap dropdown "Button". @param array $args The arguments. @return string Returns the Bootstrap dropdown "Button".
entailment
public function getProgressBar() : ProgressBar { if (!$this->progressBar) { $this->progressBar = new ProgressBar($this->getOutput(), $this->numRecords); $this->progressBar->setFormat('debug'); $this->progressBar->setBarWidth((int) exec('tput cols')); } return $this->progressBar; }
Allows to modify the progress bar instance @return ProgressBar
entailment
public function setAuthor($name, $href = null) { $this->author = new Element('small', 'author'); if (isset($href)) { $this->author->childNodes->push(new Link($name, $href)); } else { $this->author->textContent->push($name); } return $this; }
Blockquote::setAuthor @param string $name @param string|null $href @return static
entailment
public function setSource($name, $href = null) { $this->source = new Element('cite', 'source'); if (isset($href)) { $this->source->childNodes->push(new Link($name, $href)); } else { $this->source->textContent->push($name); } return $this; }
Blockquote::setSource @param string $name @param string|null $href @return static
entailment
public function render() { if ($this->paragraph instanceof Element) { $this->childNodes->push($this->paragraph); } $footer = new Element('div', 'footer'); $footer->attributes->addAttributeClass('blockquote-footer'); if ($this->author instanceof Element) { $footer->childNodes->push($this->author); if ($this->author->tagName === 'small' && $this->source instanceof Element) { $this->author->childNodes->push($this->source); } elseif ($this->source instanceof Element) { $footer->childNodes->push($this->source); } } elseif ($this->source instanceof Element) { $footer->childNodes->push($this->source); } $this->childNodes->push($footer); if ($this->hasChildNodes()) { return parent::render(); } return ''; }
Blockquote::render @return string
entailment
public function createToken($redirectUri, $owner, $client, array $scopes = []): AuthorizationCode { if (empty($scopes)) { $scopes = $this->scopeService->getDefaultScopes(); } else { $this->validateTokenScopes($scopes); } do { $token = AuthorizationCode::createNewAuthorizationCode( $this->serverOptions->getAuthorizationCodeTtl(), $redirectUri, $owner, $client, $scopes ); } while ($this->tokenRepository->tokenExists($token->getToken())); return $this->tokenRepository->save($token); }
Create a new token (and generate the token) @param string $redirectUri @param TokenOwnerInterface $owner @param Client $client @param string[]|Scope[] $scopes @return AuthorizationCode @throws OAuth2Exception
entailment
public function hash(string $password): string { $hash = \password_hash($password, $this->algo, $this->options[$this->algo]); return $hash; }
Create password hash from the given string and return it. <pre><code class="php">$password = new Password(); $hash = $password->hash('FooPassword'); //var_dump result //$2y$11$cq3ZWO18l68X7pGs9Y1fveTGcNJ/iyehrDZ10BAvbY8LaBXNvnyk6 var_dump($hash) </code></pre> @param string $password @return string Hashed password.
entailment
public function needsRehash(string $hash): bool { return \password_needs_rehash($hash, $this->algo, $this->options[$this->algo]); }
Checks if the given hash matches the algorithm and the options provided. <pre><code class="php">$password = new Password(); $hash = '$2y$11$cq3ZWO18l68X7pGs9Y1fveTGcNJ/iyehrDZ10BAvbY8LaBXNvnyk6'; //true if rehash is needed, false if no $rehashCheck = $password->needsRehash($hash); </code></pre> @param string $hash @return bool
entailment
public static function columnTypeToPhpTypeHinting(array $dataTypeInfo): string { switch ($dataTypeInfo['data_type']) { case 'tinyint': case 'smallint': case 'mediumint': case 'int': case 'bigint': case 'year': $phpType = 'int'; break; case 'decimal': $phpType = 'int|float|string'; break; case 'float': case 'double': $phpType = 'float'; break; case 'bit': case 'varbinary': case 'binary': case 'char': case 'varchar': case 'time': case 'timestamp': case 'date': case 'datetime': case 'enum': case 'set': case 'tinytext': case 'text': case 'mediumtext': case 'longtext': case 'tinyblob': case 'blob': case 'mediumblob': case 'longblob': $phpType = 'string'; break; case 'list_of_int': $phpType = 'string|int[]'; break; default: throw new FallenException('data type', $dataTypeInfo['data_type']); } return $phpType; }
Returns the corresponding PHP type hinting of a MySQL column type. @param string[] $dataTypeInfo Metadata of the MySQL data type. @return string
entailment
public static function deriveFieldLength(array $dataTypeInfo): ?int { switch ($dataTypeInfo['data_type']) { case 'tinyint': case 'smallint': case 'mediumint': case 'int': case 'bigint': case 'float': case 'double': $ret = $dataTypeInfo['numeric_precision']; break; case 'decimal': $ret = $dataTypeInfo['numeric_precision']; if ($dataTypeInfo['numeric_scale']>0) $ret += 1; break; case 'char': case 'varchar': case 'binary': case 'varbinary': case 'tinytext': case 'text': case 'mediumtext': case 'longtext': case 'tinyblob': case 'blob': case 'mediumblob': case 'longblob': case 'bit': $ret = $dataTypeInfo['character_maximum_length']; break; case 'timestamp': $ret = 16; break; case 'year': $ret = 4; break; case 'time': $ret = 8; break; case 'date': $ret = 10; break; case 'datetime': $ret = 16; break; case 'enum': case 'set': // We don't assign a width to column with type enum and set. $ret = null; break; default: throw new FallenException('data type', $dataTypeInfo['data_type']); } return $ret; }
Returns the widths of a field based on a MySQL data type. @param array $dataTypeInfo Metadata of the column on which the field is based. @return int|null
entailment
public static function escapePhpExpression(array $dataTypeInfo, string $expression, bool $lobAsString): string { switch ($dataTypeInfo['data_type']) { case 'tinyint': case 'smallint': case 'mediumint': case 'int': case 'bigint': case 'year': $ret = "'.self::quoteInt(".$expression.").'"; break; case 'float': case 'double': $ret = "'.self::quoteFloat(".$expression.").'"; break; case 'char': case 'varchar': $ret = "'.self::quoteString(".$expression.").'"; break; case 'binary': case 'varbinary': $ret = "'.self::quoteBinary(".$expression.").'"; break; case 'decimal': $ret = "'.self::quoteDecimal(".$expression.").'"; break; case 'time': case 'timestamp': case 'date': case 'datetime': $ret = "'.self::quoteString(".$expression.").'"; break; case 'enum': case 'set': $ret = "'.self::quoteString(".$expression.").'"; break; case 'bit': $ret = "'.self::quoteBit(".$expression.").'"; break; case 'tinytext': case 'text': case 'mediumtext': case 'longtext': $ret = ($lobAsString) ? $ret = "'.self::quoteString(".$expression.").'" : '?'; break; case 'tinyblob': case 'blob': case 'mediumblob': case 'longblob': $ret = ($lobAsString) ? $ret = "'.self::quoteBinary(".$expression.").'" : '?'; break; case 'list_of_int': $ret = "'.self::quoteListOfInt(".$expression.", '". addslashes($dataTypeInfo['delimiter'])."', '". addslashes($dataTypeInfo['enclosure'])."', '". addslashes($dataTypeInfo['escape'])."').'"; break; default: throw new FallenException('data type', $dataTypeInfo['data_type']); } return $ret; }
Returns PHP code escaping the value of a PHP expression that can be safely used when concatenating a SQL statement. @param array $dataTypeInfo Metadata of the column on which the field is based. @param string $expression The PHP expression. @param bool $lobAsString A flag indication LOBs must be treated as strings. @return string The generated PHP code.
entailment
public static function getBindVariableType(array $dataTypeInfo, bool $lobAsString): string { $ret = ''; switch ($dataTypeInfo['data_type']) { case 'tinyint': case 'smallint': case 'mediumint': case 'int': case 'bigint': case 'year': $ret = 'i'; break; case 'float': case 'double': $ret = 'd'; break; case 'time': case 'timestamp': case 'binary': case 'enum': case 'bit': case 'set': case 'char': case 'varchar': case 'date': case 'datetime': case 'varbinary': $ret = 's'; break; case 'decimal': $ret = 's'; break; case 'tinytext': case 'text': case 'mediumtext': case 'longtext': case 'tinyblob': case 'blob': case 'mediumblob': case 'longblob': $ret .= ($lobAsString) ? 's' : 'b'; break; case 'list_of_int': $ret = 's'; break; default: throw new FallenException('parameter type', $dataTypeInfo['data_type']); } return $ret; }
Returns the type of a bind variable. @see http://php.net/manual/en/mysqli-stmt.bind-param.php @param array $dataTypeInfo Metadata of the column on which the field is based. @param bool $lobAsString A flag indication LOBs must be treated as strings. @return string
entailment
public static function isBlobParameter(string $dataType): bool { switch ($dataType) { case 'tinytext': case 'text': case 'mediumtext': case 'longtext': case 'tinyblob': case 'blob': case 'mediumblob': case 'longblob': $isBlob = true; break; case 'tinyint': case 'smallint': case 'mediumint': case 'int': case 'bigint': case 'year': case 'decimal': case 'float': case 'double': case 'time': case 'timestamp': case 'binary': case 'enum': case 'bit': case 'set': case 'char': case 'varchar': case 'date': case 'datetime': case 'varbinary': case 'list_of_int': $isBlob = false; break; default: throw new FallenException('data type', $dataType); } return $isBlob; }
Returns true if one if a MySQL column type is a BLOB or a CLOB. @param string $dataType Metadata of the MySQL data type. @return bool
entailment
public static function phpTypeHintingToPhpTypeDeclaration(string $phpTypeHint): string { $phpType = ''; switch ($phpTypeHint) { case 'array': case 'array[]': case 'bool': case 'float': case 'int': case 'string': case 'void': $phpType = $phpTypeHint; break; default: $parts = explode('|', $phpTypeHint); $key = array_search('null', $parts); if (count($parts)==2 && $key!==false) { unset($parts[$key]); $tmp = static::phpTypeHintingToPhpTypeDeclaration(implode('|', $parts)); if ($tmp!=='') { $phpType = '?'.$tmp; } } } return $phpType; }
Returns the corresponding PHP type declaration of a MySQL column type. @param string $phpTypeHint The PHP type hinting. @return string
entailment
public function handle(ServerRequestInterface $request) { if (cache()->hasItem('maintenance')) { $maintenanceInfo = cache()->getItem('maintenance')->get(); echo view()->load('maintenance', $maintenanceInfo, true); exit(EXIT_SUCCESS); } }
Maintenance::handle Handles a request and produces a response May call other collaborating code to generate the response. @param \O2System\Psr\Http\Message\ServerRequestInterface $request
entailment
private function match(string $path, string $suffix): bool { return substr($path, -strlen($suffix)) === $suffix; }
Match transformer for the suffix? (.json?)
entailment
public function render() { $output[] = $this->open(); if ($this->hasChildNodes()) { $output[] = implode(PHP_EOL, $this->childNodes->getArrayCopy()); } return implode(PHP_EOL, $output); }
Image::render @return string
entailment
public function getFilePath($filename) { if (modules()) { $filePaths = modules()->getDirs('Views'); } else { $filePaths = array_reverse($this->filePaths); } foreach ($filePaths as $filePath) { if (is_file($filePath . $filename . '.phtml')) { return $filePath . $filename . '.phtml'; break; } elseif (is_file($filePath . 'errors' . DIRECTORY_SEPARATOR . $filename . '.phtml')) { return $filePath . 'errors' . DIRECTORY_SEPARATOR . $filename . '.phtml'; break; } } }
Output::getFilePath @param string $filename @return string
entailment
public function errorHandler($errorSeverity, $errorMessage, $errorFile, $errorLine, $errorContext = []) { $isFatalError = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $errorSeverity) === $errorSeverity); if (strpos($errorFile, 'parser') !== false) { if (function_exists('parser')) { if (services()->has('presenter')) { $vars = presenter()->getArrayCopy(); extract($vars); } $errorFile = str_replace(PATH_ROOT, DIRECTORY_SEPARATOR, parser()->getSourceFilePath()); $error = new ErrorException($errorMessage, $errorSeverity, $errorFile, $errorLine, $errorContext); $filePath = $this->getFilePath('error'); ob_start(); include $filePath; $htmlOutput = ob_get_contents(); ob_end_clean(); echo $htmlOutput; return true; } } // When the error is fatal the Kernel will throw it as an exception. if ($isFatalError) { throw new ErrorException($errorMessage, $errorSeverity, $errorLine, $errorLine, $errorContext); } // Should we ignore the error? We'll get the current error_reporting // level and add its bits with the severity bits to find out. if (($errorSeverity & error_reporting()) !== $errorSeverity) { return false; } $error = new ErrorException($errorMessage, $errorSeverity, $errorFile, $errorLine, $errorContext); // Logged the error if(services()->has('logger')) { logger()->error( implode( ' ', [ '[ ' . $error->getStringSeverity() . ' ] ', $error->getMessage(), $error->getFile() . ':' . $error->getLine(), ] ) ); } // Should we display the error? if (str_ireplace(['off', 'none', 'no', 'false', 'null'], 0, ini_get('display_errors')) == 1) { if (is_ajax()) { $this->setContentType('application/json'); $this->statusCode = 500; $this->reasonPhrase = 'Internal Server Error'; $this->send(implode( ' ', [ '[ ' . $error->getStringSeverity() . ' ] ', $error->getMessage(), $error->getFile() . ':' . $error->getLine(), ] )); exit(EXIT_ERROR); } if (services()->has('presenter')) { if (presenter()->theme) { presenter()->theme->load(); } $vars = presenter()->getArrayCopy(); extract($vars); } $filePath = $this->getFilePath('error'); ob_start(); include $filePath; $htmlOutput = ob_get_contents(); ob_end_clean(); if (services()->has('presenter')) { $htmlOutput = presenter()->assets->parseSourceCode($htmlOutput); } echo $htmlOutput; exit(EXIT_ERROR); } }
Output::errorHandler Kernel defined error handler function. @param int $errorSeverity The first parameter, errno, contains the level of the error raised, as an integer. @param string $errorMessage The second parameter, errstr, contains the error message, as a string. @param string $errorFile The third parameter is optional, errfile, which contains the filename that the error was raised in, as a string. @param string $errorLine The fourth parameter is optional, errline, which contains the line number the error was raised at, as an integer. @param array $errorContext The fifth parameter is optional, errcontext, which is an array that points to the active symbol table at the point the error occurred. In other words, errcontext will contain an array of every variable that existed in the scope the error was triggered in. User error handler must not modify error context. @return bool If the function returns FALSE then the normal error handler continues. @throws ErrorException
entailment
public function sendError($code = 204, $vars = null, $headers = []) { $languageKey = $code . '_' . error_code_string($code); $error = [ 'code' => $code, 'title' => language()->getLine($languageKey . '_TITLE'), 'message' => language()->getLine($languageKey . '_MESSAGE'), ]; $this->statusCode = $code; $this->reasonPhrase = $error[ 'title' ]; if (is_string($vars)) { $vars = ['message' => $vars]; } elseif (is_array($vars) and empty($vars[ 'message' ])) { $vars[ 'message' ] = $error[ 'message' ]; } if (isset($vars[ 'message' ])) { $error[ 'message' ] = $vars[ 'message' ]; } if (is_ajax() or $this->mimeType !== 'text/html') { $this->statusCode = $code; $this->reasonPhrase = $error[ 'title' ]; $this->send($vars); exit(EXIT_ERROR); } $this->sendHeaders($headers); if (services()->has('presenter')) { presenter()->initialize(); if (presenter()->theme) { presenter()->theme->load(); } $vars = presenter()->getArrayCopy(); extract($vars); } extract($error); ob_start(); include $this->getFilePath('error-code'); $htmlOutput = ob_get_contents(); ob_end_clean(); if (services()->has('presenter')) { $htmlOutput = presenter()->assets->parseSourceCode($htmlOutput); } echo $htmlOutput; exit(EXIT_ERROR); }
Output::sendError @param int $code @param null|array|string $vars @param array $headers
entailment
public function createToken($owner, $client, array $scopes = []): RefreshToken { if (empty($scopes)) { $scopes = $this->scopeService->getDefaultScopes(); } else { $this->validateTokenScopes($scopes); } do { $token = RefreshToken::createNewRefreshToken( $this->serverOptions->getRefreshTokenTtl(), $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 RefreshToken @throws OAuth2Exception
entailment
public function handle($request, \Closure $next) { if ($request->expectsJson()) { return $next($request); } return json_response()->error([ 'message' => 'Invalid AJAX Request', ], $this->code); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
entailment
private function base64Encode($uri) { if (null === $uri) { return null; } $splFileObject = new SplFileObject($uri); if (30100 < Kernel::VERSION_ID) { return (new DataUriNormalizer())->normalize($splFileObject); } $data = ""; while (false === $splFileObject->eof()) { $data .= $splFileObject->fgets(); } return sprintf("data:%s;base64,%s", mime_content_type($uri), base64_encode($data)); }
Encode an URI into base 64. @param string $uri The URI. @return string Returns the URI encoded into base 64. @throws ExceptionInterface Throws an exception if an error occurs
entailment
public function bootstrapImageBase64Function(array $args = []) { $src = $this->base64Encode(ArrayHelper::get($args, "src")); return $this->bootstrapImage($src, ArrayHelper::get($args, "alt"), ArrayHelper::get($args, "width"), ArrayHelper::get($args, "height"), ArrayHelper::get($args, "class"), ArrayHelper::get($args, "usemap")); }
Displays a Bootstrap image "Base 64". @param array $args The arguments. @return string Returns the Bootstrap base 64 image. @throws ExceptionInterface Throws an exception if an error occurs
entailment
public function handle(ServerRequestInterface $request) { if (null !== ($ssid = input()->get('ssid')) && services()->has('user')) { if (services()->get('user')->validate($ssid)) { set_cookie('ssid', $ssid); echo services()->get('user')->getIframeScript(); exit(EXIT_SUCCESS); } } }
Environment::handle Handles a request and produces a response May call other collaborating code to generate the response. @param \O2System\Psr\Http\Message\ServerRequestInterface $request
entailment
public static function begin(): void { $ret = self::$mysqli->autocommit(false); if (!$ret) self::mySqlError('mysqli::autocommit'); }
Starts a transaction. Wrapper around [mysqli::autocommit](http://php.net/manual/mysqli.autocommit.php), however on failure an exception is thrown. @since 1.0.0 @api
entailment
public static function connect(string $host, string $user, string $password, string $database, int $port = 3306): void { self::$mysqli = new \mysqli($host, $user, $password, $database, $port); if (self::$mysqli->connect_errno) { $message = 'MySQL Error no: '.self::$mysqli->connect_errno."\n"; $message .= str_replace('%', '%%', self::$mysqli->connect_error); $message .= "\n"; throw new RuntimeException($message); } // Set the options. foreach (self::$options as $option => $value) { self::$mysqli->options($option, $value); } // Set the default character set. $ret = self::$mysqli->set_charset(self::$charSet); if (!$ret) self::mySqlError('mysqli::set_charset'); // Set the SQL mode. self::executeNone("set sql_mode = '".self::$sqlMode."'"); // Set transaction isolation level. self::executeNone("set session tx_isolation = '".self::$transactionIsolationLevel."'"); // Set flag to use method mysqli_result::fetch_all if we are using MySQL native driver. self::$haveFetchAll = method_exists('mysqli_result', 'fetch_all'); }
Connects to a MySQL instance. Wrapper around [mysqli::__construct](http://php.net/manual/mysqli.construct.php), however on failure an exception is thrown. @param string $host The hostname. @param string $user The MySQL user name. @param string $password The password. @param string $database The default database. @param int $port The port number. @since 1.0.0 @api
entailment
public static function disconnect(): void { if (self::$mysqli!==null) { self::$mysqli->close(); self::$mysqli = null; } }
Closes the connection to the MySQL instance, if connected. @since 1.0.0 @api
entailment
public static function executeBulk(BulkHandler $bulkHandler, string $query): void { self::realQuery($query); $bulkHandler->start(); $result = self::$mysqli->use_result(); while (($row = $result->fetch_assoc())) { $bulkHandler->row($row); } $result->free(); $bulkHandler->stop(); if (self::$mysqli->more_results()) self::$mysqli->next_result(); }
Executes a query using a bulk handler. @param BulkHandler $bulkHandler The bulk handler. @param string $query The SQL statement. @since 1.0.0 @api
entailment
public static function executeMulti(string $queries): array { $ret = []; self::multiQuery($queries); do { $result = self::$mysqli->store_result(); if (self::$mysqli->errno) self::mySqlError('mysqli::store_result'); if ($result) { if (self::$haveFetchAll) { $ret[] = $result->fetch_all(MYSQLI_ASSOC); } else { $tmp = []; while (($row = $result->fetch_assoc())) { $tmp[] = $row; } $ret[] = $tmp; } $result->free(); } else { $ret[] = self::$mysqli->affected_rows; } $continue = self::$mysqli->more_results(); if ($continue) { $tmp = self::$mysqli->next_result(); if ($tmp===false) self::mySqlError('mysqli::next_result'); } } while ($continue); return $ret; }
Executes multiple queries and returns an array with the "result" of each query, i.e. the length of the returned array equals the number of queries. For SELECT, SHOW, DESCRIBE or EXPLAIN queries the "result" is the selected rows (i.e. an array of arrays), for other queries the "result" is the number of effected rows. @param string $queries The SQL statements. @return array @since 1.0.0 @api
entailment
public static function executeNone(string $query): int { self::realQuery($query); $n = self::$mysqli->affected_rows; if (self::$mysqli->more_results()) self::$mysqli->next_result(); return $n; }
Executes a query that does not select any rows. @param string $query The SQL statement. @return int The number of affected rows (if any). @since 1.0.0 @api
entailment
public static function executeSingleton0(string $query) { $result = self::query($query); $row = $result->fetch_array(MYSQLI_NUM); $n = $result->num_rows; $result->free(); if (self::$mysqli->more_results()) self::$mysqli->next_result(); if (!($n==0 || $n==1)) { throw new ResultException('0 or 1', $n, $query); } return $row[0]; }
Executes a query that returns 0 or 1 row with one column. Throws an exception if the query selects 2 or more rows. @param string $query The SQL statement. @return mixed The selected value. @since 1.0.0 @api
entailment
public static function getMaxAllowedPacket(): int { if (!isset(self::$maxAllowedPacket)) { $query = "show variables like 'max_allowed_packet'"; $max_allowed_packet = self::executeRow1($query); self::$maxAllowedPacket = $max_allowed_packet['Value']; // Note: When setting $chunkSize equal to $maxAllowedPacket it is not possible to transmit a LOB // with size $maxAllowedPacket bytes (but only $maxAllowedPacket - 8 bytes). But when setting the size of // $chunkSize less than $maxAllowedPacket than it is possible to transmit a LOB with size // $maxAllowedPacket bytes. self::$chunkSize = (int)min(self::$maxAllowedPacket - 8, 1024 * 1024); } return (int)self::$maxAllowedPacket; }
Returns the value of the MySQL variable max_allowed_packet. @return int
entailment
public static function quoteBit(?string $bits): string { if ($bits===null || $bits==='') { return 'null'; } return "b'".self::$mysqli->real_escape_string($bits)."'"; }
Returns a literal for a bit value that can be safely used in SQL statements. @param string|null $bits The bit value. @return string
entailment
public static function quoteDecimal($value): string { if ($value===null || $value==='') return 'null'; if (is_int($value) || is_float($value)) return (string)$value; return "'".self::$mysqli->real_escape_string($value)."'"; }
Returns a literal for a decimal value that can be safely used in SQL statements. @param float|int|string|null $value The value. @return string
entailment
public static function quoteString(?string $value): string { if ($value===null || $value==='') return 'null'; return "'".self::$mysqli->real_escape_string($value)."'"; }
Returns a literal for a string value that can be safely used in SQL statements. @param string|null $value The value. @return string
entailment
protected static function multiQuery(string $queries): void { if (self::$logQueries) { $time0 = microtime(true); $tmp = self::$mysqli->multi_query($queries); if ($tmp===false) { throw new DataLayerException(self::$mysqli->errno, self::$mysqli->error, $queries); } self::$queryLog[] = ['query' => $queries, 'time' => microtime(true) - $time0]; } else { $tmp = self::$mysqli->multi_query($queries); if ($tmp===false) { throw new DataLayerException(self::$mysqli->errno, self::$mysqli->error, $queries); } } }
Executes multiple SQL statements. Wrapper around [multi_mysqli::query](http://php.net/manual/mysqli.multi-query.php), however on failure an exception is thrown. @param string $queries The SQL statements. @return void
entailment
protected static function realQuery(string $query): void { if (self::$logQueries) { $time0 = microtime(true); $tmp = self::$mysqli->real_query($query); if ($tmp===false) { throw new DataLayerException(self::$mysqli->errno, self::$mysqli->error, $query); } self::$queryLog[] = ['query' => $query, 'time' => microtime(true) - $time0]; } else { $tmp = self::$mysqli->real_query($query); if ($tmp===false) { throw new DataLayerException(self::$mysqli->errno, self::$mysqli->error, $query); } } }
Execute a query without a result set. Wrapper around [mysqli::real_query](http://php.net/manual/en/mysqli.real-query.php), however on failure an exception is thrown. For SELECT, SHOW, DESCRIBE or EXPLAIN queries, see @query. @param string $query The SQL statement.
entailment
private static function executeTableShowTableColumn(array $column, $value): void { $spaces = str_repeat(' ', $column['length'] - mb_strlen((string)$value)); switch ($column['type']) { case 1: // tinyint case 2: // smallint case 3: // int case 4: // float case 5: // double case 8: // bigint case 9: // mediumint case 246: // decimal echo ' ', $spaces.$value, ' '; break; case 7: // timestamp case 10: // date case 11: // time case 12: // datetime case 13: // year case 16: // bit case 252: // is currently mapped to all text and blob types (MySQL 5.0.51a) case 253: // varchar case 254: // char echo ' ', $value.$spaces, ' '; break; default: throw new FallenException('data type id', $column['type']); } }
Helper method for method executeTable. Shows table cell with data. @param array $column The metadata of the column. @param mixed $value The value of the table cell.
entailment
public function setTextContent($textContent) { $this->entity->setEntityName('ribbon-' . $textContent); $this->textContent->push($textContent); return $this; }
Ribbon::setTextContent @param string $textContent @return static
entailment
public function insert(array $sets) { if (count($sets)) { if (method_exists($this, 'insertRecordSets')) { $this->insertRecordSets($sets); } if (method_exists($this, 'beforeInsert')) { $this->beforeInsert($sets); } if (method_exists($this, 'getRecordOrdering')) { if ($this->recordOrdering === true && empty($sets[ 'record_ordering' ])) { $sets[ 'record_ordering' ] = $this->getRecordOrdering($this->table); } } if ($this->qb->table($this->table)->insert($sets)) { if (method_exists($this, 'afterInsert')) { return $this->afterInsert(); } return true; } } return false; }
ModifierTrait::insert @param array $sets @return bool
entailment
public function insertOrUpdate(array $sets) { if ($result = $this->qb->from($this->table)->getWhere($sets)) { return $this->update($sets); } else { return $this->insert($sets); } return false; }
ModifierTrait::insertOrUpdate @param array $sets @return bool
entailment
public function insertMany(array $sets) { if (count($sets)) { if (method_exists($this, 'insertRecordSets')) { foreach ($sets as $set) { $this->insertRecordSets($set); if ($this->recordOrdering === true && empty($sets[ 'record_ordering' ])) { $set[ 'record_ordering' ] = $this->getRecordOrdering($this->table); } } } if (method_exists($this, 'beforeInsertMany')) { $this->beforeInsertMany($sets); } if ($this->qb->table($this->table)->insertBatch($sets)) { if (method_exists($this, 'afterInsertMany')) { return $this->afterInsertMany(); } return $this->db->getAffectedRows(); } } return false; }
ModifierTrait::insertMany @param array $sets @return bool|int
entailment
public function insertIfNotExists(array $sets, array $conditions = []) { if (count($sets)) { if ($result = $this->qb->from($this->table)->getWhere($conditions)) { if ($result->count() == 0) { return $this->insert($sets); } } } return false; }
ModifierTrait::insertIfNotExists @param array $sets @param array $conditions @return bool
entailment