Passed
Push — main ( a077ec...e0d381 )
by Pranjal
02:18
created

QueryBuilder::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 7
rs 10
c 2
b 0
f 0
1
<?php
2
3
namespace Scrawler\Arca;
4
5
/**
6
 * Extended implementation of \Doctrine\DBAL\Query\QueryBuilder
7
 */
8
class QueryBuilder extends \Doctrine\DBAL\Query\QueryBuilder
9
{
10
    private string $table;
11
    private array $relations= [];
12
13
    private Database $db;
14
15
    public function __construct(Database $db)
16
    {
17
        $this->db = $db;
18
        parent::__construct($this->db->connection);
19
20
    }
21
22
    public function with(string $relation): QueryBuilder
23
    {
24
        array_push($this->relations, $relation);
25
        return $this;
26
    }
27
28
    public function from($from, $alias = null): QueryBuilder
29
    {
30
        $this->table = $from;
31
        return $this->add('from', [
32
            'table' => $from,
33
            'alias' => $alias,
34
        ], true);
35
    }
36
37
    public function get(): Collection
38
    {
39
        $model = $this->db->create($this->table);
40
        $relations = $this->relations;
41
        $this->relations = [];
42
        return Collection::fromIterable($this->fetchAllAssociative())
43
            ->map(static fn($value): Model => ($model)->setProperties($value)->with($relations)->setLoaded());
44
    }
45
46
    public function first(): Model
47
    {
48
        $relations = $this->relations;
49
        $this->relations = [];
50
        $result = $this->fetchAssociative() ? $this->fetchAssociative() : [];
51
        return ($this->db->create($this->table))->setProperties($result)->with($relations)->setLoaded();
52
    }
53
}