sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function rename($dropletId, array $parameters)
{
if (!array_key_exists('name', $parameters) || !is_string($parameters['name'])) {
throw new \InvalidArgumentException('You need to provide a string "name".');
}
return $this->processQuery($this->buildQuery($dropletId, DropletsActions::ACTION_RENAME, $parameters));
} | Renames a specific droplet to a different name.
The name 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 queryWithParam(string $query, array $param): PDOStatement
{
$statement = $this->prepare($query);
foreach ($param as $value) {
$this->checkValue($value);
//reassign as reference
//because bindParam need it as reference
$ref = $value;
$ref[1] = &$value[1];
\call_user_func_array([$statement, "bindParam"], $ref);
}
$this->lastOperationStatus = $statement->execute();
return $statement;
} | Executes an SQL statement with parameters,
returning a result set as a PDOStatement object
@param string $query SQL statement
@param array $param Parameter as array as PDOStatement::bindParam
@return PDOStatement | entailment |
public function pagination()
{
$rows = $this->info->getTotal()->rows;
$rows = empty($rows) ? 0 : $rows;
$limit = input()->get('limit');
$limit = empty($limit) ? $this->info->limit : $limit;
return new Pagination($rows, $limit);
} | Result::pagination
@return \O2System\Framework\Libraries\Ui\Components\Pagination | entailment |
public function all($fields = null)
{
if (isset($fields)) {
$this->db->select($fields);
}
$result = $this->db->from($this->collection)->get();
if ($result->count() > 0) {
$this->result = new DataObjects\Result($result, $this);
return $this->result;
}
return false;
} | FinderTrait::all
Find single or many record base on criteria by specific field
@param array|null $fields
@return DataObjects\Result|bool Returns FALSE if failed. | entailment |
public function find($criteria, $field = null, $limit = null)
{
if (is_array($criteria)) {
return $this->findIn($criteria, $field);
}
$field = isset($field) ? $field : $this->primaryKey;
$result = $this->db
->from($this->collection)
->getWhere([$field => $criteria], $limit);
if ($result->count() > 0) {
$this->result = new DataObjects\Result($result, $this);
if ($result->count() == 1) {
return $this->result->first();
}
return $this->result;
}
return false;
} | FinderTrait::find
Find single or many record base on criteria by specific field
@param string $criteria Criteria value
@param string|null $field Table column field name | set to primary key by default
@return DataObjects\Result|bool Returns FALSE if failed. | entailment |
public function findIn(array $inCriteria, $field = null)
{
$field = isset($field) ? $field : $this->primaryKey;
$result = $this->db
->from($this->collection)
->whereIn($field, $inCriteria)
->get();
if ($result->count() > 0) {
$this->result = new DataObjects\Result($result, $this);
return $this->result;
}
return false;
} | FinderTrait::findIn
Find many records within criteria on specific field
@param array $inCriteria List of criteria
@param string $field Table column field name | set to primary key by default
@return DataObjects\Result|bool Returns FALSE if failed. | entailment |
public function findWhere(array $conditions, $limit = null)
{
$result = $this->db
->from($this->collection)
->getWhere($conditions, $limit);
if ($result->count() > 0) {
$this->result = new DataObjects\Result($result, $this);
if ($limit == 1) {
return $this->result->first();
}
return $this->result;
}
return false;
} | FinderTrait::findWhere
Find single record based on certain conditions
@param array $conditions List of conditions with criteria
@access protected
@return DataObjects\Result|bool Returns FALSE if failed. | entailment |
public function findNotIn(array $notInCriteria, $field = null)
{
$field = isset($field) ? $field : $this->primaryKey;
$result = $this->db
->from($this->collection)
->whereNotIn($field, $notInCriteria)
->get();
if ($result->count() > 0) {
$this->result = new DataObjects\Result($result, $this);
return $this->result;
}
return false;
} | FinderTrait::findNotIn
Find many records not within criteria on specific field
@param array $notInCriteria List of criteria
@param string $field Table column field name | set to primary key by default
@return DataObjects\Result|bool Returns FALSE if failed. | entailment |
public function createColumns(array $columns, $tagName = 'td')
{
foreach ($columns as $column) {
if ($column instanceof Column) {
$column->tagName = $tagName;
$this->childNodes->push($column);
} else {
$columnElement = $this->createColumn($tagName);
if ($column instanceof Element) {
$columnElement->entity->setEntityName($column->entity->getEntityName());
$columnElement->childNodes->push($column);
} else {
$columnElement->entity->setEntityName('col-' . $column);
$columnElement->textContent->push($column);
}
}
}
return $this;
} | Row::createColumns
@param array $columns
@param string $tagName
@return static | entailment |
public function createColumn($tagName = 'td')
{
$column = new Element($tagName);
$this->childNodes->push($column);
return $this->childNodes->last();
} | Row::createColumn
@param string $tagName
@return Element | entailment |
private function check(string $uuid): void
{
$uuid32 = \str_replace('-', '', $uuid);
if (\preg_match('/^[0-9a-f]{8}[0-9a-f]{4}[4][0-9a-f]{3}[89ab][0-9a-f]{3}[0-9a-f]{12}$/i', $uuid32) !== 1) {
throw new InvalidArgumentException('Invalid UUID version 4 provided.');
}
$this->hexUUID = $uuid;
} | Check UUID.
@param string $uuid
@return void | entailment |
private function generate(): void
{
$this->hexUUID = \sprintf(
'%s-%s-%s-%s-%s',
// 8 hex characters
\bin2hex(\random_bytes(4)),
// 4 hex characters
\bin2hex(\random_bytes(2)),
// "4" for the UUID version + 3 hex characters
// 0x4000 is 16384 in int
// 0x4fff is 20479 in int
\dechex(\random_int(16384, 20479)),
// (8, 9, a, or b) for the UUID variant 1 plus 3 hex characters
// 0x8000 is 32768 in int
// 0xbfff is 49151 in int
\dechex(\random_int(32768, 49151)),
// 12 hex characters
\bin2hex(\random_bytes(6))
);
} | Generate a random UUID v4 in hex format.
@codeCoverageIgnore
@return string | entailment |
public function jsonResponseSuccess(array $data = [], $status = 200, $code = 'success', array $headers = [], $options = 0)
{
return $this->jsonResponse()->success($data, $status, $code, $headers, $options);
} | Respond with a success response.
@param array $data
@param int $status
@param string $code
@param array $headers
@param int $options
@return \Illuminate\Http\JsonResponse | entailment |
public function jsonResponseError(array $data = [], $status = 400, $code = 'error', array $headers = [], $options = 0)
{
return $this->jsonResponse()->error($data, $status, $code, $headers, $options);
} | Respond with an error response.
@param array $data
@param int $status
@param string $code
@param array $headers
@param int $options
@return \Illuminate\Http\JsonResponse | entailment |
public function canById(int $permissionId): bool
{
if (isset($this->permission[$permissionId])) {
return true;
}
return false;
} | Check if a Permission is owned, use permission Id.
@param int $permissionId
@return bool | entailment |
public function canByName(string $permissionName): bool
{
if (\in_array($permissionName, \array_column($this->permission, 'name'), true)) {
return true;
}
return false;
} | Check if a Permission is owned, use permission name.
@param string $permissionName
@return bool | entailment |
public function offsetGet($offset)
{
if ($this->offsetExists($offset)) {
return parent::offsetGet($offset);
} elseif (null !== ($result = $this->__call($offset))) {
return $result;
}
return null;
} | Row::offsetGet
@param string $offset
@return bool|\O2System\Framework\Models\Sql\DataObjects\Result|\O2System\Framework\Models\Sql\DataObjects\Result\Row|null | entailment |
public function loadFile($filename, $subDir = null)
{
if (is_file($filename)) {
if (strpos($filename, 'font') !== false) {
$this->fonts->append($filename);
} else {
$type = pathinfo($filename, PATHINFO_EXTENSION);
switch ($type) {
case 'css':
$this->styles->append($filename);
break;
case 'js':
$this->javascripts->append($filename);
break;
}
}
} elseif (isset($subDir)) {
$type = pathinfo($filename, PATHINFO_EXTENSION);
if (empty($type)) {
$type = substr($subDir, 0, -1);
}
switch ($type) {
case 'css':
if (input()->env('DEBUG_STAGE') === 'PRODUCTION') {
if (false !== ($filePath = $this->getFilePath($filename . '.min.css', $subDir))) {
$this->styles->append($filePath);
}
} else {
if (false !== ($filePath = $this->getFilePath($filename . '.css', $subDir))) {
$this->styles->append($filePath);
}
}
break;
case 'fonts':
if (input()->env('DEBUG_STAGE') === 'PRODUCTION') {
if (false !== ($filePath = $this->getFilePath($filename . '.min.css', $subDir))) {
$this->fonts->append($filePath);
}
} else {
if (false !== ($filePath = $this->getFilePath($filename . '.css', $subDir))) {
$this->fonts->append($filePath);
}
}
break;
case 'js':
if (input()->env('DEBUG_STAGE') === 'PRODUCTION') {
if (false !== ($filePath = $this->getFilePath($filename . '.min.js', $subDir))) {
$this->styles->append($filePath);
}
} else {
if (false !== ($filePath = $this->getFilePath($filename . '.js', $subDir))) {
$this->styles->append($filePath);
}
}
break;
}
} else {
$type = pathinfo($filename, PATHINFO_EXTENSION);
if (empty($type)) {
if (input()->env('DEBUG_STAGE') === 'PRODUCTION') {
// Search Style or Font
if (false !== ($filePath = $this->getFilePath($filename . '.min.css'))) {
$this->styles->append($filePath);
} elseif (false !== ($filePath = $this->getFilePath($filename . '.min.css'))) {
$this->fonts->append($filePath);
}
// Search Javascript
if (false !== ($filePath = $this->getFilePath($filename . '.min.js'))) {
$this->javascripts->append($filePath);
}
} else {
// Search Style or Font
if (false !== ($filePath = $this->getFilePath($filename . '.css'))) {
$this->styles->append($filePath);
} elseif (false !== ($filePath = $this->getFilePath($filename . '.css'))) {
$this->fonts->append($filePath);
}
// Search Javascript
if (false !== ($filePath = $this->getFilePath($filename . '.js'))) {
$this->javascripts->append($filePath);
}
}
} else {
switch ($type) {
case 'css':
if (false !== ($filePath = $this->getFilePath($filename))) {
$this->styles->append($filePath);
}
break;
case 'js':
if (false !== ($filePath = $this->getFilePath($filename))) {
$this->javascripts->append($filePath);
}
break;
}
}
}
} | Head::loadFile
@param string $filename
@param string|null $subDir
@return void | entailment |
protected static function createNew(
int $ttl,
TokenOwnerInterface $owner = null,
Client $client = null,
array $scopes = null
): self {
if (is_array($scopes)) {
$scopes = array_map(function ($scope) {
return (string) $scope;
}, $scopes);
}
$token = new static();
$token->token = bin2hex(random_bytes(20));
$token->owner = $owner;
$token->client = $client;
$token->scopes = $scopes ?? [];
$token->expiresAt = $ttl ? (new DateTime('@' . time(), new DateTimeZone('UTC')))->modify("+$ttl seconds") : null;
return $token;
} | Create a new AbstractToken
@param int $ttl
@param TokenOwnerInterface $owner
@param Client $client
@param string[]|Scope[]|null $scopes
@return AbstractToken | entailment |
public function matchScopes($scopes): bool
{
$scopes = is_string($scopes) ? explode(' ', $scopes) : $scopes;
$diff = array_diff($scopes, $this->scopes);
return empty($diff);
} | Match the scopes of the token with the one provided in the parameter
@param array|string $scopes | entailment |
public function isValid($scopes): bool
{
if ($this->isExpired()) {
return false;
}
if (! empty($scopes) && ! $this->matchScopes($scopes)) {
return false;
}
return true;
} | Check if the token is valid, according to the given scope(s) and expiration dates
@param array|string $scopes | entailment |
public function get(string $key, $default = null)
{
//create file name
$file = $this->dir.'/'.\sha1($key).'.php';
if ($this->doesFileChecksFailed($file)) {
return $default;
}
$cacheValue = include $file;
return \unserialize($cacheValue['value']);
} | Fetches a value from the cache.
@param string $key The unique key of this item in the cache.
@param mixed $default Default value to return if the key does not exist.
@return mixed The value of the item from the cache, or $default in case of cache miss. | entailment |
private function doesFileChecksFailed(string $file): bool
{
//check if file exist
if (!\file_exists($file)) {
return true;
}
//take cache from file
$cacheValue = include $file;
//check if cache is expired and delete file from storage
if ($cacheValue['expires'] <= \time() && $cacheValue['expires'] !== 0) {
\unlink($file);
return true;
}
return false;
} | Checks for cache file.
@param string $file
@return bool | entailment |
public function set(string $key, $value, int $ttl = 0): bool
{
//create cache array
$cache = [
'key' => $key,
'value' => \serialize($value),
'expires' => $this->calculateTtl($ttl),
];
//export
// HHVM fails at __set_state, so just use object cast for now
$content = \str_replace('stdClass::__set_state', '(object)', \var_export($cache, true));
$content = "<?php return {$content};";
//write file
\file_put_contents($this->dir.'/'.\sha1($key).'.php', $content);
return true;
} | Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
@param string $key The key of the item to store.
@param mixed $value The value of the item to store, must be serializable.
@param int $ttl Optional. The TTL (time to live) value in seconds of this item.
If no value is sent and the driver supports TTL then the
library may set a default value for it or let the driver take care of that.
@return bool True on success and false on failure. | entailment |
public function delete(string $key): bool
{
//create file name
$file = $this->dir.'/'.\sha1($key).'.php';
//chek if file exist and delete
if (\file_exists($file)) {
\unlink($file);
return true;
}
return false;
} | Delete an item from the cache by its unique key.
@param string $key The unique cache key of the item to delete.
@return bool True if the item was successfully removed. False if there was an error. | entailment |
public function has(string $key): bool
{
return !$this->doesFileChecksFailed($this->dir.'/'.\sha1($key).'.php');
} | Determines whether an item is present in the cache.
NOTE: It is recommended that has() is only to be used for cache warming type purposes
and not to be used within your live applications operations for get/set, as this method
is subject to a race condition where your has() will return true and immediately after,
another script can remove it making the state of your app out of date.
@param string $key The cache item key.
@return bool | entailment |
protected function loadAgentFile()
{
if (($found = is_file(PATH_FRAMEWORK . 'Config/UserAgents.php'))) {
include(PATH_FRAMEWORK . 'Config/UserAgents.php');
}
if ($found !== true) {
return false;
}
$return = false;
if (isset($platforms)) {
static::$platforms = $platforms;
unset($platforms);
$return = true;
}
if (isset($browsers)) {
static::$browsers = $browsers;
unset($browsers);
$return = true;
}
if (isset($mobiles)) {
static::$mobiles = $mobiles;
unset($mobiles);
$return = true;
}
if (isset($robots)) {
static::$robots = $robots;
unset($robots);
$return = true;
}
return $return;
} | UserAgent::loadAgentFile
Compile the User Agent Data
@return bool | entailment |
protected function setPlatform()
{
if (is_array(static::$platforms) && count(static::$platforms) > 0) {
foreach (static::$platforms as $key => $val) {
if (preg_match('|' . preg_quote($key) . '|i', $this->string)) {
$this->platform = $val;
return true;
}
}
}
$this->platform = 'Unknown Platform';
return false;
} | UserAgent::setPlatform
Set the Platform
@return bool | entailment |
public function isBrowser($key = null)
{
if ( ! $this->isBrowser) {
return false;
}
// No need to be specific, it's a browser
if ($key === null) {
return true;
}
// Check for a specific browser
return (isset(static::$browsers[ $key ]) && $this->browser === static::$browsers[ $key ]);
} | UserAgent::isBrowser
Is Browser
@param string|null $key
@return bool | entailment |
public function isRobot($key = null)
{
if ( ! $this->isRobot) {
return false;
}
// No need to be specific, it's a robot
if ($key === null) {
return true;
}
// Check for a specific robot
return (isset(static::$robots[ $key ]) && $this->robot === static::$robots[ $key ]);
} | Is Robot
@param string $key
@return bool | entailment |
public function isMobile($key = null)
{
if ( ! $this->isMobile) {
return false;
}
// No need to be specific, it's a mobile
if ($key === null) {
return true;
}
// Check for a specific robot
return (isset(static::$mobiles[ $key ]) && $this->mobile === static::$mobiles[ $key ]);
} | UserAgent::isMobile
Is Mobile
@param string $key
@return bool | entailment |
public function isReferral()
{
if ( ! isset($this->referer)) {
if (empty($_SERVER[ 'HTTP_REFERER' ])) {
$this->referer = false;
} else {
$referer_host = @parse_url($_SERVER[ 'HTTP_REFERER' ], PHP_URL_HOST);
$own_host = parse_url(base_url(), PHP_URL_HOST);
$this->referer = ($referer_host && $referer_host !== $own_host);
}
}
return $this->referer;
} | UserAgent::isReferral
Is this a referral from another site?
@return bool | entailment |
protected function setLanguages()
{
if ((count($this->languages) === 0) && ! empty($_SERVER[ 'HTTP_ACCEPT_LANGUAGE' ])) {
$this->languages = explode(
',',
preg_replace(
'/(;\s?q=[0-9\.]+)|\s/i',
'',
strtolower(trim($_SERVER[ 'HTTP_ACCEPT_LANGUAGE' ]))
)
);
}
if (count($this->languages) === 0) {
$this->languages = ['Undefined'];
}
} | UserAgent::setLanguages
Sets the accepted languages.
@return void | entailment |
protected function setCharsets()
{
if ((count($this->charsets) === 0) && ! empty($_SERVER[ 'HTTP_ACCEPT_CHARSET' ])) {
$this->charsets = explode(
',',
preg_replace(
'/(;\s?q=.+)|\s/i',
'',
strtolower(trim($_SERVER[ 'HTTP_ACCEPT_CHARSET' ]))
)
);
}
if (count($this->charsets) === 0) {
$this->charsets = ['Undefined'];
}
} | UserAgent::setCharsets
Sets the accepted character sets
@return void | entailment |
public function parse($string)
{
// Reset values
$this->isBrowser = false;
$this->isRobot = false;
$this->isMobile = false;
$this->browser = '';
$this->browserVersion = '';
$this->mobile = '';
$this->robot = '';
// Set the new user-agent string and parse it, unless empty
$this->string = $string;
if ( ! empty($string)) {
$this->compileData();
}
} | UserAgent::parse
Parse a custom user-agent string
@param string $string
@return void | entailment |
protected function setBrowser()
{
if (is_array(static::$browsers) && count(static::$browsers) > 0) {
foreach (static::$browsers as $key => $val) {
if (preg_match('|' . $key . '.*?([0-9\.]+)|i', $this->string, $match)) {
$this->isBrowser = true;
$this->browserVersion = $match[ 1 ];
$this->browser = $val;
$this->setMobile();
return true;
}
}
}
return false;
} | UserAgent::setBrowser
Sets the user agent browser.
@return bool | entailment |
protected function setMobile()
{
if (is_array(static::$mobiles) && count(static::$mobiles) > 0) {
foreach (static::$mobiles as $key => $val) {
if (false !== (stripos($this->string, $key))) {
$this->isMobile = true;
$this->mobile = $val;
return true;
}
}
}
return false;
} | UserAgent::setMobile
Sets the user agent mobile device.
@return bool | entailment |
protected function setRobot()
{
if (is_array(static::$robots) && count(static::$robots) > 0) {
foreach (static::$robots as $key => $val) {
if (preg_match('|' . preg_quote($key) . '|i', $this->string)) {
$this->isRobot = true;
$this->robot = $val;
$this->setMobile();
return true;
}
}
}
return false;
} | UserAgent::setRobot
Sets the user agent robot.
@return bool | entailment |
public function run()
{
if ($this->count()) {
$request = server_request();
foreach ($this->registry as $offset => $handler) {
$this->process($request, $handler);
}
}
} | Middleware::run
@return void | entailment |
public function isUserInRoleById(int $userId): bool
{
if (isset($this->users[$userId])) {
return true;
}
return false;
} | Check if an user is in role, use the user Id.
@param int $userId
@return bool | entailment |
public function isUserInRoleByName(string $userName): bool
{
if (\in_array($userName, \array_column($this->users, 'name'), true)) {
return true;
}
return false;
} | Check if an user is in role, use the user name.
@param string $userName
@return bool | entailment |
public function createLabel($textContent = null, array $attributes = [])
{
$label = new Form\Elements\Label($attributes);
$label->attributes->addAttributeClass('col-form-label');
if (isset($textContent)) {
$label->textContent->push($textContent);
}
$this->childNodes->push($label);
return $this->childNodes->last();
} | Group::createLabel
@param array $attributes
@return \O2System\Framework\Libraries\Ui\Components\Form\Elements\Label | entailment |
public function createInput(array $attributes = [])
{
if (isset($attributes[ 'type' ])) {
switch ($attributes[ 'type' ]) {
default:
$input = new Form\Elements\Input($attributes);
break;
case 'checkbox':
$input = new Form\Elements\Checkbox($attributes);
break;
case 'radio':
$input = new Form\Elements\Radio($attributes);
break;
}
} else {
$input = new Form\Elements\Input($attributes);
}
$this->childNodes->push($input);
return $this->childNodes->last();
} | Group::createInput
@param array $attributes
@return \O2System\Framework\Libraries\Ui\Components\Form\Elements\Input | entailment |
public function createTextarea(array $attributes = [])
{
$this->childNodes->push(new Form\Elements\Textarea($attributes));
return $this->childNodes->last();
} | Group::createTextarea
@param array $attributes
@return \O2System\Framework\Libraries\Ui\Components\Form\Elements\Textarea | entailment |
public function createSelect(array $options = [], $selected = null, array $attributes = [])
{
$select = new Form\Elements\Select($attributes);
if (count($options)) {
$select->createOptions($options, $selected);
}
$this->childNodes->push($select);
return $this->childNodes->last();
} | Group::createSelect
@param array $options
@param null $selected
@param array $attributes
@return \O2System\Framework\Libraries\Ui\Components\Form\Elements\Select | entailment |
public function createInputGroup(array $attributes = [])
{
$inputGroup = new Form\Input\Group();
if (count($attributes)) {
$inputGroup->createInput($attributes);
}
$this->childNodes->push($inputGroup);
return $this->input = $this->childNodes->last();
} | @param array $attributes
@return \O2System\Framework\Libraries\Ui\Components\Form\Input\Group | entailment |
public function add(MapEntity $map)
{
$mapId = $map->getMapId();
$this->maps[$mapId] = $map;
parent::markAdded($mapId);
} | {@inheritDoc} | entailment |
public function sync()
{
foreach (parent::getDeleted() as $id) {
if (isset($this->maps[$id])) {
$this->connection->delete('maps', array('map_id' => $id));
unset($this->maps[$id]);
parent::reassign($id);
}
}
foreach (parent::getAdded() as $id) {
if (isset($this->maps[$id])) {
$map = $this->maps[$id];
$this->connection->insert('maps', $this->entityToRow($map));
parent::reassign($id);
}
}
foreach (parent::getModified() as $id) {
if (isset($this->maps[$id])) {
$map = $this->maps[$id];
$this->connection->update('maps', $this->entityToRow($map), array('map_id' => $id));
parent::reassign($id);
}
}
} | {@inheritDoc} | entailment |
public function getUniqueId()
{
$result = $this->connection->prepare("SELECT MAX(map_id) FROM maps");
$result->execute();
$row = $result->fetchColumn();
return (int)($row + 1);
} | {@inheritDoc} | entailment |
public function findOneByName($name)
{
foreach ($this->maps as $map) {
if ($map->getName() === $name) {
return $map;
}
}
$queryBuilder = $this->connection->createQueryBuilder();
$queryBuilder->select('map_id', 'name', 'width', 'height')->from('maps', 'm')->where('name = :name');
$queryBuilder->setParameter(':name', $name);
$result = $queryBuilder->execute();
$row = $result->fetch(\PDO::FETCH_OBJ);
$entity = $this->rowToEntity($row);
return $entity;
} | {@inheritDoc} | entailment |
public function shouldSnapshot(EventSourcedAggregateRoot $aggregateRoot)
{
$clonedAggregateRoot = clone $aggregateRoot;
foreach ($clonedAggregateRoot->getUncommittedEvents() as $domainMessage) {
if (($domainMessage->getPlayhead() + 1) % $this->eventCount === 0) {
return true;
}
}
return false;
} | {@inheritdoc} | entailment |
private function enhanceColumns(): void
{
foreach ($this->oldColumns as $table)
{
foreach ($table as $column)
{
$table_name = $column['table_name'];
$column_name = $column['column_name'];
if ($column['constant_name']=='*')
{
$constant_name = strtoupper($column['column_name']);
$this->oldColumns[$table_name][$column_name]['constant_name'] = $constant_name;
}
else
{
$constant_name = strtoupper($this->oldColumns[$table_name][$column_name]['constant_name']);
$this->oldColumns[$table_name][$column_name]['constant_name'] = $constant_name;
}
}
}
} | Enhances $oldColumns as follows:
If the constant name is *, is is replaced with the column name prefixed by $this->myPrefix in uppercase.
Otherwise the constant name is set to uppercase. | entailment |
private function executeColumnWidths(): void
{
$this->loadOldColumns();
$this->loadColumns();
$this->enhanceColumns();
$this->mergeColumns();
$this->writeColumns();
} | Gathers constants based on column widths. | entailment |
private function executeEnabled(): void
{
if ($this->constantsFilename!==null)
{
$this->executeColumnWidths();
}
if ($this->className!==null)
{
$this->executeCreateConstants();
}
$this->logNumberOfConstants();
} | Executes the enabled functionalities. | entailment |
private function extractLines(string $source): array
{
$tokens = token_get_all($source);
$line1 = null;
$line2 = null;
$line3 = null;
// Find annotation @constants
$step = 1;
foreach ($tokens as $token)
{
switch ($step)
{
case 1:
// Step 1: Find doc comment with annotation.
if (is_array($token) && $token[0]==T_DOC_COMMENT)
{
if (strpos($token[1], '@setbased.stratum.constants')!==false)
{
$line1 = $token[2];
$step = 2;
}
}
break;
case 2:
// Step 2: Find end of doc block.
if (is_array($token))
{
if ($token[0]==T_WHITESPACE)
{
$line2 = $token[2];
if (substr_count($token[1], "\n")>1)
{
// Whitespace contains new line: end doc block without constants.
$step = 4;
}
}
else
{
if ($token[0]==T_CONST)
{
$line3 = $token[2];
$step = 3;
}
else
{
$step = 4;
}
}
}
break;
case 3:
// Step 4: Find en of constants declarations.
if (is_array($token))
{
if ($token[0]==T_WHITESPACE)
{
if (substr_count($token[1], "\n")<=1)
{
// Ignore whitespace.
$line3 = $token[2];
}
else
{
// Whitespace contains new line: end of const declarations.
$step = 4;
}
}
elseif ($token[0]==T_CONST || $token[2]==$line3)
{
$line3 = $token[2];
}
else
{
$step = 4;
}
}
break;
case 4:
// Leave loop.
break;
}
}
// @todo get indent based on indent of the doc block.
return [$line1, $line2, $line3];
} | Searches for 3 lines in the source code of the class for constants. The lines are:
* The first line of the doc block with the annotation '@setbased.stratum.constants'.
* The last line of this doc block.
* The last line of continuous constant declarations directly after the doc block.
If one of these line can not be found the line number will be set to null.
@param string $source The source code of the constant class.
@return array With the 3 line number as described | entailment |
private function fillConstants(): void
{
foreach ($this->columns as $table_name => $table)
{
foreach ($table as $column_name => $column)
{
if (isset($this->columns[$table_name][$column_name]['constant_name']))
{
$this->constants[$column['constant_name']] = $column['length'];
}
}
}
foreach ($this->labels as $label => $id)
{
$this->constants[$label] = $id;
}
ksort($this->constants);
} | Merges $columns and $labels (i.e. all known constants) into $constants. | entailment |
private function loadColumns(): void
{
$rows = DataLayer::getAllTableColumns();
foreach ($rows as $row)
{
$row['length'] = DataTypeHelper::deriveFieldLength($row);
$this->columns[$row['table_name']][$row['column_name']] = $row;
}
} | Loads the width of all columns in the MySQL schema into $columns. | entailment |
private function loadLabels(): void
{
$tables = DataLayer::getLabelTables();
foreach ($tables as $table)
{
$rows = DataLayer::getLabelsFromTable($table['table_name'], $table['id'], $table['label']);
foreach ($rows as $row)
{
$this->labels[$row['label']] = $row['id'];
}
}
} | Loads all primary key labels from the MySQL database. | entailment |
private function loadOldColumns(): void
{
if (file_exists($this->constantsFilename))
{
$handle = fopen($this->constantsFilename, 'r');
$line_number = 0;
while (($line = fgets($handle)))
{
$line_number++;
if ($line!="\n")
{
$n = preg_match('/^\s*(([a-zA-Z0-9_]+)\.)?([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+)\s+(\d+)\s*(\*|[a-zA-Z0-9_]+)?\s*$/', $line, $matches);
if ($n==0)
{
throw new RuntimeException("Illegal format at line %d in file '%s'.",
$line_number,
$this->constantsFilename);
}
if (isset($matches[6]))
{
$schema_name = $matches[2];
$table_name = $matches[3];
$column_name = $matches[4];
$length = $matches[5];
$constant_name = $matches[6];
if ($schema_name)
{
$table_name = $schema_name.'.'.$table_name;
}
$this->oldColumns[$table_name][$column_name] = ['table_name' => $table_name,
'column_name' => $column_name,
'length' => $length,
'constant_name' => $constant_name];
}
}
}
if (!feof($handle))
{
throw new RuntimeException("Error reading from file '%s'.", $this->constantsFilename);
}
$ok = fclose($handle);
if ($ok===false)
{
throw new RuntimeException("Error closing file '%s'.", $this->constantsFilename);
}
}
} | Loads from file $constantsFilename the previous table and column names, the width of the column,
and the constant name (if assigned) and stores this data in $oldColumns. | entailment |
private function logNumberOfConstants(): void
{
$n_id = sizeof($this->labels);
$n_len = sizeof($this->constants) - $n_id;
$this->io->writeln('');
$this->io->text(sprintf('Number of constants based on column widths: %d', $n_len));
$this->io->text(sprintf('Number of constants based on database IDs : %d', $n_id));
} | Logs the number of constants generated. | entailment |
private function makeConstantStatements(): array
{
$width1 = 0;
$width2 = 0;
$constants = [];
foreach ($this->constants as $constant => $value)
{
$width1 = max(mb_strlen($constant), $width1);
$width2 = max(mb_strlen((string)$value), $width2);
}
$line_format = sprintf(' const %%-%ds = %%%dd;', $width1, $width2);
foreach ($this->constants as $constant => $value)
{
$constants[] = sprintf($line_format, $constant, $value);
}
return $constants;
} | Generates PHP code with constant declarations.
@return array The generated PHP code, lines are stored as rows in the array. | entailment |
private function mergeColumns(): void
{
foreach ($this->oldColumns as $table_name => $table)
{
foreach ($table as $column_name => $column)
{
if (isset($this->columns[$table_name][$column_name]))
{
$this->columns[$table_name][$column_name]['constant_name'] = $column['constant_name'];
}
}
}
} | Preserves relevant data in $oldColumns into $columns. | entailment |
private function readConfigFile(string $configFilename): array
{
$settings = parse_ini_file($configFilename, true);
$this->constantsFilename = self::getSetting($settings, false, 'constants', 'columns');
$this->className = self::getSetting($settings, false, 'constants', 'class');
return $settings;
} | Reads configuration parameters from the configuration file.
@param string $configFilename
@return array | entailment |
private function writeColumns(): void
{
$content = '';
foreach ($this->columns as $table)
{
$width1 = 0;
$width2 = 0;
foreach ($table as $column)
{
$width1 = max(mb_strlen($column['column_name']), $width1);
$width2 = max(mb_strlen((string)$column['length']), $width2);
}
foreach ($table as $column)
{
if (isset($column['length']))
{
if (isset($column['constant_name']))
{
$line_format = sprintf("%%s.%%-%ds %%%dd %%s\n", $width1, $width2);
$content .= sprintf($line_format,
$column['table_name'],
$column['column_name'],
$column['length'],
$column['constant_name']);
}
else
{
$line_format = sprintf("%%s.%%-%ds %%%dd\n", $width1, $width2);
$content .= sprintf($line_format,
$column['table_name'],
$column['column_name'],
$column['length']);
}
}
}
$content .= "\n";
}
// Save the columns, width and constants to the filesystem.
$this->writeTwoPhases($this->constantsFilename, $content);
} | Writes table and column names, the width of the column, and the constant name (if assigned) to
$constantsFilename. | entailment |
private function writeConstantClass(): void
{
// Get the class loader.
/** @var \Composer\Autoload\ClassLoader $loader */
$loader = spl_autoload_functions()[0][0];
// Find the source file of the constant class.
$file_name = $loader->findFile($this->className);
if ($file_name===false)
{
throw new RuntimeException("ClassLoader can not find class '%s'.", $this->className);
}
// Read the source of the class without actually loading the class. Otherwise, we can not (re)load the class in
// \SetBased\Stratum\MySql\RoutineLoaderCommand::getConstants.
$source = file_get_contents($file_name);
if ($source===false)
{
throw new RuntimeException("Unable the open source file '%s'.", $file_name);
}
$source_lines = explode("\n", $source);
// Search for the lines where to insert and replace constant declaration statements.
$line_numbers = $this->extractLines($source);
if (!isset($line_numbers[0]))
{
throw new RuntimeException("Annotation not found in '%s'.", $file_name);
}
// Generate the constant declaration statements.
$constants = $this->makeConstantStatements();
// Insert new and replace old (if any) constant declaration statements.
$tmp1 = array_splice($source_lines, 0, $line_numbers[1]);
$tmp2 = array_splice($source_lines, (isset($line_numbers[2])) ? $line_numbers[2] - $line_numbers[1] : 0);
$source_lines = array_merge($tmp1, $constants, $tmp2);
// Save the configuration file.
$this->writeTwoPhases($file_name, implode("\n", $source_lines));
} | Inserts new and replace old (if any) constant declaration statements in a PHP source file. | entailment |
public function execute()
{
parent::execute();
if (empty($this->optionFilename)) {
output()->write(
(new Format())
->setContextualClass(Format::DANGER)
->setString(language()->getLine('CLI_MAKE_HELPER_E_FILENAME'))
->setNewLinesAfter(1)
);
exit(EXIT_ERROR);
}
if (strpos($this->optionPath, 'Helpers') === false) {
$filePath = $this->optionPath . 'Helpers' . DIRECTORY_SEPARATOR . $this->optionFilename;
} else {
$filePath = $this->optionPath . $this->optionFilename;
}
$fileDirectory = dirname($filePath) . DIRECTORY_SEPARATOR;
if ( ! is_dir($fileDirectory)) {
mkdir($fileDirectory, 0777, true);
}
if (is_file($filePath)) {
output()->write(
(new Format())
->setContextualClass(Format::DANGER)
->setString(language()->getLine('CLI_MAKE_HELPER_E_EXISTS', [$filePath]))
->setNewLinesAfter(1)
);
exit(EXIT_ERROR);
}
$vars[ 'CREATE_DATETIME' ] = date('d/m/Y H:m');
$vars[ 'HELPER' ] = underscore(
snakecase(
pathinfo($filePath, PATHINFO_FILENAME)
)
);
$vars[ 'FILEPATH' ] = $filePath;
$phpTemplate = <<<PHPTEMPLATE
<?php
/**
* Created by O2System Framework File Generator.
* DateTime: CREATE_DATETIME
*/
// ------------------------------------------------------------------------
if ( ! function_exists( 'HELPER' ) ) {
/**
* HELPER
*/
function HELPER() {
}
}
PHPTEMPLATE;
$fileContent = str_replace(array_keys($vars), array_values($vars), $phpTemplate);
file_put_contents($filePath, $fileContent);
if (is_file($filePath)) {
output()->write(
(new Format())
->setContextualClass(Format::SUCCESS)
->setString(language()->getLine('CLI_MAKE_HELPER_S_MAKE', [$filePath]))
->setNewLinesAfter(1)
);
exit(EXIT_SUCCESS);
}
} | Helper::execute | entailment |
public function createLegend($text, array $attributes = [])
{
$node = new Fieldset\Legend($attributes);
$node->entity->setEntityName('legend');
$node->attributes->addAttribute('for', dash($text));
$node->textContent->push($text);
$this->childNodes->prepend($node);
return $this->legend = $this->childNodes->first();
} | Fieldset::createLegend
@param string $text
@param array $attributes
@return mixed | entailment |
private static function extractColumnsFromTableDescription(array $description): array
{
$ret = [];
foreach ($description as $column)
{
preg_match('/^(\w+)(.*)?$/', $column['Type'], $parts1);
$tmp = ['column_name' => $column['Field'],
'data_type' => $parts1[1],
'numeric_precision' => null,
'numeric_scale' => null,
'dtd_identifier' => $column['Type']];
switch ($parts1[1])
{
case 'tinyint':
case 'smallint':
case 'mediumint':
case 'int':
case 'bigint':
preg_match('/^\((\d+)\)/', $parts1[2], $parts2);
$tmp['numeric_precision'] = (int)$parts2[1];
$tmp['numeric_scale'] = 0;
break;
case 'year':
// Nothing to do.
break;
case 'float':
$tmp['numeric_precision'] = 12;
break;
case 'double':
$tmp['numeric_precision'] = 22;
break;
case 'binary':
case 'char':
case 'varbinary':
case 'varchar':
// Nothing to do.
break;
case 'decimal':
preg_match('/^\((\d+),(\d+)\)$/', $parts1[2], $parts2);
$tmp['numeric_precision'] = (int)$parts2[1];
$tmp['numeric_scale'] = (int)$parts2[2];;
break;
case 'time':
case 'timestamp':
case 'date':
case 'datetime':
// Nothing to do.
break;
case 'enum':
case 'set':
// Nothing to do.
break;
case 'bit':
preg_match('/^\((\d+)\)$/', $parts1[2], $parts2);
$tmp['numeric_precision'] = (int)$parts2[1];
break;
case 'tinytext':
case 'text':
case 'mediumtext':
case 'longtext':
case 'tinyblob':
case 'blob':
case 'mediumblob':
case 'longblob':
// Nothing to do.
break;
default:
throw new FallenException('data type', $parts1[1]);
}
$ret[] = $tmp;
}
return $ret;
} | Extract column metadata from the rows returend by the SQL statement 'describe table'.
@param array $description The description of the table.
@return array | entailment |
public function loadStoredRoutine(): array
{
$this->routineName = pathinfo($this->sourceFilename, PATHINFO_FILENAME);
$this->phpStratumOldMetadata = $this->phpStratumMetadata;
$this->filemtime = filemtime($this->sourceFilename);
$load = $this->mustLoadStoredRoutine();
if ($load)
{
$this->io->text(sprintf('Loading routine <dbo>%s</dbo>', OutputFormatter::escape($this->routineName)));
$this->readSourceCode();
$this->extractPlaceholders();
$this->extractDesignationType();
$this->extractReturnType();
$this->extractRoutineTypeAndName();
$this->validateReturnType();
$this->loadRoutineFile();
$this->extractBulkInsertTableColumnsInfo();
$this->extractExtendedParametersInfo();
$this->extractRoutineParametersInfo();
$this->extractDocBlockPartsWrapper();
$this->validateParameterLists();
$this->updateMetadata();
}
return $this->phpStratumMetadata;
} | Loads the stored routine into the instance of MySQL and returns the metadata of the stored routine.
@return array | entailment |
private function dropRoutine(): void
{
if (isset($this->rdbmsOldRoutineMetadata))
{
MetaDataLayer::dropRoutine($this->rdbmsOldRoutineMetadata['routine_type'], $this->routineName);
}
} | Drops the stored routine if it exists. | entailment |
private function extractBulkInsertTableColumnsInfo(): void
{
// Return immediately if designation type is not appropriate for this method.
if ($this->designationType!='bulk_insert') return;
// Check if table is a temporary table or a non-temporary table.
$table_is_non_temporary = MetaDataLayer::checkTableExists($this->bulkInsertTableName);
// Create temporary table if table is non-temporary table.
if (!$table_is_non_temporary)
{
MetaDataLayer::callProcedure($this->routineName);
}
// Get information about the columns of the table.
$description = MetaDataLayer::describeTable($this->bulkInsertTableName);
// Drop temporary table if table is non-temporary.
if (!$table_is_non_temporary)
{
MetaDataLayer::dropTemporaryTable($this->bulkInsertTableName);
}
// Check number of columns in the table match the number of fields given in the designation type.
$n1 = count($this->bulkInsertKeys);
$n2 = count($description);
if ($n1!=$n2)
{
throw new RoutineLoaderException("Number of fields %d and number of columns %d don't match.", $n1, $n2);
}
$this->bulkInsertColumns = self::extractColumnsFromTableDescription($description);
} | Extracts the column names and column types of the current table for bulk insert. | entailment |
private function extractDesignationType(): void
{
$found = true;
$key = array_search('begin', $this->routineSourceCodeLines);
if ($key!==false)
{
for ($i = 1; $i<$key; $i++)
{
$n = preg_match('/^\s*--\s+type:\s*(\w+)\s*(.+)?\s*$/',
$this->routineSourceCodeLines[$key - $i],
$matches);
if ($n==1)
{
$this->designationType = $matches[1];
switch ($this->designationType)
{
case 'bulk_insert':
$m = preg_match('/^([a-zA-Z0-9_]+)\s+([a-zA-Z0-9_,]+)$/',
$matches[2],
$info);
if ($m==0)
{
throw new RoutineLoaderException('Error: Expected: -- type: bulk_insert <table_name> <columns>');
}
$this->bulkInsertTableName = $info[1];
$this->bulkInsertKeys = explode(',', $info[2]);
break;
case 'rows_with_key':
case 'rows_with_index':
$this->indexColumns = explode(',', $matches[2]);
break;
default:
if (isset($matches[2])) $found = false;
}
break;
}
if ($i==($key - 1)) $found = false;
}
}
else
{
$found = false;
}
if ($found===false)
{
throw new RoutineLoaderException('Unable to find the designation type of the stored routine');
}
} | Extracts the designation type of the stored routine. | entailment |
private function extractDocBlockPartsSource(): void
{
// Get the DocBlock for the source.
$tmp = PHP_EOL;
foreach ($this->routineSourceCodeLines as $line)
{
$n = preg_match('/create\\s+(procedure|function)\\s+([a-zA-Z0-9_]+)/i', $line);
if ($n) break;
$tmp .= $line;
$tmp .= PHP_EOL;
}
$phpdoc = new DocBlockReflection($tmp);
// Get the short description.
$this->docBlockPartsSource['sort_description'] = $phpdoc->getShortDescription();
// Get the long description.
$this->docBlockPartsSource['long_description'] = $phpdoc->getLongDescription();
// Get the description for each parameter of the stored routine.
foreach ($phpdoc->getTags() as $key => $tag)
{
if ($tag->getName()=='param')
{
/* @var $tag ParamTag */
$this->docBlockPartsSource['parameters'][$key] = ['name' => $tag->getTypes()[0],
'description' => $tag->getDescription()];
}
}
} | Extracts the DocBlock (in parts) from the source of the stored routine. | entailment |
private function extractDocBlockPartsWrapper(): void
{
// Get the DocBlock parts from the source of the stored routine.
$this->extractDocBlockPartsSource();
// Generate the parameters parts of the DocBlock to be used by the wrapper.
$parameters = [];
foreach ($this->parameters as $parameter_info)
{
$parameters[] = ['parameter_name' => $parameter_info['parameter_name'],
'php_type' => DataTypeHelper::columnTypeToPhpTypeHinting($parameter_info).'|null',
'data_type_descriptor' => $parameter_info['data_type_descriptor'],
'description' => $this->getParameterDocDescription($parameter_info['parameter_name'])];
}
// Compose all the DocBlock parts to be used by the wrapper generator.
$this->docBlockPartsWrapper = ['sort_description' => $this->docBlockPartsSource['sort_description'],
'long_description' => $this->docBlockPartsSource['long_description'],
'parameters' => $parameters];
} | Extracts DocBlock parts to be used by the wrapper generator. | entailment |
private function extractExtendedParametersInfo(): void
{
$key = array_search('begin', $this->routineSourceCodeLines);
if ($key!==false)
{
for ($i = 1; $i<$key; $i++)
{
$k = preg_match('/^\s*--\s+param:(?:\s*(\w+)\s+(\w+)(?:(?:\s+([^\s-])\s+([^\s-])\s+([^\s-])\s*$)|(?:\s*$)))?/',
$this->routineSourceCodeLines[$key - $i + 1],
$matches);
if ($k==1)
{
$count = count($matches);
if ($count==3 || $count==6)
{
$parameter_name = $matches[1];
$data_type = $matches[2];
if ($count==6)
{
$list_delimiter = $matches[3];
$list_enclosure = $matches[4];
$list_escape = $matches[5];
}
else
{
$list_delimiter = ',';
$list_enclosure = '"';
$list_escape = '\\';
}
if (!isset($this->extendedParameters[$parameter_name]))
{
$this->extendedParameters[$parameter_name] = ['name' => $parameter_name,
'data_type' => $data_type,
'delimiter' => $list_delimiter,
'enclosure' => $list_enclosure,
'escape' => $list_escape];
}
else
{
throw new RoutineLoaderException("Duplicate parameter '%s'", $parameter_name);
}
}
else
{
throw new RoutineLoaderException('Error: Expected: -- param: <field_name> <type_of_list> [delimiter enclosure escape]');
}
}
}
}
} | Extracts extended info of the routine parameters. | entailment |
private function extractPlaceholders(): void
{
$unknown = [];
preg_match_all('(@[A-Za-z0-9\_\.]+(\%type)?@)', $this->routineSourceCode, $matches);
if (!empty($matches[0]))
{
foreach ($matches[0] as $placeholder)
{
if (isset($this->replacePairs[strtoupper($placeholder)]))
{
$this->replace[$placeholder] = $this->replacePairs[strtoupper($placeholder)];
}
else
{
$unknown[] = $placeholder;
}
}
}
$this->logUnknownPlaceholders($unknown);
} | Extracts the placeholders from the stored routine source. | entailment |
private function extractReturnType(): void
{
// Return immediately if designation type is not appropriate for this method.
if (!in_array($this->designationType, ['function', 'singleton0', 'singleton1'])) return;
$key = array_search('begin', $this->routineSourceCodeLines);
if ($key!==false)
{
for ($i = 1; $i<$key; $i++)
{
$n = preg_match('/^\s*--\s+return:\s*((\w|\|)+)\s*$/',
$this->routineSourceCodeLines[$key - $i],
$matches);
if ($n==1)
{
$this->returnType = $matches[1];
break;
}
}
}
if ($this->returnType===null)
{
$this->returnType = 'mixed';
$this->io->logNote('Unable to find the return type of stored routine');
}
} | Extracts the return type of the stored routine. | entailment |
private function extractRoutineParametersInfo(): void
{
$routine_parameters = MetaDataLayer::getRoutineParameters($this->routineName);
foreach ($routine_parameters as $key => $routine_parameter)
{
if ($routine_parameter['parameter_name'])
{
$data_type_descriptor = $routine_parameter['dtd_identifier'];
if (isset($routine_parameter['character_set_name']))
{
$data_type_descriptor .= ' character set '.$routine_parameter['character_set_name'];
}
if (isset($routine_parameter['collation_name']))
{
$data_type_descriptor .= ' collation '.$routine_parameter['collation_name'];
}
$routine_parameter['data_type_descriptor'] = $data_type_descriptor;
$this->parameters[$key] = $routine_parameter;
}
}
$this->updateParametersInfo();
} | Extracts info about the parameters of the stored routine. | entailment |
private function extractRoutineTypeAndName(): void
{
$n = preg_match('/create\\s+(procedure|function)\\s+([a-zA-Z0-9_]+)/i', $this->routineSourceCode, $matches);
if ($n==1)
{
$this->routineType = strtolower($matches[1]);
if ($this->routineName!=$matches[2])
{
throw new RoutineLoaderException("Stored routine name '%s' does not corresponds with filename", $matches[2]);
}
}
else
{
throw new RoutineLoaderException('Unable to find the stored routine name and type');
}
} | Extracts the name of the stored routine and the stored routine type (i.e. procedure or function) source. | entailment |
private function getParameterDocDescription(string $name): ?string
{
if (isset($this->docBlockPartsSource['parameters']))
{
foreach ($this->docBlockPartsSource['parameters'] as $parameter_doc_info)
{
if ($parameter_doc_info['name']===$name) return $parameter_doc_info['description'];
}
}
return null;
} | Gets description by name of the parameter as found in the DocBlock of the stored routine.
@param string $name Name of the parameter.
@return string|null | entailment |
private function loadRoutineFile(): void
{
// Set magic constants specific for this stored routine.
$this->setMagicConstants();
// Replace all place holders with their values.
$lines = explode("\n", $this->routineSourceCode);
$routine_source = [];
foreach ($lines as $i => &$line)
{
$this->replace['__LINE__'] = $i + 1;
$routine_source[$i] = strtr($line, $this->replace);
}
$routine_source = implode("\n", $routine_source);
// Unset magic constants specific for this stored routine.
$this->unsetMagicConstants();
// Drop the stored procedure or function if its exists.
$this->dropRoutine();
// Set the SQL-mode under which the stored routine will run.
MetaDataLayer::setSqlMode($this->sqlMode);
// Set the default character set and collate under which the store routine will run.
MetaDataLayer::setCharacterSet($this->characterSet, $this->collate);
// Finally, execute the SQL code for loading the stored routine.
MetaDataLayer::loadRoutine($routine_source);
} | Loads the stored routine into the database. | entailment |
private function logUnknownPlaceholders(array $unknown): void
{
// Return immediately if there are no unknown placeholders.
if (empty($unknown)) return;
sort($unknown);
$this->io->text('Unknown placeholder(s):');
$this->io->listing($unknown);
$replace = [];
foreach ($unknown as $placeholder)
{
$replace[$placeholder] = '<error>'.$placeholder.'</error>';
}
$code = strtr(OutputFormatter::escape($this->routineSourceCode), $replace);
$this->io->text(explode(PHP_EOL, $code));
throw new RoutineLoaderException('Unknown placeholder(s) found');
} | Logs the unknown placeholder (if any).
@param array $unknown The unknown placeholders. | entailment |
private function mustLoadStoredRoutine(): bool
{
// If this is the first time we see the source file it must be loaded.
if (!isset($this->phpStratumOldMetadata)) return true;
// If the source file has changed the source file must be loaded.
if ($this->phpStratumOldMetadata['timestamp']!=$this->filemtime) return true;
// If the value of a placeholder has changed the source file must be loaded.
foreach ($this->phpStratumOldMetadata['replace'] as $place_holder => $old_value)
{
if (!isset($this->replacePairs[strtoupper($place_holder)]) ||
$this->replacePairs[strtoupper($place_holder)]!==$old_value)
{
return true;
}
}
// If stored routine not exists in database the source file must be loaded.
if (!isset($this->rdbmsOldRoutineMetadata)) return true;
// If current sql-mode is different the source file must reload.
if ($this->rdbmsOldRoutineMetadata['sql_mode']!=$this->sqlMode) return true;
// If current character set is different the source file must reload.
if ($this->rdbmsOldRoutineMetadata['character_set_client']!=$this->characterSet) return true;
// If current collation is different the source file must reload.
if ($this->rdbmsOldRoutineMetadata['collation_connection']!=$this->collate) return true;
return false;
} | Returns true if the source file must be load or reloaded. Otherwise returns false.
@return bool | entailment |
private function readSourceCode(): void
{
$this->routineSourceCode = file_get_contents($this->sourceFilename);
$this->routineSourceCodeLines = explode("\n", $this->routineSourceCode);
if ($this->routineSourceCodeLines===false)
{
throw new RoutineLoaderException('Source file is empty');
}
} | Reads the source code of the stored routine. | entailment |
private function setMagicConstants(): void
{
$real_path = realpath($this->sourceFilename);
$this->replace['__FILE__'] = "'".MetaDataLayer::realEscapeString($real_path)."'";
$this->replace['__ROUTINE__'] = "'".$this->routineName."'";
$this->replace['__DIR__'] = "'".MetaDataLayer::realEscapeString(dirname($real_path))."'";
} | Adds magic constants to replace list. | entailment |
private function unsetMagicConstants(): void
{
unset($this->replace['__FILE__']);
unset($this->replace['__ROUTINE__']);
unset($this->replace['__DIR__']);
unset($this->replace['__LINE__']);
} | Removes magic constants from current replace list. | entailment |
private function updateMetadata(): void
{
$this->phpStratumMetadata['routine_name'] = $this->routineName;
$this->phpStratumMetadata['designation'] = $this->designationType;
$this->phpStratumMetadata['return'] = $this->returnType;
$this->phpStratumMetadata['parameters'] = $this->parameters;
$this->phpStratumMetadata['timestamp'] = $this->filemtime;
$this->phpStratumMetadata['replace'] = $this->replace;
$this->phpStratumMetadata['phpdoc'] = $this->docBlockPartsWrapper;
$this->phpStratumMetadata['spec_params'] = $this->extendedParameters;
$this->phpStratumMetadata['index_columns'] = $this->indexColumns;
$this->phpStratumMetadata['bulk_insert_table_name'] = $this->bulkInsertTableName;
$this->phpStratumMetadata['bulk_insert_columns'] = $this->bulkInsertColumns;
$this->phpStratumMetadata['bulk_insert_keys'] = $this->bulkInsertKeys;
} | Updates the metadata for the stored routine. | entailment |
private function updateParametersInfo(): void
{
if (!empty($this->extendedParameters))
{
foreach ($this->extendedParameters as $spec_param_name => $spec_param_info)
{
$param_not_exist = true;
foreach ($this->parameters as $key => $param_info)
{
if ($param_info['parameter_name']==$spec_param_name)
{
$this->parameters[$key] = array_merge($this->parameters[$key], $spec_param_info);
$param_not_exist = false;
break;
}
}
if ($param_not_exist)
{
throw new RoutineLoaderException("Specific parameter '%s' does not exist", $spec_param_name);
}
}
}
} | Update information about specific parameters of stored routine. | entailment |
private function validateParameterLists(): void
{
// Make list with names of parameters used in database.
$database_parameters_names = [];
foreach ($this->parameters as $parameter_info)
{
$database_parameters_names[] = $parameter_info['parameter_name'];
}
// Make list with names of parameters used in dock block of routine.
$doc_block_parameters_names = [];
if (isset($this->docBlockPartsSource['parameters']))
{
foreach ($this->docBlockPartsSource['parameters'] as $parameter)
{
$doc_block_parameters_names[] = $parameter['name'];
}
}
// Check and show warning if any parameters is missing in doc block.
$tmp = array_diff($database_parameters_names, $doc_block_parameters_names);
foreach ($tmp as $name)
{
$this->io->logNote('Parameter <dbo>%s</dbo> is missing from doc block', $name);
}
// Check and show warning if find unknown parameters in doc block.
$tmp = array_diff($doc_block_parameters_names, $database_parameters_names);
foreach ($tmp as $name)
{
$this->io->logNote('Unknown parameter <dbo>%s</dbo> found in doc block', $name);
}
} | Validates the parameters found the DocBlock in the source of the stored routine against the parameters from the
metadata of MySQL and reports missing and unknown parameters names. | entailment |
private function validateReturnType(): void
{
// Return immediately if designation type is not appropriate for this method.
if (!in_array($this->designationType, ['function', 'singleton0', 'singleton1'])) return;
$types = explode('|', $this->returnType);
$diff = array_diff($types, ['string', 'int', 'float', 'double', 'bool', 'null']);
if (!($this->returnType=='mixed' || $this->returnType=='bool' || empty($diff)))
{
throw new RoutineLoaderException("Return type must be 'mixed', 'bool', or a combination of 'int', 'float', 'string', and 'null'");
}
// The following tests are applicable for singleton0 routines only.
if (!in_array($this->designationType, ['singleton0'])) return;
// Return mixed is OK.
if (in_array($this->returnType, ['bool', 'mixed'])) return;
// In all other cases return type mus contain null.
$parts = explode('|', $this->returnType);
$key = array_search('null', $parts);
if ($key===false)
{
throw new RoutineLoaderException("Return type must be 'mixed', 'bool', or contain 'null' (with a combination of 'int', 'float', and 'string')");
}
} | Validates the specified return type of the stored routine. | entailment |
public function setImageBackground($src)
{
$this->attributes->addAttributeClass('jumbotron-bg');
if (is_file($src)) {
$src = path_to_url($src);
}
$this->attributes->addAttribute('style', 'background-image: url(\'' . $src . '\');');
return $this;
} | Jumbotron::setImageBackground
@param string $src
@return static | entailment |
public function setVideoBackground($src, $poster = null)
{
$this->attributes->addAttributeClass('jumbotron-video');
$video = new Element('video', 'jumbotron-video');
if (isset($poster)) {
$video->attributes->addAttribute('poster', $poster);
}
$video->attributes->addAttribute('width', '100%');
$video->attributes->addAttribute('preload', 'auto');
$video->attributes->addAttribute('loop', null);
$video->attributes->addAttribute('autoplay', null);
$video->attributes->addAttribute('muted', null);
$source = new Element('source', 'jumbotron-video-source');
if (is_file($src)) {
$src = path_to_url($src);
}
$source->attributes->addAttribute('src', $src);
$source->attributes->addAttribute('type', 'video/webm');
$video->textContent->push($source->render());
$this->childNodes->prepend($video);
return $this;
} | Jumbotron::setVideoBackground
@param string $src
@param string|null $poster
@return static | entailment |
public function setCarousel(Carousel $carousel)
{
$this->attributes->addAttributeClass('jumbotron-carousel');
$this->childNodes->prepend($carousel);
return $this;
} | Jumbotron::setCarousel
@param \O2System\Framework\Libraries\Ui\Components\Carousel $carousel
@return static | entailment |
public function createHeader($text, $tagName = 'h1', array $attributes = ['class' => 'display-3'])
{
$header = new Element($tagName, 'header-' . dash($text));
$header->textContent->push($text);
if (count($attributes)) {
foreach ($attributes as $name => $value) {
$header->attributes->addAttribute($name, $value);
}
}
$this->childNodes->push($header);
return $this->childNodes->last();
} | Jumbotron::createHeader
@param string $text
@param string $tagName
@param array $attributes
@return Element | entailment |
public function createHorizontalRule(array $attributes = [])
{
$hr = new Element('hr');
if (count($attributes)) {
foreach ($attributes as $name => $value) {
$hr->attributes->addAttribute($name, $value);
}
}
$this->childNodes->push($hr);
return $this->childNodes->last();
} | Jumbotron::createHorizontalRule
@param array $attributes
@return Element | entailment |
public function createParagraph($text = null, array $attributes = [])
{
$paragraph = new Paragraph();
if (count($attributes)) {
foreach ($attributes as $name => $value) {
$paragraph->attributes->addAttribute($name, $value);
}
}
if ($text instanceof Element) {
$paragraph->childNodes->push($text);
} elseif ( ! is_null($text)) {
$paragraph->textContent->push($text);
}
$this->childNodes->push($paragraph);
return $this->childNodes->last();
} | Jumbotron::createParagraph
@param string|null $text
@param array $attributes
@return Paragraph | entailment |
public function render()
{
if ($this->attributes->hasAttributeClass('jumbotron-fluid')) {
$output[] = $this->open();
$container = new Element('div', 'container');
$container->attributes->addAttributeClass('container-fluid');
if ($this->hasChildNodes()) {
foreach ($this->childNodes as $childNode) {
$container->childNodes->push($childNode);
}
}
$output[] = $container;
$output[] = $this->close();
return implode(PHP_EOL, $output);
}
return parent::render();
} | Jumbotron::render
@return string | entailment |
public static function format($hook, $type, $notification, $params) {
$event = elgg_extract('event', $params);
$comment = $event->getObject();
$recipient = elgg_extract('recipient', $params);
$language = elgg_extract('language', $params);
if (!$comment instanceof Comment) {
return;
}
$entity = $comment->getContainerEntity();
if (!$entity) {
return;
}
$messages = (new NotificationFormatter($comment, $recipient, $language))->prepare();
$notification->summary = $messages->summary;
$notification->subject = $messages->subject;
$notification->body = $messages->body;
return $notification;
} | Prepare a notification for when comment is created
@param string $hook Equals 'prepare'
@param string $type Equals ''notification:create:object:comment'
@param Notification $notification Notification object
@param array $params Additional params
@return Notification | entailment |
public static function getSubscriptions($hook, $type, $return, $params) {
$event = elgg_extract('event', $params);
if (!$event instanceof SubscriptionNotificationEvent) {
return;
}
$object = $event->getObject();
if (!$object instanceof Comment) {
return;
}
$subscriptions = [];
$actor_subscriptions = [];
$group_subscriptions = [];
$original_container = $object->getOriginalContainer();
if ($original_container instanceof \ElggObject) {
// Users subscribed to the original post in the thread
$subscriptions = elgg_get_subscriptions_for_container($original_container->guid);
$group = $original_container->getContainerEntity();
if ($group instanceof \ElggGroup) {
// Users subscribed to group notifications the thread was started in
$group_subscriptions = elgg_get_subscriptions_for_container($group->guid);
}
// @todo: Do we need to notify users subscribed to a thread within user container?
// It doesn't seem that such notifications would make sense, because they are not performed by the user container
} else if ($original_container instanceof \ElggGroup) {
$group_subscriptions = elgg_get_subscriptions_for_container($original_container->guid);
}
$actor = $event->getActor();
if ($actor instanceof \ElggUser) {
$actor_subscriptions = elgg_get_subscriptions_for_container($actor->guid);
}
$all_subscriptions = $return + $subscriptions + $group_subscriptions + $actor_subscriptions;
// Get user GUIDs that have subscribed to this entity via comment tracker
$user_guids = elgg_get_entities_from_relationship(array(
'type' => 'user',
'relationship_guid' => $original_container->guid,
'relationship' => 'comment_subscribe',
'inverse_relationship' => true,
'limit' => false,
'callback' => function($row) {
return (int) $row->guid;
},
));
/* @var int[] $user_guids */
if ($user_guids) {
// Get a comma separated list of the subscribed users
$user_guids_set = implode(',', $user_guids);
$dbprefix = elgg_get_config('dbprefix');
$site_guid = elgg_get_site_entity()->guid;
// Get relationships that are used to explicitly block specific notification methods
$blocked_relationships = get_data("
SELECT *
FROM {$dbprefix}entity_relationships
WHERE relationship LIKE 'block_comment_notify%'
AND guid_one IN ($user_guids_set)
AND guid_two = $site_guid
");
// Get the methods from the relationship names
$blocked_methods = array();
foreach ($blocked_relationships as $row) {
$method = str_replace('block_comment_notify', '', $row->relationship);
$blocked_methods[$row->guid_one][] = $method;
}
$registered_methods = _elgg_services()->notifications->getMethods();
foreach ($user_guids as $user_guid) {
// All available notification methods on the site
$methods = $registered_methods;
// Remove the notification methods that user has explicitly blocked
if (isset($blocked_methods[$user_guid])) {
$methods = array_diff($methods, $blocked_methods[$user_guid]);
}
if ($methods) {
$all_subscriptions[$user_guid] = $methods;
}
}
}
// Do not send any notifications, if user has explicitly unsubscribed
foreach ($all_subscriptions as $guid => $methods) {
if (check_entity_relationship($guid, 'comment_tracker_unsubscribed', $original_container->guid)) {
unset($all_subscriptions[$guid]);
}
}
// Do not notify the actor
unset($all_subscriptions[$actor->guid]);
return $all_subscriptions;
} | Subscribe users to comments based on original entity
@param string $hook "get"
@param string $type "subscriptions"
@param array $return Subscriptions
@param array $params Hook params
@return array | entailment |
public static function subscribe($event, $type, $entity) {
if (!$entity instanceof Comment) {
return;
}
$original_container = $entity->getOriginalContainer();
if (!$original_container instanceof \ElggObject) {
// Let core subscriptions deal with it
return;
}
if (check_entity_relationship($entity->owner_guid, 'comment_tracker_unsubscribed', $original_container->guid)) {
// User unsubscribed from notifications about this container
return;
}
add_entity_relationship($entity->owner_guid, 'comment_subscribe', $original_container->guid);
} | Subscribe users to notifications about the thread
@param string $event "create"
@param string $type "object"
@param \ElggEntity $entity Object
@return void | entailment |
Subsets and Splits