Skip to content

Commit

Permalink
add UniqueSluggableBehavior
Browse files Browse the repository at this point in the history
to validate the uniqueness of a slug in multiple repositories
  • Loading branch information
albertborsos committed Aug 29, 2019
1 parent 6b743d3 commit cd8bbf0
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/behaviors/SluggableBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,12 @@ public function init()
/**
* @return ActiveRepositoryInterface
*/
protected function getRepository()
protected function getRepository($interface = null): ActiveRepositoryInterface
{
if (!empty($interface)) {
return Yii::createObject($interface);
}

return $this->repository;
}

Expand Down
40 changes: 40 additions & 0 deletions src/behaviors/UniqueSluggableBehavior.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace albertborsos\ddd\behaviors;

use albertborsos\ddd\traits\EvaluateAttributesTrait;

abstract class UniqueSluggableBehavior extends SluggableBehavior
{
use EvaluateAttributesTrait;

public $ensureUnique = true;

/**
* List of \yii\validators\UniqueValidator configurations to validate the uniqueness of a slug in multiple repositories.
* The value of `targetClass` property is ridden from the actual repository.
*
* ```php
* [
* PageActiveRepositoryInterface::class => ['targetAttribute' => 'slug', 'filter' => $this->owner && $this->owner->id ? ['NOT', ['id' => $this->owner->id]] : []],
* PageSlugActiveRepositoryInterface::class => ['targetAttribute' => 'slug', 'filter' => $this->owner && $this->owner->id ? ['page_id' => $this->owner->id] : []],
* ]
* ```
*
* @var array
*/
abstract protected function uniqueValidators();

protected function validateSlug($slug)
{
foreach ($this->uniqueValidators() as $repositoryInterface => $validator) {
$this->uniqueValidator = array_merge($validator, ['targetClass' => $this->getRepository($repositoryInterface)->getDataModelClass()]);
$isUnique = parent::validateSlug($slug);
if (!$isUnique) {
return false;
}
}

return true;
}
}

0 comments on commit cd8bbf0

Please sign in to comment.