| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335 |
- <?php
- /**
- * 重庆赤晓店信息科技有限公司
- * https://www.chixiaodian.com
- * Copyright (c) 2023 赤店商城 All rights reserved.
- */
- namespace app\librarys\shareTree\behaviors;
- use app\librarys\shareTree\exceptions\LogicException;
- use app\librarys\shareTree\models\AbstractTreePath;
- use Yii;
- use yii\base\Behavior;
- use yii\base\Component;
- use yii\base\InvalidConfigException;
- use yii\db\ActiveQuery;
- use yii\db\ActiveRecord;
- use yii\helpers\ArrayHelper;
- /**
- * @property ActiveRecord $owner
- */
- class ClosureTableBehavior extends Behavior
- {
- /** @var int 如果有子节点,默认删除类型不会删除元素 */
- public const DELETION_TYPE_0 = 0;
- /** @var int 移除元素,首先移动在元素的父节点下的子节点 */
- public const DELETION_TYPE_1 = 1;
- /** @var string 负责嵌套树的类的名称 */
- public $treePathModelClass;
- /** @var string 保存父类的字段名 */
- public $ownerParentIdAttribute = 'parent_id';
- /** @var int 元素删除类型 */
- public $deletionType = self::DELETION_TYPE_0;
- /** @var int|null old parent id */
- protected $oldParentId;
- /**
- * @inheritDoc
- *
- * @param Component $owner
- * @throws InvalidConfigException
- */
- public function attach($owner): void
- {
- if (empty($this->treePathModelClass) || !is_string($this->treePathModelClass)) {
- throw new InvalidConfigException('在ClosureTableBehavior中没有配置树路径表名');
- }
- parent::attach($owner);
- }
- /**
- * @inheritDoc
- */
- public function events(): array
- {
- return [
- ActiveRecord::EVENT_AFTER_INSERT => 'afterInsert',
- ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeUpdate',
- ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate',
- ActiveRecord::EVENT_BEFORE_DELETE => 'beforeDelete',
- ];
- }
- /**
- * 新增数据重新计算路径
- *
- * @throws InvalidConfigException
- */
- public function afterInsert(): void
- {
- if ($this->owner->getAttribute($this->ownerParentIdAttribute)) {
- $this->addTreePathOwnerToParents();
- }
- $this->addTreePathOwnerToOwner();
- }
- /**
- * 创建父子关系.
- *
- * @throws InvalidConfigException
- */
- protected function addTreePathOwnerToParents(): void
- {
- foreach ($this->getTreePathParents() as $treePath) {
- $this->saveTreePathModel(
- $treePath->parent_id,
- $this->owner->id,
- $this->owner->getAttribute($this->ownerParentIdAttribute),
- $treePath->parent_level,
- $treePath->child_level + 1
- );
- }
- }
- /**
- * 返回节点树路径关系
- *
- * @return array
- */
- protected function getTreePathParents(): array
- {
- $primaryKey = $this->owner->getAttribute($this->ownerParentIdAttribute);
- if ($primaryKey === 0) {
- return [];
- }
- return $this->treePathModelClass::find()
- ->byChildId($primaryKey)
- ->orderBy('child_level')
- ->all();
- }
- /**
- * 保存树路径
- *
- * @param int $parentId
- * @param int $childId
- * @param int|null $nearestParentId
- * @param int $parentLevel
- * @param int $childLevel
- * @return bool
- * @throws InvalidConfigException
- */
- protected function saveTreePathModel(
- int $parentId,
- int $childId,
- ?int $nearestParentId,
- ?int $parentLevel,
- int $childLevel
- ): bool {
- $model = $this->addTreePathModelObject();
- $model->parent_id = $parentId;
- $model->child_id = $childId;
- $model->nearest_parent_id = $nearestParentId;
- $model->parent_level = $parentLevel;
- $model->child_level = $childLevel;
- return $model->save();
- }
- /**
- * 创建树路径模型对象
- *
- * @return AbstractTreePath
- * @throws InvalidConfigException
- */
- protected function addTreePathModelObject(): AbstractTreePath
- {
- return Yii::createObject($this->treePathModelClass);
- }
- /**
- * 创建 owner-owner 关系.
- *
- * @throws InvalidConfigException
- */
- protected function addTreePathOwnerToOwner(): void
- {
- $parentLevel = $this->getParentLevel();
- $this->saveTreePathModel(
- $this->owner->id,
- $this->owner->id,
- $this->owner->getAttribute($this->ownerParentIdAttribute),
- $parentLevel + 1,
- $parentLevel + 1
- );
- }
- /**
- * 返回父级别
- *
- * @return int
- */
- protected function getParentLevel(): ?int
- {
- if (empty($this->owner->getAttribute($this->ownerParentIdAttribute))) {
- return 0;
- }
- return $this->treePathModelClass::find()
- ->select('parent_level')
- ->byParentId($this->owner->getAttribute($this->ownerParentIdAttribute))
- ->byChildId($this->owner->getAttribute($this->ownerParentIdAttribute))
- ->scalar();
- }
- /**
- * 更新之前验证
- *
- * @throws LogicException
- */
- public function beforeUpdate(): void
- {
- $this->oldParentId = $this->owner->oldAttributes[$this->ownerParentIdAttribute] ?? 0;
- if ($this->owner->getAttribute($this->ownerParentIdAttribute) !== 0) {
- if ($this->hasChilds()) {
- throw new LogicException('你不能把parent移动到child下边');
- }
- }
- }
- /**
- * 验证父节点下是否有子节点
- *
- * @return bool
- */
- private function hasChilds(): bool
- {
- return (bool)$this->treePathModelClass::find()
- ->byParentId($this->owner->id)
- ->byChildId($this->owner->getAttribute($this->ownerParentIdAttribute))
- ->count();
- }
- /**
- * 删除之前检查父节点
- *
- * @throws LogicException
- */
- public function beforeDelete(): void
- {
- switch ($this->deletionType) {
- case self::DELETION_TYPE_1:
- $this->deletionType1();
- break;
- case self::DELETION_TYPE_0:
- default:
- $this->deletionType0();
- break;
- }
- }
- /**
- * 如果有子节点,删除时不会删除当前节点
- */
- protected function deletionType0(): void
- {
- if ($this->childs()->count()) {
- throw new LogicException('你不能删除包含子集的元素');
- }
- $this->removeTreePathByIds($this->owner->id);
- }
- /**
- * 移除元素,首先移动在元素的父节点下的子节点
- */
- protected function deletionType1(): void
- {
- foreach ($this->childs(1)->all() as $child) {
- $child->setAttribute(
- $this->ownerParentIdAttribute,
- $this->owner->getAttribute($this->ownerParentIdAttribute)
- );
- $child->save();
- }
- $this->removeTreePathByIds($this->owner->id);
- }
- /**
- * 在更新父节点后更新树路径
- */
- public function afterUpdate(): void
- {
- if ($this->oldParentId != $this->owner->getAttribute($this->ownerParentIdAttribute)) {
- $this->rebuildTreePath();
- }
- }
- /**
- * 获取元素所有子节点
- *
- * @param bool|false $withParent
- * @param int|null $depth
- * @param bool|false $eagerLoading
- * @return ActiveQuery
- */
- public function childs(?int $depth = null, bool $withParent = false, bool $eagerLoading = false): ActiveQuery
- {
- return $this->owner::find()
- ->childs($this->owner->id, $withParent, $depth, $eagerLoading)
- ->orderBy(['treePathsChild.child_level' => SORT_ASC]);
- }
- /**
- * 添加树路径
- *
- * @throws InvalidConfigException
- */
- public function addTreePath(): void
- {
- $this->addTreePathOwnerToParents();
- $this->addTreePathOwnerToOwner();
- }
- /**
- * 重建树路径
- *
- * @throws InvalidConfigException
- */
- public function rebuildTreePath(): void
- {
- $childs = $this->childs()->all();
- $this->removeTreePathByIds($this->owner->id);
- $this->addTreePath();
- if ($childs) {
- $this->removeTreePathByIds(ArrayHelper::map($childs, 'id', 'id'));
- foreach ($childs as $child) {
- $child->addTreePath();
- }
- }
- }
- /**
- * 删除树路径 by ids
- */
- /**
- * @param array|int $ids
- */
- protected function removeTreePathByIds($ids): void
- {
- $this->treePathModelClass::deleteAll(
- [
- 'child_id' => $ids,
- ]
- );
- }
- }
|