Completed
Push — master ( 93e8e1...4666a2 )
by vistart
03:17
created

UserOrganizationTrait::getAtDepartments()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
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\DepartmentQuery;
17
use rhosocial\organization\queries\OrganizationQuery;
18
use Yii;
19
use yii\base\InvalidConfigException;
20
use yii\base\InvalidParamException;
21
22
/**
23
 * @property string $guidAttribute GUID Attribute.
24
 * @property-read Member[] $ofMembers
25
 * @property-read Organization[] $atOrganizations
26
 *
27
 * @version 1.0
28
 * @author vistart <[email protected]>
29
 */
30
trait UserOrganizationTrait
31
{
32
    public $organizationClass = Organization::class;
33
    public $departmentClass = Department::class;
34
    public $memberClass = Member::class;
35
    private $noInitOrganization;
36
    private $noInitMember;
37
    public $lastSetUpOrganization;
38
    public $lastSetUpDepartment;
39
    /**
40
     * @return Organization
41
     */
42
    protected function getNoInitOrganization()
43
    {
44
        if (!$this->noInitOrganization) {
45
            $class = $this->organizationClass;
46
            $this->noInitOrganization = $class::buildNoInitModel();
47
        }
48
        return $this->noInitOrganization;
49
    }
50
    /**
51
     * @return Member
52
     */
53 6
    protected function getNoInitMember()
54
    {
55 6
        if (!$this->noInitMember) {
56 6
            $class = $this->memberClass;
57 6
            $this->noInitMember = $class::buildNoInitModel();
58
        }
59 6
        return $this->noInitMember;
60
    }
61
62
    /**
63
     * 
64
     * @return MemberQuery
65
     */
66 6
    public function getOfMembers()
67
    {
68 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...
69
    }
70
71
    /**
72
     * 
73
     * @return OrganizationQuery
74
     */
75 6
    public function getAtOrganizations()
76
    {
77 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...
78
    }
79
80
    /**
81
     * 
82
     * @return DepartmentQuery
83
     */
84
    public function getAtDepartments()
85
    {
86
        return $this->hasMany($this->departmentClass, [$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...
87
    }
88
89
    /**
90
     * Set up organization.
91
     * @param string $name
92
     * @param string $nickname
93
     * @param integer $gravatar_type
94
     * @param string $gravatar
95
     * @param string $timezone
96
     * @param string $description
97
     * @param BaseOrganization $parent
98
     * @return boolean Whether indicate the setting-up succeeded or not.
99
     */
100 7
    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...
101
    {
102 7
        $transaction = Yii::$app->db->beginTransaction();
103
        try {
104 7
            $models = $this->createOrganization($name, $nickname = '', $gravatar_type = 0, $gravatar = '', $timezone = 'UTC', $description = '');
105 7
            if (!array_key_exists(0, $models) || !($models[0] instanceof Organization)) {
106
                throw new InvalidConfigException('Invalid Organization Model.');
107
            }
108 7
            $result = $models[0]->register($models['associatedModels']);
109 7
            if ($result instanceof \Exception) {
110
                throw $result;
111
            }
112 7
            if ($result !== true) {
113
                throw new \Exception('Failed to set up.');
114
            }
115 7
            if ($parent instanceof BaseOrganization && !$parent->getIsNewRecord()) {
116
                $setParentResult = $models[0]->setParent($parent);
117
            }
118 7
            if (isset($setParentResult) && $setParentResult === false) {
119
                throw new \Exception('Failed to set parent.');
120
            }
121 7
            $transaction->commit();
122
        } catch (\Exception $ex) {
123
            $transaction->rollBack();
124
            Yii::error($ex->getMessage(), __METHOD__);
125
            return false;
126
        }
127 7
        $this->lastSetUpOrganization = $models[0];
128 7
        return true;
129
    }
130
131
    /**
132
     * 
133
     * @param BaseOrganization $parent
134
     * @param string $name
135
     * @param string $nickname
136
     * @param integer $gravatar_type
137
     * @param string $gravatar
138
     * @param string $timezone
139
     * @param string $description
140
     * @return boolean Whether indicate the setting-up succeeded or not.
141
     */
142 1
    public function setUpDepartment($parent, $name, $nickname = '', $gravatar_type = 0, $gravatar = '', $timezone = 'UTC', $description = '')
143
    {
144 1
        $transaction = Yii::$app->db->beginTransaction();
145
        try {
146 1
            $models = $this->createDepartment($name, $nickname, $gravatar_type, $gravatar, $timezone, $description);
147 1
            if (!array_key_exists(0, $models) || !($models[0] instanceof Department)) {
148
                throw new InvalidConfigException('Invalid Department Model.');
149
            }
150 1
            $result = $models[0]->register($models['associatedModels']);
151 1
            if ($result instanceof \Exception) {
152
                throw $result;
153
            }
154 1
            if ($result !== true) {
155
                throw new \Exception('Failed to set up.');
156
            }
157 1
            if ($parent instanceof BaseOrganization && !$parent->getIsNewRecord()) {
158 1
                $setParentResult = $models[0]->setParent($parent);
159
            } else {
160
                throw new InvalidParamException('Invalid Parent Parameter.');
161
            }
162 1
            if (isset($setParentResult) && $setParentResult === false) {
163
                throw new \Exception('Failed to set parent.');
164
            }
165 1
            $transaction->commit();
166
        } catch (\Exception $ex) {
167
            $transaction->rollBack();
168
            Yii::error($ex->getMessage(), __METHOD__);
169
            return false;
170
        }
171 1
        $this->lastSetUpDepartment = $models[0];
172 1
        return true;
173
    }
174
175
    /**
176
     * Create organization.
177
     * @param string $name
178
     * @param string $nickname
179
     * @param string $gravatar_type
180
     * @param string $gravatar
181
     * @param string $timezone
182
     * @param string $description
183
     * @return Organization
184
     */
185 7
    public function createOrganization($name, $nickname = '', $gravatar_type = 0, $gravatar = '', $timezone = 'UTC', $description = '')
186
    {
187 7
        return $this->createBaseOrganization($name, $nickname, $gravatar_type, $gravatar, $timezone, $description);
188
    }
189
190
    /**
191
     * Create department.
192
     * @param string $name
193
     * @param string $nickname
194
     * @param integer $gravatar_type
195
     * @param string $gravatar
196
     * @param string $timezone
197
     * @param string $description
198
     * @return Department
199
     */
200 1
    public function createDepartment($name, $nickname = '', $gravatar_type = 0, $gravatar = '', $timezone = 'UTC', $description = '')
201
    {
202 1
        return $this->createBaseOrganization($name, $nickname, $gravatar_type, $gravatar, $timezone, $description, BaseOrganization::TYPE_DEPARTMENT);
203
    }
204
205
    /**
206
     * Create Base Organization.
207
     * @param string $name
208
     * @param string $nickname
209
     * @param integer $gravatar_type
210
     * @param string $gravatar
211
     * @param string $timezone
212
     * @param string $description
213
     * @param integer $type
214
     * @return array This array contains two elements, the first is `Organization` or `Department` depends on `$type`.
215
     * The other is `associatedModels` array, contains two elements `Profile`(profile) and `Creator`(creator).
216
     */
217 7
    protected function createBaseOrganization($name, $nickname = '', $gravatar_type = 0, $gravatar = '', $timezone = 'UTC', $description = '', $type = BaseOrganization::TYPE_ORGANIZATION)
218
    {
219 7
        $class = $this->organizationClass;
220 7
        if ($type == BaseOrganization::TYPE_DEPARTMENT) {
221 1
            $class = $this->departmentClass;
222
        }
223 7
        $organization = new $class();
224
        /* @var $organization BaseOrganization */
225
        $profileConfig = [
226 7
            'name' => $name,
227 7
            'nickname' => $nickname,
228 7
            'gravatar_type' => $gravatar_type,
229 7
            'gravatar' => $gravatar,
230 7
            'timezone' => $timezone,
231 7
            'description' => $description,
232
        ];
233 7
        $profile = $organization->createProfile($profileConfig);
234 7
        $member = $organization->createMemberModelWithUser($this);
235 7
        return [0 => $organization, 'associatedModels' => ['profile' => $profile, 'creator'=> $member]];
236
    }
237
}
238