|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Arachne\Codeception\Module; |
| 4 | + |
| 5 | +use Arachne\Codeception\Module\Nette; |
| 6 | +use Codeception\Exception\ModuleConfig; |
| 7 | +use Codeception\Module; |
| 8 | +use Codeception\TestCase; |
| 9 | +use Doctrine\ORM\EntityManagerInterface; |
| 10 | + |
| 11 | +class Doctrine extends Module |
| 12 | +{ |
| 13 | + |
| 14 | + public function _before(TestCase $test) |
| 15 | + { |
| 16 | + if ($this->config['dump']) { |
| 17 | + $em = $this->getModule(Nette::class)->grabService(EntityManagerInterface::class); |
| 18 | + $connection = $em->getConnection(); |
| 19 | + $generator = $this->load(file_get_contents($this->config['dump'])); |
| 20 | + |
| 21 | + try { |
| 22 | + foreach ($generator as $command) { |
| 23 | + $stmt = $connection->prepare($command); |
| 24 | + if (!$stmt->execute()) { |
| 25 | + $error = $stmt->errorInfo(); |
| 26 | + throw new ModuleConfig(__CLASS__, $error[2]); |
| 27 | + } |
| 28 | + $stmt->closeCursor(); |
| 29 | + } |
| 30 | + |
| 31 | + } catch (\PDOException $e) { |
| 32 | + throw new ModuleConfig(__CLASS__, $e->getMessage(), $e); |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + public function load($sql) |
| 38 | + { |
| 39 | + $sql = explode("\n", preg_replace('%/\*(?!!\d+)(?:(?!\*/).)*\*/%s', '', $sql)); |
| 40 | + $query = ''; |
| 41 | + $delimiter = ';'; |
| 42 | + $delimiterLength = 1; |
| 43 | + foreach ($sql as $sqlLine) { |
| 44 | + if (preg_match('/DELIMITER ([\;\$\|\\\\]+)/i', $sqlLine, $match)) { |
| 45 | + $delimiter = $match[1]; |
| 46 | + $delimiterLength = strlen($delimiter); |
| 47 | + continue; |
| 48 | + } |
| 49 | + if (trim($sqlLine) == '' || trim($sqlLine) == ';' || preg_match('~^((--.*?)|(#))~s', $sqlLine)) { |
| 50 | + continue; |
| 51 | + } |
| 52 | + $query .= "\n" . rtrim($sqlLine); |
| 53 | + if (substr($query, -1 * $delimiterLength, $delimiterLength) == $delimiter) { |
| 54 | + yield substr($query, 0, -1 * $delimiterLength); |
| 55 | + $query = ''; |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments