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

PgBytea   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 57
Duplicated Lines 36.84 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 7
lcom 0
cbo 2
dl 21
loc 57
c 2
b 0
f 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A escapeByteString() 0 4 1
A toPg() 11 11 2
A fromPg() 0 7 2
A toPgStandardFormat() 10 10 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/*
3
 * This file is part of 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\Converter;
11
12
use PommProject\Foundation\Session\Session;
13
14
/**
15
 * PgBytea
16
 *
17
 * Bytea converter
18
 *
19
 * @package   Foundation
20
 * @copyright 2014 - 2015 Grégoire HUBERT
21
 * @author    Grégoire HUBERT <[email protected]>
22
 * @license   X11 {@link http://opensource.org/licenses/mit-license.php}
23
 */
24
class PgBytea implements ConverterInterface
25
{
26
    /**
27
     * @see Pomm\Converter\ConverterInterface
28
     */
29 View Code Duplication
    public function toPg($data, $type, Session $session)
30
    {
31
        return $data !== null
32
            ? sprintf(
33
                "%s '%s'",
34
                $type,
35
                $this->escapeByteString($session, $data)
36
            )
37
            : sprintf("NULL::%s", $type)
38
            ;
39
    }
40
41
    /**
42
     * @see Pomm\Converter\ConverterInterface
43
     */
44
    public function fromPg($data, $type, Session $session)
45
    {
46
        return $data !== null
47
            ? $session->getConnection()->unescapeBytea($data)
48
            : null
49
            ;
50
    }
51
52
    /**
53
     * @see Pomm\Converter\ConverterInterface
54
     */
55 View Code Duplication
    public function toPgStandardFormat($data, $type, Session $session)
56
    {
57
        return $data !== null
58
            ? sprintf(
59
                '%s',
60
                $this->escapeByteString($session, $data)
61
            )
62
            : null
63
            ;
64
    }
65
66
    /**
67
     * escapeByteString
68
     *
69
     * Escape a binary string to postgres.
70
     *
71
     * @access protected
72
     * @param  mixed     $string
73
     * @param  Session   $session
74
     * @return string
75
     */
76
    protected function escapeByteString(Session $session, $string)
77
    {
78
        return preg_replace(["/\\\\/", '/"/'], ["\\", '""'], $session->getConnection()->escapeBytea($string));
79
    }
80
}
81