Completed
Push — master ( cc2c1e...ad65a7 )
by Renato
07:15
created

BuilderResultset::current()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 10
rs 9.4285
1
<?php
2
3
namespace NwLaravel\Resultset;
4
5
use RuntimeException;
6
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
7
8
/**
9
 * Class BuilderResultset
10
 */
11
class BuilderResultset extends AbstractResultset
12
{
13
    /**
14
     * @var \Illuminate\Database\Eloquent\Builder
15
     */
16
    protected $builder = null;
17
18
    /**
19
     * @var \Illuminate\Database\Eloquent\Model
20
     */
21
    private $prototype = null;
22
23
    /**
24
     * Initialize
25
     *
26
     * @param \Illuminate\Database\Eloquent\Builder $builder Builder
27
     */
28
    public function __construct(EloquentBuilder $builder)
29
    {
30
        $this->builder = $builder;
31
32
        $this->initialize();
33
    }
34
35
    /**
36
     * Initialize
37
     *
38
     * @return void
39
     */
40
    public function initialize()
41
    {
42
        if (! $this->initialized) {
43
            $query = $this->builder->toBase();
44
            $sql = $query->toSql();
45
            $bindings = $query->getBindings();
46
            $conn = $query->getConnection();
47
            $this->statement = $conn->getPdo()->prepare($sql);
48
            $this->statement->execute($conn->prepareBindings($bindings));
49
50
            $this->prototype = $this->builder->getModel()->newFromBuilder();
51
        }
52
53
        $this->initialized = true;
54
    }
55
56
    /**
57
     * Get Prototype
58
     *
59
     * @return \Illuminate\Database\Eloquent\Model
60
     */
61
    public function getPrototype()
62
    {
63
        return $this->prototype;
64
    }
65
66
    /**
67
     * Get the data
68
     *
69
     * @return object|bool
70
     */
71
    public function current()
72
    {
73
        if (!$data = parent::current()) {
74
            return false;
75
        }
76
77
        $newInstance = clone $this->getPrototype();
78
        $newInstance->setRawAttributes((array) $data, true);
79
        return $newInstance;
80
    }
81
}
82