Completed
Push — develop ( 505f0b...e8b338 )
by Peter
01:58
created

SqlTrait::current()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
/**
3
 * Webino (http://webino.sk)
4
 *
5
 * @link        https://github.com/webino/WebinoDbDump for the canonical source repository
6
 * @copyright   Copyright (c) 2016 Webino, s. r. o. (http://webino.sk)
7
 * @license     The BSD 3-Clause License
8
 */
9
10
namespace WebinoDbDump\Db\Sql;
11
12
/**
13
 * Sql trait
14
 *
15
 * @author Peter Bačinský <[email protected]>
16
 */
17
trait SqlTrait
18
{
19
    /**
20
     * @var string
21
     */
22
    protected $delimiter = ';';
23
24
    /**
25
     * @var string|null
26
     */
27
    protected $current;
28
29
    /**
30
     * @param callable $callback
31
     * @return mixed
32
     */
33
    abstract protected function eachQuery(callable $callback);
34
35
    /**
36
     * @return string
37
     */
38
    public function getSql()
39
    {
40
        $query = '';
41
42
        $this->eachQuery(function ($line) use (&$query) {
43
            if (0 === strpos($line, '--')) {
44
                // skip comments
45
                return false;
46
            }
47
48
            $match = [];
49
            if (preg_match('~delimiter\s*([^\s]+)$~iS', $line, $match)) {
50
                $this->delimiter = $match[1];
51
                return false;
52
            }
53
54
            $query .= $line;
55
56
            if (preg_match('~' . preg_quote($this->delimiter, '~') . '\s*$~iS', $line)) {
57
                return true;
58
            }
59
60
            return null;
61
        });
62
63
        return trim($query);
64
    }
65
66
    /**
67
     * @return bool
68
     */
69
    public function valid()
70
    {
71
        if (null === $this->current) {
72
            $this->current = $this->getSql();
73
        }
74
        return !empty($this->current);
75
    }
76
77
    /**
78
     * @return string
79
     */
80
    public function current()
81
    {
82
        return $this->current;
83
    }
84
85
    /**
86
     * @return void
87
     */
88
    public function next()
89
    {
90
        $this->current = $this->getSql();
91
    }
92
}
93