Connection::validateReconnectAttempt()   B
last analyzed

Complexity

Conditions 7
Paths 5

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
c 5
b 1
f 0
dl 0
loc 21
rs 7.551
cc 7
eloc 11
nc 5
nop 2
1
<?php
2
3
namespace BsbDoctrineReconnect\DBAL;
4
5
use BsbDoctrineReconnect\DBAL\Driver as DriverInterface;
6
use Doctrine\Common\EventManager;
7
use Doctrine\DBAL\Cache\QueryCacheProfile;
8
use Doctrine\DBAL\Configuration;
9
use Doctrine\DBAL\Connection as DBALConnection;
10
use Doctrine\DBAL\DBALException;
11
use Doctrine\DBAL\Driver\Connection as DriverConnection;
12
use Doctrine\DBAL\Driver\PDOMySql\Driver as DBALDriver;
13
14
/**
15
 * Class Connection
16
 *
17
 * @package BsbDoctrineReconnect\DBAL
18
 */
19
class Connection extends DBALConnection implements DriverConnection
20
{
21
    /**
22
     * @var int
23
     */
24
    protected $reconnectAttempts = 0;
25
26
    /**
27
     * {@inheritdoc}
28
     */
29
    public function __construct(
30
        array $params,
31
        DBALDriver $driver,
32
        Configuration $config = null,
33
        EventManager $eventManager = null
34
    ) {
35
        if ($driver instanceof DriverInterface) {
36
            if (count($driver->getReconnectExceptions()) && isset($params['driverOptions']['x_reconnect_attempts'])) {
37
                $this->reconnectAttempts = (int) $params['driverOptions']['x_reconnect_attempts'];
38
            }
39
        }
40
41
        parent::__construct($params, $driver, $config, $eventManager);
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null)
48
    {
49
        $stmt    = null;
50
        $attempt = 0;
51
        $retry   = true;
52
        while ($retry) {
53
            $retry = false;
54
            try {
55
                $stmt = parent::executeQuery($query, $params, $types);
56
            } catch (DBALException $e) {
57
                error_log("");
58
                error_log("      ,--.!,");
59
                error_log("   __/   -*-");
60
                error_log(" ,d08b.  '|`");
61
                error_log(" 0088MM");
62
                error_log(" `9MMP'");
63
                error_log("");
64
65
66
                error_log("DBAL EXCEPTION THROWN");
67
                error_log("└ txn nesting level: " . $this->getTransactionNestingLevel());
68
                error_log(" └ error: " . $e->getMessage());
69
                error_log("");
70
71
                if ($this->validateReconnectAttempt($e, $attempt)) {
72
                    error_log("  └ OK - successfully validated");
73
                    $this->close();
74
                    $attempt++;
75
76
                    if ($this->_driver->shouldStall($e)) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\DBAL\Driver as the method shouldStall() does only exist in the following implementations of said interface: BsbDoctrineReconnect\DBAL\Driver\PDOMySql\Driver.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
77
                        error_log("   ├ waitstate deemed beneficial, sleeping 5 seconds...");
78
                        sleep(5);
79
                    }
80
81
                    sleep(1);
82
                    $retry = true;
83
                } else {
84
                    error_log("  └ FAIL - could not be validated");
85
                    throw $e;
86
                }
87
            }
88
        }
89
90
        return $stmt;
91
    }
92
93
    /**
94
     * {@inheritdoc}
95
     */
96
    public function query()
97
    {
98
        $stmt    = null;
99
        $args    = func_get_args();
100
        $attempt = 0;
101
        $retry   = true;
102
        while ($retry) {
103
            $retry = false;
104
            try {
105
                // max arguments is 4 -> anything is better then calling call_user_func_array()!
106
                switch (count($args)) {
107
                    case 1:
108
                        $stmt = parent::query($args[0]);
109
                        break;
110
                    case 2:
111
                        $stmt = parent::query($args[0], $args[1]);
112
                        break;
113 View Code Duplication
                    case 3:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
114
                        $stmt = parent::query($args[0], $args[1], $args[2]);
115
                        break;
116 View Code Duplication
                    case 4:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
117
                        $stmt = parent::query($args[0], $args[1], $args[2], $args[3]);
118
                        break;
119
                    default:
120
                        $stmt = parent::query();
121
                }
122
            } catch (DBALException $e) {
123 View Code Duplication
                if ($this->validateReconnectAttempt($e, $attempt)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
124
                    $this->close();
125
                    $attempt++;
126
                    sleep(1);
127
                    $retry = true;
128
                } else {
129
                    throw $e;
130
                }
131
            }
132
        }
133
134
        return $stmt;
135
    }
136
137
    /**
138
     * {@inheritdoc}
139
     */
140
    public function executeUpdate($query, array $params = [], array $types = [])
141
    {
142
        $stmt    = null;
143
        $attempt = 0;
144
        $retry   = true;
145
        while ($retry) {
146
            $retry = false;
147
            try {
148
                $stmt = parent::executeUpdate($query, $params, $types);
149
            } catch (DBALException $e) {
150 View Code Duplication
                if ($this->validateReconnectAttempt($e, $attempt)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
151
                    $this->close();
152
                    $attempt++;
153
                    sleep(1);
154
                    $retry = true;
155
                } else {
156
                    throw $e;
157
                }
158
            }
159
        }
160
161
        return $stmt;
162
    }
163
164
    /**
165
     * {@inheritdoc}
166
     */
167
    public function prepare($sql)
168
    {
169
        return $this->prepareWrapped($sql);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->prepareWrapped($sql); (BsbDoctrineReconnect\DBAL\Statement) is incompatible with the return type of the parent method Doctrine\DBAL\Connection::prepare of type Doctrine\DBAL\Statement.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
170
    }
171
172
    /**
173
     * @param string $sql
174
     * @return Statement
175
     */
176
    protected function prepareWrapped($sql)
177
    {
178
        // returns a reconnect-wrapper for Statements
179
        return new Statement($sql, $this);
180
    }
181
182
    /**
183
     * do not use, only used by Statement-class
184
     *
185
     * needs to be public for access from the Statement-class
186
     *
187
     * @deprecated
188
     * @param string $sql
189
     */
190
    public function prepareUnwrapped($sql)
191
    {
192
        // returns the actual statement
193
        return parent::prepare($sql);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (prepare() instead of prepareUnwrapped()). Are you sure this is correct? If so, you might want to change this to $this->prepare().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
194
    }
195
196
    /**
197
     * @param DBALException         $e
198
     * @param               integer $attempt
199
     * @return bool
200
     */
201
    public function validateReconnectAttempt(DBALException $e, $attempt)
202
    {
203
        if ($this->getTransactionNestingLevel()) {
204
            return false;
205
        }
206
207
        if ($this->reconnectAttempts && $attempt < $this->reconnectAttempts) {
208
            $reconnectExceptions = $this->_driver->getReconnectExceptions();
0 ignored issues
show
Bug introduced by
The method getReconnectExceptions() does not exist on Doctrine\DBAL\Driver. Did you maybe mean connect()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
209
            $message             = $e->getMessage();
210
211
            if (!empty($reconnectExceptions)) {
212
                foreach ($reconnectExceptions as $reconnectException) {
213
                    if (strpos($message, $reconnectException) !== false) {
214
                        return true;
215
                    }
216
                }
217
            }
218
        }
219
220
        return false;
221
    }
222
}
223