-
-
Notifications
You must be signed in to change notification settings - Fork 33
Add path enumerable trait #155
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
Open
bennothommo
wants to merge
9
commits into
develop
Choose a base branch
from
wip/path-enumerable-trait
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
cda7f10
Add path enumerable trait
bennothommo 62411f8
Add getNested method and test
bennothommo 5975793
Fix a couple of hard references to path column
bennothommo 4af1e27
Merge branch 'develop' into wip/path-enumerable-trait
bennothommo 1edb90e
Add ability to define a custom segment column.
bennothommo 9e57356
Prevent forward-slashes in segment column from breaking hierarachy
bennothommo f27ded7
Fix comments
bennothommo 7111f16
Merge remote-tracking branch 'origin/develop' into wip/path-enumerabl…
bennothommo 082905b
Merge branch 'develop' into wip/path-enumerable-trait
bennothommo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,322 @@ | ||
| <?php | ||
|
|
||
| namespace Winter\Storm\Database\Traits; | ||
|
|
||
| use Illuminate\Database\Eloquent\SoftDeletingScope; | ||
| use Winter\Storm\Database\Builder; | ||
| use Winter\Storm\Database\Collection; | ||
| use Winter\Storm\Database\Model; | ||
| use Winter\Storm\Database\TreeCollection; | ||
|
|
||
| /** | ||
| * "Enumerable path" model trait | ||
| * | ||
| * Provides an implementation of "path enumeration" in PHP, storing hierarchal data using a single "path" column that | ||
| * contains the an ID path to a specific record. | ||
| * | ||
| * It can be added to a model with the following: | ||
| * | ||
| * ```php | ||
| * use Winter\Storm\Database\Traits\PathEnumerable; | ||
| * ``` | ||
| * | ||
| * By default, an "enumerable path" model must have a `parent_id` and a `path` column in the database table, but these | ||
| * columns can be changed by defining the following constants in the model: | ||
| * | ||
| * ```php | ||
| * const PARENT_ID = 'my_parent_id'; | ||
| * const PATH_COLUMN = 'my_path_column'; | ||
| * ``` | ||
| * | ||
| * Include the following columns in your database table migration - ensuring that the column names match the constants | ||
| * or the default column names: | ||
| * | ||
| * ```php | ||
| * $table->integer('parent_id')->unsigned()->nullable(); | ||
| * $table->string('path')->nullable(); | ||
| * ``` | ||
| * | ||
| * @author Ben Thomson <git@alfreido.com> | ||
| * @copyright Winter CMS | ||
| * @link https://www.waitingforcode.com/mysql/managing-hierarchical-data-in-mysql-path-enumeration/read | ||
| * @link https://vadimtropashko.wordpress.com/2008/08/09/one-more-nested-intervals-vs-adjacency-list-comparison/ | ||
| */ | ||
| trait PathEnumerable | ||
| { | ||
| /** | ||
| * Stores the new parent ID on update. If set to `false`, no change is pending. | ||
| */ | ||
| protected int|null|false $newParentId = false; | ||
|
|
||
| public static function bootPathEnumerable(): void | ||
| { | ||
| static::extend(function (Model $model) { | ||
| // Define relationships | ||
|
|
||
| $model->hasMany['children'] = [ | ||
| get_class($model), | ||
| 'key' => $model->getParentColumnName() | ||
| ]; | ||
|
|
||
| $model->belongsTo['parent'] = [ | ||
| get_class($model), | ||
| 'key' => $model->getParentColumnName() | ||
| ]; | ||
|
|
||
| // Add event listeners | ||
| $model->bindEvent('model.afterCreate', function () use ($model) { | ||
| $model->setEnumerablePath(); | ||
| }); | ||
|
|
||
| $model->bindEvent('model.beforeUpdate', function () use ($model) { | ||
| $model->storeNewParent(); | ||
| }); | ||
|
|
||
| $model->bindEvent('model.afterUpdate', function () use ($model) { | ||
| $model->moveToNewParent(); | ||
| }); | ||
|
|
||
| $model->bindEvent('model.beforeDelete', function () use ($model) { | ||
| $model->deleteDescendants(); | ||
| }); | ||
|
|
||
| if (static::hasGlobalScope(SoftDeletingScope::class)) { | ||
| $model->bindEvent('model.afterRestore', function () use ($model) { | ||
| $model->restoreDescendants(); | ||
| $model->setEnumerablePath(); | ||
| }); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Gets the direct parent of the current record. | ||
| */ | ||
| public function getParent(): Collection | ||
| { | ||
| return $this->parent()->get(); | ||
| } | ||
|
|
||
| /** | ||
| * Gets all ancestral records of the current record. | ||
| */ | ||
| public function getParents(): Collection | ||
| { | ||
| return $this->newQuery()->ancestors()->get(); | ||
| } | ||
|
|
||
| /** | ||
| * Gets all direct children of the current record. | ||
| */ | ||
| public function getChildren(): Collection | ||
| { | ||
| return $this->children()->get(); | ||
| } | ||
|
|
||
| /** | ||
| * Gets all children (ancestors) of the current record. | ||
| * | ||
| * This will include children records of the child records, and so on. | ||
| */ | ||
| public function getAllChildren(): Collection | ||
| { | ||
| return $this->newQuery()->descendants()->get(); | ||
| } | ||
|
|
||
| /** | ||
| * Gets a nested collection of all records. | ||
| */ | ||
| public function getNested(): Collection | ||
| { | ||
| return $this->newQuery()->get()->toNested(); | ||
| } | ||
|
|
||
| /** | ||
| * Root nodes scope. | ||
| * | ||
| * Gets all record that form the root nodes of the hierarchy. | ||
| */ | ||
| public function scopeRoot(Builder $query): void | ||
| { | ||
| $query->whereNull($this->getParentColumnName()); | ||
| } | ||
|
|
||
| /** | ||
| * Descendants scope. | ||
| * | ||
| * Gets all children records, and all children of those records, and so on. | ||
| */ | ||
| public function scopeDescendants(Builder $query): void | ||
| { | ||
| if (!$this->exists()) { | ||
| return; | ||
| } | ||
|
|
||
| $query->where($this->getPathColumnName(), 'LIKE', $this->getPath() . '/%'); | ||
| } | ||
|
|
||
| /** | ||
| * Ancestors scope. | ||
| * | ||
| * Gets all records that are direct ancestors (parents) of the current record. | ||
| */ | ||
| public function scopeAncestors(Builder $query): void | ||
| { | ||
| if (!$this->exists()) { | ||
| return; | ||
| } | ||
|
|
||
| $query->whereIn($this->getKeyName(), $this->getAncestorIds()); | ||
| } | ||
|
|
||
| /** | ||
| * Gets the enumerable path on the current record. | ||
| * | ||
| * This will take into account any parent changes, allowing you to get the new path before the record is saved. | ||
| */ | ||
| public function getEnumerablePath(): string | ||
| { | ||
| if ($this->parent()->exists()) { | ||
| return $this->parent->{$this->getPathColumnName()} . '/' . $this->id; | ||
| } | ||
|
|
||
| return '/' . $this->id; | ||
| } | ||
|
|
||
| /** | ||
| * Sets the enumerable path on the current record. | ||
| */ | ||
| public function setEnumerablePath(): void | ||
| { | ||
| $this->{$this->getPathColumnName()} = $path = $this->getEnumerablePath(); | ||
|
|
||
| $this->newQuery() | ||
| ->where($this->getKeyName(), $this->id) | ||
| ->update([$this->getPathColumnName() => $path]); | ||
| } | ||
|
|
||
| /** | ||
| * Stores the new parent ID in preparation for an update. | ||
| */ | ||
| public function storeNewParent(): void | ||
| { | ||
| $isDirty = $this->isDirty($this->getParentColumnName()); | ||
|
|
||
| if (!$isDirty) { | ||
| return; | ||
| } | ||
|
|
||
| $this->newParentId = $this->getParentId(); | ||
| } | ||
|
|
||
| /** | ||
| * Moves a record, and all of its children, to a new parent. | ||
| * | ||
| * This will update the enumerated paths of all records. | ||
| */ | ||
| public function moveToNewParent(): void | ||
| { | ||
| if ($this->newParentId === false) { | ||
| return; | ||
| } | ||
|
|
||
| $oldPath = $this->getPath(); | ||
| $newPath = $this->getEnumerablePath(); | ||
|
|
||
| $this->getConnection()->transaction(function () use ($oldPath, $newPath) { | ||
| foreach ($this->getAllChildren() as $child) { | ||
| $child->{$this->getPathColumnName()} = str_replace( | ||
| $oldPath . '/', | ||
| $newPath . '/', | ||
| $child->{$this->getPathColumnName()} | ||
| ); | ||
| $child->saveQuietly(); | ||
| } | ||
| }); | ||
|
|
||
| $this->setEnumerablePath(); | ||
| $this->newParentId = false; | ||
| } | ||
|
|
||
| /** | ||
| * Deletes all descendants. | ||
| */ | ||
| public function deleteDescendants(): void | ||
| { | ||
| $this->newQuery()->descendants()->delete(); | ||
| } | ||
|
|
||
| /** | ||
| * Deletes all descendants. | ||
| */ | ||
| public function restoreDescendants(): void | ||
| { | ||
| $this->newQuery()->descendants()->restore(); | ||
| } | ||
|
|
||
| /** | ||
| * Determines the depth of the current record. | ||
| * | ||
| * A root node is considered a depth of `0`. A child node of a root node is considered a depth of `1`, and so on. | ||
| */ | ||
| public function getDepth(): int | ||
| { | ||
| return substr_count($this->getPath(), '/') - 1; | ||
| } | ||
|
|
||
| /** | ||
| * Gets the parent column name. | ||
| */ | ||
| public function getParentColumnName(): string | ||
| { | ||
| return defined('static::PARENT_ID') ? constant('static::PARENT_ID') : 'parent_id'; | ||
| } | ||
|
|
||
| /** | ||
| * Gets the parent column name. | ||
| */ | ||
| public function getPathColumnName(): string | ||
| { | ||
| return defined('static::PATH_COLUMN') ? constant('static::PATH_COLUMN') : 'path'; | ||
| } | ||
|
|
||
| /** | ||
| * Gets the ID of the parent record for the current record. | ||
| * | ||
| * This will be `null` if the record has no parent (root node). | ||
| */ | ||
| public function getParentId(): ?int | ||
| { | ||
| return $this->getAttribute($this->getParentColumnName()); | ||
| } | ||
|
|
||
| /** | ||
| * Gets the ID of all direct ancestors of the current record. | ||
| * | ||
| * @return int[] | ||
| */ | ||
| public function getAncestorIds(): array | ||
| { | ||
| $ids = explode('/', $this->getPath()); | ||
| array_pop($ids); | ||
| return $ids; | ||
| } | ||
|
|
||
| /** | ||
| * Gets the current path of the record. | ||
| */ | ||
| public function getPath(): string | ||
| { | ||
| return $this->getAttribute($this->getPathColumnName()); | ||
| } | ||
|
|
||
| /** | ||
| * Return a custom TreeCollection collection | ||
| * | ||
| * @param Model[] $models | ||
| */ | ||
| public function newCollection(array $models = []): TreeCollection | ||
| { | ||
| return new TreeCollection($models); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.