code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
public function update(AccountSettingsRequest $request)
{
$data = $request->validated();
$currentUser = $request->user($this->getGuard());
! $request->hasFile('profile_picture')
|| $currentUser->addMediaFromRequest('profile_picture')
->sanitizingFileName(function ($fileName) {
return md5($fileName).'.'.pathinfo($fileName, PATHINFO_EXTENSION);
})
->toMediaCollection('profile_picture', config('cortex.auth.media.disk'));
! $request->hasFile('cover_photo')
|| $currentUser->addMediaFromRequest('cover_photo')
->sanitizingFileName(function ($fileName) {
return md5($fileName).'.'.pathinfo($fileName, PATHINFO_EXTENSION);
})
->toMediaCollection('cover_photo', config('cortex.auth.media.disk'));
// Update profile
$currentUser->fill($data)->save();
return intend([
'back' => true,
'with' => ['success' => trans('cortex/auth::messages.account.updated_account')]
+ (isset($data['two_factor']) ? ['warning' => trans('cortex/auth::messages.verification.twofactor.phone.auto_disabled')] : []),
]);
} | Update account settings.
@param \Cortex\Auth\Http\Requests\Adminarea\AccountSettingsRequest $request
@return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse |
public function update(AccountAttributesRequest $request)
{
$data = $request->validated();
$currentUser = $request->user($this->getGuard());
// Update profile
$currentUser->fill($data)->save();
return intend([
'back' => true,
'with' => ['success' => trans('cortex/auth::messages.account.updated_attributes')],
]);
} | Update account attributes.
@param \Cortex\Auth\Http\Requests\Adminarea\AccountAttributesRequest $request
@return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse |
protected function doAuthenticate($username, $password)
{
$hashedPassword = $this->getHashedPassword($username);
if ($hashedPassword === false)
{
$this->status = Authentication::NO_SUCH_USER;
return false;
}
if (!$this->verifyPassword($username, $password, $hashedPassword))
{
$this->status = Authentication::INVALID_CREDENTIALS;
return false;
}
$this->status = Authentication::SUCCESS;
return $username;
} | Attempt to authenticate the username and password pair.
@param string $username The username to authenticate.
@param string $password The password to attempt authentication with.
@return string|boolean A string containing a username if authentication is successful, false otherwise.
@since 1.1.0 |
protected function prepareForValidation(): void
{
$data = $this->all();
// Set abilities
if (! empty($data['abilities'])) {
if ($this->user($this->route('guard'))->can('grant', \Cortex\Auth\Models\Ability::class)) {
$abilities = array_map('intval', $this->get('abilities', []));
$data['abilities'] = $this->user($this->route('guard'))->isA('superadmin') ? $abilities
: $this->user($this->route('guard'))->getAbilities()->pluck('id')->intersect($abilities)->toArray();
} else {
unset($data['abilities']);
}
}
$this->replace($data);
} | Prepare the data for validation.
@return void |
public function rules(): array
{
$user = $this->route('role') ?? new Role();
$user->updateRulesUniques();
$rules = $user->getRules();
$rules['abilities'] = 'nullable|array';
return $rules;
} | Get the validation rules that apply to the request.
@return array |
private function getAlignedArray(array $array, $depth, array $options, callable $encode)
{
$next = 0;
$omit = $options['array.omit'];
foreach (array_keys($array) as $key) {
if ($key !== $next++) {
$omit = false;
break;
}
}
return $omit
? $this->getFormattedArray($array, $depth, $options, $encode)
: $this->buildArray($this->getAlignedPairs($array, $encode), $depth, $options);
} | Returns the PHP code for aligned array accounting for omitted keys and inline arrays.
@param array $array Array to encode
@param int $depth Current indentation depth of the output
@param array $options List of encoder options
@param callable $encode Callback used to encode values
@return string The PHP code representation for the array |
private function getFormattedArray(array $array, $depth, array $options, callable $encode)
{
$lines = $this->getPairs($array, ' ', $options['array.omit'], $encode, $omitted);
if ($omitted && $options['array.inline'] !== false) {
$output = $this->getInlineArray($lines, $options);
if ($output !== false) {
return $output;
}
}
return $this->buildArray($lines, $depth, $options);
} | Returns the PHP code for the array as inline or multi line array.
@param array $array Array to encode
@param int $depth Current indentation depth of the output
@param array $options List of encoder options
@param callable $encode Callback used to encode values
@return string The PHP code representation for the array |
private function getInlineArray(array $lines, array $options)
{
$output = $this->wrap(implode(', ', $lines), $options['array.short']);
if (preg_match('/[\r\n\t]/', $output)) {
return false;
} elseif ($options['array.inline'] === true || \strlen($output) <= (int) $options['array.inline']) {
return $output;
}
return false;
} | Returns the code for the inline array, if possible.
@param string[] $lines Encoded key and value pairs
@param array $options List of encoder options
@return string|false Array encoded as single line of PHP code or false if not possible |
private function buildArray(array $lines, $depth, array $options)
{
$indent = $this->buildIndent($options['array.base'], $options['array.indent'], $depth + 1);
$last = $this->buildIndent($options['array.base'], $options['array.indent'], $depth);
$eol = $options['array.eol'] === false ? \PHP_EOL : (string) $options['array.eol'];
return $this->wrap(
sprintf('%s%s%s,%1$s%s', $eol, $indent, implode(',' . $eol . $indent, $lines), $last),
$options['array.short']
);
} | Builds the complete array from the encoded key and value pairs.
@param string[] $lines Encoded key and value pairs
@param int $depth Current indentation depth of the output
@param array $options List of encoder options
@return string Array encoded as PHP code |
private function buildIndent($base, $indent, $depth)
{
$base = \is_int($base) ? str_repeat(' ', $base) : (string) $base;
return $depth === 0 ? $base : $base . str_repeat(
\is_int($indent) ? str_repeat(' ', $indent) : (string) $indent,
$depth
);
} | Builds the indentation based on the options.
@param string|int $base The base indentation
@param string|int $indent A single indentation level
@param int $depth The level of indentation
@return string The indentation for the current depth |
private function getAlignedPairs(array $array, callable $encode)
{
$keys = [];
$values = [];
foreach ($array as $key => $value) {
$keys[] = $encode($key, 1);
$values[] = $encode($value, 1);
}
$format = sprintf('%%-%ds => %%s', max(array_map('strlen', $keys)));
$pairs = [];
for ($i = 0, $count = \count($keys); $i < $count; $i++) {
$pairs[] = sprintf($format, $keys[$i], $values[$i]);
}
return $pairs;
} | Returns each encoded key and value pair with aligned assignment operators.
@param array $array Array to convert into code
@param callable $encode Callback used to encode values
@return string[] Each of key and value pair encoded as php |
private function getPairs(array $array, $space, $omit, callable $encode, & $omitted = true)
{
$pairs = [];
$nextIndex = 0;
$omitted = true;
$format = '%s' . $space . '=>' . $space . '%s';
foreach ($array as $key => $value) {
if ($omit && $this->canOmitKey($key, $nextIndex)) {
$pairs[] = $encode($value, 1);
} else {
$pairs[] = sprintf($format, $encode($key, 1), $encode($value, 1));
$omitted = false;
}
}
return $pairs;
} | Returns each key and value pair encoded as array assignment.
@param array $array Array to convert into code
@param string $space Whitespace between array assignment operator
@param bool $omit True to omit unnecessary keys, false to not
@param callable $encode Callback used to encode values
@param bool $omitted Set to true, if all the keys were omitted, false otherwise
@return string[] Each of key and value pair encoded as php |
private function canOmitKey($key, & $nextIndex)
{
$result = $key === $nextIndex;
if (\is_int($key)) {
$nextIndex = max($key + 1, $nextIndex);
}
return $result;
} | Tells if the key can be omitted from array output based on expected index.
@param int|string $key Current array key
@param int $nextIndex Next expected key that can be omitted
@return bool True if the key can be omitted, false if not |
protected function prepareForValidation(): void
{
$data = $this->all();
$guardian = $this->route('guardian') ?? app('cortex.auth.guardian');
if ($guardian->exists && empty($data['password'])) {
unset($data['password'], $data['password_confirmation']);
}
$this->replace($data);
} | Prepare the data for validation.
@return void |
public function rules(): array
{
$guardian = $this->route('guardian') ?? app('cortex.auth.guardian');
$guardian->updateRulesUniques();
$rules = $guardian->getRules();
$rules['password'] = $guardian->exists
? 'confirmed|min:'.config('cortex.auth.password_min_chars')
: 'required|confirmed|min:'.config('cortex.auth.password_min_chars');
return $rules;
} | Get the validation rules that apply to the request.
@return array |
public function import(Ability $ability, ImportRecordsDataTable $importRecordsDataTable)
{
return $importRecordsDataTable->with([
'resource' => $ability,
'tabs' => 'adminarea.abilities.tabs',
'url' => route('adminarea.abilities.stash'),
'id' => "adminarea-abilities-{$ability->getRouteKey()}-import-table",
])->render('cortex/foundation::adminarea.pages.datatable-dropzone');
} | Import abilities.
@param \Cortex\Auth\Models\Ability $ability
@param \Cortex\Foundation\DataTables\ImportRecordsDataTable $importRecordsDataTable
@return \Illuminate\View\View |
protected function form(Request $request, Ability $ability)
{
$roles = $request->user($this->getGuard())->getManagedRoles();
$entityTypes = app('cortex.auth.ability')->distinct()->get(['entity_type'])->pluck('entity_type', 'entity_type')->toArray();
return view('cortex/auth::adminarea.pages.ability', compact('ability', 'roles', 'entityTypes'));
} | Show ability create/edit form.
@param \Illuminate\Http\Request $request
@param \Cortex\Auth\Models\Ability $ability
@return \Illuminate\View\View |
protected function process(FormRequest $request, Ability $ability)
{
// Prepare required input fields
$data = $request->validated();
// Save ability
$ability->fill($data)->save();
return intend([
'url' => route('adminarea.abilities.index'),
'with' => ['success' => trans('cortex/foundation::messages.resource_saved', ['resource' => trans('cortex/auth::common.ability'), 'identifier' => $ability->title])],
]);
} | Process stored/updated ability.
@param \Illuminate\Foundation\Http\FormRequest $request
@param \Cortex\Auth\Models\Ability $ability
@return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse |
public function destroy(Ability $ability)
{
$ability->delete();
return intend([
'url' => route('adminarea.abilities.index'),
'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/auth::common.ability'), 'identifier' => $ability->title])],
]);
} | Destroy given ability.
@param \Cortex\Auth\Models\Ability $ability
@throws \Exception
@return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse |
public function build($overrides = array(), $associated = array()) {
$data = $this->_defaults;
if($associated) {
foreach($associated as $name => $document) {
if(!isset($this->_associations[$name])) {
throw new \Exception("No association '$name' defined");
}
$association = $this->_associations[$name];
if(!$association instanceof Association\EmbedsMany &&
!$association instanceof Association\EmbedsOne) {
throw new \Exception("Invalid association object for '$name'");
}
$overrides[$name] = $document;
}
}
$this->_evalSequence($data);
if($overrides) {
foreach($overrides as $field => $value) {
$data[$field] = $value;
}
}
return $data;
} | /*
Build the document as an array, but don't save it to the db.
@param array $overrides field => value pairs which override the defaults for this blueprint
@param array $associated [name] => [Association] pairs
@return array the document |
public function create($overrides = array(), $associated = array()) {
$data = $this->build($overrides, $associated);
$this->_collection->insert($data,array("w"=>1));
return $data;
} | /*
Create document in the database and return it.
@param array $overrides field => value pairs which override the defaults for this blueprint
@param array $associated [name] => [Association] pairs
@return array the created document |
public function buildWithAssociations($blueprint_name, $associations = array(), $overrides = array()) {
if(! ($blueprint = $this->_blueprints[$blueprint_name]) ) {
throw new \Exception("No blueprint defined for '$blueprint_name'");
}
foreach($associations as $association) {
if($association instanceof Association\ManyToMany) {
throw new \Exception("ManyToMany associations cannot be used in Phactory::build()");
}
}
return $blueprint->build($overrides, $associations);
} | /*
Build a Row object, optionally
overriding some or all of the default values.
The row is not saved to the database.
@param string $blueprint_name name of the blueprint to use
@param array $associations [table name] => [Row]
@param array $overrides key => value pairs of column => value
@return object Row |
public function get($table_name, $byColumns) {
$all = $this->getAll($table_name, $byColumns);
return array_shift($all);
} | /*
Get a row from the database as a Row.
$byColumn is like array('id' => 123).
@param string $table_name name of the table
@param array $byColumn
@return object Row |
public function manyToOne($to_table, $from_column = null, $to_column = null) {
$to_table = new Table($to_table, true, $this);
return new Association\ManyToOne($to_table, $from_column, $to_column);
} | /*
Create a many-to-one association object for use in define().
@param string $to_table the table to associate with
@param string $from_column the fk column on the left table
@param string $to_column the pk column of the right table, or null to autodetect
@return object Association\ManyToOne |
public function oneToOne($to_table, $from_column, $to_column = null) {
$to_table = new Table($to_table, true, $this);
return new Association\OneToOne($to_table, $from_column, $to_column);
} | /*
Create a one-to-one association object for use in define().
@param string $to_table the table to associate with
@param string $from_column the fk column on the left table
@param string $to_column the pk column of the right table, or null to autodetect
@return object Association\OneToOne |
public function addEncoder(Encoder\Encoder $encoder, $prepend = false)
{
$prepend ? array_unshift($this->encoders, $encoder) : array_push($this->encoders, $encoder);
} | Adds a new encoder.
Values are always encoded by the first encoder that supports encoding
that type of value. By setting the second optional parameter to true,
you can prepend the encoder to the list to ensure that it will be tested
first.
@param Encoder\Encoder $encoder Encoder for encoding values
@param bool $prepend True to prepend the encoder to the list, false to add it as last |
public function setOption($option, $value)
{
if (!$this->isValidOption($option)) {
throw new InvalidOptionException(sprintf("Invalid encoder option '%s'", $option));
}
$this->options[$option] = $value;
} | Sets the value for an encoder option.
@param string $option Name of the option
@param mixed $value Value for the option
@throws InvalidOptionException If the provided encoder option is invalid |
private function isValidOption($option)
{
if (array_key_exists($option, $this->options)) {
return true;
}
foreach ($this->encoders as $encoder) {
if (array_key_exists($option, $encoder->getDefaultOptions())) {
return true;
}
}
return false;
} | Tells if the given string is a valid option name.
@param string $option Option name to validate
@return bool True if the name is a valid option name, false if not |
public function getAllOptions(array $overrides = [])
{
$options = $this->options;
foreach ($this->encoders as $encoder) {
$options += $encoder->getDefaultOptions();
}
foreach ($overrides as $name => $value) {
if (!array_key_exists($name, $options)) {
throw new InvalidOptionException(sprintf("Invalid encoder option '%s'", $name));
}
$options[$name] = $value;
}
ksort($options);
return $options;
} | Returns a list of all encoder options.
@param array $overrides Options to override in the returned array
@return array List of encoder options
@throws InvalidOptionException If any of the encoder option overrides are invalid |
private function generate($value, $depth, array $options, array $recursion = [])
{
if ($this->detectRecursion($value, $options, $recursion)) {
$recursion[] = $value;
}
if ($options['recursion.max'] !== false && $depth > (int) $options['recursion.max']) {
throw new \RuntimeException('Maximum encoding depth reached');
}
$callback = function ($value, $level = 0, array $overrides = []) use ($depth, $options, $recursion) {
return $this->generate($value, $depth + (int) $level, $overrides + $options, $recursion);
};
return $this->encodeValue($value, $depth, $options, $callback);
} | Generates the code for the given value recursively.
@param mixed $value Value to encode
@param int $depth Current indentation depth of the output
@param array $options List of encoder options
@param array $recursion Previously encoded values for recursion detection
@return string The PHP code that represents the given value
@throws \RuntimeException If max depth is reached or a recursive value is detected |
private function detectRecursion(& $value, array $options, array $recursion)
{
if ($options['recursion.detect']) {
if (array_search($value, $recursion, true) !== false) {
if ($options['recursion.ignore']) {
$value = null;
} else {
throw new \RuntimeException('A recursive value was detected');
}
}
return true;
}
return false;
} | Attempts to detect circular references in values.
@param mixed $value Value to try for circular reference
@param array $options List of encoder options
@param array $recursion Upper values in the encoding tree
@return bool True if values should be recorded, false if not
@throws \RuntimeException If a recursive value is detected |
private function encodeValue($value, $depth, array $options, callable $encode)
{
foreach ($this->encoders as $encoder) {
if ($encoder->supports($value)) {
return $encoder->encode($value, $depth, $options, $encode);
}
}
throw new \InvalidArgumentException(sprintf("Unsupported value type '%s'", \gettype($value)));
} | Encodes the value using one of the encoders that supports the value type.
@param mixed $value Value to encode
@param int $depth Current indentation depth of the output
@param array $options List of encoder options
@param callable $encode Callback used to encode values
@return string The PHP code that represents the given value
@throws \InvalidArgumentException If the provided value contains an unsupported value type |
public function rules(): array
{
$user = $this->user($this->route('guard'));
// Attach attribute rules
$user->getEntityAttributes()->each(function ($attribute, $attributeName) use (&$rules) {
switch ($attribute->type) {
case 'datetime':
$type = 'date';
break;
case 'text':
case 'check':
case 'select':
case 'varchar':
$type = 'string';
break;
default:
$type = $attribute->type;
break;
}
$rule = ($attribute->is_required ? 'required|' : 'nullable|').$type;
$rules[$attributeName.($attribute->is_collection ? '.*' : '')] = $rule;
});
return $rules ?? [];
} | Get the validation rules that apply to the request.
@return array |
public function belongsTo($model, $localKey = null)
{
$attrName = $this->getAttributeName($model);
if (empty($localKey)) {
$localKey = $attrName."_id";
}
$instance = new $model();
$modelAttrs = $this->getAttribute($attrName);
if (is_array($modelAttrs)) {
$instance->setAttributes($modelAttrs);
}
$modelId = $this->getAttribute($localKey);
if (!empty($modelId)) {
$instance->setId($modelId);
}
if (!$instance->getId()) {
return null;
}
if($this->parent) {
$instance->setParent($this->parent);
}
return $instance;
} | /*
Relations |
public function post($path=null, $params=null)
{
$response = $this->request('post', $path, $params);
if (is_array($response)) {
$this->setAttributes($response);
}
return $this;
} | /*
REST |
public static function pluralize($word) {
foreach(self::$_exceptions as $exception) {
if($exception['singular'] == $word){
return $exception['plural'];
}
}
return parent::pluralize($word);
} | /*
Pluralize a word, obeying any stored exceptions.
@param string $word the word to pluralize |
private function encodeObject($object, array $options, callable $encode)
{
if ($options['object.format'] === 'string') {
return $encode((string) $object);
} elseif ($options['object.format'] === 'serialize') {
return sprintf('unserialize(%s)', $encode(serialize($object)));
} elseif ($options['object.format'] === 'export') {
return sprintf('\\%s::__set_state(%s)', \get_class($object), $encode($this->getObjectState($object)));
}
return $this->encodeObjectArray($object, $options, $encode);
} | Encodes the object as string according to encoding options.
@param object $object Object to encode as PHP
@param array $options List of encoder options
@param callable $encode Callback used to encode values
@return string The object encoded as string |
private function encodeObjectArray($object, array $options, callable $encode)
{
if (!\in_array((string) $options['object.format'], ['array', 'vars', 'iterate'], true)) {
throw new \RuntimeException('Invalid object encoding format: ' . $options['object.format']);
}
$output = $encode($this->getObjectArray($object, $options['object.format']));
if ($options['object.cast']) {
$output = '(object)' . ($options['whitespace'] ? ' ' : '') . $output;
}
return $output;
} | Encodes the object into one of the array formats.
@param object $object Object to encode as PHP
@param array $options List of encoder options
@param callable $encode Callback used to encode values
@return string The object encoded as string
@throws \RuntimeException If the object format is invalid |
private function getObjectArray($object, $format)
{
if ($format === 'array') {
return (array) $object;
} elseif ($format === 'vars') {
return get_object_vars($object);
}
$array = [];
foreach ($object as $key => $value) {
$array[$key] = $value;
}
return $array;
} | Converts the object into array that can be encoded.
@param object $object Object to convert to an array
@param string $format Object conversion format
@return array The object converted into an array
@throws \RuntimeException If object conversion format is invalid |
private function getObjectState($object)
{
$class = new \ReflectionClass($object);
$visibility = \ReflectionProperty::IS_PRIVATE | \ReflectionProperty::IS_PROTECTED;
$values = [];
do {
foreach ($class->getProperties($visibility) as $property) {
$property->setAccessible(true);
$values[$property->getName()] = $property->getValue($object);
}
$class = $class->getParentClass();
$visibility = \ReflectionProperty::IS_PRIVATE;
} while ($class);
return get_object_vars($object) + $values;
} | Returns an array of object properties as would be generated by var_export.
@param object $object Object to turn into array
@return array Properties of the object as passed to var_export |
public function up()
{
Schema::create(config('cortex.auth.tables.roles'), function (Blueprint $table) {
// Columns
$table->increments('id');
$table->string('name', 150);
$table->{$this->jsonable()}('title')->nullable();
$table->integer('level')->unsigned()->nullable();
$table->integer('scope')->nullable();
$table->auditableAndTimestamps();
// Indexes
$table->index(['scope']);
$table->unique(['name', 'scope'], 'roles_name_unique');
});
} | Run the migrations.
@return void |
private function encodeNumber($float, array $options, callable $encode)
{
if ($this->isInteger($float, $options['float.integers'])) {
return $this->encodeInteger($float, $encode);
} elseif ($float === 0.0) {
return '0.0';
} elseif ($options['float.export']) {
return var_export((float) $float, true);
}
return $this->encodeFloat($float, $this->determinePrecision($options));
} | Encodes the number as a PHP number representation.
@param float $float The number to encode
@param array $options The float encoding options
@param callable $encode Callback used to encode values
@return string The PHP code representation for the number |
private function isInteger($float, $allowIntegers)
{
if (!$allowIntegers || round($float) !== $float) {
return false;
} elseif (abs($float) < self::FLOAT_MAX) {
return true;
}
return $allowIntegers === 'all';
} | Tells if the number can be encoded as an integer.
@param float $float The number to test
@param bool|string $allowIntegers Whether integers should be allowed
@return bool True if the number can be encoded as an integer, false if not |
private function encodeInteger($float, callable $encode)
{
$minimum = \defined('PHP_INT_MIN') ? \PHP_INT_MIN : ~\PHP_INT_MAX;
if ($float >= $minimum && $float <= \PHP_INT_MAX) {
return $encode((int) $float);
}
return number_format($float, 0, '.', '');
} | Encodes the given float as an integer.
@param float $float The number to encode
@param callable $encode Callback used to encode values
@return string The PHP code representation for the number |
private function determinePrecision($options)
{
$precision = $options['float.precision'];
if ($precision === false) {
$precision = ini_get('serialize_precision');
}
return max(1, (int) $precision);
} | Determines the float precision based on the options.
@param array $options The float encoding options
@return int The precision used to encode floats |
private function encodeFloat($float, $precision)
{
$log = (int) floor(log(abs($float), 10));
if ($log > -5 && abs($float) < self::FLOAT_MAX && abs($log) < $precision) {
return $this->formatFloat($float, $precision - $log - 1);
}
// Deal with overflow that results from rounding
$log += (int) (round(abs($float) / 10 ** $log, $precision - 1) / 10);
$string = $this->formatFloat($float / 10 ** $log, $precision - 1);
return sprintf('%sE%+d', $string, $log);
} | Encodes the number using a floating point representation.
@param float $float The number to encode
@param int $precision The maximum precision of encoded floats
@return string The PHP code representation for the number |
private function formatFloat($float, $digits)
{
$digits = max((int) $digits, 1);
$string = rtrim(number_format($float, $digits, '.', ''), '0');
return substr($string, -1) === '.' ? $string . '0' : $string;
} | Formats the number as a decimal number.
@param float $float The number to format
@param int $digits The maximum number of decimal digits
@return string The number formatted as a decimal number |
public function getHeaderWrapper(MenuItem $item): string
{
return '<li class="header">'.($item->icon ? '<i class="'.$item->icon.'"></i> ' : '').$item->title.'</li>';
} | {@inheritdoc} |
public function getMenuWithoutDropdownWrapper(MenuItem $item): string
{
return '<li class="'.($item->isActive() ? 'active' : '').'">
<a href="'.$item->getUrl().'" '.$item->getAttributes().'>
'.($item->icon ? '<i class="'.$item->icon.'"></i>' : '').'
<span>'.$item->title.'</span>
</a>
</li>';
} | {@inheritdoc} |
public function getMenuWithDropDownWrapper(MenuItem $item, bool $specialSidebar = false): string
{
return $specialSidebar
? $this->getHeaderWrapper($item).$this->getChildMenuItems($item)
: '<li class="treeview'.($item->hasActiveOnChild() ? ' active' : '').'">
<a href="#">
'.($item->icon ? '<i class="'.$item->icon.'"></i>' : '').'
<span>'.$item->title.'</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
'.$this->getChildMenuItems($item).'
</ul>
</li>';
} | {@inheritdoc} |
public function getMultiLevelDropdownWrapper(MenuItem $item): string
{
return '<li class="treeview'.($item->hasActiveOnChild() ? ' active' : '').'">
<a href="#">
'.($item->icon ? '<i class="'.$item->icon.'"></i>' : '').'
<span>'.$item->title.'</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
'.$this->getChildMenuItems($item).'
</ul>
</li>';
} | Get multilevel menu wrapper.
@param \Rinvex\Menus\Models\MenuItem $item
@return string` |
public function withValidator($validator): void
{
$credentials = $this->only('email', 'expiration', 'token');
$passwordResetBroker = app('auth.password')->broker($this->route('passwordResetBroker'));
$validator->after(function ($validator) use ($passwordResetBroker, $credentials) {
if (! ($user = $passwordResetBroker->getUser($credentials))) {
$validator->errors()->add('email', trans('cortex/auth::'.PasswordResetBrokerContract::INVALID_USER));
}
if ($user && ! $passwordResetBroker->validateToken($user, $credentials)) {
$validator->errors()->add('email', trans('cortex/auth::'.PasswordResetBrokerContract::INVALID_TOKEN));
}
if (! $passwordResetBroker->validateTimestamp($credentials['expiration'])) {
$validator->errors()->add('email', trans('cortex/auth::'.PasswordResetBrokerContract::EXPIRED_TOKEN));
}
});
} | Configure the validator instance.
@param \Illuminate\Validation\Validator $validator
@return void |
public function update(AccountPasswordRequest $request)
{
$currentUser = $request->user($this->getGuard());
// Update profile
$currentUser->fill(['password' => $request->get('new_password')])->forceSave();
return intend([
'back' => true,
'with' => ['success' => trans('cortex/auth::messages.account.updated_password')],
]);
} | Update account password.
@param \Cortex\Auth\Http\Requests\Adminarea\AccountPasswordRequest $request
@return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse |
public function up(): void
{
Schema::create(config('cortex.auth.tables.guardians'), function (Blueprint $table) {
// Columns
$table->increments('id');
$table->string('username');
$table->string('password');
$table->rememberToken();
$table->string('email');
$table->boolean('is_active')->default(true);
$table->auditableAndTimestamps();
$table->softDeletes();
// Indexes
$table->unique('email');
$table->unique('username');
});
} | Run the migrations.
@return void |
protected static function parse(\ReflectionClass $oReflectionClass)
{
$sContent = file_get_contents($oReflectionClass->getFileName());
$aTokens = token_get_all($sContent);
$sDocComment = null;
$bIsConst = false;
foreach ($aTokens as $aToken) {
if (!is_array($aToken) || count($aToken) <= 1) {
continue;
}
list($iTokenType, $sTokenValue) = $aToken;
switch ($iTokenType) {
// Ignored tokens
case T_WHITESPACE:
case T_COMMENT:
break;
case T_DOC_COMMENT:
$sDocComment = $sTokenValue;
break;
case T_CONST:
$bIsConst = true;
break;
case T_STRING:
if ($bIsConst) {
static::$aDescriptions[$sTokenValue] = self::extractDescription($sDocComment);
static::$aArguments[$sTokenValue] = self::extractArgument($sDocComment);
}
$sDocComment = null;
$bIsConst = false;
break;
// All other tokens reset the parser
default:
$sDocComment = null;
$bIsConst = false;
break;
}
}
} | Parses a class for constants and DocComments
@param \ReflectionClass $oReflectionClass |
protected static function clean($sDocComment, $sPattern)
{
if ($sDocComment === null) {
return [];
}
$aOut = [];
$aLines = preg_split('/\R/', $sDocComment);
foreach ($aLines as $sLine) {
$sLine = trim($sLine, "/* \t\x0B\0");
if ($sLine === '' || !preg_match($sPattern, $sLine)) {
continue;
}
$aOut[] = $sLine;
}
return $aOut;
} | Returns lines from a DocComment which match $sPattern
@param string $sDocComment The DocComment
@param string $sPattern The pattern to match
@return array |
public static function getEventNamespace()
{
$oComponent = Components::detectClassComponent(get_called_class());
if (empty($oComponent)) {
throw new NailsException('Could not detect class\' component');
}
return $oComponent->slug;
} | Calculates the event's namespace
@return string
@throws NailsException
@throws \ReflectionException |
public static function info()
{
$oReflectionClass = new \ReflectionClass(get_called_class());
static::parse($oReflectionClass);
$aOut = [];
foreach ($oReflectionClass->getConstants() as $sConstant => $sValue) {
$aOut[$sConstant] = (object) [
'constant' => get_called_class() . '::' . $sConstant,
'namespace' => static::getEventNamespace(),
'value' => $sValue,
'description' => ArrayHelper::getFromArray($sConstant, static::$aDescriptions),
'arguments' => ArrayHelper::getFromArray($sConstant, static::$aArguments),
];
}
return $aOut;
} | Returns an array of the available events with supporting information
@return array |
public function execute()
{
/**
* Migrate encrypted app settings to use new Encryption library
*/
$oResult = $this->query('SELECT id, value FROM {{NAILS_DB_PREFIX}}app_setting WHERE `is_encrypted` = 1');
$oEncrypt = Factory::service('Encrypt');
while ($oRow = $oResult->fetch(\PDO::FETCH_OBJ)) {
$sNewCipher = $oEncrypt->migrate($oRow->value, APP_PRIVATE_KEY);
// Update the record
$sQuery = '
UPDATE `{{NAILS_DB_PREFIX}}app_setting`
SET
`value` = :newValue
WHERE
`id` = :id
';
$oSth = $this->prepare($sQuery);
$oSth->bindParam(':newValue', $sNewCipher, \PDO::PARAM_STR);
$oSth->bindParam(':id', $oRow->id, \PDO::PARAM_INT);
$oSth->execute();
}
} | Execute the migration
@return Void |
public function setHeader($sHeader, $mValue)
{
if (empty($this->aHeaders)) {
$this->aHeaders = [];
}
$this->aHeaders[$sHeader] = $mValue;
return $this;
} | Sets a header
@param $sHeader
@param $mValue
@return $this |
public function getHeader($sHeader)
{
return isset($this->aHeaders[$sHeader]) ? $this->aHeaders[$sHeader] : null;
} | Returns a single header
@param string $sHeader The header to return
@return mixed|null |
public function asUser($iUserId)
{
return $this
->setHeader(Testing::TEST_HEADER_NAME, Testing::TEST_HEADER_VALUE)
->setHeader(Testing::TEST_HEADER_USER_NAME, $iUserId);
} | Set the required headers for imitating a user
@param integer $iUserId the user to imitate
@return $this |
public function execute()
{
$aClientConfig = [
'base_uri' => $this->sBaseUri,
'verify' => !(Environment::is(Environment::ENV_DEV) || Environment::is(Environment::ENV_TEST)),
'allow_redirects' => Environment::not(Environment::ENV_TEST),
'http_errors' => Environment::not(Environment::ENV_TEST),
];
$aRequestOptions = [
'headers' => $this->aHeaders,
];
$this->compile($aClientConfig, $aRequestOptions);
$oClient = Factory::factory('HttpClient', '', $aClientConfig);
return Factory::factory(
'HttpResponse',
'',
$oClient->request(static::HTTP_METHOD, $this->sPath, $aRequestOptions)
);
} | Configures and executes the HTTP request
@return HttpResponse
@throws \Nails\Common\Exception\FactoryException |
public function detect(): \Nails\Common\Factory\Locale
{
/**
* Detect the locale from the request, weakest first
* - Request headers
* - Active user preference
* - The URL (/{locale}/.*)
* - A locale cookie
* - Explicitly provided via $_GET['locale']
*/
$oLocale = $this->getDefautLocale();
if (static::ENABLE_SNIFF) {
if (static::ENABLE_SNIFF_HEADER) {
$this->sniffHeader($oLocale);
}
if (static::ENABLE_SNIFF_USER) {
$this->sniffActiveUser($oLocale);
}
if (static::ENABLE_SNIFF_URL) {
$this->sniffUrl($oLocale);
}
if (static::ENABLE_SNIFF_COOKIE) {
$this->sniffCookie($oLocale);
}
if (static::ENABLE_SNIFF_QUERY) {
$this->sniffQuery($oLocale);
}
if (!$this->isSupportedLocale($oLocale)) {
$oLocale = $this->getDefautLocale();
}
}
return $this
->set($oLocale)
->get();
} | Attempts to detect the locale from the request
@return \Nails\Common\Factory\Locale|null |
public function sniffLocale(\Nails\Common\Factory\Locale $oLocale = null): \Nails\Common\Factory\Locale
{
if (!$oLocale) {
$oLocale = $this->getDefautLocale();
}
$this
->sniffHeader($oLocale)
->sniffActiveUser($oLocale)
->sniffUrl($oLocale)
->sniffCookie($oLocale)
->sniffQuery($oLocale);
return $oLocale;
} | Sniff various items to determine the user's locale
@param \Nails\Common\Factory\Locale $oLocale The locale to set
@return \Nails\Common\Factory\Locale |
public function sniffHeader(\Nails\Common\Factory\Locale &$oLocale)
{
$this->setFromString(
$oLocale,
$this->oInput->server('HTTP_ACCEPT_LANGUAGE') ?? ''
);
return $this;
} | Parses the request headers for a locale and updates $oLocale object
@param \Nails\Common\Factory\Locale $oLocale The locale object to update
@return $this |
public function sniffActiveUser(\Nails\Common\Factory\Locale &$oLocale)
{
$this->setFromString(
$oLocale,
activeUser('locale') ?? ''
);
return $this;
} | Checks the user locale preference and updates $oLocale object
@param \Nails\Common\Factory\Locale $oLocale The locale object to update
@return $this |
public function sniffUrl(\Nails\Common\Factory\Locale &$oLocale)
{
// Manually query the URL as CI might not be available
$sUrl = preg_replace(
'/\/index\.php\/(.*)/',
'$1',
$this->oInput->server('PHP_SELF')
);
preg_match($this->getUrlRegex(), $sUrl, $aMatches);
$sLocale = !empty($aMatches[1]) ? $aMatches[1] : '';
// If it's a vanity locale, then convert to the full locale
if (array_search($sLocale, static::URL_VANITY_MAP) !== false) {
$sLocale = array_search($sLocale, static::URL_VANITY_MAP);
}
$this->setFromString($oLocale, $sLocale);
return $this;
} | Parses the URL for a langauge and updates $oLocale object
@param \Nails\Common\Factory\Locale $oLocale The locale object to update
@return $this |
public function sniffCookie(\Nails\Common\Factory\Locale &$oLocale)
{
$this->setFromString(
$oLocale,
$this->oInput->get(static::COOKIE_NAME) ?? null
);
return $this;
} | Looks for a locale cookie and updates the $oLocale object
@param \Nails\Common\Factory\Locale $oLocale The locale object to update
@return $this |
public function sniffQuery(\Nails\Common\Factory\Locale &$oLocale)
{
$this->setFromString(
$oLocale,
$this->oInput->get(static::QUERY_PARAM) ?? null
);
return $this;
} | Looks for a locale in the query string and updates the locale object
@param \Nails\Common\Factory\Locale $oLocale The locale object to update
@return $this |
public function setFromString(\Nails\Common\Factory\Locale &$oLocale, string $sLocale): ?\Nails\Common\Factory\Locale
{
if (!empty($sLocale)) {
list($sLanguage, $sRegion, $sScript) = static::parseLocaleString($sLocale);
if ($sLanguage) {
$oLocale
->setLanguage(Factory::factory('LocaleLanguage', null, $sLanguage));
}
if ($sRegion) {
$oLocale
->setRegion(Factory::factory('LocaleRegion', null, $sRegion));
}
if ($sScript) {
$oLocale
->setScript(Factory::factory('LocaleScript', null, $sScript));
}
}
return $oLocale;
} | Updates $oLocale based on values parsed from $sLocale
@param \Nails\Common\Factory\Locale $oLocale The Locale object to update
@param string $sLocale The string to parse
@return \Nails\Common\Factory\Locale
@throws \Nails\Common\Exception\FactoryException |
public static function parseLocaleString(?string $sLocale): array
{
return [
\Locale::getPrimaryLanguage($sLocale),
\Locale::getRegion($sLocale),
\Locale::getScript($sLocale),
];
} | Parses a locale string into it's respective framgments
@param string $sLocale The string to parse
@return string[] |
public function set(\Nails\Common\Factory\Locale $oLocale = null): self
{
$this->oLocale = $oLocale;
return $this;
} | Manually sets a locale
@param \Nails\Common\Factory\Locale $oLocale |
public function getDefautLocale(): \Nails\Common\Factory\Locale
{
return Factory::factory('Locale')
->setLanguage(Factory::factory('LocaleLanguage', null, static::DEFAULT_LANGUAGE))
->setRegion(Factory::factory('LocaleRegion', null, static::DEFAULT_REGION))
->setScript(Factory::factory('LocaleScript', null, static::DEFAULT_SCRIPT));
} | Returns the default locale to use for the system
@return \Nails\Common\Factory\Locale
@throws \Nails\Common\Exception\FactoryException |
public function isSupportedLocale(\Nails\Common\Factory\Locale $oLocale): bool
{
return in_array($oLocale, $this->getSupportedLocales());
} | Returns whetehr the supplied locale is supported or not
@param \Nails\Common\Factory\Locale $oLocale The locale to test
@return bool |
public function getUrlRegex(): string
{
$aSupportedLocales = $this->getSupportedLocales();
$aUrlLocales = [];
foreach ($aSupportedLocales as $oLocale) {
$sVanity = $this->getUrlSegment($oLocale);
$aUrlLocales[] = $sVanity;
}
return '/^(' . implode('|', array_filter($aUrlLocales)) . ')?(\/)?(.*)$/';
} | Returns a regex suitable for detecting a language flag at the beginning of the URL
@return string |
public static function flagEmoji(\Nails\Common\Factory\Locale $oLocale): string
{
$sRegion = $oLocale->getRegion();
$aCountries = json_decode(
file_get_contents(
NAILS_APP_PATH . 'vendor/annexare/countries-list/dist/countries.emoji.json'
)
);
return !empty($aCountries->{$sRegion}->emoji) ? $aCountries->{$sRegion}->emoji : '';
} | Returns an emoji flag for a locale
@param \Nails\Common\Factory\Locale $oLocale The locale to query
@return string |
public function getUrlSegment(\Nails\Common\Factory\Locale $oLocale): string
{
if ($oLocale == $this->getDefautLocale()) {
return '';
} else {
return getFromArray((string) $oLocale, static::URL_VANITY_MAP, (string) $oLocale);
}
} | Returns the URL prefix for a given locale, considering any vanity preferences
@param \Nails\Common\Factory\Locale $oLocale The locale to query
@return string
@throws \Nails\Common\Exception\FactoryException |
private function addDefaultPreviewRule(?array $scopeRules, array $defaultRule): array
{
$scopeRules = is_array($scopeRules) ? $scopeRules : [];
$blockManagerRules = $scopeRules['ngbm_app_preview'] ?? [];
$blockManagerRules += [
'___ngbm_app_preview_default___' => $defaultRule,
];
$scopeRules['ngbm_app_preview'] = $blockManagerRules;
return $scopeRules;
} | Adds the default eZ content preview template to default scope as a fallback
when no preview rules are defined. |
public static function encode($mValue, $sSalt = '')
{
try {
return Crypto::encryptWithPassword(
$mValue,
static::getKey($sSalt)
);
} catch (EnvironmentIsBrokenException $e) {
throw new EnvironmentException(
$e->getMessage(),
$e->getCode()
);
}
} | Encodes a given value using the supplied key
@param mixed $mValue The value to encode
@param string $sSalt The salt to add to the key
@throws EnvironmentException
@return string |
public static function decode($sCipher, $sSalt = '')
{
try {
return Crypto::decryptWithPassword(
$sCipher,
static::getKey($sSalt)
);
} catch (EnvironmentIsBrokenException $e) {
throw new EnvironmentException(
$e->getMessage(),
$e->getCode()
);
} catch (WrongKeyOrModifiedCiphertextException $e) {
throw new DecodeException(
$e->getMessage(),
$e->getCode()
);
}
} | Decodes a given value using the supplied key
@param mixed $sCipher The value to decode
@param string $sSalt The salt to add to the key
@throws EnvironmentException
@throws DecodeException
@return string |
public static function migrate($sCipher, $sOldKey, $sNewSalt = '')
{
require_once NAILS_CI_SYSTEM_PATH . 'libraries/Encrypt.php';
$oEncryptCi = new \CI_Encrypt();
$oEncrypt = Factory::service('Encrypt');
return $oEncrypt::encode(
$oEncryptCi->decode(
$sCipher,
$sOldKey
),
$sNewSalt
);
} | Migrates a cipher from CI encrypt library, to Defuse\Crypto library
@param string $sCipher The cipher to migrate
@param string $sOldKey The key used to encode originally
@param string $sNewSalt The salt to add to the new key
@return string |
public static function get($mKeys = null, $bXssClean = false)
{
$aArray = isset($_GET) ? $_GET : [];
return static::getItemsFromArray($mKeys, $bXssClean, $aArray);
} | Returns keys from the global $_GET array
@param string|array $mKeys The key(s) to return
@param bool $bXssClean Whether to run the result through the XSS filter
@return array|mixed
@throws \Nails\Common\Exception\FactoryException |
public static function post($mKeys = null, $bXssClean = false)
{
$aArray = isset($_POST) ? $_POST : [];
return static::getItemsFromArray($mKeys, $bXssClean, $aArray);
} | Returns keys from the global $_POST array
@param string|array $mKeys The key(s) to return
@param bool $bXssClean Whether to run the result through the XSS filter
@return array|mixed
@throws \Nails\Common\Exception\FactoryException |
public static function server($mKeys = null, $bXssClean = false)
{
$aArray = isset($_SERVER) ? $_SERVER : [];
return static::getItemsFromArray($mKeys, $bXssClean, $aArray);
} | Returns keys from the global $_SERVER array
@param string|array $mKeys The key(s) to return
@param bool $bXssClean Whether to run the result through the XSS filter
@return array|mixed
@throws \Nails\Common\Exception\FactoryException |
public static function cookie($mKeys = null, $bXssClean = false)
{
$aArray = isset($_COOKIE) ? $_COOKIE : [];
return static::getItemsFromArray($mKeys, $bXssClean, $aArray);
} | Returns keys from the global $_COOKIE array
@param string|array $mKeys The key(s) to return
@param bool $bXssClean Whether to run the result through the XSS filter
@return array|mixed
@throws \Nails\Common\Exception\FactoryException |
public static function file($mKeys = null)
{
$aArray = isset($_FILES) ? $_FILES : [];
return static::getItemsFromArray($mKeys, false, $aArray);
} | Returns keys from the global $_FILES array
@param string|array $mKeys The key(s) to return
@return array|mixed
@throws \Nails\Common\Exception\FactoryException |
public static function isValidIp($sIp, $sType = null)
{
switch (strtoupper($sType)) {
case 'IPV4':
return filter_var($sIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
break;
case 'IPV6':
return filter_var($sIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
break;
default:
return filter_var($sIp, FILTER_VALIDATE_IP);
break;
}
} | Validate an IP address
@param string $sIp The IP to validate
@param string $sType The type of IP (IPV4 or IPV6)
@return mixed |
protected static function getItemsFromArray($mKeys = null, $bXssClean = false, $aArray = [])
{
$aArrayKeys = array_keys($aArray);
$aArrayKeysLower = array_map('strtolower', $aArrayKeys);
$aArrayKeysMap = array_combine($aArrayKeysLower, $aArrayKeys);
$aRequestedKeys = $mKeys !== null ? (array) $mKeys : array_keys($aArray);
$aRequestedKeys = array_map('strtolower', $aRequestedKeys);
$aOut = [];
foreach ($aRequestedKeys as $sKey) {
if (array_key_exists($sKey, $aArrayKeysMap)) {
$aOut[$aArrayKeysMap[$sKey]] = ArrayHelper::getFromArray($aArrayKeysMap[$sKey], $aArray);
if ($bXssClean) {
$aOut[$aArrayKeysMap[$sKey]] = Factory::service('Security')
->xss_clean($aOut[$aArrayKeysMap[$sKey]]);
}
}
}
return is_string($mKeys) ? reset($aOut) : $aOut;
} | Returns keys from the supplied $aArray array
@param string|array $mKeys The key(s) to return
@param bool $bXssClean Whether to run the result through the XSS filter
@param array $aArray The array to inspect
@return array|mixed
@throws \Nails\Common\Exception\FactoryException |
protected function getSeeders()
{
$aSeedClasses = [];
$aAllComponents = Components::available();
foreach ($aAllComponents as $oComponent) {
$sPath = $oComponent->path . 'src/Seed/';
if (is_dir($sPath)) {
$aSeeds = directory_map($sPath);
$aSeeds = array_map(
function ($sClass) {
return basename($sClass, '.php');
},
$aSeeds
);
sort($aSeeds);
if (empty($aSeeds)) {
continue;
}
foreach ($aSeeds as $sClass) {
$aSeedClasses[] = (object) [
'component' => $oComponent->slug,
'namespace' => $oComponent->namespace,
'class' => $sClass,
];
}
}
}
return $aSeedClasses;
} | -------------------------------------------------------------------------- |
private function getContentType(Content $content): EzContentType
{
if (method_exists($content, 'getContentType')) {
return $content->getContentType();
}
// @deprecated Remove when support for eZ kernel < 7.4 ends
return $this->contentTypeService->loadContentType(
$content->contentInfo->contentTypeId
);
} | Loads the content type for provided content.
@deprecated Acts as a BC layer for eZ kernel <7.4 |
private function createSeeder(): void
{
$aFields = $this->getArguments();
$aCreated = [];
try {
$aModels = array_filter(explode(',', $aFields['MODEL_NAME']));
sort($aModels);
foreach ($aModels as $sModel) {
$aFields['MODEL_NAME'] = $sModel;
$this->oOutput->write('Creating seeder <comment>' . $sModel . '</comment>... ');
// Validate model exists by attempting to load it
if (!stringToBoolean($this->oInput->getOption('skip-check'))) {
Factory::model($sModel, $aFields['MODEL_PROVIDER']);
}
// Check for existing seeder
$sPath = static::SEEDER_PATH . $sModel . '.php';
if (file_exists($sPath)) {
throw new SeederExistsException(
'Seeder "' . $sModel . '" exists already at path "' . $sPath . '"'
);
}
$this->createFile($sPath, $this->getResource('template/seeder.php', $aFields));
$aCreated[] = $sPath;
$this->oOutput->writeln('<info>done!</info>');
}
} catch (\Exception $e) {
$this->oOutput->writeln('<error>failed!</error>');
// Clean up created seeders
if (!empty($aCreated)) {
$this->oOutput->writeln('<error>Cleaning up - removing newly created files</error>');
foreach ($aCreated as $sPath) {
@unlink($sPath);
}
}
throw $e;
}
} | Create the Seeder
@throws \Exception
@return void |
protected function generateFilePath(array $aServiceBits): string
{
$sClassName = array_pop($aServiceBits);
return implode(
DIRECTORY_SEPARATOR,
array_map(
function ($sItem) {
return rtrim($sItem, DIRECTORY_SEPARATOR);
},
array_merge(
[static::APP_PATH],
$aServiceBits,
[$sClassName . '.php']
)
)
);
} | Generate the class file path
@param array $aServiceBits The supplied classname "bits"
@return string |
public function display_error($error = '', $swap = '', $native = false)
{
if (is_array($error)) {
$error = implode('; ', $error);
}
throw new QueryException($error);
} | Display an error message using an exception rather than a view
@param string $error The error message
@param string $swap Any "swap" values
@param bool $native Whether to localize the message
@return void |
protected function _update($table, $values)
{
$aValues = [];
foreach ($values as $key => $val) {
$aValues[] = $key . ' = ' . $val;
}
return 'UPDATE ' . $table . ' ' . $this->_compile_join() . ' SET ' . implode(', ', $aValues)
. $this->_compile_wh('qb_where')
. $this->_compile_order_by()
. ($this->qb_limit ? ' LIMIT ' . $this->qb_limit : '');
} | Update statement
Generates a platform-specific update string from the supplied data
@param string $table The table name
@param array $values The update data
@return string |
protected function _compile_join()
{
$sSql = '';
// Write the "JOIN" portion of the query
if (count($this->qb_join) > 0) {
$sSql .= "\n" . implode("\n", $this->qb_join);
}
return $sSql;
} | Compiles the JOIN string
@return string |
protected function determineModuleState($sModuleName, $sMigrationsPath): ?\stdClass
{
$oModule = (object) [
'name' => $sModuleName,
'start' => null,
'end' => null,
];
// --------------------------------------------------------------------------
// Work out if the module needs migrated and if so between what and what
$aDirMap = $this->mapDir($sMigrationsPath);
if (!empty($aDirMap)) {
// Work out all the files we have and get their index
$aMigrations = [];
foreach ($aDirMap as $dir) {
$aMigrations[$dir['path']] = [
'index' => $dir['index'],
];
}
// --------------------------------------------------------------------------
// Work out the current version
$sSql = "SELECT `version` FROM `" . NAILS_DB_PREFIX . "migration` WHERE `module` = '$sModuleName';";
$oResult = $this->oDb->query($sSql);
if ($oResult->rowCount() === 0) {
// Add a row for the module
$sSql = "INSERT INTO `" . NAILS_DB_PREFIX . "migration` (`module`, `version`) VALUES ('$sModuleName', NULL);";
$this->oDb->query($sSql);
$iCurrentVersion = null;
} else {
$iCurrentVersion = $oResult->fetch(\PDO::FETCH_OBJ)->version;
$iCurrentVersion = is_null($iCurrentVersion) ? null : (int) $iCurrentVersion;
}
// --------------------------------------------------------------------------
// Define the variable
$aLastMigration = end($aMigrations);
$oModule->start = $iCurrentVersion;
$oModule->end = $aLastMigration['index'];
}
return $oModule->start === $oModule->end ? null : $oModule;
} | Determines whether or not the module needs to migration, and if so between what versions
@param string $sModuleName The module's name
@param string $sMigrationsPath The module's path
@return \stdClass|null stdClass when migration needed, null when not needed |
protected function findEnabledModules(): array
{
$aModules = Components::available(false);
$aOut = [];
foreach ($aModules as $oModule) {
$aOut[] = $this->determineModuleState($oModule->slug, $oModule->path . 'migrations/');
}
return array_filter($aOut);
} | Looks for enabled Nails modules which support migration
@return array |
protected function doMigration($oModule): bool
{
$oOutput = $this->oOutput;
// --------------------------------------------------------------------------
// Map the directory and fetch only the files we need
$sPath = $oModule->name == 'APP' ? 'application/migrations/' : 'vendor/' . $oModule->name . '/migrations/';
$aDirMap = $this->mapDir($sPath);
// Set the current version to -1 if null so migrations with a zero index are picked up
$iCurrent = is_null($oModule->start) ? -1 : $oModule->start;
// Go through all the migrations, skip any which have already been executed
foreach ($aDirMap as $aMigration) {
if ($aMigration['index'] > $iCurrent) {
if (!$this->executeMigration($oModule, $aMigration)) {
return false;
}
}
// Mark this migration as complete
$sSql = "UPDATE `" . NAILS_DB_PREFIX . "migration` SET `version` = " . $aMigration['index'] . " WHERE `module` = '" . $oModule->name . "'";
$oResult = $this->oDb->query($sSql);
}
if (!$oResult) {
// Error updating migration record
$oOutput->writeln('');
$oOutput->writeln('');
$oOutput->writeln('<error>ERROR</error>: Failed to update migration record for <info>' . $oModule->name . '</info>.');
return false;
}
return true;
} | Executes a migration
@param \stdClass $oModule The migration details object
@return boolean |
private function mapDir($sDir): ?array
{
if (is_dir($sDir)) {
$aOut = [];
foreach (new \DirectoryIterator($sDir) as $oFileInfo) {
if ($oFileInfo->isDot()) {
continue;
}
// In the correct format?
if (preg_match(static::VALID_MIGRATION_PATTERN, $oFileInfo->getFilename(), $aMatches)) {
$aOut[$aMatches[1]] = [
'path' => $oFileInfo->getPathname(),
'index' => (int) $aMatches[1],
];
}
}
ksort($aOut);
return $aOut;
} else {
return null;
}
} | Generates an array of files in a directory
@param string $sDir The directory to analyse
@return array|null |