forked from factorenergia/yii2-ldap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathActiveRecord.php
285 lines (258 loc) · 9.95 KB
/
ActiveRecord.php
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
<?php
/**
* @link https://github.com/chrmorandi/yii2-ldap for the canonical source repository
* @package yii2-ldap
* @author Christopher Mota <[email protected]>
* @license MIT License - view the LICENSE file that was distributed with this source code.
*/
namespace websvc\ldap;
use websvc\ldap\ActiveQuery;
use websvc\ldap\Connection;
use Exception;
use Yii;
use yii\db\BaseActiveRecord;
/**
* ActiveRecord is the base class for classes representing relational data in terms of objects.
*
* This class implements the ActiveRecord pattern for the [ldap] protocol.
*
* For defining a record a subclass should at least implement the [[attributes()]] method to define
* attributes or use some prepared traits for specific objects. A primary key can be defined via [[primaryKey()]] which defaults to `cn` if not specified.
*
* The following is an example model called `User`:
*
* ```php
* class User extends \websvc\ldap\ActiveRecord
* {
* public function attributes()
* {
* return ['objectClass', 'cn', 'name'];
* }
* }
* ```
* Or
*
* ```php
* public function attributes() {
* return \websvc\ldap\schemas\ADUser::getAttributes();
* }
* ```
*
* @since 1.0.0
*/
class ActiveRecord extends BaseActiveRecord
{
/**
* Returns the LDAP connection used by this AR class.
*
* @return Connection the LDAP connection used by this AR class.
*/
public static function getDb()
{
return Yii::$app->get('ldap');
}
/**
* @inheritdoc
* @return ActiveQuery the newly created [[ActiveQuery]] instance.
*/
public static function find()
{
return Yii::createObject(ActiveQuery::class, [get_called_class()]);
}
/**
* Returns the primary key name(s) for this AR class.
* This method should be overridden by child classes to define the primary key.
*
* @return string[] the primary keys of this record.
*/
public static function primaryKey()
{
return ['dn'];
}
/**
* Returns the list of attribute names.
* You must override this method to define avaliable attributes.
* @return array list of attribute names.
*/
public function attributes()
{
throw new InvalidConfigException('The attributes() method of ldap ActiveRecord has to be implemented by child classes.');
}
/**
* Inserts a row into the associated database table using the attribute values of this record.
*
* This method performs the following steps in order:
*
* 1. call [[beforeValidate()]] when `$runValidation` is true. If [[beforeValidate()]]
* returns `false`, the rest of the steps will be skipped;
* 2. call [[afterValidate()]] when `$runValidation` is true. If validation
* failed, the rest of the steps will be skipped;
* 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
* the rest of the steps will be skipped;
* 4. insert the record into database. If this fails, it will skip the rest of the steps;
* 5. call [[afterSave()]];
*
* In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
* [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_INSERT]], and [[EVENT_AFTER_INSERT]]
* will be raised by the corresponding methods.
*
* Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.
*
* If the table's primary key is auto-incremental and is null during insertion,
* it will be populated with the actual value after insertion.
*
* For example, to insert a customer record:
*
* ```php
* $customer = new Customer;
* $customer->name = $name;
* $customer->email = $email;
* $customer->insert();
* ```
*
* @param boolean $runValidation whether to perform validation (calling [[validate()]])
* before saving the record. Defaults to `true`. If the validation fails, the record
* will not be saved to the database and this method will return `false`.
* @param string[]|null $attributes list of attributes that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved. meaning all attributes that are loaded from DB will be saved.
* meaning all attributes that are loaded from DB will be saved.
* @return boolean whether the attributes are valid and the record is inserted successfully.
* @throws Exception in case insert failed.
*/
public function insert($runValidation = true, $attributes = null)
{
if ($runValidation && !$this->validate($attributes)) {
Yii::info('Model not inserted due to validation error.', __METHOD__);
return false;
}
return $this->insertInternal($attributes);
}
/**
* Inserts an ActiveRecord into LDAP without.
*
* @param string[]|null $attributes list of attributes that need to be saved. Defaults to null,
* meaning all attributes that are loaded will be saved.
* @return boolean whether the record is inserted successfully.
*/
protected function insertInternal($attributes = null)
{
if (!$this->beforeSave(true)) {
return false;
}
$primaryKey = static::primaryKey();
$values = $this->getDirtyAttributes($attributes);
$dn = $values[$primaryKey[0]];
unset($values[$primaryKey[0]]);
static::getDb()->open();
if (static::getDb()->add($dn, $values) === false) {
return false;
}
$this->setAttribute($primaryKey[0], $dn);
$values[$primaryKey[0]] = $dn;
$changedAttributes = array_fill_keys(array_keys($values), null);
$this->setOldAttributes($values);
$this->afterSave(true, $changedAttributes);
static::getDb()->close();
return true;
}
/**
* @see update()
* @param array $attributes attributes to update
* @return integer number of rows updated
* @throws StaleObjectException
*/
protected function updateInternal($attributes = null)
{
if (!$this->beforeSave(false)) {
return false;
}
$values = $this->getDirtyAttributes($attributes);
if (empty($values)) {
$this->afterSave(false, $values);
return 0;
}
if(($condition = $this->getOldPrimaryKey(true)) !== $this->getPrimaryKey(true)) {
// TODO Change DN
// static::getDb()->rename($condition, $newRdn, $newParent, true);
// if (!$this->refresh()){
// Yii::info('Model not refresh.', __METHOD__);
// return false;
// }
}
foreach ($values as $key => $value) {
if($key == 'dn'){
continue;
}
if(empty ($this->getOldAttribute($key)) && $value === ''){
unset($values[$key]);
} else if($value === ''){
$attributes[] = ['attrib' => $key, 'modtype' => LDAP_MODIFY_BATCH_REMOVE];
} else if (empty ($this->getOldAttribute($key))) {
$attributes[] = ['attrib' => $key, 'modtype' => LDAP_MODIFY_BATCH_ADD, 'values' => is_array($value) ? $value : [$value]];
} else {
$attributes[] = ['attrib' => $key, 'modtype' => LDAP_MODIFY_BATCH_REPLACE, 'values' => is_array($value) ? $value : [$value]];
}
}
if (empty($attributes)) {
$this->afterSave(false, $attributes);
return 0;
}
// We do not check the return value of updateAll() because it's possible
// that the UPDATE statement doesn't change anything and thus returns 0.
$rows = static::updateAll($attributes, $condition);
// $changedAttributes = [];
// foreach ($values as $key => $value) {
// $changedAttributes[$key] = empty($this->getOldAttributes($key)) ? $this->getOldAttributes($key) : null;
// $this->setOldAttributes([$key=>$value]);
// }
// $this->afterSave(false, $changedAttributes);
return $rows;
}
/**
* Updates the whole table using the provided attribute values and conditions.
* For example, to change the status to be 1 for all customers whose status is 2:
*
* ```php
* Customer::updateAll(['status' => 1], 'status = 2');
* ```
*
* @param array $attributes attribute values (name-value pairs) to be saved into the table
* @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
* Please refer to [[Query::where()]] on how to specify this parameter.
* @return integer the number of rows updated
*/
public static function updateAll($attributes, $condition = '')
{
if(is_array($condition)){
$condition = $condition['dn'];
}
static::getDb()->open();
static::getDb()->modify($condition, $attributes);
static::getDb()->close();
return count($attributes);
}
/**
* Deletes rows in the table using the provided conditions.
* WARNING: If you do not specify any condition, this method will delete ALL rows in the ldap directory.
*
* For example, to delete all customers whose status is 3:
*
* ```php
* Customer::deleteAll('status = 3');
* ```
*
* @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
* Please refer to [[Query::where()]] on how to specify this parameter.
* @return integer the number of rows deleted
*/
public static function deleteAll($condition = '')
{
$entries = (new Query())->select(self::primaryKey())->where($condition)->execute()->toArray();
$count = 0;
foreach ($entries as $entry) {
$dn = $entry[self::primaryKey()[0]];
static::getDb()->delete($dn);
$count++;
}
return $count;
}
}