|
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 array<string> |
|
27
|
|
|
*/ |
|
28
|
|
|
private array $relations = []; |
|
29
|
|
|
|
|
30
|
|
|
private readonly AbstractSchemaManager $SchemaManager; |
|
31
|
|
|
|
|
32
|
|
|
public function __construct( |
|
33
|
|
|
Connection $connection, |
|
34
|
|
|
private readonly ModelManager $modelManager, |
|
35
|
|
|
) { |
|
36
|
|
|
$this->SchemaManager = $connection->createSchemaManager(); |
|
|
|
|
|
|
37
|
|
|
parent::__construct($connection); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public function from(string $table, ?string $alias = null): QueryBuilder |
|
41
|
|
|
{ |
|
42
|
|
|
$this->table = $table; |
|
43
|
|
|
|
|
44
|
|
|
return parent::from($table, $alias); |
|
|
|
|
|
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public function get(): Collection |
|
48
|
|
|
{ |
|
49
|
|
|
if (!$this->SchemaManager->tableExists($this->table)) { |
|
50
|
|
|
return Collection::fromIterable([]); |
|
51
|
|
|
} |
|
52
|
|
|
$model = $this->modelManager->create($this->table); |
|
53
|
|
|
$relations = $this->relations; |
|
54
|
|
|
$this->relations = []; |
|
55
|
|
|
$results = $this->fetchAllAssociative(); |
|
56
|
|
|
|
|
57
|
|
|
return Collection::fromIterable($results) |
|
58
|
|
|
->map(static fn ($value): Model => $model->setLoadedProperties($value)->with($relations)->setLoaded()); |
|
|
|
|
|
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
public function first(): ?Model |
|
62
|
|
|
{ |
|
63
|
|
|
if (!$this->SchemaManager->tableExists($this->table)) { |
|
64
|
|
|
return null; |
|
65
|
|
|
} |
|
66
|
|
|
$relations = $this->relations; |
|
67
|
|
|
$this->relations = []; |
|
68
|
|
|
$result = $this->fetchAssociative() ?: []; |
|
69
|
|
|
if ([] === $result) { |
|
70
|
|
|
return null; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
return $this->modelManager->create($this->table)->setLoadedProperties($result)->with($relations)->setLoaded(); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|