ManyToManyBehavior.php 14.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
<?php
namespace voskobovich\behaviors;
use Yii;
use yii\base\Behavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\base\ErrorException;
use yii\db\Exception;
use yii\helpers\ArrayHelper;
/**
 * Class ManyToManyBehavior
 * @package voskobovich\behaviors
 *
 * See README.md for examples
 */
class ManyToManyBehavior extends Behavior
{
    /**
     * Stores a list of relations, affected by the behavior. Configurable property.
     * @var array
     */
    public $relations = [];
    /**
     * Stores values of relation attributes. All entries in this array are considered
     * dirty (changed) attributes and will be saved in saveRelations().
     * @var array
     */
    private $_values = [];
    /**
     * Used to store fields that this behavior creates. Each field refers to a relation
     * and has optional getters and setters.
     * @var array
     */
    private $_fields = [];
    /**
     * Events list
     * @return array
     */
    public function events()
    {
        return [
            ActiveRecord::EVENT_AFTER_INSERT => 'saveRelations',
            ActiveRecord::EVENT_AFTER_UPDATE => 'saveRelations',
        ];
    }
    /**
     * Invokes init of parent class and assigns proper values to internal _fields variable
     */
    public function init()
    {
        parent::init();
        //configure _fields
        foreach ($this->relations as $attributeName => $params) {
            //add primary field
            $this->_fields[$attributeName] = [
                'attribute' => $attributeName,
            ];
            if (isset($params['get'])) {
                $this->_fields[$attributeName]['get'] = $params['get'];
            }
            if (isset($params['set'])) {
                $this->_fields[$attributeName]['set'] = $params['set'];
            }
            // Add secondary fields
            if (isset($params['fields'])) {
                foreach ($params['fields'] as $fieldName => $adjustments) {
                    $fullFieldName = $attributeName.'_'.$fieldName;
                    if (isset($this->_fields[$fullFieldName])) {
                        throw new ErrorException("Ambiguous field name definition: {$fullFieldName}");
                    }
                    $this->_fields[$fullFieldName] = [
                        'attribute' => $attributeName,
                    ];
                    if (isset($adjustments['get'])) {
                        $this->_fields[$fullFieldName]['get'] = $adjustments['get'];
                    }
                    if (isset($adjustments['set'])) {
                        $this->_fields[$fullFieldName]['set'] = $adjustments['set'];
                    }
                }
            }
        }
    }
    /**
     * Save all dirty (changed) relation values ($this->_values) to the database
     * @throws ErrorException
     * @throws Exception
     */
    public function saveRelations()
    {
        /** @var ActiveRecord $primaryModel */
        $primaryModel = $this->owner;
        if (is_array($primaryModelPk = $primaryModel->getPrimaryKey())) {
            throw new ErrorException('This behavior does not support composite primary keys');
        }
        foreach ($this->relations as $attributeName => $params) {
            $relationName = $this->getRelationName($attributeName);
            $relation = $primaryModel->getRelation($relationName);
            if (!$this->hasNewValue($attributeName)) {
                continue;
            }
            if (!empty($relation->via) && $relation->multiple) {
                // Many-to-many
                $this->saveManyToManyRelation($relation, $attributeName);
            } elseif (!empty($relation->link) && $relation->multiple) {
                // One-to-many on the many side
                $this->saveOneToManyRelation($relation, $attributeName);
            } else {
                throw new ErrorException('Relationship type not supported.');
            }
        }
    }
    /**
     * @param ActiveQuery $relation
     * @param string $attributeName
     * @throws Exception
     */
    private function saveManyToManyRelation($relation, $attributeName)
    {
        /** @var ActiveRecord $primaryModel */
        $primaryModel = $this->owner;
        $primaryModelPk = $primaryModel->getPrimaryKey();
        $bindingKeys = $this->getNewValue($attributeName);
        // Assuming junction column is visible from the primary model connection
        if (is_array($relation->via)) {
            // via()
            $via = $relation->via[1];
            /** @var ActiveRecord $junctionModelClass */
            $junctionModelClass = $via->modelClass;
            $junctionTable = $junctionModelClass::tableName();
            list($junctionColumn) = array_keys($via->link);
        } else {
            // viaTable()
            list($junctionTable) = array_values($relation->via->from);
            list($junctionColumn) = array_keys($relation->via->link);
        }
        list($relatedColumn) = array_values($relation->link);
        $connection = $primaryModel::getDb();
        $transaction = $connection->beginTransaction();
        try {
            // Remove old relations
            $connection->createCommand()
                ->delete($junctionTable, ArrayHelper::merge(
                    [$junctionColumn => $primaryModelPk],
                    $this->getCustomDeleteCondition($attributeName)
                ))
                ->execute();
            // Write new relations
            if (!empty($bindingKeys)) {
                $junctionRows = [];
                $viaTableParams = $this->getViaTableParams($attributeName);
                foreach ($bindingKeys as $relatedPk) {
                    $row = [$primaryModelPk, $relatedPk];
                    // Calculate additional viaTable values
                    foreach (array_keys($viaTableParams) as $viaTableColumn) {
                        $row[] = $this->getViaTableValue($attributeName, $viaTableColumn, $relatedPk);
                    }
                    array_push($junctionRows, $row);
                }
                $cols = [$junctionColumn, $relatedColumn];
                // Additional viaTable columns
                foreach (array_keys($viaTableParams) as $viaTableColumn) {
                    $cols[] = $viaTableColumn;
                }
                $connection->createCommand()
                    ->batchInsert($junctionTable, $cols, $junctionRows)
                    ->execute();
            }
            $transaction->commit();
        } catch (Exception $ex) {
            $transaction->rollback();
            throw $ex;
        }
    }
    /**
     * @param ActiveQuery $relation
     * @param string $attributeName
     * @throws Exception
     */
    private function saveOneToManyRelation($relation, $attributeName)
    {
        /** @var ActiveRecord $primaryModel */
        $primaryModel = $this->owner;
        $primaryModelPk = $primaryModel->getPrimaryKey();
        $bindingKeys = $this->getNewValue($attributeName);
        // HasMany, primary model HAS MANY foreign models, must update foreign model table
        /** @var ActiveRecord $foreignModel */
        $foreignModel = new $relation->modelClass();
        $manyTable = $foreignModel->tableName();
        list($manyTableFkColumn) = array_keys($relation->link);
        $manyTableFkValue = $primaryModelPk;
        list($manyTablePkColumn) = ($foreignModel->primaryKey());
        $connection = $foreignModel::getDb();
        $transaction = $connection->beginTransaction();
        $defaultValue = $this->getDefaultValue($attributeName);
        try {
            // Remove old relations
            $connection->createCommand()
                ->update(
                    $manyTable,
                    [$manyTableFkColumn => $defaultValue],
                    [$manyTableFkColumn => $manyTableFkValue])
                ->execute();
            // Write new relations
            if (!empty($bindingKeys)) {
                $connection->createCommand()
                    ->update(
                        $manyTable,
                        [$manyTableFkColumn => $manyTableFkValue],
                        ['in', $manyTablePkColumn, $bindingKeys])
                    ->execute();
            }
            $transaction->commit();
        } catch (Exception $ex) {
            $transaction->rollback();
            throw $ex;
        }
    }
    /**
     * Call user function
     * @param $function
     * @param $value
     * @return mixed
     * @throws ErrorException
     */
    private function callUserFunction($function, $value)
    {
        if (!is_array($function) && !$function instanceof \Closure) {
            throw new ErrorException('This value is not a function');
        }
        return call_user_func($function, $value);
    }
    /**
     * Check if an attribute is dirty and must be saved (its new value exists)
     * @param string $attributeName
     * @return null
     */
    private function hasNewValue($attributeName)
    {
        return isset($this->_values[$attributeName]);
    }
    /**
     * Get value of a dirty attribute by name
     * @param string $attributeName
     * @return null
     */
    private function getNewValue($attributeName)
    {
        return $this->_values[$attributeName];
    }
    /**
     * Get default value for an attribute (used for 1-N relations)
     * @param string $attributeName
     * @return mixed
     */
    private function getDefaultValue($attributeName)
    {
        $relationParams = $this->getRelationParams($attributeName);
        if (!isset($relationParams['default'])) {
            return null;
        }
        if ($relationParams['default'] instanceof \Closure) {
            $closure = $relationParams['default'];
            $relationName = $this->getRelationName($attributeName);
            return call_user_func($closure, $this->owner, $relationName, $attributeName);
        }
        return $relationParams['default'];
    }
    /**
     * Calculate additional value of viaTable
     * @param string $attributeName
     * @param string $viaTableAttribute
     * @param integer $relatedPk
     * @return mixed
     */
    private function getViaTableValue($attributeName, $viaTableAttribute, $relatedPk)
    {
        $viaTableParams = $this->getViaTableParams($attributeName);
        if (!isset($viaTableParams[$viaTableAttribute])) {
            return null;
        }
        if ($viaTableParams[$viaTableAttribute] instanceof \Closure) {
            $closure = $viaTableParams[$viaTableAttribute];
            $relationName = $this->getRelationName($attributeName);
            return call_user_func($closure, $this->owner, $relationName, $attributeName, $relatedPk);
        }
        return $viaTableParams[$viaTableAttribute];
    }
    /**
     * Get additional parameters of viaTable
     * @param string $attributeName
     * @return array
     */
    private function getViaTableParams($attributeName)
    {
        $params = $this->getRelationParams($attributeName);
        return isset($params['viaTableValues'])
            ? $params['viaTableValues']
            : [];
    }
    /**
     * Get custom condition used to delete old records.
     * @param string $attributeName
     * @return array
     */
    private function getCustomDeleteCondition($attributeName)
    {
        $params = $this->getRelationParams($attributeName);
        return isset($params['customDeleteCondition'])
            ? $params['customDeleteCondition']
            : [];
    }
    /**
     * Get parameters of a field
     * @param string $fieldName
     * @return mixed
     * @throws ErrorException
     */
    private function getFieldParams($fieldName)
    {
        if (empty($this->_fields[$fieldName])) {
            throw new ErrorException('Parameter "' . $fieldName . '" does not exist');
        }
        return $this->_fields[$fieldName];
    }
    /**
     * Get parameters of a relation
     * @param string $attributeName
     * @return mixed
     * @throws ErrorException
     */
    private function getRelationParams($attributeName)
    {
        if (empty($this->relations[$attributeName])) {
            throw new ErrorException('Parameter "' . $attributeName . '" does not exist.');
        }
        return $this->relations[$attributeName];
    }
    /**
     * Get name of a relation
     * @param string $attributeName
     * @return null
     */
    private function getRelationName($attributeName)
    {
        $params = $this->getRelationParams($attributeName);
        if (is_string($params)) {
            return $params;
        }
        if (is_array($params) && !empty($params[0])) {
            return $params[0];
        }
        return null;
    }
    /**
     * @inheritdoc
     */
    public function canGetProperty($name, $checkVars = true)
    {
        return array_key_exists($name, $this->_fields) ?
            true : parent::canGetProperty($name, $checkVars);
    }
    /**
     * @inheritdoc
     */
    public function canSetProperty($name, $checkVars = true)
    {
        return array_key_exists($name, $this->_fields) ?
            true : parent::canSetProperty($name, $checkVars = true);
    }
    /**
     * @inheritdoc
     */
    public function __get($name)
    {
        $fieldParams = $this->getFieldParams($name);
        $attributeName = $fieldParams['attribute'];
        $relationName = $this->getRelationName($attributeName);
        if ($this->hasNewValue($attributeName)) {
            $value = $this->getNewValue($attributeName);
        } else {
            /** @var ActiveRecord $owner */
            $owner = $this->owner;
            $relation = $owner->getRelation($relationName);
            /** @var ActiveRecord $foreignModel */
            $foreignModel = new $relation->modelClass();
            $value = $relation->select($foreignModel->getPrimaryKey())->column();
        }
        if (empty($fieldParams['get'])) {
            return $value;
        }
        return $this->callUserFunction($fieldParams['get'], $value);
    }
    /**
     * @inheritdoc
     */
    public function __set($name, $value)
    {
        $fieldParams = $this->getFieldParams($name);
        $attributeName = $fieldParams['attribute'];
        if (!empty($fieldParams['set'])) {
            $this->_values[$attributeName] = $this->callUserFunction($fieldParams['set'], $value);
        } else {
            $this->_values[$attributeName] = $value;
        }
    }
}