Issues (11)

Security Analysis    no request data  

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

src/DBAL/Connection.php (8 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
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
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
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
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
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
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