akaunting/app/Traits/Relationships.php

71 lines
1.9 KiB
PHP
Raw Normal View History

2019-11-16 10:21:14 +03:00
<?php
namespace App\Traits;
use App\Events\Common\RelationshipCounting;
use App\Events\Common\RelationshipDeleting;
2019-11-16 10:21:14 +03:00
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Str;
2019-11-16 10:21:14 +03:00
trait Relationships
{
public function countRelationships($model, $relationships): array
2019-11-16 10:21:14 +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;
}
$text = Str::contains($text, '::') ? $text : 'general.' . $text;
$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
* @param $permanently
2019-11-16 10:21:14 +03:00
*/
public function deleteRelationships($model, $relationships, $permanently = false): void
2019-11-16 10:21:14 +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;
}
$items = [];
$relation = $model->$relationship;
2019-11-16 10:21:14 +03:00
if ($relation instanceof Collection) {
$items = $relation->all();
} else {
$items[] = $relation;
2019-11-16 10:21:14 +03:00
}
$function = $permanently ? 'forceDelete' : 'delete';
2019-11-16 10:21:14 +03:00
foreach ((array) $items as $item) {
$item->$function();
2019-11-16 10:21:14 +03:00
}
}
}
}