sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function createRow()
{
$row = new Row();
$this->childNodes->push($row);
return $this->childNodes->last();
} | Body::createRow
@return Row | entailment |
public function createBlockquote($text = null)
{
$blockquote = new Blockquote();
if (isset($text)) {
$blockquote->setParagraph($text);
}
$this->childNodes->push($blockquote);
return $this->childNodes->last();
} | Body::createBlockquote
@param string|null $text
@return \O2System\Framework\Libraries\Ui\Components\Card\Body\Blockquote | 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()) {
return parent::render();
}
return '';
} | Body::render
@return string | entailment |
public function render()
{
if ( ! $this->label->hasTextContent()) {
$this->input->attributes->addAttributeClass('position-static');
}
return parent::render();
} | Checkbox::render
@return string | entailment |
private function generateWrapperClass(): void
{
$this->io->title('Wrapper');
/** @var NameMangler $mangler */
$mangler = new $this->nameMangler();
$routines = $this->readRoutineMetadata();
if (!empty($routines))
{
// Sort routines by their wrapper method name.
$sorted_routines = [];
foreach ($routines as $routine)
{
$method_name = $mangler->getMethodName($routine['routine_name']);
$sorted_routines[$method_name] = $routine;
}
ksort($sorted_routines);
// Write methods for each stored routine.
foreach ($sorted_routines as $method_name => $routine)
{
// If routine type is hidden don't create routine wrapper.
if ($routine['designation']!='hidden')
{
$this->writeRoutineFunction($routine, $mangler);
}
}
}
else
{
echo "No files with stored routines found.\n";
}
$wrappers = $this->codeStore->getRawCode();
$this->codeStore = new PhpCodeStore();
// Write the header of the wrapper class.
$this->writeClassHeader();
// Write methods of the wrapper calls.
$this->codeStore->append($wrappers, false);
// Write the trailer of the wrapper class.
$this->writeClassTrailer();
// Write the wrapper class to the filesystem.
$this->storeWrapperClass();
} | Generates the wrapper class. | entailment |
private function readConfigurationFile(string $configFilename): void
{
// Read the configuration file.
$settings = parse_ini_file($configFilename, true);
// Set default values.
if (!isset($settings['wrapper']['lob_as_string']))
{
$settings['wrapper']['lob_as_string'] = false;
}
if (!isset($settings['wrapper']['strict_types']))
{
$settings['wrapper']['strict_types'] = true;
}
$this->wrapperClassName = self::getSetting($settings, false, 'wrapper', 'wrapper_class');
if ($this->wrapperClassName!==null)
{
$this->parentClassName = self::getSetting($settings, true, 'wrapper', 'parent_class');
$this->nameMangler = self::getSetting($settings, true, 'wrapper', 'mangler_class');
$this->wrapperFilename = self::getSetting($settings, true, 'wrapper', 'wrapper_file');
$this->lobAsString = !empty(self::getSetting($settings, true, 'wrapper', 'lob_as_string'));
$this->metadataFilename = self::getSetting($settings, true, 'loader', 'metadata');
$this->wrapperClassType = self::getSetting($settings, true, 'wrapper', 'wrapper_type');
$this->strictTypes = !empty(self::getSetting($settings, true, 'wrapper', 'strict_types'));
}
} | Reads parameters from the configuration file.
@param string $configFilename The filename of the configuration file. | entailment |
private function readRoutineMetadata(): array
{
$data = file_get_contents($this->metadataFilename);
$routines = (array)json_decode($data, true);
if (json_last_error()!=JSON_ERROR_NONE)
{
throw new RuntimeException("Error decoding JSON: '%s'.", json_last_error_msg());
}
return $routines;
} | Returns the metadata of stored routines.
@return array | entailment |
private function storeWrapperClass(): void
{
$code = $this->codeStore->getCode();
switch ($this->wrapperClassType)
{
case 'static':
// Nothing to do.
break;
case 'non static':
$code = NonStatic::nonStatic($code);
break;
default:
throw new FallenException('wrapper class type', $this->wrapperClassType);
}
$this->writeTwoPhases($this->wrapperFilename, $code);
} | Writes the wrapper class to the filesystem. | entailment |
private function writeClassHeader(): void
{
$p = strrpos($this->wrapperClassName, '\\');
if ($p!==false)
{
$namespace = ltrim(substr($this->wrapperClassName, 0, $p), '\\');
$class_name = substr($this->wrapperClassName, $p + 1);
}
else
{
$namespace = null;
$class_name = $this->wrapperClassName;
}
// Write PHP tag.
$this->codeStore->append('<?php');
// Write strict types.
if ($this->strictTypes)
{
$this->codeStore->append('declare(strict_types=1);');
}
// Write name space of the wrapper class.
if ($namespace!==null)
{
$this->codeStore->append('');
$this->codeStore->append(sprintf('namespace %s;', $namespace));
$this->codeStore->append('');
}
// If the child class and parent class have different names import the parent class. Otherwise use the fully
// qualified parent class name.
$parent_class_name = substr($this->parentClassName, strrpos($this->parentClassName, '\\') + 1);
if ($class_name!=$parent_class_name)
{
$this->imports[] = $this->parentClassName;
$this->parentClassName = $parent_class_name;
}
// Write use statements.
if (!empty($this->imports))
{
$this->imports = array_unique($this->imports, SORT_REGULAR);
foreach ($this->imports as $import)
{
$this->codeStore->append(sprintf('use %s;', $import));
}
$this->codeStore->append('');
}
// Write class name.
$this->codeStore->append('/**');
$this->codeStore->append(' * The data layer.', false);
$this->codeStore->append(' */', false);
$this->codeStore->append(sprintf('class %s extends %s', $class_name, $this->parentClassName));
$this->codeStore->append('{');
} | Generate a class header for stored routine wrapper. | entailment |
private function writeClassTrailer(): void
{
$this->codeStore->appendSeparator();
$this->codeStore->append('}');
$this->codeStore->append('');
$this->codeStore->appendSeparator();
} | Generate a class trailer for stored routine wrapper. | entailment |
private function writeRoutineFunction(array $routine, NameMangler $nameMangler): void
{
$wrapper = Wrapper::createRoutineWrapper($routine, $this->codeStore, $nameMangler, $this->lobAsString);
$wrapper->writeRoutineFunction();
$this->imports = array_merge($this->imports, $wrapper->getImports());
} | Generates a complete wrapper method for a stored routine.
@param array $routine The metadata of the stored routine.
@param NameMangler $nameMangler The mangler for wrapper and parameter names. | entailment |
public function createLink($label, $href = null)
{
$link = new Link($label, $href);
if ( ! $this->links instanceof ArrayIterator) {
$this->links = new ArrayIterator();
}
$this->links->push($link);
} | LinksCollectorTrait::createLink
@param string $label
@param string|null $href | entailment |
public function addLink(Link $link)
{
if ( ! $this->links instanceof ArrayIterator) {
$this->links = new ArrayIterator();
}
$this->links->push($link);
return $this;
} | LinksCollectorTrait
@param \O2System\Framework\Libraries\Ui\Contents\Link $link
@return static | entailment |
public function getAttemptsLeftWithSameUser(string $userName): int
{
$attemptsLeft = ((int) $this->maxAttemptsForUserName) - $this->enhancedAuthenticationMapper->fetchAttemptsWithSameUser($userName, $this->banTimeInSeconds);
return \max(0, $attemptsLeft);
} | Return how many attemps are left for incorrect password.
@param string $userName
@return int Number of attempts with same user. | entailment |
public function getAttemptsLeftWithSameSession(string $sessionId): int
{
$attemptsLeft = ((int) $this->maxAttemptsForSessionId) - $this->enhancedAuthenticationMapper->fetchAttemptsWithSameSession($sessionId, $this->banTimeInSeconds);
return \max(0, $attemptsLeft);
} | Return how many attemps are left for same session id.
@param string $sessionId
@return int Number of attempts with same session. | entailment |
public function getAttemptsLeftWithSameIp(string $ipAddress): int
{
$attemptsLeft = ((int) $this->maxAttemptsForIpAddress) - $this->enhancedAuthenticationMapper->fetchAttemptsWithSameIp($ipAddress, $this->banTimeInSeconds);
return \max(0, $attemptsLeft);
} | Return how many attemps are left for same ip.
@param string $ipAddress
@return int Number of attempts with same ip. | entailment |
public function logDebug()
{
if ($this->getVerbosity()>=OutputInterface::VERBOSITY_DEBUG)
{
$args = func_get_args();
$format = array_shift($args);
$this->writeln(vsprintf('<info>'.$format.'</info>', $args));
}
} | -------------------------------------------------------------------------------------------------------------------- | entailment |
public function logInfo()
{
if ($this->getVerbosity()>=OutputInterface::VERBOSITY_NORMAL)
{
$args = func_get_args();
$format = array_shift($args);
$this->writeln(vsprintf('<info>'.$format.'</info>', $args));
}
} | -------------------------------------------------------------------------------------------------------------------- | entailment |
public function logVerbose()
{
if ($this->getVerbosity()>=OutputInterface::VERBOSITY_VERBOSE)
{
$args = func_get_args();
$format = array_shift($args);
$this->writeln(vsprintf('<info>'.$format.'</info>', $args));
}
} | -------------------------------------------------------------------------------------------------------------------- | entailment |
public function logVeryVerbose()
{
if ($this->getVerbosity()>=OutputInterface::VERBOSITY_VERY_VERBOSE)
{
$args = func_get_args();
$format = array_shift($args);
$this->writeln(vsprintf('<info>'.$format.'</info>', $args));
}
} | -------------------------------------------------------------------------------------------------------------------- | entailment |
public function rebuildTree($idParent = 0, $left = 1, $depth = 0)
{
ini_set('xdebug.max_nesting_level', 10000);
ini_set('memory_limit', '-1');
if ($childs = $this->qb
->table($this->table)
->select('id')
->where($this->parentKey, $idParent)
->orderBy('id')
->get()) {
$right = $left + 1;
$i = 0;
foreach ($childs as $child) {
if ($i == 0) {
$this->qb
->from($this->table)
->where('id', $child->id)
->update($update = [
'record_left' => $left,
'record_right' => $right,
'record_depth' => $depth,
]);
} else {
$this->qb
->from($this->table)
->where('id', $child->id)
->update($update = [
'record_left' => $left = $right + 1,
'record_right' => $right = $left + 1,
'record_depth' => $depth,
]);
}
$update[ 'id' ] = $child->id;
if ($this->qb
->table($this->table)
->select('id')
->where($this->parentKey, $child->id)
->orderBy('id')
->get()) {
$right = $this->rebuildTree($child->id, $right, $depth + 1);
$this->qb
->from($this->table)
->where('id', $child->id)
->update($update = [
'record_right' => $right,
]);
$update[ 'id' ] = $child->id;
}
$i++;
}
}
return $right + 1;
} | HierarchicalTrait::rebuildTree
@param int $idParent
@param int $left
@param int $depth
@return int | entailment |
public function getParents($id, $ordering = 'ASC')
{
if ($parents = $this->qb
->select($this->table . '.*')
->from($this->table)
->from($this->table . ' AS node')
->whereBetween('node.record_left', [$this->table . '.record_left', $this->table . '.record_right'])
->where([
'node.id' => $id,
])
->orderBy($this->table . '.record_left', $ordering)
->get()) {
if ($parents->count()) {
return $parents;
}
}
return false;
} | HierarchicalTrait::getParents
@param int $id
@param string $ordering ASC|DESC
@return bool|\O2System\Framework\Models\Sql\DataObjects\Result | entailment |
public function getParent($idParent)
{
if ($parent = $this->qb
->select($this->table . '.*')
->from($this->table)
->where($this->primaryKey, $idParent)
->get(1)) {
if ($parent->count() == 1) {
return $parent->first();
}
}
return false;
} | HierarchicalTrait::getParent
@param int $idParent
@return bool|\O2System\Framework\Models\Sql\DataObjects\Result\Row | entailment |
public function getNumOfParent($id)
{
if ($parents = $this->qb
->table($this->table)
->select('id')
->where('id', $id)
->get()) {
return $parents->count();
}
return 0;
} | HierarchicalTrait::getNumOfParent
@param int $idParent
@return int | entailment |
public function hasParent($id, $direct = true)
{
if ($numOfParents = $this->getNumOfParent($idParent, $direct)) {
return (bool)($numOfParents == 0 ? false : true);
}
return false;
} | HierarchicalTrait::hasParent
@param int $id
@return bool | entailment |
public function hasParents($id)
{
if ($numOfParents = $this->getNumOfParents($id)) {
return (bool)($numOfParents == 0 ? false : true);
}
return false;
} | HierarchicalTrait::hasParents
@param int $id
@return bool | entailment |
public function getChilds($idParent, $ordering = 'ASC')
{
if ($childs = $this->qb
->select($this->table . '.*')
->from($this->table)
->from($this->table . ' AS node')
->whereBetween('node.record_left', [$this->table . '.record_left', $this->table . '.record_right'])
->where([
$this->table . '.id' => $id,
])
->get()) {
if ($childs->count()) {
return $childs;
}
}
return false;
} | HierarchicalTrait::getChilds
@param int $idParent
@param string $ordering ASC|DESC
@return bool|\O2System\Framework\Models\Sql\DataObjects\Result | entailment |
public function getNumOfChilds($idParent, $direct = true)
{
if($childs = $this->getChilds($idParent)) {
return $childs->count();
}
return 0;
} | HierarchicalTrait::getNumOfChilds
@param int $idParent
@param bool $direct
@return int | entailment |
public function hasChilds($idParent)
{
if ($numOfChilds = $this->getNumOfChilds($idParent)) {
return (bool)($numOfChilds == 0 ? false : true);
}
return false;
} | HierarchicalTrait::hasChilds
@param int $idParent
@return bool | entailment |
public function load($widgetOffset)
{
$widgetDirectory = modules()->top()->getRealPath() . 'Widgets' . DIRECTORY_SEPARATOR . studlycase($widgetOffset) . DIRECTORY_SEPARATOR;
if (is_dir($widgetDirectory)) {
$widget = new DataStructures\Module\Widget($widgetDirectory);
$this->store(camelcase($widgetOffset), $widget);
}
return $this->exists($widgetOffset);
} | Widgets::load
@param string $widgetOffset
@return bool | entailment |
public function get($offset)
{
if (null !== ($widget = parent::get($offset))) {
$widgetViewFilePath = $widget->getRealPath() . 'Views' . DIRECTORY_SEPARATOR . $offset . '.phtml';
if (presenter()->theme->use === true) {
$widgetViewReplacementPath = str_replace(
$widget->getRealPath() . 'Views' . DIRECTORY_SEPARATOR,
presenter()->theme->active->getPathName() . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, [
'views',
'widgets',
]) . DIRECTORY_SEPARATOR,
$widgetViewFilePath
);
$viewsFileExtensions = [
'.php',
'.phtml',
];
// Add Theme File Extensions
if (presenter()->theme->active->getPresets()->offsetExists('extension')) {
array_unshift($viewsFileExtensions,
presenter()->theme->active->getPresets()->offsetGet('extension'));
} elseif (presenter()->theme->active->getPresets()->offsetExists('extensions')) {
$viewsFileExtensions = array_merge(
presenter()->theme->active->getPresets()->offsetGet('extensions'),
$viewsFileExtensions
);
}
foreach ($viewsFileExtensions as $viewsFileExtension) {
if (is_file($widgetViewReplacementPath . $viewsFileExtension)) {
$widgetViewFilePath = $widgetViewReplacementPath . $viewsFileExtension;
}
}
}
loader()->addNamespace($widget->getNamespace(), $widget->getRealPath());
$widgetPresenterClassName = $widgetPresenterClassName = $widget->getNamespace() . 'Presenters\\' . studlycase($offset);
$widgetPresenter = new $widgetPresenterClassName();
if (is_file($widgetViewFilePath)) {
parser()->loadVars($widgetPresenter->getArrayCopy());
parser()->loadFile($widgetViewFilePath);
return parser()->parse();
} elseif (method_exists($widgetPresenter, 'render')) {
return $widgetPresenter->render();
}
}
return null;
} | Widgets::get
@param string $offset
@return string | entailment |
public function loadPluginConfiguration(): void
{
if ($this->compiler->getPlugin(CoreDecoratorPlugin::PLUGIN_NAME) === null) {
throw new InvalidStateException(sprintf('Plugin "%s" must be enabled', CoreDecoratorPlugin::class));
}
$builder = $this->getContainerBuilder();
$config = $this->getConfig();
$globalConfig = $this->compiler->getExtension()->getConfig();
$builder->addDefinition($this->prefix('transformer.json'))
->setFactory(JsonTransformer::class)
->addSetup('setDebugMode', [$globalConfig['debug']])
->addTag(ApiExtension::NEGOTIATION_TRANSFORMER_TAG, ['suffix' => 'json'])
->setAutowired(false);
$builder->addDefinition($this->prefix('transformer.csv'))
->setFactory(CsvTransformer::class)
->addSetup('setDebugMode', [$globalConfig['debug']])
->addTag(ApiExtension::NEGOTIATION_TRANSFORMER_TAG, ['suffix' => 'csv'])
->setAutowired(false);
$builder->addDefinition($this->prefix('transformer.fallback'))
->setFactory(JsonTransformer::class)
->addSetup('setDebugMode', [$globalConfig['debug']])
->addTag(ApiExtension::NEGOTIATION_TRANSFORMER_TAG, ['suffix' => '*', 'fallback' => true])
->setAutowired(false);
$builder->addDefinition($this->prefix('transformer.renderer'))
->setFactory(RendererTransformer::class)
->addSetup('setDebugMode', [$globalConfig['debug']])
->addTag(ApiExtension::NEGOTIATION_TRANSFORMER_TAG, ['suffix' => '#'])
->setAutowired(false);
$builder->addDefinition($this->prefix('negotiation'))
->setFactory(ContentNegotiation::class);
$builder->addDefinition($this->prefix('negotiator.suffix'))
->setFactory(SuffixNegotiator::class)
->addTag(ApiExtension::NEGOTIATION_NEGOTIATOR_TAG, ['priority' => 100]);
$builder->addDefinition($this->prefix('negotiator.default'))
->setFactory(DefaultNegotiator::class)
->addTag(ApiExtension::NEGOTIATION_NEGOTIATOR_TAG, ['priority' => 200]);
$builder->addDefinition($this->prefix('negotiator.fallback'))
->setFactory(FallbackNegotiator::class)
->addTag(ApiExtension::NEGOTIATION_NEGOTIATOR_TAG, ['priority' => 300]);
$builder->addDefinition($this->prefix('decorator.response'))
->setFactory(ResponseEntityDecorator::class)
->addTag(ApiExtension::CORE_DECORATOR_TAG, ['priority' => 500]);
if ($config['unification'] === true) {
$builder->removeDefinition($this->prefix('transformer.fallback'));
$builder->removeDefinition($this->prefix('transformer.json'));
$builder->addDefinition($this->prefix('transformer.fallback'))
->setFactory(JsonUnifyTransformer::class)
->addSetup('setDebugMode', [$globalConfig['debug']])
->addTag(ApiExtension::NEGOTIATION_TRANSFORMER_TAG, ['suffix' => '*', 'fallback' => true])
->setAutowired(false);
$builder->addDefinition($this->prefix('transformer.json'))
->setFactory(JsonUnifyTransformer::class)
->addSetup('setDebugMode', [$globalConfig['debug']])
->addTag(ApiExtension::NEGOTIATION_TRANSFORMER_TAG, ['suffix' => 'json'])
->setAutowired(false);
}
} | Register services | entailment |
public function getAccessToken(ServerRequestInterface $request, $scopes = [])
{
if (! $token = $this->extractAccessToken($request)) {
return null;
}
$token = $this->accessTokenService->getToken($token);
if ($token === null || ! $token->isValid($scopes)) {
throw InvalidAccessTokenException::invalidToken('Access token has expired or has been deleted');
}
return $token;
} | Get the access token
Note that this method will only match tokens that are not expired and match the given scopes (if any).
If no token is pass, this method will return null, but if a token is given does not exist (ie. has been
deleted) or is not valid, then it will trigger an exception
@link http://tools.ietf.org/html/rfc6750#page-5
@param array|string|Scope[] $scopes
@return AccessToken|null
@throws InvalidAccessTokenException If given access token is invalid or expired | entailment |
private function extractAccessToken(ServerRequestInterface $request)
{
// The preferred way is using Authorization header
if ($request->hasHeader('Authorization')) {
// Header value is expected to be "Bearer xxx"
$parts = explode(' ', $request->getHeaderLine('Authorization'));
if (count($parts) < 2) {
return null;
}
return end($parts);
}
// Default back to authorization in query param
$queryParams = $request->getQueryParams();
return $queryParams['access_token'] ?? null;
} | Extract the token either from Authorization header or query params
@return string|null | entailment |
public function handle(ServerRequestInterface $request)
{
if (services()->has('csrfProtection')) {
if (hash_equals(input()->server('REQUEST_METHOD'), 'POST')) {
if ( ! services()->get('csrfProtection')->verify()) {
output()->sendError(403, [
'message' => language()->getLine('403_INVALID_CSRF'),
]);
}
}
}
} | Csrf::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 function loadDir($dir)
{
$partialsFiles = scandir($dir);
$partialsFiles = array_slice($partialsFiles, 2);
foreach ($partialsFiles as $partialsFile) {
$partialsFilePath = $dir . $partialsFile;
if (is_file($partialsFilePath)) {
$this->loadFile($partialsFilePath);
} elseif (is_dir($partialsFilePath)) {
$this->loadDir($partialsFilePath . DIRECTORY_SEPARATOR);
}
}
} | Partials::loadDir
@param string $dir | entailment |
public function loadFile($filePath)
{
if (strrpos($filePath, $this->extension) !== false) {
$fileKey = str_replace([$this->path, $this->extension, DIRECTORY_SEPARATOR], ['', '', '-'], $filePath);
$this->store(camelcase($fileKey), new SplFileInfo($filePath));
}
} | Partials::loadFile
@param string $filePath | entailment |
public function get($partial)
{
$partialContent = parent::get($partial);
if (is_file($partialContent)) {
parser()->loadFile($partialContent);
return parser()->parse();
} elseif (is_string($partialContent)) {
return $partialContent;
}
return null;
} | Partials::get
@param string $partial
@return false|mixed|string|null | entailment |
public static function renderType(ProgressBarInterface $progressBar) {
return null !== $progressBar->getType() ? $progressBar->getPrefix() . $progressBar->getType() : null;
} | Render a type.
@param ProgressBarInterface $progressBar The progress bar.
@return string|null Returns the rendered type. | entailment |
public function setTotal($total)
{
$this->total = (int)$total;
$this->setPages(ceil($total / $this->limit));
return $this;
} | Pagination::setTotal
@param int $total
@return static | entailment |
public function setLimit($limit)
{
$this->limit = (int)$limit;
if ($this->total > 0 && $this->limit > 0) {
$this->setPages(ceil($this->total / $limit));
}
return $this;
} | Pagination::setLimit
@param int $limit
@return static | entailment |
public function render()
{
// returning empty string if the num pages is zero
if ($this->pages == 0 || $this->pages == 1) {
return '';
}
$output[] = $this->open() . PHP_EOL;
$current = (int)input()->get('page');
$current = $current == 0 ? 1 : $current;
$previous = new Element('span');
$previous->entity->setEntityName('previous');
$previous->attributes->addAttribute('aria-hidden', true);
$previous->textContent->push('«');
if ($current == 1) {
$this->createList(new Link($previous, '#'));
$this->childNodes->current()->disabled();
} else {
$this->createList(new Link($previous, current_url('', ['page' => $current - 1])));
}
foreach (range(1, $this->pages) as $page) {
$this->createList(new Link($page, current_url('', ['page' => $page])));
if ($current == $page) {
$currentNode = $this->childNodes->current();
$currentNode->active();
$srOnly = new Element('span');
$srOnly->entity->setEntityName('current');
$srOnly->attributes->addAttributeClass('sr-only');
$srOnly->textContent->push('(current)');
$currentNode->childNodes->first()->childNodes->push($srOnly);
}
}
$next = new Element('span');
$next->entity->setEntityName('next');
$next->attributes->addAttribute('aria-hidden', true);
$next->textContent->push('»');
if ($current == $this->pages) {
$this->createList(new Link($next, '#'));
$this->childNodes->current()->disabled();
} else {
$this->createList(new Link($next, current_url('', ['page' => $current + 1])));
}
if ($this->hasChildNodes()) {
$output[] = implode(PHP_EOL, $this->childNodes->getArrayCopy());
}
$output[] = PHP_EOL . $this->close();
return implode('', $output);
} | Pagination::render
@return string | entailment |
protected function pushChildNode(Element $node)
{
$node->attributes->addAttributeClass('page-item');
if ($node->childNodes->first() instanceof Link) {
$node->childNodes->first()->attributes->addAttributeClass('page-link');
}
parent::pushChildNode($node);
} | Pagination::pushChildNode
@param \O2System\Framework\Libraries\Ui\Element $node | entailment |
protected function returnStorageObject()
{
$driver = $this->driver;
$options = $this->options;
if (isset($this->supportedDriver[$driver])) {
$class = $this->supportedDriver[$driver];
return new $class($options);
}
throw new InvalidArgumentException("[{$driver}] not supported.");
} | Return Storage Object.
@throws InvalidArgumentException If required driver is not supported
@return mixed | entailment |
public function createButton($label)
{
$node = new Button();
if ($label instanceof Button) {
$node = $label;
} elseif ($label instanceof Dropdown) {
$node = clone $label;
$node->attributes->removeAttributeClass('dropdown');
$node->attributes->addAttributeClass('btn-group');
$node->attributes->addAttribute('role', 'group');
$node->childNodes->push($label->toggle);
$node->childNodes->push($label->menu);
} else {
$node->setLabel($label);
if (is_numeric($label)) {
$node->entity->setEntityName('button-' . $label);
} else {
$node->entity->setEntityName($label);
}
}
$this->childNodes->push($node);
return $this->childNodes->last();
} | Group::createButton
@param string $label
@return Button | entailment |
protected function bootstrapDropdownButton($content, $id, $expanded, $class) {
$classes = ButtonEnumerator::enumTypes();
$attributes = [];
$attributes["class"][] = "btn";
$attributes["class"][] = true === in_array($class, $classes) ? "btn-" . $class : "btn-default";
$attributes["class"][] = "dropdown-toggle";
$attributes["type"][] = "button";
$attributes["id"][] = null !== $id ? $id : "";
$attributes["data-toggle"][] = "dropdown";
$attributes["aria-haspopup"][] = "true";
$attributes["aria-expanded"][] = StringHelper::parseBoolean($expanded);
$innerHTML = (null !== $content ? $content : "") . "<span class=\"caret\"></span>";
return static::coreHTMLElement("button", $innerHTML, $attributes);
} | Displays a Bootstrap dropdown "Button".
@param string $content The content.
@param string $id The id.
@param bool $expanded Expanded ?
@param string $class The class.
@return string Returns the Bootstrap dropdown "Button". | entailment |
public function run(): void
{
//attach Oserver to Subjetc
$this->model->attach($this->view);
//run action before controller
$this->beforeAfterController('before');
$this->beforeAfterControllerAction('before');
//run controller
$this->runController();
//run action after controller
$this->beforeAfterControllerAction('after');
$this->beforeAfterController('after');
//notify model changes to view
$this->model->notify();
//run view
$this->runView();
} | Run mvc pattern.
@return void | entailment |
private function beforeAfterControllerAction(string $when): void
{
$method = $when.\ucfirst($this->routeAction);
if (\method_exists($this->controller, $method) && $method !== $when) {
\call_user_func([$this->controller, $method]);
}
} | Run action before or after controller action execution.
@param string $when
@return void | entailment |
private function beforeAfterController(string $when): void
{
if (\method_exists($this->controller, $when)) {
\call_user_func([$this->controller, $when]);
}
} | Run action before or after controller execution.
@param string $when
@return void | entailment |
private function runController(): void
{
//get route information
$action = $this->routeAction;
$param = $this->routeParam;
//action - call controller passing params
if (!empty($param)) {
\call_user_func_array([$this->controller, $action], $param);
return;
}
//action - call controller
if ($action) {
\call_user_func([$this->controller, $action]);
}
} | Run controller.
@return void | entailment |
private function runView(): void
{
$action = ($this->routeAction) ? $this->routeAction : 'index';
\call_user_func([$this->view, $action]);
} | Run view.
@return void | entailment |
public function getMarkedQuery(string $style = 'error'): array
{
$query = trim($this->query); // MySQL ignores leading whitespace in queries.
$message = [];
if (strpos($query, PHP_EOL)!==false && $this->isQueryError())
{
// Query is a multi line query.
// The format of a 1064 message is: %s near '%s' at line %d
$error_line = trim(strrchr($this->error, ' '));
// Prepend each line with line number.
$lines = explode(PHP_EOL, $query);
$digits = ceil(log(sizeof($lines) + 1, 10));
$format = sprintf('%%%dd %%s', $digits);
foreach ($lines as $i => $line)
{
if (($i + 1)==$error_line)
{
$message[] = sprintf('<%s>'.$format.'</%s>', $style, $i + 1, OutputFormatter::escape($line), $style);
}
else
{
$message[] = sprintf($format, $i + 1, OutputFormatter::escape($line));
}
}
}
else
{
// Query is a single line query or a method name.
$message[] = $query;
}
return $message;
} | Returns an array with the lines of the SQL statement. The line where the error occurred will be styled.
@param string $style The style for highlighting the line with error.
@return array The lines of the SQL statement. | entailment |
private function message(int $errno, string $error, string $query): string
{
$message = 'MySQL Error no: '.$errno."\n";
$message .= $error;
$message .= "\n";
$query = trim($query);
if (strpos($query, "\n")!==false)
{
// Query is a multi line query.
$message .= "\n";
// Prepend each line with line number.
$lines = explode("\n", $query);
$digits = ceil(log(sizeof($lines), 10));
$format = sprintf("%%%dd %%s\n", $digits);
foreach ($lines as $i => $line)
{
$message .= sprintf($format, $i + 1, $line);
}
}
else
{
// Query is a single line query or method name.
$message .= $query;
}
return $message;
} | Composes the exception message.
@param int $errno The error code value of the error ($mysqli->errno).
@param string $error Description of the error ($mysqli->error).
@param string $query The SQL query or method name.
@return string | entailment |
public function render()
{
$output[] = $this->left;
$output[] = $this->right;
return implode(PHP_EOL, $output);
} | Control::render
@return string | entailment |
public function route()
{
$segments = server_request()->getUri()->getSegments()->getParts();
if (false !== ($key = array_search('images', $segments))) {
$segments = array_slice($segments, $key);
} else {
array_shift($segments);
}
$this->imageFilePath = $this->imageNotFoundFilename;
$this->imageSize[ 'width' ] = $this->input->get('width');
$this->imageSize[ 'height' ] = $this->input->get('height');
$this->imageScale = $this->input->get('scale');
$this->imageQuality = $this->input->get('quality');
$this->imageCrop = $this->input->get('crop');
if (false !== ($key = array_search('crop', $segments))) {
$this->imageCrop = true;
unset($segments[ $key ]);
$segments = array_values($segments);
}
if (count($segments) == 1) {
$this->imageFilePath = $this->storagePath . end($segments);
} elseif (count($segments) >= 2) {
if (preg_match("/(\d+)(x)(\d+)/", $segments[ count($segments) - 2 ], $matches)) {
$this->imageSize[ 'width' ] = $matches[ 1 ];
$this->imageSize[ 'height' ] = $matches[ 3 ];
if (count($segments) == 2) {
$this->imageFilePath = $this->storagePath . end($segments);
} else {
$this->imageFilePath = $this->storagePath . implode(DIRECTORY_SEPARATOR,
array_slice($segments, 0,
count($segments) - 2)) . DIRECTORY_SEPARATOR . end($segments);
}
} elseif (preg_match("/(\d+)(p)/", $segments[ count($segments) - 2 ],
$matches) or is_numeric($segments[ count($segments) - 2 ])
) {
$this->imageScale = isset($matches[ 1 ]) ? $matches[ 1 ] : $segments[ count($segments) - 2 ];
if (count($segments) == 2) {
$this->imageFilePath = $this->storagePath . end($segments);
} else {
$this->imageFilePath = $this->storagePath . implode(DIRECTORY_SEPARATOR,
array_slice($segments, 0,
count($segments) - 2)) . DIRECTORY_SEPARATOR . end($segments);
}
} else {
$this->imageFilePath = $this->storagePath . implode(DIRECTORY_SEPARATOR, $segments);
}
}
$imageFilePath = $this->imageFilePath;
$extensions[ 0 ] = pathinfo($imageFilePath, PATHINFO_EXTENSION);
for ($i = 0; $i < 2; $i++) {
$extension = pathinfo($imageFilePath, PATHINFO_EXTENSION);
if ($extension !== '') {
$extensions[ $i ] = $extension;
$imageFilePath = str_replace('.' . $extensions[ $i ], '', $imageFilePath);
}
}
$mimes = [
'gif' => 'image/gif',
'jpg' => 'image/jpeg',
'png' => 'image/png',
'webp' => 'image/webp',
];
if (count($extensions) == 2) {
$this->imageFilePath = $imageFilePath . '.' . $extensions[ 1 ];
}
if (array_key_exists($extension = reset($extensions), $mimes)) {
$this->imageFileMime = $mimes[ $extension ];
} elseif (array_key_exists($extension = pathinfo($this->imageFilePath, PATHINFO_EXTENSION), $mimes)) {
$this->imageFileMime = $mimes[ $extension ];
}
if ( ! is_file($this->imageFilePath)) {
$this->imageFilePath = $this->imageNotFoundFilename;
}
if ( ! empty($this->imageScale)) {
$this->scale();
} elseif ( ! empty($this->imageSize[ 'width' ]) || ! empty($this->imageSize[ 'height' ])) {
$this->resize();
} else {
$this->original();
}
} | Images::route | entailment |
protected function scale()
{
$config = config('image', true);
if ( ! empty($this->imageQuality)) {
$config->offsetSet('quality', intval($this->imageQuality));
}
if ($config->cached === true) {
if ($this->imageFilePath !== $this->imageNotFoundFilename) {
$cacheImageKey = 'image-' . $this->imageScale . '-' . str_replace($this->storagePath, '',
$this->imageFilePath);
if (cache()->hasItemPool('images')) {
$cacheItemPool = cache()->getItemPool('images');
if ($cacheItemPool->hasItem($cacheImageKey)) {
$cacheImageString = $cacheItemPool->getItem($cacheImageKey)->get();
$manipulation = new Manipulation($config);
$manipulation->setImageFile($this->imageFilePath);
$manipulation->setImageString($cacheImageString);
$manipulation->displayImage(intval($this->imageQuality), $this->imageFileMime);
} else {
$manipulation = new Manipulation($config);
$manipulation->setImageFile($this->imageFilePath);
$manipulation->scaleImage($this->imageScale);
$cacheItemPool->save(new Item($cacheImageKey, $manipulation->getBlobImage(), false));
$manipulation->displayImage(intval($this->imageQuality), $this->imageFileMime);
exit(EXIT_SUCCESS);
}
}
}
}
$manipulation = new Manipulation($config);
$manipulation->setImageFile($this->imageFilePath);
$manipulation->scaleImage($this->imageScale);
$manipulation->displayImage(intval($this->imageQuality), $this->imageFileMime);
exit(EXIT_SUCCESS);
} | Images::scale
@throws \O2System\Spl\Exceptions\Runtime\FileNotFoundException | entailment |
protected function resize()
{
$config = config('image', true);
if ( ! empty($this->imageQuality)) {
$config->offsetSet('quality', intval($this->imageQuality));
}
if ($config->cached === true) {
if ($this->imageFilePath !== $this->imageNotFoundFilename) {
$cacheImageKey = 'image-' . ($this->input->get('crop') ? 'crop-' : '') . implode('x',
$this->imageSize) . '-' . str_replace($this->storagePath, '', $this->imageFilePath);
if (cache()->hasItemPool('images')) {
$cacheItemPool = cache()->getItemPool('images');
if ($cacheItemPool->hasItem($cacheImageKey)) {
$cacheImageString = $cacheItemPool->getItem($cacheImageKey)->get();
$manipulation = new Manipulation($config);
$manipulation->setImageFile($this->imageFilePath);
$manipulation->setImageString($cacheImageString);
$manipulation->displayImage(intval($this->imageQuality), $this->imageFileMime);
} else {
$manipulation = new Manipulation($config);
$manipulation->setImageFile($this->imageFilePath);
$manipulation->resizeImage($this->imageSize[ 'width' ], $this->imageSize[ 'height' ],
(bool)$this->imageCrop);
$cacheItemPool->save(new Item($cacheImageKey, $manipulation->getBlobImage(), false));
$manipulation->displayImage(intval($this->imageQuality), $this->imageFileMime);
exit(EXIT_SUCCESS);
}
}
}
}
$manipulation = new Manipulation($config);
$manipulation->setImageFile($this->imageFilePath);
$manipulation->resizeImage($this->imageSize[ 'width' ], $this->imageSize[ 'height' ], (bool)$this->imageCrop);
$manipulation->displayImage(intval($this->imageQuality), $this->imageFileMime);
exit(EXIT_SUCCESS);
} | Images::resize
@throws \O2System\Spl\Exceptions\Runtime\FileNotFoundException | entailment |
protected function original()
{
$config = config('image', true);
if ( ! empty($this->imageQuality)) {
$config->offsetSet('quality', intval($this->imageQuality));
}
$manipulation = new Manipulation($config);
$manipulation->setImageFile($this->imageFilePath);
$manipulation->displayImage(intval($this->imageQuality), $this->imageFileMime);
exit(EXIT_SUCCESS);
} | Images::original
@throws \O2System\Spl\Exceptions\Runtime\FileNotFoundException | entailment |
private function applyColor($label, $content, $color) {
$searches = ">" . $content;
$replaces = " style=\"background-color:" . $color . ";\"" . $searches;
return StringHelper::replace($label, [$searches], [$replaces]);
} | Apply the color.
@param string $label The label.
@param string $content The content.
@param string $color The color.
@return string Returns the label with applied color. | entailment |
public function bootstrapRoleLabelFunction(UserInterface $user = null, array $roleColors = [], array $roleTrans = []) {
if (null === $user) {
return "";
}
$output = [];
foreach ($user->getRoles() as $current) {
$role = true === $current instanceof Role ? $current->getRole() : $current;
$trans = $role;
if (true === array_key_exists($role, $roleTrans)) {
$trans = $this->getTranslator()->trans($roleTrans[$role]);
}
$label = $this->getLabelTwigExtension()->bootstrapLabelDefaultFunction(["content" => $trans]);
if (true === array_key_exists($role, $roleColors)) {
$label = $this->applyColor($label, $trans, $roleColors[$role]);
}
$output[] = $label;
}
return implode(" ", $output);
} | Display a Bootstrap role label.
@param UserInterface $user The user.
@param array $roleColors The role colors.
@param array $roleTrans The role translations.
@return string Returns the Bootstrap role label. | entailment |
protected function __reconstruct()
{
// Modules default app
if (null !== ($defaultApp = config('app'))) {
if (false !== ($defaultModule = modules()->getApp($defaultApp))) {
// Register Domain App Module Namespace
loader()->addNamespace($defaultModule->getNamespace(), $defaultModule->getRealPath());
// Push Domain App Module
modules()->push($defaultModule);
} elseif (false !== ($defaultModule = modules()->getModule($defaultApp))) {
// Register Path Module Namespace
loader()->addNamespace($defaultModule->getNamespace(), $defaultModule->getRealPath());
// Push Path Module
modules()->push($defaultModule);
}
}
if (profiler() !== false) {
profiler()->watch('Calling Hooks Service: Post System');
}
hooks()->callEvent(Framework\Services\Hooks::POST_SYSTEM);
if (is_cli()) {
$this->cliHandler();
} else {
$this->httpHandler();
}
} | Framework::__reconstruct | entailment |
private function cliHandler()
{
// Instantiate CLI Router Service
$this->services->load(Kernel\Cli\Router::class);
if (profiler() !== false) {
profiler()->watch('Parse Router Request');
}
router()->parseRequest();
if ($commander = router()->getCommander()) {
if ($commander instanceof Kernel\Cli\Router\DataStructures\Commander) {
// Autoload Language
language()->loadFile($commander->getParameter());
language()->loadFile($commander->getRequestMethod());
language()->loadFile($commander->getParameter() . '/' . $commander->getRequestMethod());
$modules = $this->modules->getArrayCopy();
// Run Module Autoloader
foreach ($modules as $module) {
if (in_array($module->getType(), ['KERNEL', 'FRAMEWORK'])) {
continue;
}
$module->loadModel();
}
// Autoload Model
$modelClassName = str_replace('Commanders', 'Models', $commander->getName());
if (class_exists($modelClassName)) {
$this->models->load($modelClassName, 'commander');
}
// Initialize Controller
if (profiler() !== false) {
profiler()->watch('Calling Hooks Service: Pre Commander');
}
hooks()->callEvent(Framework\Services\Hooks::PRE_COMMANDER);
if (profiler() !== false) {
profiler()->watch('Instantiating Requested Commander: ' . $commander->getClass());
}
$requestCommander = $commander->getInstance();
if (profiler() !== false) {
profiler()->watch('Calling Hooks Service: Post Commander');
}
hooks()->callEvent(Framework\Services\Hooks::POST_COMMANDER);
if (profiler() !== false) {
profiler()->watch('Execute Requested Commander: ' . $commander->getClass());
}
$requestCommander->execute();
exit(EXIT_SUCCESS);
}
}
} | Framework::cliHandler
@return void
@throws \ReflectionException | entailment |
private function httpHandler()
{
if (config()->loadFile('view') === true) {
// Instantiate Http UserAgent Service
$this->services->load(Framework\Http\UserAgent::class, 'userAgent');
// Instantiate Http View Service
$this->services->load(Framework\Http\Parser::class);
// Instantiate Http View Service
$this->services->load(Framework\Http\View::class);
// Instantiate Http Presenter Service
$this->services->load(Framework\Http\Presenter::class);
}
// Instantiate Http Router Service
$this->services->load(Framework\Http\Router::class);
if (profiler() !== false) {
profiler()->watch('Parse Router Request');
}
router()->parseRequest();
if (config()->loadFile('session') === true) {
// Instantiate Session Service
$session = new Session(config('session', true));
$session->setLogger($this->services->get('logger'));
if ( ! $session->isStarted()) {
$session->start();
}
$this->services->add($session, 'session');
if ($session->has('language') and $this->services->has('language')) {
language()->setDefault($session->get('language'));
} else {
$session->set('language', language()->getDefault());
}
if (config('security')->protection[ 'csrf' ] === true) {
$csrfProtection = new Security\Protections\Csrf();
$this->services->add($csrfProtection, 'csrfProtection');
}
if (config('security')->protection[ 'xss' ] === true) {
$xssProtection = new Security\Protections\Xss();
$this->services->add($xssProtection, 'xssProtection');
}
}
// Instantiate Http Middleware Service
$this->services->load(Framework\Http\Middleware::class);
if (profiler() !== false) {
profiler()->watch('Running Middleware Service: Pre Controller');
}
middleware()->run();
if ($this->services->has('controller')) {
$controller = $this->services->get('controller');
$controllerParameter = dash($controller->getParameter());
$controllerRequestMethod = dash($controller->getRequestMethod());
$modules = $this->modules->getArrayCopy();
// Run Module Autoloader
foreach ($modules as $module) {
if (in_array($module->getType(), ['KERNEL', 'FRAMEWORK'])) {
continue;
}
// Autoload Module Language
if ($this->services->has('language')) {
language()->loadFile($module->getParameter());
}
// Autoload Module Model
$module->loadModel();
// Add View Resource Directory
if($this->services->has('view')) {
view()->addFilePath($module->getResourcesDir());
presenter()->assets->pushFilePath($module->getResourcesDir());
}
}
if ($this->services->has('view')) {
presenter()->initialize();
}
// Autoload Language
if ($this->services->has('language')) {
language()->loadFile($controller->getParameter());
language()->loadFile($controller->getRequestMethod());
language()->loadFile($controller->getParameter() . '/' . $controller->getRequestMethod());
}
// Autoload Model
$modelClassName = str_replace(['Controllers', 'Presenters'], 'Models', $controller->getName());
if (class_exists($modelClassName)) {
$this->models->load($modelClassName, 'controller');
}
if ($this->services->has('view')) {
// Autoload Presenter
$presenterClassName = str_replace('Controllers', 'Presenters', $controller->getName());
if (class_exists($presenterClassName)) {
$presenterClassObject = new $presenterClassName();
if ($presenterClassObject instanceof Framework\Http\Presenter) {
$this->services->add($presenterClassObject, 'presenter');
}
}
}
// Initialize Controller
if (profiler() !== false) {
profiler()->watch('Calling Hooks Service: Pre Controller');
}
hooks()->callEvent(Framework\Services\Hooks::PRE_CONTROLLER);
if (profiler() !== false) {
profiler()->watch('Instantiating Requested Controller: ' . $controller->getClass());
}
$requestController = $controller->getInstance();
if (method_exists($requestController, '__reconstruct')) {
$requestController->__reconstruct();
}
if (profiler() !== false) {
profiler()->watch('Calling Hooks Service: Post Controller');
}
hooks()->callEvent(Framework\Services\Hooks::POST_CONTROLLER);
if (profiler() !== false) {
profiler()->watch('Calling Middleware Service: Post Controller');
}
middleware()->run();
$requestMethod = $controller->getRequestMethod();
$requestMethodArgs = $controller->getRequestMethodArgs();
// Call the requested controller method
if (profiler() !== false) {
profiler()->watch('Execute Requested Controller Method');
}
ob_start();
$requestController->__call($requestMethod, $requestMethodArgs);
$requestControllerOutput = ob_get_contents();
ob_end_clean();
if (is_numeric($requestControllerOutput)) {
output()->sendError($requestControllerOutput);
} elseif (is_bool($requestControllerOutput)) {
if ($requestControllerOutput === true) {
output()->sendError(200);
} elseif ($requestControllerOutput === false) {
output()->sendError(204);
}
} elseif (is_array($requestControllerOutput) or is_object($requestControllerOutput)) {
output()->sendPayload($requestControllerOutput);
} elseif ($requestController instanceof Framework\Http\Controllers\Restful) {
if (empty($requestControllerOutput)) {
$requestController->sendError(204);
} elseif (is_string($requestControllerOutput)) {
if (is_json($requestControllerOutput)) {
output()->setContentType('application/json');
} else {
output()->setContentType('text/plain');
}
echo $requestControllerOutput;
}
} elseif (is_string($requestControllerOutput)) {
if (is_json($requestControllerOutput)) {
output()->setContentType('application/json');
echo $requestControllerOutput;
} elseif ($this->services->has('view')) {
if (empty($requestControllerOutput)) {
$filenames = [
$controllerRequestMethod,
$controllerParameter . DIRECTORY_SEPARATOR . $controllerRequestMethod,
];
if ($controllerRequestMethod === 'index') {
array_unshift($filenames, $controllerParameter);
}
foreach ($filenames as $filename) {
if (false !== ($filePath = view()->getFilePath($filename))) {
view()->load($filePath);
break;
}
}
} else {
presenter()->partials->offsetSet('content', $requestControllerOutput);
}
if (presenter()->partials->offsetExists('content')) {
if(is_ajax()) {
echo presenter()->partials->content;
} else {
$htmlOutput = view()->render();
if (empty($htmlOutput)) {
output()->sendError(204);
} else {
output()->setContentType('text/html');
output()->send($htmlOutput);
}
}
} else {
output()->sendError(204);
}
} elseif (empty($requestControllerOutput) or $requestControllerOutput === '') {
output()->sendError(204);
} else {
output()->setContentType('text/plain');
output()->send($requestControllerOutput);
}
}
} else {
// Show Error (404) Page Not Found
output()->sendError(404);
}
} | Framework::httpHandler
@return void
@throws \ReflectionException | entailment |
public function get($property)
{
if (empty($get[ $property ])) {
if (services()->has($property)) {
return services()->get($property);
} elseif (array_key_exists($property, $this->validSubModels)) {
return $this->loadSubModel($property);
} elseif (o2system()->__isset($property)) {
return o2system()->__get($property);
} elseif (models()->__isset($property)) {
return models()->get($property);
}
}
} | Model::get
@param string $property
@return mixed | entailment |
public static function createRoutineWrapper(array $routine,
PhpCodeStore $codeStore,
NameMangler $nameMangler,
bool $lobAsString): Wrapper
{
switch ($routine['designation'])
{
case 'bulk':
$wrapper = new BulkWrapper($routine, $codeStore, $nameMangler, $lobAsString);
break;
case 'bulk_insert':
$wrapper = new BulkInsertWrapper($routine, $codeStore, $nameMangler, $lobAsString);
break;
case 'log':
$wrapper = new LogWrapper($routine, $codeStore, $nameMangler, $lobAsString);
break;
case 'map':
$wrapper = new MapWrapper($routine, $codeStore, $nameMangler, $lobAsString);
break;
case 'none':
$wrapper = new NoneWrapper($routine, $codeStore, $nameMangler, $lobAsString);
break;
case 'row0':
$wrapper = new Row0Wrapper($routine, $codeStore, $nameMangler, $lobAsString);
break;
case 'row1':
$wrapper = new Row1Wrapper($routine, $codeStore, $nameMangler, $lobAsString);
break;
case 'rows':
$wrapper = new RowsWrapper($routine, $codeStore, $nameMangler, $lobAsString);
break;
case 'rows_with_key':
$wrapper = new RowsWithKeyWrapper($routine, $codeStore, $nameMangler, $lobAsString);
break;
case 'rows_with_index':
$wrapper = new RowsWithIndexWrapper($routine, $codeStore, $nameMangler, $lobAsString);
break;
case 'singleton0':
$wrapper = new Singleton0Wrapper($routine, $codeStore, $nameMangler, $lobAsString);
break;
case 'singleton1':
$wrapper = new Singleton1Wrapper($routine, $codeStore, $nameMangler, $lobAsString);
break;
case 'function':
$wrapper = new FunctionWrapper($routine, $codeStore, $nameMangler, $lobAsString);
break;
case 'table':
$wrapper = new TableWrapper($routine, $codeStore, $nameMangler, $lobAsString);
break;
default:
throw new FallenException('routine type', $routine['designation']);
}
return $wrapper;
} | A factory for creating the appropriate object for generating a wrapper method for a stored routine.
@param array $routine The metadata of the stored routine.
@param PhpCodeStore $codeStore The code store for the generated code.
@param NameMangler $nameMangler The mangler for wrapper and parameter names.
@param bool $lobAsString If set BLOBs and CLOBs are treated as string. Otherwise, BLOBs and CLOBs will be
send as long data.
@return Wrapper | entailment |
public function isBlobParameter(?array $parameters): bool
{
$hasBlob = false;
if ($parameters)
{
foreach ($parameters as $parameter_info)
{
$hasBlob = $hasBlob || DataTypeHelper::isBlobParameter($parameter_info['data_type']);
}
}
return $hasBlob;
} | Returns true if one of the parameters is a BLOB or CLOB.
@param array|null $parameters The parameters info (name, type, description).
@return bool | entailment |
public function writeRoutineFunction(): void
{
if (!$this->lobAsStringFlag && $this->isBlobParameter($this->routine['parameters']))
{
$this->writeRoutineFunctionWithLob();
}
else
{
$this->writeRoutineFunctionWithoutLob();
}
} | Generates a complete wrapper method. | entailment |
public function writeRoutineFunctionWithLob(): void
{
$wrapper_args = $this->getWrapperArgs();
$routine_args = $this->getRoutineArgs();
$method_name = $this->nameMangler->getMethodName($this->routine['routine_name']);
$bindings = '';
$nulls = '';
foreach ($this->routine['parameters'] as $parameter_info)
{
$binding = DataTypeHelper::getBindVariableType($parameter_info, $this->lobAsStringFlag);
if ($binding=='b')
{
$bindings .= 'b';
if ($nulls!=='') $nulls .= ', ';
$nulls .= '$null';
}
}
$this->codeStore->appendSeparator();
$this->generatePhpDoc();
$this->codeStore->append('public static function '.$method_name.'('.$wrapper_args.')');
$this->codeStore->append('{');
$this->codeStore->append('$query = \'call '.$this->routine['routine_name'].'('.$routine_args.')\';');
$this->codeStore->append('$stmt = self::$mysqli->prepare($query);');
$this->codeStore->append('if (!$stmt) self::mySqlError(\'mysqli::prepare\');');
$this->codeStore->append('');
$this->codeStore->append('$null = null;');
$this->codeStore->append('$b = $stmt->bind_param(\''.$bindings.'\', '.$nulls.');');
$this->codeStore->append('if (!$b) self::mySqlError(\'mysqli_stmt::bind_param\');');
$this->codeStore->append('');
$this->codeStore->append('self::getMaxAllowedPacket();');
$this->codeStore->append('');
$blobArgumentIndex = 0;
foreach ($this->routine['parameters'] as $parameter_info)
{
if (DataTypeHelper::getBindVariableType($parameter_info, $this->lobAsStringFlag)=='b')
{
$mangledName = $this->nameMangler->getParameterName($parameter_info['parameter_name']);
$this->codeStore->append('self::sendLongData($stmt, '.$blobArgumentIndex.', $'.$mangledName.');');
$blobArgumentIndex++;
}
}
if ($blobArgumentIndex>0)
{
$this->codeStore->append('');
}
$this->codeStore->append('if (self::$logQueries)');
$this->codeStore->append('{');
$this->codeStore->append('$time0 = microtime(true);');
$this->codeStore->append('');
$this->codeStore->append('$b = $stmt->execute();');
$this->codeStore->append('if (!$b) self::mySqlError(\'mysqli_stmt::execute\');');
$this->codeStore->append('');
$this->codeStore->append('self::$queryLog[] = [\'query\' => $query,');
$this->codeStore->append(' \'time\' => microtime(true) - $time0];', false);
$this->codeStore->append('}');
$this->codeStore->append('else');
$this->codeStore->append('{');
$this->codeStore->append('$b = $stmt->execute();');
$this->codeStore->append('if (!$b) self::mySqlError(\'mysqli_stmt::execute\');');
$this->codeStore->append('}');
$this->codeStore->append('');
$this->writeRoutineFunctionLobFetchData();
$this->codeStore->append('$stmt->close();');
$this->codeStore->append('if (self::$mysqli->more_results()) self::$mysqli->next_result();');
$this->codeStore->append('');
$this->writeRoutineFunctionLobReturnData();
$this->codeStore->append('}');
$this->codeStore->append('');
} | Generates a complete wrapper method for a stored routine with a LOB parameter. | entailment |
public function writeRoutineFunctionWithoutLob(): void
{
$wrapperArgs = $this->getWrapperArgs();
$methodName = $this->nameMangler->getMethodName($this->routine['routine_name']);
$returnType = $this->getReturnTypeDeclaration();
$this->codeStore->appendSeparator();
$this->generatePhpDoc();
$this->codeStore->append('public static function '.$methodName.'('.$wrapperArgs.')'.$returnType);
$this->codeStore->append('{');
$this->writeResultHandler();
$this->codeStore->append('}');
$this->codeStore->append('');
} | Returns a wrapper method for a stored routine without LOB parameters. | entailment |
protected function getRoutineArgs(): string
{
$ret = '';
foreach ($this->routine['parameters'] as $parameter_info)
{
$mangledName = $this->nameMangler->getParameterName($parameter_info['parameter_name']);
if ($ret) $ret .= ',';
$ret .= DataTypeHelper::escapePhpExpression($parameter_info, '$'.$mangledName, $this->lobAsStringFlag);
}
return $ret;
} | Returns code for the arguments for calling the stored routine in a wrapper method.
@return string | entailment |
protected function getWrapperArgs(): string
{
$ret = '';
if ($this->routine['designation']=='bulk')
{
$ret .= 'BulkHandler $bulkHandler';
}
foreach ($this->routine['parameters'] as $i => $parameter)
{
if ($ret!='') $ret .= ', ';
$dataType = DataTypeHelper::columnTypeToPhpTypeHinting($parameter);
$declaration = DataTypeHelper::phpTypeHintingToPhpTypeDeclaration($dataType.'|null');
if ($declaration!=='')
{
$ret .= $declaration.' ';
}
$ret .= '$'.$this->nameMangler->getParameterName($parameter['parameter_name']);
}
return $ret;
} | Returns code for the parameters of the wrapper method for the stored routine.
@return string | entailment |
private function generatePhpDoc(): void
{
$this->codeStore->append('/**', false);
// Generate phpdoc with short description of routine wrapper.
$this->generatePhpDocSortDescription();
// Generate phpdoc with long description of routine wrapper.
$this->generatePhpDocLongDescription();
// Generate phpDoc with parameters and descriptions of parameters.
$this->generatePhpDocParameters();
// Generate return parameter doc.
$this->generatePhpDocBlockReturn();
$this->codeStore->append(' */', false);
} | Generate php doc block in the data layer for stored routine. | entailment |
private function generatePhpDocBlockReturn(): void
{
$return = $this->getDocBlockReturnType();
if ($return!=='')
{
$this->codeStore->append(' *', false);
$this->codeStore->append(' * @return '.$return, false);
}
} | Generates the PHP doc block for the return type of the stored routine wrapper. | entailment |
private function generatePhpDocLongDescription(): void
{
if ($this->routine['phpdoc']['long_description']!=='')
{
$this->codeStore->append(' * '.$this->routine['phpdoc']['long_description'], false);
}
} | Generates the long description of stored routine wrapper. | entailment |
private function generatePhpDocParameters(): void
{
$parameters = [];
foreach ($this->routine['phpdoc']['parameters'] as $parameter)
{
$mangledName = $this->nameMangler->getParameterName($parameter['parameter_name']);
$parameters[] = ['php_name' => '$'.$mangledName,
'description' => $parameter['description'],
'php_type' => $parameter['php_type'],
'data_type_descriptor' => $parameter['data_type_descriptor']];
}
$this->enhancePhpDocParameters($parameters);
if (!empty($parameters))
{
// Compute the max lengths of parameter names and the PHP types of the parameters.
$max_name_length = 0;
$max_type_length = 0;
foreach ($parameters as $parameter)
{
$max_name_length = max($max_name_length, mb_strlen($parameter['php_name']));
$max_type_length = max($max_type_length, mb_strlen($parameter['php_type']));
}
$this->codeStore->append(' *', false);
// Generate phpDoc for the parameters of the wrapper method.
foreach ($parameters as $parameter)
{
$format = sprintf(' * %%-%ds %%-%ds %%-%ds %%s', mb_strlen('@param'), $max_type_length, $max_name_length);
$lines = explode(PHP_EOL, $parameter['description'] ?? '');
if (!empty($lines))
{
$line = array_shift($lines);
$this->codeStore->append(sprintf($format, '@param', $parameter['php_type'], $parameter['php_name'], $line), false);
foreach ($lines as $line)
{
$this->codeStore->append(sprintf($format, ' ', ' ', ' ', $line), false);
}
}
else
{
$this->codeStore->append(sprintf($format, '@param', $parameter['php_type'], $parameter['php_name'], ''), false);
}
if ($parameter['data_type_descriptor']!==null)
{
$this->codeStore->append(sprintf($format, ' ', ' ', ' ', $parameter['data_type_descriptor']), false);
}
}
}
} | Generates the doc block for parameters of stored routine wrapper. | entailment |
private function generatePhpDocSortDescription(): void
{
if ($this->routine['phpdoc']['sort_description']!=='')
{
$this->codeStore->append(' * '.$this->routine['phpdoc']['sort_description'], false);
}
} | Generates the sort description of stored routine wrapper. | entailment |
public function backgroundLight($gradient = false)
{
$this->textDark();
$this->attributes->addAttributeClass('bg-' . ($gradient === true ? 'gradient-' : '') . 'light');
return $this;
} | ColorUtilitiesTrait::backgroundLight
@param bool $gradient
@return static | entailment |
public function backgroundDark($gradient = false)
{
$this->textLight();
$this->attributes->addAttributeClass('bg-' . ($gradient === true ? 'gradient-' : '') . 'dark');
return $this;
} | ColorUtilitiesTrait::backgroundDark
@param bool $gradient
@return static | entailment |
public function setSegments($segments)
{
$this->segments = is_array($segments) ? implode('/', $segments) : $segments;
return $this;
} | Module::setSegments
@param array|string $segments
@return static | entailment |
public function setParentSegments($parentSegments)
{
$this->parentSegments = is_array($parentSegments) ? implode('/', $parentSegments) : $parentSegments;
return $this;
} | Module::setParentSegments
@param array|string $parentSegments
@return static | entailment |
public function setProperties(array $properties)
{
if (isset($properties[ 'presets' ])) {
$this->setPresets($properties[ 'presets' ]);
unset($properties[ 'presets' ]);
}
$this->properties = $properties;
return $this;
} | Module::setProperties
@param array $properties
@return static | entailment |
public function getThemes()
{
$directory = new SplDirectoryInfo($this->getResourcesDir() . 'themes' . DIRECTORY_SEPARATOR);
$themes = [];
foreach ($directory->getTree() as $themeName => $themeTree) {
if (($theme = $this->getTheme($themeName)) instanceof Module\Theme) {
$themes[ $themeName ] = $theme;
}
}
return $themes;
} | Module::getThemes
@return array | entailment |
public function getResourcesDir($subDir = null)
{
$dirResources = PATH_RESOURCES;
$dirPath = str_replace(PATH_APP, '', $this->getRealPath());
$dirPathParts = explode(DIRECTORY_SEPARATOR, $dirPath);
if(count($dirPathParts)) {
$dirPathParts = array_map('dash', $dirPathParts);
$dirResources.= implode(DIRECTORY_SEPARATOR, $dirPathParts);
}
if (is_null($subDir)) {
return $dirResources;
} elseif (is_dir($dirResources . $subDir . DIRECTORY_SEPARATOR)) {
return $dirResources . $subDir . DIRECTORY_SEPARATOR;
}
return false;
} | Module::getResourcesDir
@param string|null $subDir
@return bool|string | entailment |
public function getTheme($theme, $failover = true)
{
$theme = dash($theme);
if ($failover === false) {
if (is_dir($themePath = $this->getResourcesDir('themes') . $theme . DIRECTORY_SEPARATOR)) {
$themeObject = new Module\Theme($themePath);
if ($themeObject->isValid()) {
return $themeObject;
}
}
} else {
foreach (modules() as $module) {
if (in_array($module->getType(), ['KERNEL', 'FRAMEWORK'])) {
continue;
} elseif ($themeObject = $module->getTheme($theme, false)) {
return $themeObject;
}
}
}
return false;
} | Module::getTheme
@param string $theme
@param bool $failover
@return bool|Module\Theme | entailment |
public function getDir($subDir, $psrDir = false)
{
$subDir = $psrDir === true ? prepare_class_name($subDir) : $subDir;
$subDir = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $subDir);
if (is_dir($dirPath = $this->getRealPath() . $subDir)) {
return $dirPath . DIRECTORY_SEPARATOR;
}
return false;
} | Module::getDir
@param string $subDir
@param bool $psrDir
@return bool|string | entailment |
public function hasTheme($theme)
{
if (is_dir($this->getThemesDir() . $theme)) {
return true;
} else {
foreach (modules() as $module) {
if (in_array($module->getType(), ['KERNEL', 'FRAMEWORK'])) {
continue;
} elseif (is_dir($module->getResourcesDir('themes') . $theme)) {
return true;
}
}
}
return false;
} | Module::hasTheme
@param string $theme
@return bool | entailment |
public function loadModel()
{
$modelClassName = $this->namespace . 'Models\Base';
if (class_exists($modelClassName)) {
models()->load($modelClassName, strtolower($this->type));
}
} | Module::loadModel | entailment |
public function setTooltip($text, $placement = 'right')
{
$placement = in_array($placement, ['top', 'bottom', 'left', 'right']) ? $placement : 'right';
$this->attributes->addAttribute('data-toggle', 'tooltip');
$this->attributes->addAttribute('data-placement', $placement);
$this->attributes->addAttribute('title', $text);
return $this;
} | TooltipSetterTrait::setTooltip
@param string $text
@param string $placement
@return static | entailment |
public function transform(ApiRequest $request, ApiResponse $response, array $context = []): ApiResponse
{
// Return immediately if context hasn't defined renderer
if (!isset($context['renderer'])) return $response;
// Fetch service
$service = $this->container->getByType($context['renderer'], false);
if (!$service) {
throw new InvalidStateException(sprintf('Renderer "%s" is not registered in container', $context['renderer']));
}
if (!is_callable($service)) {
throw new InvalidStateException(sprintf('Renderer "%s" must implement __invoke() method', $context['renderer']));
}
return $service($request, $response, $context);
} | Encode given data for response
@param mixed[] $context | entailment |
public function load($id): AggregateRoot
{
$snapshot = $this->snapshotRepository->load($id);
if (null === $snapshot) {
return $this->eventSourcingRepository->load($id);
}
$aggregateRoot = $snapshot->getAggregateRoot();
$aggregateRoot->initializeState(
$this->eventStore->loadFromPlayhead($id, $snapshot->getPlayhead() + 1)
);
return $aggregateRoot;
} | {@inheritdoc} | entailment |
public function save(AggregateRoot $aggregate)
{
$takeSnaphot = $this->trigger->shouldSnapshot($aggregate);
$this->eventSourcingRepository->save($aggregate);
if ($takeSnaphot) {
$this->snapshotRepository->save(
new Snapshot($aggregate)
);
}
} | {@inheritdoc} | entailment |
public static function matchPath(string $pattern, string $path, bool $isCaseSensitive = true): bool
{
// Explicitly exclude directory itself.
if ($path=='' && $pattern=='**/*')
{
return false;
}
$dirSep = preg_quote(DIRECTORY_SEPARATOR, '/');
$trailingDirSep = '(('.$dirSep.')?|('.$dirSep.').+)';
$patternReplacements = [$dirSep.'\*\*'.$dirSep => $dirSep.'.*'.$trailingDirSep,
$dirSep.'\*\*' => $trailingDirSep,
'\*\*'.$dirSep => '(.*'.$dirSep.')?',
'\*\*' => '.*',
'\*' => '[^'.$dirSep.']*',
'\?' => '[^'.$dirSep.']'];
$rePattern = preg_quote($pattern, '/');
$rePattern = str_replace(array_keys($patternReplacements), array_values($patternReplacements), $rePattern);
$rePattern = '/^'.$rePattern.'$/'.($isCaseSensitive ? '' : 'i');
return (bool)preg_match($rePattern, $path);
} | Tests whether or not a given path matches a given pattern.
(This method is heavily inspired by SelectorUtils::matchPath from phing.)
@param string $pattern The pattern to match against.
@param string $path The path to match.
@param bool $isCaseSensitive Whether or not matching should be performed case sensitively.
@return bool | entailment |
public function setFile($filePath)
{
if (is_file($filePath)) {
$this->file = new SplFileInfo($filePath);
if (file_exists(
$propertiesFilePath = $this->file->getPath() . DIRECTORY_SEPARATOR . str_replace(
'.phtml',
'.json',
strtolower($this->file->getBasename())
)
)) {
$properties = file_get_contents($propertiesFilePath);
$properties = json_decode($properties, true);
if (isset($properties[ 'vars' ])) {
$this->vars = $properties[ 'vars' ];
}
if (isset($properties[ 'presets' ])) {
$this->presets = new SplArrayObject($properties[ 'presets' ]);
}
}
}
return $this;
} | Page::setFile
@param $filePath
@return static | entailment |
public function setHeader($header)
{
$header = trim($header);
$header = language($header);
$this->store('header', $header);
presenter()->meta->title->append($header);
return $this;
} | Page::setHeader
@param string $header
@return static | entailment |
public function setTitle($title)
{
$title = trim($title);
$title = language($title);
$this->store('title', $title);
presenter()->meta->title->append($title);
return $this;
} | Page::setTitle
@param string $title
@return static | entailment |
public function create(array $parameters)
{
if (!array_key_exists('name', $parameters) || !is_string($parameters['name'])) {
throw new \InvalidArgumentException('A new droplet must have a string "name".');
}
if (!array_key_exists('size_id', $parameters) || !is_int($parameters['size_id'])) {
throw new \InvalidArgumentException('A new droplet must have an integer "size_id".');
}
if (!array_key_exists('image_id', $parameters) || !is_int($parameters['image_id'])) {
throw new \InvalidArgumentException('A new droplet must have an integer "image_id".');
}
if (!array_key_exists('region_id', $parameters) || !is_int($parameters['region_id'])) {
throw new \InvalidArgumentException('A new droplet must have an integer "region_id".');
}
if (array_key_exists('ssh_key_ids', $parameters) && !is_string($parameters['ssh_key_ids'])) {
throw new \InvalidArgumentException('You need to provide an list of "ssh_key_ids" comma separeted.');
}
return $this->processQuery($this->buildQuery(null, DropletsActions::ACTION_NEW, $parameters));
} | Creates a new droplet.
The parameter should be an array with 4 required keys: name, sized_id, image_id and region_id.
The ssh_key_ids key is optional. If any, it should be a list of numbers comma separated.
@param array $parameters An array of parameters.
@return StdClass
@throws \InvalidArgumentException | entailment |
public function resize($dropletId, array $parameters)
{
if (!array_key_exists('size_id', $parameters) || !is_int($parameters['size_id'])) {
throw new \InvalidArgumentException('You need to provide an integer "size_id".');
}
return $this->processQuery($this->buildQuery($dropletId, DropletsActions::ACTION_RESIZE, $parameters));
} | Resizes a specific droplet to a different size.
This will affect the number of processors and memory allocated to the droplet.
The size_id key is required.
@param integer $dropletId The id of the droplet.
@param array $parameters An array of parameters.
@return StdClass
@throws \InvalidArgumentException | entailment |
public function snapshot($dropletId, array $parameters = array())
{
return $this->processQuery($this->buildQuery($dropletId, DropletsActions::ACTION_SNAPSHOT, $parameters));
} | Takes a snapshot of the running droplet, which can later be restored or
used to create a new droplet from the same image.
Please be aware this may cause a reboot.
The name key is optional.
@param integer $dropletId The id of the droplet.
@param array $parameters An array of parameters (optional).
@return StdClass | entailment |
public function restore($dropletId, array $parameters)
{
if (!array_key_exists('image_id', $parameters) || !is_int($parameters['image_id'])) {
throw new \InvalidArgumentException('You need to provide the "image_id" to restore.');
}
return $this->processQuery($this->buildQuery($dropletId, DropletsActions::ACTION_RESTORE, $parameters));
} | Restores a droplet with a previous image or snapshot.
This will be a mirror copy of the image or snapshot to your droplet.
Be sure you have backed up any necessary information prior to restore.
The image_id is required.
@param integer $dropletId The id of the droplet.
@param array $parameters An array of parameters.
@return StdClass
@throws \InvalidArgumentException | entailment |
public function rebuild($dropletId, array $parameters)
{
if (!array_key_exists('image_id', $parameters) || !is_int($parameters['image_id'])) {
throw new \InvalidArgumentException('You need to provide the "image_id" to rebuild.');
}
return $this->processQuery($this->buildQuery($dropletId, DropletsActions::ACTION_REBUILD, $parameters));
} | Reinstalls a droplet with a default image.
This is useful if you want to start again but retain the same IP address for your droplet.
The image_id is required.
@param integer $dropletId The id of the droplet.
@param array $parameters An array of parameters.
@return StdClass
@throws \InvalidArgumentException | entailment |
Subsets and Splits