code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
public function readUIntBySize($size)
{
if ($size === self::UNSIGNED_CHAR_LENGTH) {
return $this->readUInt8();
}
if ($size === self::UNSIGNED_SHORT_LENGTH) {
return $this->readUInt16();
}
if ($size === self::UNSIGNED_INT24_LENGTH) {
return $this->readUInt24();
}
if ($size === self::UNSIGNED_INT32_LENGTH) {
return $this->readUInt32();
}
if ($size === self::UNSIGNED_INT40_LENGTH) {
return $this->readUInt40();
}
if ($size === self::UNSIGNED_INT48_LENGTH) {
return $this->readUInt48();
}
if ($size === self::UNSIGNED_INT56_LENGTH) {
return $this->readUInt56();
}
if ($size === self::UNSIGNED_INT64_LENGTH) {
return $this->readUInt64();
}
throw new BinaryDataReaderException('$size ' . $size . ' not handled');
} | Read a little endian integer values based on byte number
@param int $size
@return mixed
@throws BinaryDataReaderException |
public function readIntBeBySize($size)
{
if ($size === self::UNSIGNED_CHAR_LENGTH) {
return $this->readInt8();
}
if ($size === self::UNSIGNED_SHORT_LENGTH) {
return $this->readInt16Be();
}
if ($size === self::UNSIGNED_INT24_LENGTH) {
return $this->readInt24Be();
}
if ($size === self::UNSIGNED_INT32_LENGTH) {
return $this->readInt32Be();
}
if ($size === self::UNSIGNED_INT40_LENGTH) {
return $this->readInt40Be();
}
throw new BinaryDataReaderException('$size ' . $size . ' not handled');
} | Read a big endian integer values based on byte number
@param int $size
@return int
@throws BinaryDataReaderException |
public function getBinarySlice($binary, $start, $size, $binaryLength)
{
$binary >>= $binaryLength - ($start + $size);
$mask = ((1 << $size) - 1);
return $binary & $mask;
} | Read a part of binary data and extract a number
@param int $binary
@param int $start
@param int $size
@param int $binaryLength
@return int |
public function getMultiple($keys, $default = null)
{
$data = [];
foreach ($keys as $key) {
if ($this->has($key)) {
$data[$key] = self::$tableMapCache[$key];
}
}
return [] !== $data ? $data : $default;
} | Obtains multiple cache items by their unique keys.
@param iterable $keys A list of keys that can obtained in a single operation.
@param mixed $default Default value to return for keys that do not exist.
@return iterable A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value.
@throws \Psr\SimpleCache\InvalidArgumentException
MUST be thrown if $keys is neither an array nor a Traversable,
or if any of the $keys are not a legal value. |
public function set($key, $value, $ttl = null)
{
// automatically clear table cache to save memory
if (count(self::$tableMapCache) > Config::getTableCacheSize()) {
self::$tableMapCache = array_slice(
self::$tableMapCache,
ceil(Config::getTableCacheSize() / 2),
null,
true
);
}
self::$tableMapCache[$key] = $value;
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 null|int|\DateInterval $ttl Optional. The TTL value of this item. If no value is sent and
the driver supports TTL then the library may set a default value
for it or let the driver take care of that.
@return bool True on success and false on failure.
@throws \Psr\SimpleCache\InvalidArgumentException
MUST be thrown if the $key string is not a legal value. |
protected function getDecimal(array $column)
{
$digitsPerInteger = 9;
$compressedBytes = [0, 1, 1, 2, 2, 3, 3, 4, 4, 4];
$integral = $column['precision'] - $column['decimals'];
$unCompIntegral = (int)($integral / $digitsPerInteger);
$unCompFractional = (int)($column['decimals'] / $digitsPerInteger);
$compIntegral = $integral - ($unCompIntegral * $digitsPerInteger);
$compFractional = $column['decimals'] - ($unCompFractional * $digitsPerInteger);
$value = $this->binaryDataReader->readUInt8();
if (0 !== ($value & 0x80)) {
$mask = 0;
$res = '';
} else {
$mask = -1;
$res = '-';
}
$this->binaryDataReader->unread(pack('C', $value ^ 0x80));
$size = $compressedBytes[$compIntegral];
if ($size > 0) {
$value = $this->binaryDataReader->readIntBeBySize($size) ^ $mask;
$res .= $value;
}
for ($i = 0; $i < $unCompIntegral; ++$i) {
$value = $this->binaryDataReader->readInt32Be() ^ $mask;
$res .= sprintf('%09d', $value);
}
$res .= '.';
for ($i = 0; $i < $unCompFractional; ++$i) {
$value = $this->binaryDataReader->readInt32Be() ^ $mask;
$res .= sprintf('%09d', $value);
}
$size = $compressedBytes[$compFractional];
if ($size > 0) {
$value = $this->binaryDataReader->readIntBeBySize($size) ^ $mask;
$res .= sprintf('%0' . $compFractional . 'd', $value);
}
return bcmul($res, 1, $column['precision']);
} | Read MySQL's new decimal format introduced in MySQL 5
https://dev.mysql.com/doc/refman/5.6/en/precision-math-decimal-characteristics.html
@param array $column
@return string
@throws BinaryDataReaderException |
protected function getDatetime2(array $column)
{
$data = $this->binaryDataReader->readIntBeBySize(5);
$yearMonth = $this->binaryDataReader->getBinarySlice($data, 1, 17, 40);
$year = (int)($yearMonth / 13);
$month = $yearMonth % 13;
$day = $this->binaryDataReader->getBinarySlice($data, 18, 5, 40);
$hour = $this->binaryDataReader->getBinarySlice($data, 23, 5, 40);
$minute = $this->binaryDataReader->getBinarySlice($data, 28, 6, 40);
$second = $this->binaryDataReader->getBinarySlice($data, 34, 6, 40);
try {
$date = new \DateTime($year . '-' . $month . '-' . $day . ' ' . $hour . ':' . $minute . ':' . $second);
} catch (\Exception $exception) {
return null;
}
// not all errors are thrown as exception :(
if (array_sum(\DateTime::getLastErrors()) > 0) {
return null;
}
return $date->format('Y-m-d H:i:s') . $this->getFSP($column);
} | Date Time
1 bit sign (1= non-negative, 0= negative)
17 bits year*13+month (year 0-9999, month 0-12)
5 bits day (0-31)
5 bits hour (0-23)
6 bits minute (0-59)
6 bits second (0-59)
---------------------------
40 bits = 5 bytes
@param array $column
@return string|null
@throws BinaryDataReaderException
@link https://dev.mysql.com/doc/internals/en/date-and-time-data-type-representation.html |
protected function getTime2(array $column)
{
$data = $this->binaryDataReader->readInt24Be();
$hour = $this->binaryDataReader->getBinarySlice($data, 2, 10, 24);
$minute = $this->binaryDataReader->getBinarySlice($data, 12, 6, 24);
$second = $this->binaryDataReader->getBinarySlice($data, 18, 6, 24);
return (new \DateTime())->setTime($hour, $minute, $second)->format('H:i:s') . $this->getFSP($column);
} | TIME encoding for non fractional part:
1 bit sign (1= non-negative, 0= negative)
1 bit unused (reserved for future extensions)
10 bits hour (0-838)
6 bits minute (0-59)
6 bits second (0-59)
---------------------
24 bits = 3 bytes
@param array $column
@return string
@throws BinaryDataReaderException |
protected function getBit(array $column)
{
$res = '';
for ($byte = 0; $byte < $column['bytes']; ++$byte) {
$current_byte = '';
$data = $this->binaryDataReader->readUInt8();
if (0 === $byte) {
if (1 === $column['bytes']) {
$end = $column['bits'];
} else {
$end = $column['bits'] % 8;
if (0 === $end) {
$end = 8;
}
}
} else {
$end = 8;
}
for ($bit = 0; $bit < $end; ++$bit) {
if ($data & (1 << $bit)) {
$current_byte .= '1';
} else {
$current_byte .= '0';
}
}
$res .= strrev($current_byte);
}
return $res;
} | Read MySQL BIT type
@param array $column
@return string |
private function isWriteSuccessful($data)
{
$head = ord($data[0]);
if (!in_array($head, $this->packageOkHeader, true)) {
$errorCode = unpack('v', $data[1] . $data[2])[1];
$errorMessage = '';
$packetLength = strlen($data);
for ($i = 9; $i < $packetLength; ++$i) {
$errorMessage .= $data[$i];
}
throw new BinLogException($errorMessage, $errorCode);
}
} | @param string $data
@throws BinLogException |
private static function getCapabilities()
{
/*
Left only as information
$foundRows = 1 << 1;
$connectWithDb = 1 << 3;
$compress = 1 << 5;
$odbc = 1 << 6;
$localFiles = 1 << 7;
$ignoreSpace = 1 << 8;
$multiStatements = 1 << 16;
$multiResults = 1 << 17;
$interactive = 1 << 10;
$ssl = 1 << 11;
$ignoreSigPipe = 1 << 12;
*/
$noSchema = 1 << 4;
$longPassword = 1;
$longFlag = 1 << 2;
$transactions = 1 << 13;
$secureConnection = 1 << 15;
$protocol41 = 1 << 9;
return ($longPassword | $longFlag | $transactions | $protocol41 | $secureConnection | $noSchema);
} | http://dev.mysql.com/doc/internals/en/capability-flags.html#packet-protocol::capabilityflags
https://github.com/siddontang/mixer/blob/master/doc/protocol.txt
@return int |
public function getAll($termType) {
$arr = array();
foreach ($this->terms as $term) {
if ((string)$term->getTermType() === $termType) {
array_push($arr, $term);
}
}
return $arr;
} | Returns all terms that have the given term type, or empty array if none.
@param string $termType
@return Term[] |
public function getFirst($termType) {
foreach ($this->terms as $term) {
if ((string)$term->getTermType() === $termType) {
return $term;
}
}
return null;
} | Returns the first term that has the given term type, or null if none.
@param string $termType
@return Term |
public function convert($asset, $basePath)
{
$extension = $this->getExtension($asset);
if ($extension !== 'scss') {
return $asset;
}
$cssAsset = $this->getCssAsset($asset, 'css');
$inFile = "$basePath/$asset";
$outFile = "$basePath/$cssAsset";
$this->compiler->setImportPaths(dirname($inFile));
if (!$this->storage->exists($inFile)) {
Yii::error("Input file $inFile not found.", __METHOD__);
return $asset;
}
$this->convertAndSaveIfNeeded($inFile, $outFile);
return $cssAsset;
} | Converts a given SCSS asset file into a CSS file.
@param string $asset the asset file path, relative to $basePath
@param string $basePath the directory the $asset is relative to.
@return string the converted asset file path, relative to $basePath. |
protected function getCssAsset(string $filename, string $newExtension): string
{
$extensionlessFilename = pathinfo($filename, PATHINFO_FILENAME);
/** @var int $filenamePosition */
$filenamePosition = strrpos($filename, $extensionlessFilename);
$relativePath = substr($filename, 0, $filenamePosition);
return "$relativePath$extensionlessFilename.$newExtension";
} | Get the relative path and filename of the asset
@param string $filename e.g. path/asset.css
@param string $newExtension e.g. scss
@return string e.g. path/asset.scss |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('core23_antispam');
// Keep compatibility with symfony/config < 4.2
if (!method_exists($treeBuilder, 'getRootNode')) {
$rootNode = $treeBuilder->root('core23_antispam');
} else {
$rootNode = $treeBuilder->getRootNode();
}
\assert($rootNode instanceof ArrayNodeDefinition);
$this->addTwigSection($rootNode);
$this->addTimeSection($rootNode);
$this->addHoneypotSection($rootNode);
return $treeBuilder;
} | {@inheritdoc} |
public function buildForm(FormBuilderInterface $builder, array $options): void
{
if (!$options['antispam_honeypot']) {
return;
}
$builder
->setAttribute('antispam_honeypot_factory', $builder->getFormFactory())
->addEventSubscriber(new AntiSpamHoneypotListener($this->translator, $options['antispam_honeypot_field']))
;
} | {@inheritdoc} |
public function finishView(FormView $view, FormInterface $form, array $options): void
{
if ($view->parent || !$options['antispam_honeypot'] || !$options['compound']) {
return;
}
if ($form->has($options['antispam_honeypot_field'])) {
throw new RuntimeException(sprintf('Honeypot field "%s" is already used.', $options['antispam_honeypot_field']));
}
$factory = $form->getConfig()->getAttribute('antispam_honeypot_factory');
if (!$factory instanceof FormFactoryInterface) {
throw new RuntimeException('Invalid form factory to create a honeyput.');
}
$formOptions = $this->createViewOptions($options);
$formView = $factory
->createNamed($options['antispam_honeypot_field'], TextType::class, null, $formOptions)
->createView($view)
;
$view->children[$options['antispam_honeypot_field']] = $formView;
} | {@inheritdoc} |
private function createViewOptions(array $options): array
{
$formOptions = [
'mapped' => false,
'label' => false,
'required' => false,
];
if (!\array_key_exists('antispam_honeypot_class', $options) || null === $options['antispam_honeypot_class']) {
$formOptions['attr'] = [
'style' => 'display:none',
];
} else {
$formOptions['attr'] = [
'class' => $options['antispam_honeypot_class'],
];
}
return $formOptions;
} | @param array $options
@return array |
public function createFormProtection(string $name): void
{
$startTime = new DateTime();
$key = $this->getSessionKey($name);
$this->session->set($key, $startTime);
} | {@inheritdoc} |
public function isValid(string $name, array $options): bool
{
$startTime = $this->getFormTime($name);
if (null === $startTime) {
return false;
}
$currentTime = new DateTime();
if (\array_key_exists('min', $options) && null !== $options['min']) {
$minTime = clone $startTime;
$minTime->modify(sprintf('+%d seconds', $options['min']));
if ($minTime > $currentTime) {
return false;
}
}
if (\array_key_exists('max', $options) && null !== $options['max']) {
$maxTime = clone $startTime;
$maxTime->modify(sprintf('+%d seconds', $options['max']));
if ($maxTime < $currentTime) {
return false;
}
}
return true;
} | {@inheritdoc} |
public function removeFormProtection(string $name): void
{
$key = $this->getSessionKey($name);
$this->session->remove($key);
} | {@inheritdoc} |
private function hasFormProtection(string $name): bool
{
$key = $this->getSessionKey($name);
return $this->session->has($key);
} | Check if a form has a time protection.
@param string $name
@return bool |
private function getFormTime(string $name): ?DateTime
{
$key = $this->getSessionKey($name);
if ($this->hasFormProtection($name)) {
return $this->session->get($key);
}
return null;
} | Gets the form time for specified form.
@param string $name Name of form to get
@return DateTime|null |
public static function fromEncoded(string $encoded): self
{
$decoded = \json_decode($encoded);
if (null === $decoded && \JSON_ERROR_NONE !== \json_last_error()) {
throw Exception\InvalidJsonEncodedException::fromEncoded($encoded);
}
return new self(
$encoded,
$decoded
);
} | @param string $encoded
@throws Exception\InvalidJsonEncodedException
@return self |
public function format(): Format\Format
{
if (null === $this->format) {
$this->format = Format\Format::fromJson($this);
}
return $this->format;
} | Returns the format of the original JSON value.
@return Format\Format |
public static function detectMbstringOverload()
{
// this method can be removed when minimal php version is bumped to the version with mbstring.func_overload removed
$funcOverload = intval(ini_get('mbstring.func_overload')); // false and empty string will be 0 and the test will pass
if ($funcOverload & self::MBSTRING_OVERLOAD_CONFLICT) {
// @codeCoverageIgnoreStart
// This exception is thrown on a misconfiguration that is not possible to be set dynamically
// and therefore is excluded from testing
throw new RuntimeException(
sprintf('mbstring.func_overload is set to %d, func_overload level 2 has known conflicts with Bencode library', $funcOverload)
);
// @codeCoverageIgnoreEnd
}
} | strlen |
public function setSerialized($serialized)
{
try {
parent::setSerialized($serialized);
} catch (\Exception $e) {
Yii::error('Failed to unserlialize cart: ' . $e->getMessage(), __METHOD__);
$this->_positions = [];
$this->saveToSession();
}
} | Sets cart from serialized string
@param string $serialized |
public function addXmls($importXml = false, $offersXml = false, $ordersXml = false)
{
$this->loadImportXml($importXml);
$this->loadOffersXml($offersXml);
$this->loadOrdersXml($ordersXml);
} | Add XML files.
@param string|bool $importXml
@param string|bool $offersXml
@param bool $ordersXml |
private function push(int $newState)
{
array_push($this->stateStack, $this->state);
$this->state = $newState;
if ($this->state !== self::STATE_ROOT) {
array_push($this->valueStack, $this->value);
}
$this->value = [];
} | Push previous layer to the stack and set new state
@param int $newState |
private function pop($valueToPrevLevel)
{
$this->state = array_pop($this->stateStack);
if ($this->state !== self::STATE_ROOT) {
$this->value = array_pop($this->valueStack);
$this->value []= $valueToPrevLevel;
} else {
// we have final result
$this->decoded = $valueToPrevLevel;
}
} | Pop previous layer from the stack and give it a parsed value
@param mixed $valueToPrevLevel |
public function buildForm(FormBuilderInterface $builder, array $options): void
{
if (!$options['antispam_time']) {
return;
}
$providerOptions = [
'min' => $options['antispam_time_min'],
'max' => $options['antispam_time_max'],
];
$builder
->addEventSubscriber(new AntiSpamTimeListener($this->timeProvider, $this->translator, $providerOptions))
;
} | {@inheritdoc} |
public function finishView(FormView $view, FormInterface $form, array $options): void
{
if ($view->parent || !$options['antispam_time'] || !$options['compound']) {
return;
}
$this->timeProvider->createFormProtection($form->getName());
} | {@inheritdoc} |
public function configureOptions(OptionsResolver $resolver): void
{
$resolver
->setDefaults([
'antispam_time' => $this->defaults['global'],
'antispam_time_min' => $this->defaults['min'],
'antispam_time_max' => $this->defaults['max'],
])
->setAllowedTypes('antispam_time', 'bool')
->setAllowedTypes('antispam_time_min', 'int')
->setAllowedTypes('antispam_time_max', 'int')
;
} | {@inheritdoc} |
public function antispam(string $string, bool $html = true): string
{
if ($html) {
return preg_replace_callback(self::MAIL_HTML_PATTERN, [$this, 'encryptMail'], $string) ?: '';
}
return preg_replace_callback(self::MAIL_TEXT_PATTERN, [$this, 'encryptMailText'], $string) ?: '';
} | Replaces E-Mail addresses with an alternative text representation.
@param string $string input string
@param bool $html Secure html or text
@return string with replaced links |
private function encryptMailText(array $matches): string
{
$email = $matches[1];
return $this->getSecuredName($email).
$this->mailAtText[array_rand($this->mailAtText)].
$this->getSecuredName($email, true);
} | @param string[] $matches
@return string |
private function encryptMail(array $matches): string
{
[, $email, $text] = $matches;
if ($text === $email) {
$text = '';
}
return
'<span'.(!empty($this->mailCssClass) ? ' class="'.$this->mailCssClass.'"' : '').'>'.
'<span>'.$this->getSecuredName($email).'</span>'.
$this->mailAtText[array_rand($this->mailAtText)].
'<span>'.$this->getSecuredName($email, true).'</span>'.
($text ? ' (<span>'.$text.'</span>)' : '').
'</span>';
} | @param string[] $matches
@return string |
private function getSecuredName(string $name, bool $isDomain = false): string
{
$index = strpos($name, '@');
\assert(false !== $index && -1 !== $index);
if ($isDomain) {
$name = substr($name, $index + 1);
} else {
$name = substr($name, 0, $index);
}
return str_replace('.', $this->mailDotText[array_rand($this->mailDotText)], $name ?: '');
} | @param string $name
@param bool $isDomain
@return string |
public function import(Category $category, ImportRecordsDataTable $importRecordsDataTable)
{
return $importRecordsDataTable->with([
'resource' => $category,
'tabs' => 'adminarea.categories.tabs',
'url' => route('adminarea.categories.stash'),
'id' => "adminarea-categories-{$category->getRouteKey()}-import-table",
])->render('cortex/foundation::adminarea.pages.datatable-dropzone');
} | Import categories.
@param \Cortex\Categories\Models\Category $category
@param \Cortex\Foundation\DataTables\ImportRecordsDataTable $importRecordsDataTable
@return \Illuminate\View\View |
protected function process(FormRequest $request, Category $category)
{
// Prepare required input fields
$data = $request->validated();
// Save category
$category->fill($data)->save();
return intend([
'url' => route('adminarea.categories.index'),
'with' => ['success' => trans('cortex/foundation::messages.resource_saved', ['resource' => trans('cortex/categories::common.category'), 'identifier' => $category->name])],
]);
} | Process stored/updated category.
@param \Illuminate\Foundation\Http\FormRequest $request
@param \Cortex\Categories\Models\Category $category
@return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse |
public function destroy(Category $category)
{
$category->delete();
return intend([
'url' => route('adminarea.categories.index'),
'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/categories::common.category'), 'identifier' => $category->name])],
]);
} | Destroy given category.
@param \Cortex\Categories\Models\Category $category
@throws \Exception
@return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse |
public static function fromString(string $string): self
{
if (1 !== \preg_match('/^(?>\r\n|\n|\r)$/', $string)) {
throw Exception\InvalidNewLineStringException::fromString($string);
}
return new self($string);
} | @param string $string
@throws Exception\InvalidNewLineStringException
@return self |
public static function fromString(string $string): self
{
if (1 !== \preg_match('/^( *|\t+)$/', $string)) {
throw Exception\InvalidIndentStringException::fromString($string);
}
return new self($string);
} | @param string $string
@throws Exception\InvalidIndentStringException
@return self |
public static function fromSizeAndStyle(int $size, string $style): self
{
$minimumSize = 1;
if ($minimumSize > $size) {
throw Exception\InvalidIndentSizeException::fromSizeAndMinimumSize(
$size,
$minimumSize
);
}
$characters = [
'space' => ' ',
'tab' => "\t",
];
if (!\array_key_exists($style, $characters)) {
throw Exception\InvalidIndentStyleException::fromStyleAndAllowedStyles(
$style,
...\array_keys($characters)
);
}
$value = \str_repeat(
$characters[$style],
$size
);
return new self($value);
} | @param int $size
@param string $style
@throws Exception\InvalidIndentSizeException
@throws Exception\InvalidIndentStyleException
@return self |
public function xpath($path)
{
$this->registerNamespace();
if (!$this->namespaceRegistered) {
$path = str_replace('c:', '', $path);
}
return $this->xml->xpath($path);
} | Лучше использовать данный метод, вместо стандартного xpath у SimpleXMLElement,
т.к. есть проблемы с неймспейсами xmlns
Для каждого элемента необходимо указывать наймспейс "c", например:
//c:Свойство/c:ВариантыЗначений/c:Справочник[c:ИдЗначения = '{$id}']
@param string $path
@return \SimpleXMLElement[] |
private function normalizeData($data, \stdClass $schema)
{
if (\is_array($data)) {
return $this->normalizeArray(
$data,
$schema
);
}
if ($data instanceof \stdClass) {
return $this->normalizeObject(
$data,
$schema
);
}
return $data;
} | @param null|array|bool|float|int|\stdClass|string $data
@param \stdClass $schema
@throws \InvalidArgumentException
@return null|array|bool|float|int|\stdClass|string |
public function register(): void
{
// Bind eloquent models to IoC container
$this->app['config']['rinvex.categories.models.category'] === Category::class
|| $this->app->alias('rinvex.categories.category', Category::class);
// Register console commands
! $this->app->runningInConsole() || $this->registerCommands();
} | Register any application services.
This service provider is a great spot to register your various container
bindings with the application. As you can see, we are registering our
"Registrar" implementation here. You can add your own bindings too!
@return void |
public function boot(Router $router): void
{
// Bind route models and constrains
$router->pattern('category', '[a-zA-Z0-9-]+');
$router->model('category', config('rinvex.categories.models.category'));
// Map relations
Relation::morphMap([
'category' => config('rinvex.categories.models.category'),
]);
// Load resources
require __DIR__.'/../../routes/breadcrumbs/adminarea.php';
$this->loadRoutesFrom(__DIR__.'/../../routes/web/adminarea.php');
$this->loadViewsFrom(__DIR__.'/../../resources/views', 'cortex/categories');
$this->loadTranslationsFrom(__DIR__.'/../../resources/lang', 'cortex/categories');
! $this->app->runningInConsole() || $this->loadMigrationsFrom(__DIR__.'/../../database/migrations');
$this->app->runningInConsole() || $this->app->afterResolving('blade.compiler', function () {
require __DIR__.'/../../routes/menus/adminarea.php';
});
// Publish Resources
! $this->app->runningInConsole() || $this->publishResources();
} | Bootstrap any application services.
@return void |
public static function dump(string $filename, $data, array $options = []): bool
{
return file_put_contents($filename, self::encode($data, $options)) !== false;
} | Dump data to bencoded file
@param string $filename
@param mixed $data
@param array $options
@return bool success of file_put_contents |
public function toString() {
$str = $this->protocol . '://' . $this->hostName;
if ($this->protocol==='http' && $this->portNumber==80) {
//don't add port
} else if ($this->protocol==='https' && $this->portNumber==443) {
//don't add port
} else {
$str .= ':'. $this->portNumber;
}
return $str;
} | Returns something like 'http://api.nameapi.org' and omits the port if it's a default port (like 80 for http). |
public function init()
{
parent::init();
if (!$this->has(static::CART_COMPONENT_ID)) {
$this->set(static::CART_COMPONENT_ID, array_merge([
'class' => 'hiqdev\yii2\cart\ShoppingCart',
], $this->shoppingCartOptions));
}
$this->get(static::CART_COMPONENT_ID)->module = $this;
$this->registerTranslations();
} | {@inheritdoc}
@throws \yii\base\InvalidConfigException |
public function load(array $configs, ContainerBuilder $container): void
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
$this->configureTwig($config, $container);
$this->configureTime($container, $config);
$this->configureHoneypot($container, $config);
} | {@inheritdoc} |
public static function fromInt(int $value): self
{
if (0 > $value) {
throw Exception\InvalidJsonEncodeOptionsException::fromJsonEncodeOptions($value);
}
return new self($value);
} | @param int $value
@throws Exception\InvalidJsonEncodeOptionsException
@return JsonEncodeOptions |
public function src($email, $size = null, $rating = null)
{
if (is_null($size)) {
$size = $this->defaultSize;
}
$size = max(1, min(self::MAX_SIZE, $size));
$this->setAvatarSize($size);
if (!is_null($rating)) {
$this->setMaxRating($rating);
}
return $this->buildGravatarURL($email);
} | Return the URL of a Gravatar. Note: it does not check for the existence of this Gravatar.
@param string $email The email address.
@param int $size Override the size of the Gravatar.
@param null|string $rating Override the default rating if you want to.
@return string The URL of the Gravatar. |
public function image($email, $alt = null, $attributes = [], $rating = null)
{
$dimensions = [];
if (array_key_exists('width', $attributes)) {
$dimensions[] = $attributes['width'];
}
if (array_key_exists('height', $attributes)) {
$dimensions[] = $attributes['height'];
}
if (count($dimensions) > 0) {
$size = min(self::MAX_SIZE, max($dimensions));
} else {
$size = $this->defaultSize;
}
$src = $this->src($email, $size, $rating);
if (!array_key_exists('width', $attributes) && !array_key_exists('height', $attributes)) {
$attributes['width'] = $this->size;
$attributes['height'] = $this->size;
}
return $this->formatImage($src, $alt, $attributes);
} | Return the code of HTML image for a Gravatar.
@param string $email The email address.
@param string $alt The alt attribute for the image.
@param array $attributes Override the 'height' and the 'width' of the image if you want.
@param null|string $rating Override the default rating if you want to.
@return string The code of the HTML image. |
public function exists($email)
{
$this->setDefaultImage('404');
$url = $this->buildGravatarURL($email);
$headers = get_headers($url, 1);
return substr($headers[0], 9, 3) == '200';
} | Check if a Gravatar image exists.
@param string $email The email address.
@return bool True if the Gravatar exists, false otherwise. |
public function getClass($className)
{
$collect = $this->models->filter(
function ($element) use ($className) {
return $element instanceof ClassModel
&& $element->getName() === $className;
}
);
if (count($collect) === 0) {
throw new \Exception(
sprintf('Class "%s" not found.', $className)
);
}
return $collect->first();
} | {@inheritdoc} |
public function getNamespace($namespaceName)
{
$collect = $this->models->filter(
function ($element) use ($namespaceName) {
$accept = ($element->getNamespaceName() === $namespaceName)
&& ($element instanceof ClassModel);
return $accept;
}
);
if (count($collect) === 0) {
throw new \Exception(
sprintf('Namespace "%s" not found.', $namespaceName)
);
}
return $collect;
} | {@inheritdoc} |
public function getNamespace($namespaceName)
{
$classes = $this->broker->getNamespace($namespaceName)->getClasses();
return array_values($classes);
} | {@inheritdoc} |
protected function renderObjects()
{
$clusterString = '';
foreach ($this->objects as $ns => $objects) {
$undeclared = false;
if (!empty($ns)) {
$clusterString .= $this->formatLine('namespace ' . str_replace('\\', '.', $ns) . ' %fillcolor% {');
}
foreach ($objects as $shortName => $values) {
$clusterString .= $values['pre'];
if ($values['undeclared']) {
$undeclared = true;
}
}
if (!empty($ns)) {
if ($undeclared) {
// set background-color of undeclared namespace elements
$clusterString = str_replace('%fillcolor%', '#EB937F', $clusterString);
} else {
$clusterString = str_replace('%fillcolor%', '', $clusterString);
}
$clusterString .= $this->formatLine('}');
}
}
return $clusterString;
} | Prints all objects (class, interface, trait)
@return string |
protected function pushObject(
$ns,
$shortName,
$longName,
$type,
$stereotype = '',
$undeclared = true,
$constants = array(),
$properties = array(),
$methods = array()
) {
if (empty($stereotype)) {
$stereotype = sprintf('<< %s >>', $type);
}
$indent = 1;
$objectString = $this->formatLine(
sprintf(
'%s %s %s {',
$type,
$shortName,
$stereotype
),
$indent
);
$indent++;
// prints class constants
$objectString .= $this->writeConstantElements($constants, '%s%s', $indent);
if (count($constants) && count($properties)) {
// print separator between constants and properties
$objectString .= $this->formatLine('..', $indent);
}
// prints class properties
$objectString .= $this->writePropertyElements($properties, '%s%s', $indent);
if (count($methods)
&& (count($properties) || count($constants))
) {
// print separator between properties and methods or constants and methods
$objectString .= $this->formatLine('--', $indent);
}
// prints class methods
$objectString .= $this->writeMethodElements($methods, '%s%s()', $indent);
$objectString .= $this->formatLine('}', --$indent);
$this->objects[$ns][$shortName] = array(
'undeclared' => $undeclared,
'pre' => $objectString
);
} | {@inheritdoc} |
protected function getDefaultInputDefinition()
{
$definition = parent::getDefaultInputDefinition();
if (\Phar::running()) {
$definition->addOption(
new InputOption(
'--manifest',
null,
InputOption::VALUE_NONE,
'Show which versions of dependencies are bundled.'
)
);
}
return $definition;
} | {@inheritDoc} |
protected function getDefaultCommands()
{
$defaultCommands = parent::getDefaultCommands();
$defaultCommands[] = new DiagramRender();
$defaultCommands[] = new DiagramRenderClass();
$defaultCommands[] = new DiagramRenderNamespace();
return $defaultCommands;
} | {@inheritDoc} |
public function renderClass($className)
{
$this->reset();
$this->writeObjectElement(
$this->reflector->getClass($className)
);
return $this->render();
} | {@inheritdoc} |
public function renderNamespace($namespaceName)
{
$this->reset();
foreach ($this->reflector->getNamespace($namespaceName) as $object) {
$this->writeObjectElement($object);
}
return $this->render();
} | {@inheritdoc} |
public function render()
{
// starts main graph
$graph = $this->writeGraphHeader();
// one or more namespace/object
if (empty($this->objects)) {
$namespaces = array();
foreach ($this->reflector->getClasses() as $class) {
$ns = $class->getNamespaceName();
if (in_array($ns, $namespaces)) {
continue;
}
$namespaces[] = $ns;
// proceed objects of a same namespace
foreach ($this->reflector->getNamespace($ns) as $object) {
$this->writeObjectElement($object);
}
}
}
// prints all namespaces with objects
$graph .= $this->renderObjects();
// prints all edges
$graph .= $this->renderEdges();
// ends main graph
$graph .= $this->writeGraphFooter();
return $graph;
} | {@inheritdoc} |
protected function renderEdges($indent)
{
$edgeString = '';
foreach (array_unique($this->edges) as $edge) {
$edgeString .= $this->formatLine($edge, $indent);
}
return $edgeString;
} | Renders all edges (extends, implements) connecting objects
@param int $indent Indent multiplier (greater or equal to zero)
@return string |
protected function formatLine($string, $indent = 0)
{
return str_repeat($this->spaces, $indent) . $string . $this->linebreak;
} | Formats a line |
protected function writeObjectElement($object)
{
$stereotype = '';
if ($object->isTrait()) {
$type = 'class';
$stereotype = '<< (T,#FF7700) trait >>';
} elseif ($object->isInterface()) {
$type = 'interface';
} elseif ($object->isAbstract()) {
$type = 'abstract';
} else {
$type = 'class';
}
$this->pushObject(
$object->getNamespaceName(),
$object->getShortName(),
$object->getName(),
$type,
$stereotype,
false,
$object->getConstants(),
$object->getProperties(),
$object->getMethods()
);
// prints inheritance (if exists)
$parentName = $object->getParentClassName();
if ($parentName) {
$this->writeObjectInheritance($object, $parentName);
}
// prints interfaces (if exists)
$interfaces = $object->getInterfaceNames();
if (count($interfaces)) {
$this->writeObjectInterfaces($object, $interfaces);
}
} | Prints class/interface/trait
@param ReflectionClass $object class/interface/trait instance |
protected function writeObjectInheritance($object, $parentName)
{
try {
$parent = $this->reflector->getClass($parentName);
$longName = $parent->getName();
$this->writeObjectElement($parent);
} catch (\Exception $e) {
// object is undeclared in data source
$parts = explode('\\', $parentName);
$shortName = array_pop($parts);
$longName = $parentName;
$ns = implode($this->namespaceSeparator, $parts);
if (!isset($this->objects[$ns])) {
$this->objects[$ns] = array();
}
if (!array_key_exists($shortName, $this->objects[$ns])) {
$type = $object->isInterface() ? 'interface' : 'class';
$this->pushObject($ns, $shortName, $longName, $type);
}
}
$this->pushEdge(array($object->getName(), $longName));
} | Prints an object inheritance
@param ReflectionClass $object class/interface instance
@param string $parentName Fully qualified name of the parent
@return void |
protected function writeObjectInterfaces($object, $interfaces)
{
foreach ($interfaces as $interfaceName) {
try {
$interface = $this->reflector->getClass($interfaceName);
$longName = $interface->getName();
$this->writeObjectElement($interface);
} catch (\Exception $e) {
// interface is undeclared in data source
$parts = explode('\\', $interfaceName);
$shortName = array_pop($parts);
$longName = $interfaceName;
$ns = implode($this->namespaceSeparator, $parts);
if (!isset($this->objects[$ns])) {
$this->objects[$ns] = array();
}
if (!array_key_exists($shortName, $this->objects[$ns])) {
$this->pushObject($ns, $shortName, $longName, 'interface');
}
}
$this->pushEdge(
array($object->getName(), $longName),
array('arrowhead' => 'empty', 'style' => 'dashed')
);
}
} | Prints interfaces that implement an object
@param ReflectionClass $object class/interface instance
@param array $interfaces Names of each interface implemented
@return void |
protected function writeConstantElements($constants, $format = '%s %s\l', $indent = -1)
{
$constantString = '';
foreach ($constants as $name => $value) {
$line = sprintf($format, '+', $name);
if ($indent >= 0) {
$constantString .= $this->formatLine($line, $indent);
} else {
$constantString .= $line;
}
}
return $constantString;
} | Prints class constants
@param ReflectionConstant[] $constants List of constant instance
@param string $format (optional) Constant formatter
@param int $indent (optional) Indent multiplier
@return string |
protected function writePropertyElements($properties, $format = '%s %s\l', $indent = -1)
{
$propertyString = '';
foreach ($properties as $property) {
if ($property->isPrivate()) {
$visibility = '-';
} elseif ($property->isProtected()) {
$visibility = '#';
} else {
$visibility = '+';
}
$line = sprintf(
$format,
$visibility,
$property->getName()
);
if ($indent >= 0) {
$propertyString .= $this->formatLine($line, $indent);
} else {
$propertyString .= $line;
}
}
return $propertyString;
} | Prints class properties
@param ReflectionProperty[] $properties List of property instance
@param string $format (optional) Property formatter
@param int $indent (optional) Indent multiplier
@return string |
protected function writeMethodElements($methods, $format = '%s %s()\l', $indent = -1)
{
$methodString = '';
foreach ($methods as $method) {
if ($method->isPrivate()) {
$visibility = '-';
} elseif ($method->isProtected()) {
$visibility = '#';
} else {
$visibility = '+';
}
if ($method->isStatic()) {
$modifier = '<u>%s</u>';
} elseif ($method->isAbstract()) {
$modifier = '<i>%s</i>';
} else {
$modifier = '%s';
}
$line = sprintf(
$format,
$visibility,
sprintf($modifier, $method->getShortName())
);
if ($indent >= 0) {
$methodString .= $this->formatLine($line, $indent);
} else {
$methodString .= $line;
}
}
return $methodString;
} | Prints class methods
@param ReflectionMethod[] $methods List of method instance
@param string $format (optional) Method formatter
@param int $indent (optional) Indent multiplier
@return string |
protected function renderObjects()
{
static $cluster = 0;
$clusterString = '';
$indent = 1;
foreach ($this->objects as $ns => $objects) {
$undeclared = false;
$clusterString .= $this->formatLine('subgraph cluster_' . $cluster . ' {', $indent);
$cluster++;
$indent++;
$clusterString .= $this->formatLine('label="' . str_replace('\\', '\\\\', $ns) . '";', $indent);
foreach ($objects as $shortName => $values) {
$clusterString .= $this->formatLine($values['pre'], $indent);
if ($values['undeclared']) {
$undeclared = true;
}
}
if ($undeclared) {
// set background-color of undeclared namespace elements
$clusterString .= $this->formatLine('bgcolor="#EB937F";', $indent);
}
$indent--;
$clusterString .= $this->formatLine('}', $indent);
}
return $clusterString;
} | Prints all objects (class, interface, trait)
@return string |
protected function writeGraphHeader()
{
$nodeAttributes = array(
'fontname' => "Verdana",
'fontsize' => 8,
'shape' => "none",
'margin' => 0,
'fillcolor' => '#FEFECE',
'style' => 'filled',
);
$edgeAttributes = array(
'fontname' => "Verdana",
'fontsize' => 8,
);
$indent = 1;
$graph = $this->formatLine('digraph ' . $this->graphId . ' {');
$graph .= $this->formatLine('overlap = false;', $indent);
$graph .= $this->formatLine('node [' . $this->attributes($nodeAttributes) . '];', $indent);
$graph .= $this->formatLine('edge [' . $this->attributes($edgeAttributes) . '];', $indent);
return $graph;
} | Prints header of the main graph
@return string |
protected function pushObject(
$ns,
$shortName,
$longName,
$type,
$stereotype = '',
$undeclared = true,
$constants = array(),
$properties = array(),
$methods = array()
) {
$attributes = '';
$attributes .= $this->writeConstantElements(
$constants,
'<tr><td align="left">%s %s</td></tr>',
0
);
$attributes .= $this->writePropertyElements(
$properties,
'<tr><td align="left">%s %s</td></tr>',
0
);
if (empty($attributes)) {
$attributes = ' ';
} else {
$attributes = sprintf(
"<table border=\"0\" cellspacing=\"0\" cellpadding=\"2\">\n%s</table>",
$attributes
);
}
if (empty($methods) || $undeclared) {
$operations = ' ';
} else {
$operations = sprintf(
"<table border=\"0\" cellspacing=\"0\" cellpadding=\"2\">\n%s</table>",
$this->writeMethodElements(
$methods,
'<tr><td align="left">%s%s()</td></tr>',
0
)
);
}
$label = sprintf(
'
<table border="0" cellborder="1" cellspacing="0">
<tr><td align="center">%s<br/><b>%s</b></td></tr>
<tr><td>%s</td></tr>
<tr><td>%s</td></tr>
</table>
',
$this->formatClassStereotype($type),
$shortName,
$attributes,
$operations
);
$this->objects[$ns][$shortName] = array(
'undeclared' => $undeclared,
'pre' => '"' . str_replace('\\', '\\\\', $longName) . '"' .
' [label=<' . $label . '>];'
);
} | {@inheritdoc} |
protected function pushEdge(array $list, array $attributes = array())
{
$escape = function ($value) {
return '"' . str_replace('\\', '\\\\', $value). '"';
};
$list = array_map($escape, $list);
$edge = implode(' -> ', $list);
$this->edges[] = $edge .
($attributes ? ' [' . $this->attributes($attributes) . ']' : '') .
";"
;
} | {@inheritdoc} |
public function handle(): void
{
$name = $this->getNameInput();
$path = app_path($name);
// First we will check to see if the class already exists. If it does, we don't want
// to create the class and overwrite the user's code. So, we will bail out so the
// code is untouched. Otherwise, we will continue generating this class' files.
if ($this->files->exists($path)) {
$this->error($this->type.' already exists!');
return;
}
// Next, we will generate the path to the location where this class' file should get
// written. Then, we will build the class and make the proper replacements on the
// stub files so that it gets the correctly formatted namespace and class name.
$stubs = __DIR__.'/../../../resources/stubs/module';
$this->processStubs($stubs, $path);
$this->generateSamples();
$this->info($this->type.' created successfully.');
} | Execute the console command.
@return void |
protected function makeDirectory($path): string
{
if (! $this->files->isDirectory($path)) {
$this->files->makeDirectory($path, 0777, true, true);
}
return $path;
} | Build the directory for the class if necessary.
@param string $path
@return string |
protected function generateSamples(): void
{
$module = str_after($this->getNameInput(), '/');
$this->call('make:config', ['name' => 'config', '--module' => $this->getNameInput()]);
$this->call('make:model', ['name' => 'Example', '--module' => $this->getNameInput()]);
$this->call('make:policy', ['name' => 'ExamplePolicy', '--module' => $this->getNameInput()]);
$this->call('make:provider', ['name' => ucfirst($module).'ServiceProvider', '--module' => $this->getNameInput()]);
$this->call('make:command', ['name' => 'ExampleCommand', '--module' => $this->getNameInput()]);
$this->call('make:controller', ['name' => 'ExampleController', '--module' => $this->getNameInput()]);
$this->call('make:request', ['name' => 'ExampleRequest', '--module' => $this->getNameInput()]);
$this->call('make:middleware', ['name' => 'ExampleMiddleware', '--module' => $this->getNameInput()]);
$this->call('make:transformer', ['name' => 'ExampleTransformer', '--model' => 'Example', '--module' => $this->getNameInput()]);
$this->call('make:datatable', ['name' => 'ExampleDatatable', '--model' => 'Example', '--transformer' => 'ExampleTransformer', '--module' => $this->getNameInput()]);
$this->warn('Optionally create migrations and seeds (it may take some time):');
$this->warn("artisan make:migration create_{$module}_example_table --module {$this->getNameInput()}");
$this->warn("artisan make:seeder ExampleSeeder --module {$this->getNameInput()}");
} | Generate code samples.
@return void |
protected function processStubs($stubs, $path): void
{
$this->makeDirectory($path);
$this->files->copyDirectory($stubs, $path);
$files = [
($phpunit = $path.DIRECTORY_SEPARATOR.'phpunit.xml.dist') => $this->files->get($phpunit),
($composer = $path.DIRECTORY_SEPARATOR.'composer.json') => $this->files->get($composer),
($changelog = $path.DIRECTORY_SEPARATOR.'CHANGELOG.md') => $this->files->get($changelog),
($readme = $path.DIRECTORY_SEPARATOR.'README.md') => $this->files->get($readme),
];
$module = ucfirst(str_after($this->getNameInput(), '/'));
$name = implode(' ', array_map('ucfirst', explode('/', $this->getNameInput())));
$jsonNamespace = implode('\\\\', array_map('ucfirst', explode('/', $this->getNameInput())));
foreach ($files as $key => &$file) {
$file = str_replace('DummyModuleName', $name, $file);
$file = str_replace('Dummy\\\\Module', $jsonNamespace, $file);
$file = str_replace('DummyModuleServiceProvider', $jsonNamespace."\\\\Providers\\\\{$module}ServiceProvider", $file);
$file = str_replace('dummy/module', $this->getNameInput(), $file);
$file = str_replace('dummy-module', str_replace('/', '-', $this->getNameInput()), $file);
$file = str_replace('dummy:module', str_replace('/', ':', $this->getNameInput()), $file);
$file = str_replace('dummy.module', str_replace('/', '.', $this->getNameInput()), $file);
$this->files->put($key, $file);
}
} | Process stubs placeholders.
@param string $stubs
@param string $path
@return void |
protected function getNameInput(): string
{
$name = trim($this->argument('name'));
if (mb_strpos($name, '/') === false) {
throw new \Exception('Module name must consist of two segments: vendor/module');
}
return $name;
} | Get the desired class name from the input.
@throws \Exception
@return string |
public function route($route, $parameters = [], $status = 302, $headers = [])
{
return ($previousUrl = $this->generator->getRequest()->get('previous_url'))
? $this->to($previousUrl) : parent::route($route, $parameters, $status, $headers);
} | {@inheritdoc} |
protected function getMessages(): array
{
$messages = [];
foreach (array_merge(array_values(app('translation.loader')->namespaces()), [$this->sourcePath]) as $directory) {
foreach ($this->file->allFiles($directory) as $file) {
$path = mb_substr($file->getPath(), 0, mb_strrpos($file->getPath(), DIRECTORY_SEPARATOR));
$namespace = array_search($path, app('translation.loader')->namespaces());
$pathName = $file->getRelativePathName();
$extension = $file->getExtension();
if (! in_array($extension, ['json', 'php'])) {
continue;
}
if ($this->isMessagesExcluded($pathName)) {
continue;
}
$key = mb_substr($pathName, 0, -4);
$key = str_replace('\\', '.', $key);
$key = str_replace('/', '.', $key);
if ($namespace) {
$key = mb_substr($key, 0, mb_strpos($key, '.') + 1).str_replace('/', '.', $namespace).'::'.mb_substr($key, mb_strpos($key, '.') + 1);
}
if (starts_with($key, 'vendor')) {
$key = $this->getVendorKey($key);
}
if ($extension === 'php') {
$messages[$key] = include $file->getRealPath();
} else {
$key = $key.$this->stringsDomain;
$fileContent = file_get_contents($file->getRealPath());
$messages[$key] = json_decode($fileContent, true);
}
}
}
$this->sortMessages($messages);
return $messages;
} | Return all language messages.
@throws \Exception
@return array |
protected function rootNamespace(): string
{
return $this->rootNamespace ?? $this->rootNamespace = implode('\\', array_map('ucfirst', explode('/', trim($this->moduleName()))));
} | Get the root namespace for the class.
@return string |
protected function moduleName(): string
{
return $this->moduleName ?? $this->input->getOption('module') ?? $this->moduleName = $this->ask('What is your module?');
} | Get the module name for the class.
@return string |
public static function createContent(SchemaInterface $schema, AbstractTable $table): self
{
$context = new self();
$context->class = $schema->getClass();
$context->database = $schema->getDatabase();
$context->table = $schema->getTable();
$context->role = $schema->getRole();
$context->schema = $table;
return $context;
} | @param SchemaInterface $schema
@param AbstractTable $table
@return RelationContext
@throws SchemaException |
public function getColumn(string $name): AbstractColumn
{
if (!$this->schema->hasColumn($name)) {
throw new DefinitionException("Undefined column {$name} in {$this->schema->getName()}");
}
return clone $this->schema->column($name);
} | @param string $name
@return AbstractColumn |
public function up(): void
{
Schema::create(config('cortex.foundation.tables.temporary_uploads'), function (Blueprint $table) {
$table->string('id');
$table->string('session_id')->nullable();
$table->timestamps();
});
} | Run the migrations.
@return void |
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$serviceHandler = $request->getAttribute(RouterMiddleware::ATTRIBUTE);
/* @var \Swoft\Rpc\Server\Router\HandlerAdapter $handlerAdapter */
$handlerAdapter = App::getBean('serviceHandlerAdapter');
$response = $handlerAdapter->doHandler($request, $serviceHandler);
return $response;
} | execute service with handler
@param \Psr\Http\Message\ServerRequestInterface $request
@param \Psr\Http\Server\RequestHandlerInterface $handler
@return \Psr\Http\Message\ResponseInterface |
public function create($fields = [], string $class = null): EntityInterface
{
//Create model with filtered set of fields
return $this->orm->make($class ?? $this->class, $fields, ORMInterface::STATE_NEW);
} | Create new DocumentEntity based on set of provided fields.
@final Change static method of entity, not this one.
@param array $fields
@param string $class Due ODM models can be inherited you can use this argument to specify
custom model class.
@return EntityInterface|Record |
public function findByPK($id, array $load = [])
{
return $this->getSelector()->wherePK($id)->load($load)->findOne();
} | Find document by it's primary key.
@see findOne()
@param string|int $id Primary key value.
@param array $load Relations to pre-load.
@return EntityInterface|Record|null |
public function findOne(array $query = [], array $sortBy = [], array $load = [])
{
return $this->getSelector()->orderBy($sortBy)->load($load)->findOne($query);
} | Select one document from mongo collection.
@param array $query Fields and conditions to query by.
@param array $sortBy Always specify sort by to ensure that results are stable.
@param array $load Relations to pre-load.
@return EntityInterface|Record|null |
public function count(array $query = [], string $column = null): int
{
return $this->getSelector()->where($query)->count();
} | @param array $query
@param string $column Column to count by, PK or * by default.
@return int |
public function withSelector(RecordSelector $selector): RecordSource
{
$source = clone $this;
$source->setSelector($selector);
return $source;
} | Create source with new associated selector.
@param RecordSelector $selector
@return RecordSource |
protected function getSelector(): RecordSelector
{
if (empty($this->selector)) {
//Requesting selector on demand
$this->selector = $this->orm->selector($this->class);
}
return clone $this->selector;
} | Get associated selector.
@return RecordSelector |
public function declareTables(SchemaBuilder $builder): array
{
$sourceTable = $this->sourceTable($builder);
$targetTable = $this->targetTable($builder);
if (!$targetTable->hasColumn($this->option(Record::OUTER_KEY))) {
throw new RelationSchemaException(sprintf("Outer key '%s'.'%s' (%s) does not exists",
$targetTable->getName(),
$this->option(Record::OUTER_KEY),
$this->definition->getName()
));
}
//Column to be used as outer key
$outerKey = $targetTable->column($this->option(Record::OUTER_KEY));
//Column to be used as inner key
$innerKey = $sourceTable->column($this->option(Record::INNER_KEY));
//Syncing types
$innerKey->setType($this->resolveType($outerKey));
//If nullable
$innerKey->nullable($this->option(Record::NULLABLE));
//Do we need indexes?
if ($this->option(Record::CREATE_INDEXES)) {
//Always belongs to one parent
$sourceTable->index([$innerKey->getName()]);
}
if ($this->isConstrained()) {
$this->createForeign(
$sourceTable,
$innerKey,
$outerKey,
$this->option(Record::CONSTRAINT_ACTION),
$this->option(Record::CONSTRAINT_ACTION)
);
}
return [$sourceTable];
} | {@inheritdoc} |
public function getRole(): string
{
$role = $this->reflection->getProperty('model_role');
//When role not defined we are going to use short class name
return $role ?? lcfirst(Inflector::tableize($this->reflection->getShortName()));
} | {@inheritdoc} |
public function getTable(): string
{
$table = $this->reflection->getProperty('table');
if (empty($table)) {
//Generate table using short class name
$table = Inflector::tableize($this->reflection->getShortName());
$table = Inflector::pluralize($table);
}
return $table;
} | {@inheritdoc} |