1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of the Scrawler package. |
4
|
|
|
* |
5
|
|
|
* (c) Pranjal Pandey <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Scrawler\Arca; |
12
|
|
|
|
13
|
|
|
use Doctrine\DBAL\Connection; |
14
|
|
|
use Doctrine\DBAL\Query\QueryBuilder as DoctrineQueryBuilder; |
15
|
|
|
use Doctrine\DBAL\Schema\AbstractSchemaManager; |
16
|
|
|
use Scrawler\Arca\Manager\ModelManager; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Extended implementation of \Doctrine\DBAL\Query\QueryBuilder. |
20
|
|
|
*/ |
21
|
|
|
final class QueryBuilder extends DoctrineQueryBuilder |
22
|
|
|
{ |
23
|
|
|
private string $table; |
24
|
|
|
/** |
25
|
|
|
* @var array<string> |
26
|
|
|
*/ |
27
|
|
|
private array $relations = []; |
28
|
|
|
|
29
|
|
|
private readonly AbstractSchemaManager $SchemaManager; |
30
|
|
|
|
31
|
|
|
public function __construct( |
32
|
|
|
Connection $connection, |
33
|
|
|
private readonly ModelManager $modelManager, |
34
|
|
|
) { |
35
|
|
|
$this->SchemaManager = $connection->createSchemaManager(); |
|
|
|
|
36
|
|
|
parent::__construct($connection); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function with(string $relation): QueryBuilder |
40
|
|
|
{ |
41
|
|
|
$this->relations[] = $relation; |
42
|
|
|
|
43
|
|
|
return $this; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function from(string $table, ?string $alias = null): QueryBuilder |
47
|
|
|
{ |
48
|
|
|
$this->table = $table; |
49
|
|
|
|
50
|
|
|
return parent::from($table, $alias); |
|
|
|
|
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public function get(): Collection |
54
|
|
|
{ |
55
|
|
|
if (!$this->SchemaManager->tableExists($this->table)) { |
56
|
|
|
return Collection::fromIterable([]); |
57
|
|
|
} |
58
|
|
|
$model = $this->modelManager->create($this->table); |
59
|
|
|
$relations = $this->relations; |
60
|
|
|
$this->relations = []; |
61
|
|
|
$results = $this->fetchAllAssociative(); |
62
|
|
|
|
63
|
|
|
return Collection::fromIterable($results) |
64
|
|
|
->map(static fn ($value): Model => $model->setLoadedProperties($value)->with($relations)->setLoaded()); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
public function first(): ?Model |
68
|
|
|
{ |
69
|
|
|
if (!$this->SchemaManager->tableExists($this->table)) { |
70
|
|
|
return null; |
71
|
|
|
} |
72
|
|
|
$relations = $this->relations; |
73
|
|
|
$this->relations = []; |
74
|
|
|
$result = $this->fetchAssociative() ?: []; |
75
|
|
|
if ([] === $result) { |
76
|
|
|
return null; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
return $this->modelManager->create($this->table)->setLoadedProperties($result)->with($relations)->setLoaded(); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|