Completed
Pull Request — master (#1)
by
unknown
08:32
created

PrepareQuery::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
namespace Dazzle\PgSQL\Statement;
3
4
use Dazzle\PgSQL\Connection\ConnectorInterface;
5
use Dazzle\Promise\Deferred;
6
7
class PrepareQuery extends Deferred implements Statement
8
{
9
    use StatementAwareTrait;
10
    
11
    protected $name;
12
    /**
13
     * @var ConnectorInterface
14
     */
15
    protected $pipeline;
16
17
    public function __construct($sql)
18
    {
19
        parent::__construct();
20
        $this->sql = $sql;
21
        $this->name = $this->generateName();
22
    }
23
24
    public function getName()
25
    {
26
        return $this->name;
27
    }
28
29
    public function setName($name)
30
    {
31
        $this->name = $name;
32
33
        return $this;
34
    }
35
36
    public function getPipe()
37
    {
38
        return $this->pipeline;
39
    }
40
41
    public function execute(ConnectorInterface $connector)
42
    {
43
        $this->pipeline = $connector;
44
45
        return \pg_send_prepare($connector->getStream(), $this->name, $this->getSQL());
46
    }
47
48
    /**
49
     * @overwrite
50
     * @param resource $result
51
     * @return mixed
52
     */
53
    public function handle($result)
54
    {
55
        $stat = pg_result_status($result, \PGSQL_STATUS_LONG);
56
        if ($stat != PGSQL_COMMAND_OK) {
57
            return new \Exception('error');
58
        }
59
60
        return new Prepared($this);
61
    }
62
63
    private function generateName($length = 6)
64
    {
65
        $id = md5(microtime());
66
        $size = strlen($id);
67
        $offset = mt_rand(0, $size - $length);
68
        $end = mt_rand($offset + $length, $size);
69
70
        return substr($id, $offset, $end);
71
    }
72
}