Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancement HasPosition trait #1351

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,6 @@ public function save()
if (! $this->attribute->id) {
$this->attribute->attribute_type = $this->group->attributable_type;
$this->attribute->attribute_group_id = $this->group->id;
$this->attribute->position = Attribute::whereAttributeGroupId(
$this->group->id
)->count() + 1;
$this->attribute->save();
$this->notify(
__('adminhub::notifications.attribute-edit.created')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,6 @@ public function create()
}

$this->attributeGroup->attributable_type = $this->attributableType;
$this->attributeGroup->position = AttributeGroup::whereAttributableType(
$this->attributableType
)->count() + 1;

$this->attributeGroup->handle = $handle;
$this->attributeGroup->save();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,10 +198,6 @@ public function save()
return;
}

if (! $this->productOption->position) {
$this->productOption->position = ProductOption::count() + 1;
}

$this->productOption->save();

$this->productOption = new ProductOption();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,6 @@ public function save()
$this->validate();

if (! $this->optionValue->id) {
$this->optionValue->position = ProductOptionValue::whereProductOptionId(
$this->option->id
)->count() + 1;

$this->optionValue->option()->associate($this->option);
$this->optionValue->save();
$this->notify(
Expand Down
3 changes: 0 additions & 3 deletions packages/core/database/factories/AttributeFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,13 @@

class AttributeFactory extends Factory
{
private static $position = 1;

protected $model = Attribute::class;

public function definition(): array
{
return [
'attribute_group_id' => AttributeGroup::factory(),
'attribute_type' => Product::class,
'position' => self::$position++,
'name' => [
'en' => $this->faker->name(),
],
Expand Down
3 changes: 0 additions & 3 deletions packages/core/database/factories/ProductOptionFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@

class ProductOptionFactory extends Factory
{
private static $position = 1;

protected $model = ProductOption::class;

public function definition(): array
Expand All @@ -24,7 +22,6 @@ public function definition(): array
'label' => [
'en' => $name,
],
'position' => self::$position++,
];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Lunar\Base\Migration;
use Lunar\Facades\PositionManifest;
use Lunar\Models\Attribute;
use Lunar\Models\AttributeGroup;
use Lunar\Models\ProductOption;
use Lunar\Models\ProductOptionValue;

return new class extends Migration {
/**
* Run the migrations.
*/
public function up(): void
{
/**
* Model's with `HasPosition` trait
*/
$models = [
Attribute::class,
AttributeGroup::class,
ProductOption::class,
ProductOptionValue::class,
];
/**
* Ensure that all position values are unique
*/
foreach ($models as $model) {
$model = app($model);
Schema::table($model->getTable(), function (Blueprint $table) use ($model) {
DB::table($table->getTable())
->select(array_merge(
[$model->getKeyName()],
PositionManifest::constraints($model)
))
->orderBy('position')
->orderBy('id')
->get()
->groupBy(fn (stdClass $row, int $key) =>
collect($row)
->except([$model->getKeyName(), 'position'])
->join('-')
)->each
->each(fn(stdClass $row, int $key) => $row->position = $key + 1);
});
}
/**
* Add unique position index under consideration of
* the model's position constraints
*/
foreach ($models as $model) {
$model = app($model);
Schema::table($model->getTable(), function (Blueprint $table) use ($model) {
$schema = Schema::getConnection()
->getDoctrineSchemaManager()
->introspectTable($model->getTable());
$table->unsignedBigInteger('position')
->nullable(false)
->default(null)
->change();
$index = $model->getTable() . '_position_index';
if ($schema->hasIndex($index)) {
$table->dropIndex($index);
}
$index = $model->getTable() . '_position_unique';
if ($schema->hasIndex($index)) {
$table->dropIndex($index);
}
$table->unique(PositionManifest::constraints($model), $index);
});
}
}
};
142 changes: 142 additions & 0 deletions packages/core/src/Base/PositionManifest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
<?php

namespace Lunar\Base;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Str;

class PositionManifest implements PositionManifestInterface
{
/**
* {@inheritDoc}
*/
public function saving(Model $model): void
{
if (
$model->isDirty($this->constraints($model))
|| !(intval($model->position) > 0)
|| $model->query()
->where($model->getKeyName(), '!=', $model->getKey())
->wherePosition($model->position)
->wherePositionUniqueConstraints($model->getAttributes())
->exists()
) {
$model->position = $model->query()
->where($model->getKeyName(), '!=', $model->getKey())
->wherePositionUniqueConstraints($model->getAttributes())
->max('position') + 1;
}
}

/**
*
* {@inheritDoc}
*/
public function constraints(Model $model): array
{
return array_merge(
!property_exists($model, 'positionUniqueConstraints')
|| !is_array($model->positionUniqueConstraints)
? [] : $model->positionUniqueConstraints,
['position']
);
}

/**
* {@inheritDoc}
*/
public function query(Builder $query, int $position, array $constraints = []): void
{
$query
->wherePosition($position)
->wherePositionUniqueConstraints($constraints);
}

/**
* {@inheritDoc}
*/
public function queryPosition(Builder $query, int $position): void
{
$query->where('position', $position);
}

/**
* {@inheritDoc}
*/
public function queryUniqueConstraints(Builder $query, array $constraints): void
{
$constraints = collect($constraints);
$modelConstraints = collect($this->constraints($query->getModel()))->reject('position');

if (count($modelConstraints) && !$constraints->hasAny($modelConstraints->toArray())) {
throw new \InvalidArgumentException(
sprintf(
'Position constraints "%s" for "%s" not defined!',
$modelConstraints->diff($constraints)->join('", "', '" and "'),
get_class($query->getModel())
)
);
}

$modelConstraints->each(
function ($attribute) use ($query, $constraints) {
if (method_exists($query, Str::camel('scope_' . $attribute))) {
$method = Str::camel($attribute);
} else {
$method = Str::camel('where_' . $attribute);
}
$query->{$method}($constraints[$attribute]);
}
);
}

/**
* {@inheritDoc}
*/
public static function registerBlueprintMacros(): void
{
/**
* Add a `position` column to the table and define a unique positions index
* with the given constraints
*
* The constraints can defined as array or assigned from the corsponding
* model property `positionUniqueConstraints` if model object or
* model classname is given.
*
* @param array|string|\Illuminate\Database\Eloquent\Model $constraints
* @return void
*/
Blueprint::macro('position', function (array|string|Model $constraints = []) {
/** @var Blueprint $this */
if (is_string($constraints)) {
$constraints = app($constraints);
}
if (!is_array($constraints)) {
$constraints = \Lunar\Facades\PositionManifest::constraints($constraints);
} else {
$constraints = collect($constraints)
->push('position')
->unique()
->all();
}
$this->unsignedBigInteger('position');

Check failure on line 124 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 - L^9.0 ↑

Undefined variable: $this

Check failure on line 124 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 - L^10.0 ↑

Undefined variable: $this

Check failure on line 124 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 - L^9.0 ↑

Undefined variable: $this

Check failure on line 124 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 - L^10.0 ↑

Undefined variable: $this
$index = strtolower($this->prefix . $this->table . '_position_unique');

Check failure on line 125 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 - L^9.0 ↑

Undefined variable: $this

Check failure on line 125 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 - L^9.0 ↑

Undefined variable: $this

Check failure on line 125 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 - L^10.0 ↑

Undefined variable: $this

Check failure on line 125 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 - L^10.0 ↑

Undefined variable: $this

Check failure on line 125 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 - L^9.0 ↑

Undefined variable: $this

Check failure on line 125 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 - L^9.0 ↑

Undefined variable: $this

Check failure on line 125 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 - L^10.0 ↑

Undefined variable: $this

Check failure on line 125 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 - L^10.0 ↑

Undefined variable: $this
$this->unique($constraints, $index);

Check failure on line 126 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 - L^9.0 ↑

Undefined variable: $this

Check failure on line 126 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 - L^10.0 ↑

Undefined variable: $this

Check failure on line 126 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 - L^9.0 ↑

Undefined variable: $this

Check failure on line 126 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 - L^10.0 ↑

Undefined variable: $this
});

/**
* Remove the `position` column to the table and drop the unique positions index
*
* @param array|string|\Illuminate\Database\Eloquent\Model $constraints
* @return void
*/
Blueprint::macro('dropPosition', function () {
/** @var Blueprint $this */
$index = strtolower($this->prefix . $this->table . '_position_unique');

Check failure on line 137 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 - L^9.0 ↑

Undefined variable: $this

Check failure on line 137 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 - L^9.0 ↑

Undefined variable: $this

Check failure on line 137 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 - L^10.0 ↑

Undefined variable: $this

Check failure on line 137 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 - L^10.0 ↑

Undefined variable: $this

Check failure on line 137 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 - L^9.0 ↑

Undefined variable: $this

Check failure on line 137 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 - L^9.0 ↑

Undefined variable: $this

Check failure on line 137 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 - L^10.0 ↑

Undefined variable: $this

Check failure on line 137 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 - L^10.0 ↑

Undefined variable: $this
$this->dropUnique($index);

Check failure on line 138 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 - L^9.0 ↑

Undefined variable: $this

Check failure on line 138 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 - L^10.0 ↑

Undefined variable: $this

Check failure on line 138 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 - L^9.0 ↑

Undefined variable: $this

Check failure on line 138 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 - L^10.0 ↑

Undefined variable: $this
$this->dropColumn('position');

Check failure on line 139 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 - L^9.0 ↑

Undefined variable: $this

Check failure on line 139 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.1 - L^10.0 ↑

Undefined variable: $this

Check failure on line 139 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 - L^9.0 ↑

Undefined variable: $this

Check failure on line 139 in packages/core/src/Base/PositionManifest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 - L^10.0 ↑

Undefined variable: $this
});
}
}
62 changes: 62 additions & 0 deletions packages/core/src/Base/PositionManifestInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php
namespace Lunar\Base;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

interface PositionManifestInterface
{
/**
* Before model gets saved, check if relevant model attributes has changed
* and position value is greate than zero and unique and if not, set position
* to next greatest value
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function saving(Model $model): void;

/**
* Return the defined constraints from model's positionUniqueConstraints
* property array
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return array
*/
public function constraints(Model $model): array;

/**
* Scope the query to only include given position and constraints
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param int $position
* @param array $constraints
* @return void
*/
public function query(Builder $query, int $position, array $constraints = []): void;

/**
* Scope the query to only include given position
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param int $position
* @return void
*/
public function queryPosition(Builder $query, int $position): void;

/**
* Scope the query to only include given constraints
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param array|\Illuminate\Support\Collection $constraints
* @return void
*/
public function queryUniqueConstraints(Builder $query, array $constraints): void;

/**
* Regster blueprint macros to allow ease
* ddefinition and removement from `position` columne
* @return void
*/
public static function registerBlueprintMacros(): void;
}
Loading
Loading