Issues (36)

src/MyAssignModel.php (2 issues)

1
<?php
2
namespace andmemasin\myabstract;
3
4
use Yii;
5
6
/**
7
 * This is a base class for models that bind/assign child models to
8
 * parent models. Typically named as ParentHasChild pattern
9
 * @property bool $isAlreadyAssigned whether there is already a model with this parent-child relation
10
 */
11
class MyAssignModel extends MyActiveRecord
12
{
13
14
    /* @var $parentIdColumnName string Column name containing parent id FK */
0 ignored issues
show
Documentation Bug introduced by
The doc comment $parentIdColumnName at position 0 could not be parsed: Unknown type name '$parentIdColumnName' at position 0 in $parentIdColumnName.
Loading history...
15
    public $parentIdColumnName;
16
17
    /* @var $childIdColumnName string Column name containing child id FK */
0 ignored issues
show
Documentation Bug introduced by
The doc comment $childIdColumnName at position 0 could not be parsed: Unknown type name '$childIdColumnName' at position 0 in $childIdColumnName.
Loading history...
18
    public $childIdColumnName;
19
20
    public function rules()
21
    {
22
        return array_merge(parent::rules(), [
23
            [[$this->parentIdColumnName, $this->childIdColumnName], 'required'],
24
            [$this->childIdColumnName, function($attribute) {
25
                if ($this->isAlreadyAssigned) {
26
                    $this->addError($attribute, Yii::t('app', "Can only be used once!"));
27
                }
28
            }],
29
        ]);
30
    }
31
32
    /**
33
     * @param MyActiveRecord $parent
34
     * @param MyActiveRecord $child
35
     * @return void
36
     */
37
    public function assign($parent, $child)
38
    {
39
        $this->{$this->parentIdColumnName} = $parent->primaryKey;
40
        $this->{$this->childIdColumnName} = $child->primaryKey;
41
        return null;
42
    }
43
44
    /**
45
     * @return bool
46
     */
47
    public function getIsAlreadyAssigned() {
48
        if ($this->isNewRecord) {
49
            $model = static::find()
50
                ->andWhere([$this->parentIdColumnName => $this->{$this->parentIdColumnName}])
51
                ->andWhere([$this->childIdColumnName => $this->{$this->childIdColumnName}])
52
                ->all();
53
            return !empty($model);
54
        }
55
        return false;
56
    }
57
58
}