2019-11-16 10:21:14 +03:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Traits;
|
|
|
|
|
2021-07-08 10:33:43 +03:00
|
|
|
use App\Events\Common\RelationshipCounting;
|
|
|
|
use App\Events\Common\RelationshipDeleting;
|
2019-11-16 10:21:14 +03:00
|
|
|
use Illuminate\Database\Eloquent\Collection;
|
2021-01-26 12:44:12 +06:00
|
|
|
use Illuminate\Support\Str;
|
2019-11-16 10:21:14 +03:00
|
|
|
|
|
|
|
trait Relationships
|
|
|
|
{
|
2021-09-11 15:18:10 +03:00
|
|
|
public function countRelationships($model, $relationships): array
|
2019-11-16 10:21:14 +03:00
|
|
|
{
|
2021-07-08 10:33:43 +03:00
|
|
|
$record = new \stdClass();
|
|
|
|
$record->model = $model;
|
|
|
|
$record->relationships = $relationships;
|
|
|
|
|
|
|
|
event(new RelationshipCounting($record));
|
|
|
|
|
2019-11-16 10:21:14 +03:00
|
|
|
$counter = [];
|
|
|
|
|
2021-07-08 11:30:41 +03:00
|
|
|
foreach ((array) $record->relationships as $relationship => $text) {
|
2019-11-16 10:21:14 +03:00
|
|
|
if (!$c = $model->$relationship()->count()) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2021-01-26 12:44:12 +06:00
|
|
|
$text = Str::contains($text, '::') ? $text : 'general.' . $text;
|
2022-11-23 14:59:14 +03:00
|
|
|
$counter[] = (($c > 1) ? $c . ' ' : null ) . strtolower(trans_choice($text, ($c > 1) ? 2 : 1));
|
2019-11-16 10:21:14 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return $counter;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Mass delete relationships with events being fired.
|
|
|
|
*
|
|
|
|
* @param $model
|
|
|
|
* @param $relationships
|
2021-09-11 15:18:10 +03:00
|
|
|
* @param $permanently
|
2019-11-16 10:21:14 +03:00
|
|
|
*/
|
2021-09-11 15:18:10 +03:00
|
|
|
public function deleteRelationships($model, $relationships, $permanently = false): void
|
2019-11-16 10:21:14 +03:00
|
|
|
{
|
2021-07-08 10:33:43 +03:00
|
|
|
$record = new \stdClass();
|
|
|
|
$record->model = $model;
|
|
|
|
$record->relationships = $relationships;
|
|
|
|
|
|
|
|
event(new RelationshipDeleting($record));
|
|
|
|
|
2021-07-08 11:30:41 +03:00
|
|
|
foreach ((array) $record->relationships as $relationship) {
|
2019-11-16 10:21:14 +03:00
|
|
|
if (empty($model->$relationship)) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2021-04-02 13:34:34 +03:00
|
|
|
$items = [];
|
|
|
|
$relation = $model->$relationship;
|
2019-11-16 10:21:14 +03:00
|
|
|
|
2021-04-02 13:34:34 +03:00
|
|
|
if ($relation instanceof Collection) {
|
|
|
|
$items = $relation->all();
|
|
|
|
} else {
|
|
|
|
$items[] = $relation;
|
2019-11-16 10:21:14 +03:00
|
|
|
}
|
|
|
|
|
2021-09-11 15:18:10 +03:00
|
|
|
$function = $permanently ? 'forceDelete' : 'delete';
|
|
|
|
|
2019-11-16 10:21:14 +03:00
|
|
|
foreach ((array) $items as $item) {
|
2021-09-11 15:18:10 +03:00
|
|
|
$item->$function();
|
2019-11-16 10:21:14 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|