forked from doppar/framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInteractsWithModelQueryProcessing.php
More file actions
603 lines (500 loc) · 16.1 KB
/
InteractsWithModelQueryProcessing.php
File metadata and controls
603 lines (500 loc) · 16.1 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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
<?php
namespace Phaseolies\Database\Entity\Query;
use Phaseolies\Utilities\Casts\CastToDate;
use Phaseolies\Support\Collection;
use Phaseolies\Database\Entity\Model;
use Phaseolies\Database\Entity\Builder;
use Phaseolies\Database\Database;
trait InteractsWithModelQueryProcessing
{
/**
* @var bool
*/
protected static bool $isHookShouldBeCalled = true;
/**
* Creates and returns a new query builder instance for the model.
*
* @param $connection = 'mysql'
* @return \Phaseolies\Database\Entity\Builder
*/
public static function query(?string $connection = null): Builder
{
$model = new static();
$connection = $connection ?? $model->connection;
return new Builder(
Database::getPdoInstance($connection),
$model->getTable(),
static::class,
$model->pageSize
);
}
/**
* Disable the execution of model hooks for the current instance.
*
* @return \Phaseolies\Database\Entity\Builder
*/
public static function withoutHook(): Builder
{
self::$isHookShouldBeCalled = false;
return static::query();
}
/**
* Retrieves all records from the model's table.
*
* @return Collection
*/
public static function all(): Collection
{
return static::query()->get();
}
/**
* Alias for the `all` method. Retrieves all records from the model's table.
*
* @return Collection
*/
public static function get(): Collection
{
return static::all();
}
/**
* Finds a model record by its primary key.
*
* @param string|array $primaryKey
* @return mixed
*/
public static function find(string|int|array $primaryKey)
{
$query = static::query();
$key = (new static())->getKeyName();
if (is_array($primaryKey)) {
$models = $query->whereIn($key, $primaryKey)->get();
foreach ($models as $model) {
$model->originalAttributes = $model->attributes;
}
return $models;
}
$model = $query->where($key, $primaryKey)->first();
if ($model) {
$model->originalAttributes = $model->attributes;
}
return $model;
}
/**
* Returns the total number of records in the model's table.
*
* @return int
*/
public static function count(): int
{
return static::query()->count();
}
/**
* Pluck an array of values from a single column.
*
* @param string $value
* @param string|null $key
* @return Collection
*/
public function pluck(string $value, ?string $key = null): Collection
{
$results = [];
foreach ($this->get() as $item) {
$itemValue = $item->{$value} ?? null;
if (is_null($key)) {
$results[] = $itemValue;
} else {
$itemKey = $item->{$key} ?? null;
if (!is_null($itemKey)) {
$results[$itemKey] = $itemValue;
} else {
$results[] = $itemValue;
}
}
}
return new Collection($this->modelClass, $results);
}
/**
* Converts the model's attributes to a JSON string.
*
* @param int $options
* @return string
* @throws \Exception
*/
public function toJson($options = 0): string
{
try {
$json = json_encode($this->toArray(), $options | JSON_THROW_ON_ERROR);
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
return $json;
}
/**
* Save the model to the database.
*
* @return bool
*/
public function save(): bool
{
static $attributeCache = [];
$class = static::class;
if (!array_key_exists($class, $attributeCache)) {
$attributeCache[$class] = $this->propertyHasAttribute(new static(), 'timeStamps', CastToDate::class);
}
$dateTime = $attributeCache[$class] ? now()->startOfDay() : now();
try {
$isUpdatable = isset($this->attributes[$this->primaryKey]);
if ($isUpdatable) {
if (self::$isHookShouldBeCalled && $this->fireBeforeHooks('updated') === false) {
return false;
}
$dirtyAttributes = $this->getDirtyAttributes();
if (!empty($this->creatable)) {
$dirtyAttributes = array_intersect_key($dirtyAttributes, array_flip($this->creatable));
}
if (empty($dirtyAttributes)) {
return true;
}
if ($this->timeStamps) {
$dirtyAttributes['updated_at'] = $dateTime;
}
$response = $this->query()
->where($this->primaryKey, $this->attributes[$this->primaryKey])
->update($dirtyAttributes);
if (self::$isHookShouldBeCalled && $response) {
$this->fireAfterHooks('updated');
$this->originalAttributes = $this->attributes;
}
return $response;
}
if (self::$isHookShouldBeCalled && $this->fireBeforeHooks('created') === false) {
return false;
}
$attributes = $this->getCreatableAttributes();
if ($this->timeStamps) {
$attributes['created_at'] = $dateTime;
$attributes['updated_at'] = $dateTime;
}
$id = $this->query()->insert($attributes);
if ($id && self::$isHookShouldBeCalled) {
$this->fireAfterHooks('created');
}
if ($id) {
$this->attributes[$this->primaryKey] = $id;
return true;
}
return false;
} finally {
self::$isHookShouldBeCalled = true;
}
}
/**
* Get model dirty attributes
*
* @return array
*/
public function getDirtyAttributes(): array
{
$dirty = [];
foreach ($this->attributes as $key => $value) {
if (
!array_key_exists($key, $this->originalAttributes) ||
!$this->valuesAreEqual($this->originalAttributes[$key], $value)
) {
$dirty[$key] = $value;
}
}
return $dirty;
}
/**
* Compare original and current values for equality, treating nulls as equal
*
* @param mixed $original
* @param mixed $current
* @return bool
*/
protected function valuesAreEqual(mixed $original, mixed $current): bool
{
if ($original === null && $current === null) return true;
if ($original === null || $current === null) return false;
return (string)$original === (string)$current;
}
/**
* Insert multiple records into the database
*
* @param array $rows
* @return int
*/
public static function saveMany(array $rows, int $chunkSize = 100): int
{
$model = new static();
$usesTimestamps = $model->timeStamps;
$hasCastToDate = $usesTimestamps
? (new static())->propertyHasAttribute(new static(), 'timeStamps', CastToDate::class)
: false;
$dateTime = $hasCastToDate ? now()->startOfDay() : now();
$filteredRows = array_map(function ($row) use ($model, $usesTimestamps, $dateTime) {
$creatable = $model->creatable;
if (empty($creatable)) {
$creatable = array_keys($row);
if (($key = array_search($model->primaryKey, $creatable)) !== false) {
unset($creatable[$key]);
}
}
$filtered = array_intersect_key($row, array_flip($creatable));
if ($usesTimestamps) {
$filtered['created_at'] = $filtered['created_at'] ?? $dateTime;
$filtered['updated_at'] = $dateTime;
}
return $filtered;
}, $rows);
return static::query()->insertMany($filteredRows, $chunkSize);
}
/**
* Update an existing record or create a new one if it doesn't exist.
*
* @param array $attributes
* @param array $values
* @return Model
*/
public static function updateOrCreate(array $attributes, array $values = []): Model
{
$query = static::query();
foreach ($attributes as $field => $value) {
$query->where($field, $value);
}
$model = $query->first();
if ($model) {
$model->fill($values);
$model->save();
} else {
$model = static::create(array_merge($attributes, $values));
}
return $model;
}
/**
* Retrieve the first model matching the attributes, or create it if not found.
*
* @param array $attributes
* @param array $values
* @return Model
*/
public static function firstOrCreate(array $attributes, array $values = []): Model
{
$query = static::query();
foreach ($attributes as $field => $value) {
$query->where($field, $value);
}
$model = $query->first();
if (! $model) {
$model = static::create(array_merge($attributes, $values));
}
return $model;
}
/**
* Update an existing record or ignore
*
* @param array $attributes
* @param array $values
* @return Model|null
*/
public static function updateOrIgnore(array $attributes, array $values = []): ?Model
{
$query = static::query();
foreach ($attributes as $field => $value) {
$query->where($field, $value);
}
$model = $query->first();
if ($model) {
$model->fill($values);
$model->save();
}
return $model;
}
/**
* Create a new model instance and save it to the database.
*
* @param array $attributes
* @return static
*/
public static function create(array $attributes): static
{
$model = new static();
$model->fill($attributes);
$model->save();
return $model;
}
/**
* Create a new model instance from another model and save it to the database.
*
* @param Model $model
* @return static
*/
public static function createFromModel(Model $model): static
{
return self::create($model->getAttributes());
}
/**
* Get the attributes that are allowed to be mass-assigned.
*
* @return array
*/
protected function getCreatableAttributes(): array
{
if (empty($this->creatable)) {
throw new \RuntimeException(
"Model " . static::class . " has no \$creatable attributes defined."
);
}
$creatableAttributes = [];
foreach ($this->creatable as $attribute) {
if (isset($this->attributes[$attribute])) {
$creatableAttributes[$attribute] = $this->attributes[$attribute];
}
}
return $creatableAttributes;
}
/**
* Filter models based on dynamic conditions
*
* @param array|callable $filters
* @return \Phaseolies\Database\Entity\Builder
*/
public static function match(array|callable $filters): Builder
{
$query = static::query();
if (is_callable($filters)) {
$filters($query);
} else {
foreach ($filters as $field => $value) {
if (is_array($value)) {
$query->whereIn($field, $value);
} elseif ($value === null) {
$query->whereNull($field);
} elseif ($value instanceof \Closure) {
$value($query);
} else {
$query->where($field, $value);
}
}
}
return $query;
}
/**
* Update the model in the database.
*
* @param array $attributes
* @return bool
*/
public function update(array $attributes): bool
{
if (!isset($this->attributes[$this->primaryKey])) {
return false;
}
foreach ($attributes as $key => $value) {
$this->setAttribute($key, $value);
}
if (self::$isHookShouldBeCalled && $this->fireBeforeHooks('updated') === false) {
return false;
}
$dirty = $this->getDirtyAttributes();
if (empty($dirty)) {
return true;
}
if (!empty($this->creatable)) {
$dirty = array_intersect_key($dirty, array_flip($this->creatable));
}
if ($this->usesTimestamps()) {
$hasCastToDate = $this->propertyHasAttribute(static::class, 'timeStamps', CastToDate::class);
$dirty['updated_at'] = $hasCastToDate
? now()->startOfDay()
: now();
}
try {
$result = static::query()
->where($this->primaryKey, $this->attributes[$this->primaryKey])
->update($dirty);
if ($result) {
if (self::$isHookShouldBeCalled) {
$this->fireAfterHooks('updated');
}
$this->originalAttributes = $this->attributes;
}
} finally {
self::$isHookShouldBeCalled = true;
}
return $result;
}
/**
* Accesses a private or protected property of a class using reflection.
*
* @param string $class
* @param string $attribute
* @return mixed
* @throws \Exception
*/
protected function getClassProperty(string $class, string $attribute): mixed
{
$reflection = new \ReflectionClass($class);
if ($reflection->hasProperty($attribute)) {
$property = $reflection->getProperty($attribute);
$property->setAccessible(true);
return $property->isStatic()
? $property->getValue()
: $property->getValue(new $this->modelClass());
}
throw new \Exception("Property '{$attribute}' does not exist in class '{$class}'.");
}
/**
* Checks whether a class property has a specific attribute.
*
* @param object|string $class
* @param string $attribute
* @param string $attributeClass
* @return bool
* @throws \Exception
*/
protected function propertyHasAttribute(object|string $class, string $attribute, string $attributeClass): bool
{
$reflection = new \ReflectionClass($class);
if (! $reflection->hasProperty($attribute)) {
throw new \Exception("Property '{$attribute}' does not exist in class '{$class}'.");
}
$property = $reflection->getProperty($attribute);
$attributes = $property->getAttributes($attributeClass);
return !empty($attributes);
}
/**
* Handle dynamic static method calls into the model.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public static function __callStatic($method, $parameters)
{
if (method_exists(static::class, $bindMethod = '__' . $method)) {
return (new static())->$bindMethod(static::query(), ...$parameters);
}
return static::query()->$method(...$parameters);
}
/**
* Create a copy of the model instance without the primary key
*
* @param array|null $except
* @return static
*/
public function fork(?array $except = null): static
{
$defaults = [$this->primaryKey];
$except = array_merge($defaults, (array) $except);
$attributes = array_diff_key($this->attributes, array_flip($except));
$replica = new static();
$replica->fill($attributes);
foreach ($this->relations as $key => $relation) {
$replica->setRelation($key, $relation);
}
$replica->originalAttributes = array_diff_key($this->originalAttributes, array_flip($except));
return $replica;
}
}