Passed
Push — master ( 3dc8f7...93e8e1 )
by vistart
03:02
created

UserOrganizationTrait::getAtOrganizations()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 1
b 0
f 1
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link https://vistart.me/
9
 * @copyright Copyright (c) 2016 - 2017 vistart
10
 * @license https://vistart.me/license/
11
 */
12
13
namespace rhosocial\organization;
14
15
use rhosocial\organization\queries\MemberQuery;
16
use rhosocial\organization\queries\OrganizationQuery;
17
use Yii;
18
use yii\base\InvalidConfigException;
19
20
/**
21
 * @property string $guidAttribute GUID Attribute.
22
 * @property-read Member[] $ofMembers
23
 * @property-read Organization[] $atOrganizations
24
 *
25
 * @version 1.0
26
 * @author vistart <[email protected]>
27
 */
28
trait UserOrganizationTrait
29
{
30
    public $organizationClass = Organization::class;
31
    public $departmentClass = Department::class;
32
    public $memberClass = Member::class;
33
    private $noInitOrganization;
34
    private $noInitMember;
35
    public $lastSetUpOrganization;
36
    public $lastSetUpDepartment;
37
    /**
38
     * @return Organization
39
     */
40
    protected function getNoInitOrganization()
41
    {
42
        if (!$this->noInitOrganization) {
43
            $class = $this->organizationClass;
44
            $this->noInitOrganization = $class::buildNoInitModel();
45
        }
46
        return $this->noInitOrganization;
47
    }
48
    /**
49
     * @return Member
50
     */
51 6
    protected function getNoInitMember()
52
    {
53 6
        if (!$this->noInitMember) {
54 6
            $class = $this->memberClass;
55 6
            $this->noInitMember = $class::buildNoInitModel();
56
        }
57 6
        return $this->noInitMember;
58
    }
59
60
    /**
61
     * 
62
     * @return MemberQuery
63
     */
64 6
    public function getOfMembers()
65
    {
66 6
        return $this->hasMany($this->memberClass, [$this->getNoInitMember()->memberAttribute => $this->guidAttribute])->inverseOf('memberUser');
0 ignored issues
show
Bug introduced by
It seems like hasMany() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
67
    }
68
69
    /**
70
     * 
71
     * @return OrganizationQuery
72
     */
73 6
    public function getAtOrganizations()
74
    {
75 6
        return $this->hasMany($this->organizationClass, [$this->guidAttribute => $this->getNoInitMember()->createdByAttribute])->via('ofMembers');
0 ignored issues
show
Bug introduced by
It seems like hasMany() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
76
    }
77
78
    /**
79
     * Set up organization.
80
     * @param string $name
81
     * @param string $nickname
82
     * @param integer $gravatar_type
83
     * @param string $gravatar
84
     * @param string $timezone
85
     * @param string $description
86
     * @param BaseOrganization $parent
87
     * @return boolean Whether indicate the setting-up succeeded or not.
88
     */
89 6
    public function setUpOrganization($name, $nickname = '', $gravatar_type = 0, $gravatar = '', $timezone = 'UTC', $description = '', $parent = null)
0 ignored issues
show
Unused Code introduced by
The parameter $nickname is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $gravatar_type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $gravatar is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $timezone is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $description is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
90
    {
91 6
        $transaction = Yii::$app->db->beginTransaction();
92
        try {
93 6
            $models = $this->createOrganization($name, $nickname = '', $gravatar_type = 0, $gravatar = '', $timezone = 'UTC', $description = '');
94 6
            if (!array_key_exists(0, $models) || !($models[0] instanceof Organization)) {
95
                throw new InvalidConfigException('Invalid Organization Model.');
96
            }
97 6
            $result = $models[0]->register($models['associatedModels']);
98 6
            if ($result instanceof \Exception) {
99
                throw $result;
100
            }
101 6
            if ($result !== true) {
102
                throw new \Exception('Failed to set up.');
103
            }
104 6
            if ($parent instanceof BaseOrganization && !$parent->getIsNewRecord()) {
105
                $result = $models[0]->setParent($parent);
106
            }
107 6
            if ($result === false) {
108
                throw new \Exception('Failed to set parent.');
109
            }
110 6
            $transaction->commit();
111
        } catch (\Exception $ex) {
112
            $transaction->rollBack();
113
            Yii::error($ex->getMessage(), __METHOD__);
114
            return false;
115
        }
116 6
        $this->lastSetUpOrganization = $models[0];
117 6
        return true;
118
    }
119
120
    /**
121
     * 
122
     * @param BaseOrganization $parent
123
     * @param string $name
124
     * @param string $nickname
125
     * @param integer $gravatar_type
126
     * @param string $gravatar
127
     * @param string $timezone
128
     * @param string $description
129
     * @return boolean Whether indicate the setting-up succeeded or not.
130
     */
131
    public function setUpDepartment($parent, $name, $nickname = '', $gravatar_type = 0, $gravatar = '', $timezone = 'UTC', $description = '')
132
    {
133
        $transaction = Yii::$app->db->beginTransaction();
134
        try {
135
            $models = $this->createDepartment($name, $nickname, $gravatar_type, $gravatar, $timezone, $description);
136
            if (!array_key_exists(0, $models) || !($models[0] instanceof Department)) {
137
                throw new InvalidConfigException('Invalid Department Model.');
138
            }
139
            $result = $models[0]->register($models['associatedModels']);
140
            if ($result instanceof \Exception) {
141
                throw $result;
142
            }
143
            if ($result !== true) {
144
                throw new \Exception('Failed to set up.');
145
            }
146
            if ($parent instanceof BaseOrganization && !$parent->getIsNewRecord()) {
147
                $result = $models[0]->setParent($parent);
148
            }
149
            if ($result === false) {
150
                throw new \Exception('Failed to set parent.');
151
            }
152
            $transaction->commit();
153
        } catch (\Exception $ex) {
154
            $transaction->rollBack();
155
            Yii::error($ex->getMessage(), __METHOD__);
156
            return false;
157
        }
158
        $this->lastSetUpDepartment = $models[0];
159
        return true;
160
    }
161
162
    /**
163
     * Create organization.
164
     * @param string $name
165
     * @param string $nickname
166
     * @param string $gravatar_type
167
     * @param string $gravatar
168
     * @param string $timezone
169
     * @param string $description
170
     * @return Organization
171
     */
172 6
    public function createOrganization($name, $nickname = '', $gravatar_type = 0, $gravatar = '', $timezone = 'UTC', $description = '')
173
    {
174 6
        return $this->createBaseOrganization($name, $nickname, $gravatar_type, $gravatar, $timezone, $description);
175
    }
176
177
    /**
178
     * Create department.
179
     * @param string $name
180
     * @param string $nickname
181
     * @param integer $gravatar_type
182
     * @param string $gravatar
183
     * @param string $timezone
184
     * @param string $description
185
     * @return Department
186
     */
187
    public function createDepartment($name, $nickname = '', $gravatar_type = 0, $gravatar = '', $timezone = 'UTC', $description = '')
188
    {
189
        return $this->createBaseOrganization($name, $nickname, $gravatar_type, $gravatar, $timezone, $description, BaseOrganization::TYPE_DEPARTMENT);
190
    }
191
192
    /**
193
     * Create Base Organization.
194
     * @param string $name
195
     * @param string $nickname
196
     * @param integer $gravatar_type
197
     * @param string $gravatar
198
     * @param string $timezone
199
     * @param string $description
200
     * @param integer $type
201
     * @return array This array contains two elements, the first is `Organization` or `Department` depends on `$type`.
202
     * The other is `associatedModels` array, contains two elements `Profile`(profile) and `Creator`(creator).
203
     */
204 6
    protected function createBaseOrganization($name, $nickname = '', $gravatar_type = 0, $gravatar = '', $timezone = 'UTC', $description = '', $type = BaseOrganization::TYPE_ORGANIZATION)
205
    {
206 6
        $class = $this->organizationClass;
207 6
        if ($type == BaseOrganization::TYPE_DEPARTMENT) {
208
            $class = $this->departmentClass;
209
        }
210 6
        $organization = new $class();
211
        /* @var $organization BaseOrganization */
212
        $profileConfig = [
213 6
            'name' => $name,
214 6
            'nickname' => $nickname,
215 6
            'gravatar_type' => $gravatar_type,
216 6
            'gravatar' => $gravatar,
217 6
            'timezone' => $timezone,
218 6
            'description' => $description,
219
        ];
220 6
        $profile = $organization->createProfile($profileConfig);
221 6
        $member = $organization->createMemberModelWithUser($this);
222 6
        return [0 => $organization, 'associatedModels' => ['profile' => $profile, 'creator'=> $member]];
223
    }
224
}
225