<?php
    
    namespace backend\behaviors;
    
    use yii\base\Behavior;
    use yii\db\ActiveRecord;
    
    /**
     * Class LevelBehavior
     *
     * @package artbox\catalog\behaviors
     */
    class LevelBehavior extends Behavior
    {
        public $levelField = 'level';
        
        public $parentIdField = 'parent_id';
        
        /**
         * @inheritdoc
         */
        public function events()
        {
            return [
                ActiveRecord::EVENT_BEFORE_INSERT => 'beforeSave',
                ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeSave',
            ];
        }
        
        public function beforeSave($event)
        {
            /**
             * @var ActiveRecord $owner
             */
            $levelField = $this->levelField;
            $parentIdField = $this->parentIdField;
            $owner = $this->owner;
            
            if (empty($owner->$parentIdField) && $owner->$parentIdField == 0) {
                $owner->$levelField = 0;
            } else {
                $parent = $owner::findOne($owner->$parentIdField);
                $owner->$levelField = (int) $parent->$levelField + 1;
            }
            
        }
    }