1<?php
2
3namespace Doctrine\DBAL\Schema\Visitor;
4
5use Doctrine\DBAL\Platforms\AbstractPlatform;
6use Doctrine\DBAL\Schema\ForeignKeyConstraint;
7use Doctrine\DBAL\Schema\SchemaException;
8use Doctrine\DBAL\Schema\Sequence;
9use Doctrine\DBAL\Schema\Table;
10use SplObjectStorage;
11use function strlen;
12
13/**
14 * Gathers SQL statements that allow to completely drop the current schema.
15 */
16class DropSchemaSqlCollector extends AbstractVisitor
17{
18    /** @var SplObjectStorage */
19    private $constraints;
20
21    /** @var SplObjectStorage */
22    private $sequences;
23
24    /** @var SplObjectStorage */
25    private $tables;
26
27    /** @var AbstractPlatform */
28    private $platform;
29
30    public function __construct(AbstractPlatform $platform)
31    {
32        $this->platform = $platform;
33        $this->clearQueries();
34    }
35
36    /**
37     * {@inheritdoc}
38     */
39    public function acceptTable(Table $table)
40    {
41        $this->tables->attach($table);
42    }
43
44    /**
45     * {@inheritdoc}
46     */
47    public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkConstraint)
48    {
49        if (strlen($fkConstraint->getName()) === 0) {
50            throw SchemaException::namedForeignKeyRequired($localTable, $fkConstraint);
51        }
52
53        $this->constraints->attach($fkConstraint, $localTable);
54    }
55
56    /**
57     * {@inheritdoc}
58     */
59    public function acceptSequence(Sequence $sequence)
60    {
61        $this->sequences->attach($sequence);
62    }
63
64    /**
65     * @return void
66     */
67    public function clearQueries()
68    {
69        $this->constraints = new SplObjectStorage();
70        $this->sequences   = new SplObjectStorage();
71        $this->tables      = new SplObjectStorage();
72    }
73
74    /**
75     * @return string[]
76     */
77    public function getQueries()
78    {
79        $sql = [];
80
81        foreach ($this->constraints as $fkConstraint) {
82            $localTable = $this->constraints[$fkConstraint];
83            $sql[]      = $this->platform->getDropForeignKeySQL($fkConstraint, $localTable);
84        }
85
86        foreach ($this->sequences as $sequence) {
87            $sql[] = $this->platform->getDropSequenceSQL($sequence);
88        }
89
90        foreach ($this->tables as $table) {
91            $sql[] = $this->platform->getDropTableSQL($table);
92        }
93
94        return $sql;
95    }
96}
97