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

EloquentDataProvider   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 7
c 2
b 0
f 0
lcom 0
cbo 6
dl 0
loc 36
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
B validateSource() 0 14 6
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