QueryBuilder::get()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 3 Features 0
Metric Value
cc 2
eloc 6
c 8
b 3
f 0
nc 2
nop 0
dl 0
loc 10
rs 10
1
<?php
2
3
/*
4
 * This file is part of the Scrawler package.
5
 *
6
 * (c) Pranjal Pandey <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Scrawler\Arca;
13
14
use Doctrine\DBAL\Connection;
15
use Doctrine\DBAL\Query\QueryBuilder as DoctrineQueryBuilder;
16
use Doctrine\DBAL\Schema\AbstractSchemaManager;
17
use Scrawler\Arca\Manager\ModelManager;
18
19
/**
20
 * Extended implementation of \Doctrine\DBAL\Query\QueryBuilder.
21
 */
22
final class QueryBuilder extends DoctrineQueryBuilder
23
{
24
    private string $table;
25
    /**
26
     * @var AbstractSchemaManager
27
     */
28
    private readonly AbstractSchemaManager $schemaManager;
29
30
    public function __construct(
31
        Connection $connection,
32
        private readonly ModelManager $modelManager,
33
    ) {
34
        $this->schemaManager = $connection->createSchemaManager();
0 ignored issues
show
Bug introduced by
The property schemaManager is declared read-only in Scrawler\Arca\QueryBuilder.
Loading history...
35
        parent::__construct($connection);
36
    }
37
38
    public function from(string $table, ?string $alias = null): QueryBuilder
39
    {
40
        $this->table = $table;
41
42
        return parent::from($table, $alias);
0 ignored issues
show
Bug Best Practice introduced by
The expression return parent::from($table, $alias) returns the type Doctrine\DBAL\Query\QueryBuilder which includes types incompatible with the type-hinted return Scrawler\Arca\QueryBuilder.
Loading history...
43
    }
44
45
    public function get(): Collection
46
    {
47
        if (!$this->schemaManager->tableExists($this->table)) {
48
            return Collection::fromIterable([]);
49
        }
50
        $model = $this->modelManager->create($this->table);
51
        $results = $this->fetchAllAssociative();
52
53
        return Collection::fromIterable($results)
54
            ->map(static fn ($value): Model => $model->setLoadedProperties($value)->setLoaded());
55
    }
56
57
    public function first(): ?Model
58
    {
59
        if (!$this->schemaManager->tableExists($this->table)) {
60
            return null;
61
        }
62
63
        $result = $this->fetchAssociative() ?: [];
64
        if ([] === $result) {
65
            return null;
66
        }
67
68
        return $this->modelManager->create($this->table)->setLoadedProperties($result)->setLoaded();
69
    }
70
}
71