Completed
Pull Request — 2.0 (#75)
by Julien
02:32
created

QueryParameterParserTrait   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 6
Bugs 1 Features 0
Metric Value
wmc 3
lcom 0
cbo 0
dl 0
loc 60
rs 10
c 6
b 1
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
getSession() 0 1 ?
A unorderParameters() 0 4 1
A orderParameters() 0 12 1
A getParametersType() 0 6 1
1
<?php
2
/*
3
 * This file is part of the Pomm's Foundation package.
4
 *
5
 * (c) 2014 - 2015 Grégoire HUBERT <[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
namespace PommProject\Foundation\QueryManager;
11
12
/**
13
 * QueryParameterParserTrait
14
 *
15
 * Trait that makes query managers to parse, expand anc convert query
16
 * parameters.
17
 *
18
 * @package     Foundation
19
 * @copyright   2014 - 2015 Grégoire HUBERT
20
 * @author      Grégoire HUBERT
21
 * @license     X11 {@link http://opensource.org/licenses/mit-license.php}
22
 */
23
trait QueryParameterParserTrait
24
{
25
    abstract protected function getSession();
26
27
    /**
28
     * unorderParameters
29
     *
30
     * Transform an ordered parameters list with $1, $2 to $* parameters.
31
     *
32
     * @access public
33
     * @param  string $string
34
     * @return string
35
     */
36
    public function unorderParameters($string)
37
    {
38
        return preg_replace('/\$[0-9]+/', '$*', $string);
39
    }
40
41
    /**
42
     * orderParameters
43
     *
44
     * Transform an unordered parameters list $* to ordered $1, $2 parameters.
45
     *
46
     * @access public
47
     * @param  string $string
48
     * @return string
49
     */
50
    public function orderParameters($string)
51
    {
52
        return preg_replace_callback(
53
            '/\$\*/',
54
            function () {
55
                static $nb = 0;
56
57
                return sprintf("$%d", ++$nb);
58
            },
59
            $string
60
        );
61
    }
62
63
    /**
64
     * getParametersType
65
     *
66
     * Return an array of the type specified with the parameters if any. It is
67
     * possible to give the type when passing parameters like « SELECT … WHERE
68
     * field = $*::timestamptz ». In this case, PostgreSQL will assume the
69
     * given parameter is a timestamp. Pomm uses these type hints to convert
70
     * PHP representation to PostgreSQL data value.
71
     *
72
     * @access  public
73
     * @param   mixed $string SQL query.
74
     * @return  array
75
     */
76
    public function getParametersType($string)
77
    {
78
        preg_match_all('/\$\*(?:::([\w\."]+(?:\[\])?))?/', $string, $matches);
79
80
        return str_replace('"', '', $matches[1]);
81
    }
82
}
83