EloquentPersister::persist()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 1
1
<?php
2
3
namespace Ck\Laravel\Alice\Persister;
4
5
use Ck\Laravel\Alice\Test\Model\User;
6
use Illuminate\Database\Connection;
7
use Illuminate\Database\Eloquent\Model;
8
use Nelmio\Alice\PersisterInterface;
9
10
class EloquentPersister implements PersisterInterface
11
{
12
    /**
13
     * @var Connection
14
     */
15
    private $connection;
16
17
    public function __construct(Connection $connection)
18
    {
19
        $this->connection = $connection;
20
    }
21
22
    /**
23
     * Persists objects into the database.
24
     *
25
     * @param Model[] $models
26
     */
27
    public function persist(array $models)
28
    {
29
        $this->connection->beginTransaction();
30
31
        foreach ($models as $model) {
32
33
            if (!$model instanceof Model) {
34
                $this->connection->rollBack();
35
            }
36
37
            $model->save();
38
        }
39
40
        $this->connection->commit();
41
    }
42
43
    /**
44
     * Finds an object by class and id.
45
     *
46
     * @param string $class
47
     * @param int $id
48
     *
49
     * @return object|null
50
     */
51
    public function find($class, $id)
52
    {
53
        return $class::findOrFail($id);
54
    }
55
}
56