Completed
Push — master ( 4f8ab0...cc471b )
by Vitaliy
07:43
created

EloquentDataProvider::validateSource()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
rs 8.8571
cc 6
eloc 7
nc 3
nop 1
1
<?php
2
3
namespace ViewComponents\Eloquent;
4
5
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Query\Builder;
8
use ViewComponents\Eloquent\Exception\InvalidDataSourceException;
9
use ViewComponents\ViewComponents\Data\AbstractDataProvider;
10
use ViewComponents\ViewComponents\Data\Operation\OperationInterface;
11
12
class EloquentDataProvider extends AbstractDataProvider
13
{
14
    /**
15
     * Constructor.
16
     *
17
     * @param Builder|EloquentBuilder|string $src Illuminate\Database\Eloquent\Builder instance
18
     *                                            or Illuminate\Database\Query\Builder instance
19
     *                                            or class name of target Eloquent model
20
     * @param OperationInterface[] $operations
21
     */
22
    public function __construct($src, array $operations = [])
23
    {
24
        $src = $this->validateSource($src);
25
        $this->operations()->set($operations);
26
        $this->processingService = new EloquentProcessingService(
27
            new EloquentProcessorResolver(),
28
            $this->operations(),
29
            $src
30
        );
31
    }
32
33
    protected function validateSource($src)
34
    {
35
        if ($src instanceof EloquentBuilder || $src instanceof Builder) {
36
            return $src;
37
        }
38
39
        if (is_string($src) && class_exists($src) && is_a($src, Model::class, true)) {
40
            /** @var  Model $model */
41
            $model = new $src;
42
            return $model->newQuery();
43
        }
44
45
        throw InvalidDataSourceException::forSrc($src);
46
    }
47
}
48