PersistenceService   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 15
c 2
b 0
f 0
dl 0
loc 49
ccs 17
cts 17
cp 1
rs 10
wmc 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A persist() 0 4 1
A persistRecursive() 0 15 1
A getPersistenceStrategy() 0 6 1
1
<?php
2
3
namespace Anfischer\Cloner;
4
5
use Anfischer\Cloner\Exceptions\NoCompatiblePersistenceStrategyFound;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Eloquent\Relations\Pivot;
8
use Illuminate\Support\Collection;
9
use ReflectionObject;
10
11
class PersistenceService implements PersistenceServiceInterface
12
{
13
    /**
14
     * Persists a model and its relationships
15
     *
16
     * @param Model $model
17
     * @return Model
18
     */
19 20
    public function persist(Model $model) : Model
20
    {
21 20
        $model->save();
22 20
        return $this->persistRecursive($model);
23
    }
24
25
    /**
26
     * Recursively persists a model and its relationships
27
     *
28
     * @param $parent
29
     * @return mixed
30
     */
31 20
    private function persistRecursive($parent)
32
    {
33 20
        Collection::wrap($parent)->each(function ($model) {
34 20
            Collection::wrap($model->getRelations())->filter(function ($relationModel) {
35 16
                return ! is_a($relationModel, Pivot::class);
36 20
            })->each(function ($relationModel, $relationName) use ($model) {
37 16
                $className = get_class((new ReflectionObject($model))->newInstance()->{$relationName}());
38 16
                $strategy = $this->getPersistenceStrategy($className);
39 14
                (new $strategy($model))->persist($relationName, $relationModel);
40
41 14
                $this->persistRecursive($relationModel);
42
            });
43
        });
44
45 18
        return $parent;
46
    }
47
48
    /**
49
     * Gets the strategy to use for persisting a relation type
50
     *
51
     * @param string $relationType
52
     * @return string
53
     */
54 16
    public function getPersistenceStrategy(string $relationType): string
55
    {
56 16
        $config = config('cloner.persistence_strategies');
57
58 16
        return collect($config)->get($relationType, function () use ($relationType) {
59 2
            throw NoCompatiblePersistenceStrategyFound::forType($relationType);
60
        });
61
    }
62
}
63