Completed
Push — master ( baba12...502b0f )
by Andreas
08:34
created

ProfilerController::explainAction()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 8.6897
c 0
b 0
f 0
cc 6
nc 9
nop 3
1
<?php
2
3
namespace Doctrine\Bundle\DoctrineBundle\Controller;
4
5
use Doctrine\DBAL\Connection;
6
use Doctrine\DBAL\Platforms\SqlitePlatform;
7
use Doctrine\DBAL\Platforms\SQLServerPlatform;
8
use Exception;
9
use PDO;
10
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
11
use Symfony\Component\DependencyInjection\ContainerInterface;
12
use Symfony\Component\HttpFoundation\Response;
13
use Symfony\Component\HttpKernel\Profiler\Profiler;
14
use Symfony\Component\VarDumper\Cloner\Data;
15
16
class ProfilerController implements ContainerAwareInterface
17
{
18
    /** @var ContainerInterface */
19
    private $container;
20
21
    /**
22
     * {@inheritDoc}
23
     */
24
    public function setContainer(ContainerInterface $container = null)
25
    {
26
        $this->container = $container;
27
    }
28
29
    /**
30
     * Renders the profiler panel for the given token.
31
     *
32
     * @param string $token          The profiler token
33
     * @param string $connectionName
34
     * @param int    $query
35
     *
36
     * @return Response A Response instance
37
     */
38
    public function explainAction($token, $connectionName, $query)
39
    {
40
        /** @var Profiler $profiler */
41
        $profiler = $this->container->get('profiler');
42
        $profiler->disable();
43
44
        $profile = $profiler->loadProfile($token);
45
        $queries = $profile->getCollector('db')->getQueries();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\HttpKe...\DataCollectorInterface as the method getQueries() does only exist in the following implementations of said interface: Doctrine\Bundle\Doctrine...r\DoctrineDataCollector, Symfony\Bridge\Doctrine\...r\DoctrineDataCollector.

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...
46
47
        if (! isset($queries[$connectionName][$query])) {
48
            return new Response('This query does not exist.');
49
        }
50
51
        $query = $queries[$connectionName][$query];
52
        if (! $query['explainable']) {
53
            return new Response('This query cannot be explained.');
54
        }
55
56
        /** @var Connection $connection */
57
        $connection = $this->container->get('doctrine')->getConnection($connectionName);
58
        try {
59
            $platform = $connection->getDatabasePlatform();
60
            if ($platform instanceof SqlitePlatform) {
61
                $results = $this->explainSQLitePlatform($connection, $query);
62
            } elseif ($platform instanceof SQLServerPlatform) {
63
                $results = $this->explainSQLServerPlatform($connection, $query);
64
            } else {
65
                $results = $this->explainOtherPlatform($connection, $query);
66
            }
67
        } catch (Exception $e) {
68
            return new Response('This query cannot be explained.');
69
        }
70
71
        return new Response($this->container->get('twig')->render('@Doctrine/Collector/explain.html.twig', [
72
            'data' => $results,
73
            'query' => $query,
74
        ]));
75
    }
76
77 View Code Duplication
    private function explainSQLitePlatform(Connection $connection, $query)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
78
    {
79
        $params = $query['params'];
80
81
        if ($params instanceof Data) {
82
            $params = $params->getValue(true);
83
        }
84
85
        return $connection->executeQuery('EXPLAIN QUERY PLAN ' . $query['sql'], $params, $query['types'])
86
            ->fetchAll(PDO::FETCH_ASSOC);
87
    }
88
89
    private function explainSQLServerPlatform(Connection $connection, $query)
90
    {
91
        if (stripos($query['sql'], 'SELECT') === 0) {
92
            $sql = 'SET STATISTICS PROFILE ON; ' . $query['sql'] . '; SET STATISTICS PROFILE OFF;';
93
        } else {
94
            $sql = 'SET SHOWPLAN_TEXT ON; GO; SET NOEXEC ON; ' . $query['sql'] . '; SET NOEXEC OFF; GO; SET SHOWPLAN_TEXT OFF;';
95
        }
96
97
        $params = $query['params'];
98
99
        if ($params instanceof Data) {
100
            $params = $params->getValue(true);
101
        }
102
103
        $stmt = $connection->executeQuery($sql, $params, $query['types']);
104
        $stmt->nextRowset();
105
106
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
107
    }
108
109 View Code Duplication
    private function explainOtherPlatform(Connection $connection, $query)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
110
    {
111
        $params = $query['params'];
112
113
        if ($params instanceof Data) {
114
            $params = $params->getValue(true);
115
        }
116
117
        return $connection->executeQuery('EXPLAIN ' . $query['sql'], $params, $query['types'])
118
            ->fetchAll(PDO::FETCH_ASSOC);
119
    }
120
}
121