Completed
Push — master ( c0099d...e7d5d6 )
by Andreas
02:04 queued 10s
created

ImportMappingDoctrineCommandTest   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 98
Duplicated Lines 44.9 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 6
dl 44
loc 98
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A setup() 0 14 1
A tearDown() 0 11 2
A testExecuteXmlWithBundle() 8 8 1
A testExecuteAnnotationsWithBundle() 12 11 1
A testExecuteThrowsExceptionWithNamespaceAndNoPath() 0 4 1
A testExecuteXmlWithNamespace() 11 11 1
A testExecuteAnnotationsWithNamespace() 12 12 1
A getProjectDir() 0 4 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
namespace Doctrine\Bundle\DoctrineBundle\Tests\Command;
4
5
use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
6
use PHPUnit\Framework\TestCase;
7
use Psr\Log\NullLogger;
8
use Symfony\Bundle\FrameworkBundle\Console\Application;
9
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
10
use Symfony\Component\Config\Loader\LoaderInterface;
11
use Symfony\Component\Console\Tester\CommandTester;
12
use Symfony\Component\DependencyInjection\ContainerBuilder;
13
use Symfony\Component\Filesystem\Filesystem;
14
use Symfony\Component\HttpKernel\Bundle\Bundle;
15
use Symfony\Component\HttpKernel\Kernel;
16
use function method_exists;
17
18
class ImportMappingDoctrineCommandTest extends TestCase
19
{
20
    /** @var Kernel|null */
21
    private $kernel;
22
23
    /** @var CommandTester|null */
24
    private $commandTester;
25
26
    protected function setup()
27
    {
28
        $this->kernel = new ImportMappingTestingKernel();
29
        $this->kernel->boot();
30
31
        $connection = $this->kernel->getContainer()
32
            ->get('doctrine')
33
            ->getConnection();
34
        $connection->executeQuery('CREATE TABLE product (id integer primary key, name varchar(20), hint text)');
35
36
        $application         = new Application($this->kernel);
37
        $command             = $application->find('doctrine:mapping:import');
38
        $this->commandTester = new CommandTester($command);
39
    }
40
41
    protected function tearDown()
42
    {
43
        $fs = new Filesystem();
44
        if ($this->kernel !== null) {
45
            $fs->remove($this->kernel->getCacheDir());
46
        }
47
48
        $fs->remove(sys_get_temp_dir() . '/import_mapping_bundle');
49
        $this->kernel        = null;
50
        $this->commandTester = null;
51
    }
52
53 View Code Duplication
    public function testExecuteXmlWithBundle()
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...
54
    {
55
        $this->commandTester->execute(['name' => 'ImportMappingTestFooBundle']);
56
57
        $expectedMetadataPath = sys_get_temp_dir() . '/import_mapping_bundle/Resources/config/doctrine/Product.orm.xml';
58
        $this->assertFileExists($expectedMetadataPath);
59
        $this->assertContains('"Doctrine\Bundle\DoctrineBundle\Tests\Command\Entity\Product"', file_get_contents($expectedMetadataPath), 'Metadata contains correct namespace');
60
    }
61
62 View Code Duplication
    public function testExecuteAnnotationsWithBundle()
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...
63
    {
64
        $this->commandTester->execute([
65
            'name' => 'ImportMappingTestFooBundle',
66
            'mapping-type' => 'annotation',
67
        ]);
68
69
        $expectedMetadataPath = sys_get_temp_dir() . '/import_mapping_bundle/Entity/Product.php';
70
        $this->assertFileExists($expectedMetadataPath);
71
        $this->assertContains('namespace Doctrine\Bundle\DoctrineBundle\Tests\Command\Entity;', file_get_contents($expectedMetadataPath), 'File contains correct namespace');
72
    }
73
74
    /**
75
     * @expectedException \InvalidArgumentException
76
     * @expectedExceptionMessageRegExp /The --path option is required/
77
     */
78
    public function testExecuteThrowsExceptionWithNamespaceAndNoPath()
79
    {
80
        $this->commandTester->execute(['name' => 'Some\Namespace']);
81
    }
82
83 View Code Duplication
    public function testExecuteXmlWithNamespace()
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...
84
    {
85
        $this->commandTester->execute([
86
            'name' => 'Some\Namespace\Entity',
87
            '--path' => $this->getProjectDir($this->kernel) . '/config/doctrine',
0 ignored issues
show
Bug introduced by
It seems like $this->kernel can be null; however, getProjectDir() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
88
        ]);
89
90
        $expectedMetadataPath = $this->getProjectDir($this->kernel) . '/config/doctrine/Product.orm.xml';
0 ignored issues
show
Bug introduced by
It seems like $this->kernel can be null; however, getProjectDir() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
91
        $this->assertFileExists($expectedMetadataPath);
92
        $this->assertContains('"Some\Namespace\Entity\Product"', file_get_contents($expectedMetadataPath), 'Metadata contains correct namespace');
93
    }
94
95 View Code Duplication
    public function testExecuteAnnotationsWithNamespace()
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...
96
    {
97
        $this->commandTester->execute([
98
            'name' => 'Some\Namespace\Entity',
99
            '--path' => $this->getProjectDir($this->kernel) . '/src/Entity',
0 ignored issues
show
Bug introduced by
It seems like $this->kernel can be null; however, getProjectDir() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
100
            'mapping-type' => 'annotation',
101
        ]);
102
103
        $expectedMetadataPath = $this->getProjectDir($this->kernel) . '/src/Entity/Product.php';
0 ignored issues
show
Bug introduced by
It seems like $this->kernel can be null; however, getProjectDir() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
104
        $this->assertFileExists($expectedMetadataPath);
105
        $this->assertContains('namespace Some\Namespace\Entity;', file_get_contents($expectedMetadataPath), 'Metadata contains correct namespace');
106
    }
107
108
    /**
109
     * BC layer to support Symfony < 4.2 and Symfony >= 5.0. Once support for Symfony < 4.2 has been removed, this method can be dropped.
110
     */
111
    private function getProjectDir(Kernel $kernel) : string
112
    {
113
        return method_exists($kernel, 'getProjectDir') ? $kernel->getProjectDir() : $kernel->getRootDir();
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Component\HttpKernel\Kernel::getRootDir() has been deprecated with message: since Symfony 4.2, use getProjectDir() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
114
    }
115
}
116
117
class ImportMappingTestingKernel extends Kernel
118
{
119
    public function __construct()
120
    {
121
        parent::__construct('test', true);
122
    }
123
124
    public function registerBundles()
125
    {
126
        return [
127
            new FrameworkBundle(),
128
            new DoctrineBundle(),
129
            new ImportMappingTestFooBundle(),
130
        ];
131
    }
132
133
    public function registerContainerConfiguration(LoaderInterface $loader)
134
    {
135
        $loader->load(function (ContainerBuilder $container) {
136
            // @todo Setting the kernel.name parameter can be removed once the dependency on DoctrineCacheBundle has been dropped
137
            $container->setParameter('kernel.name', 'foo');
138
            $container->loadFromExtension('framework', ['secret' => 'F00']);
139
140
            $container->loadFromExtension('doctrine', [
141
                'dbal' => [
142
                    'driver' => 'pdo_sqlite',
143
                    'path' => $this->getCacheDir() . '/testing.db',
144
                ],
145
                'orm' => [],
146
            ]);
147
148
            // Register a NullLogger to avoid getting the stderr default logger of FrameworkBundle
149
            $container->register('logger', NullLogger::class);
150
        });
151
    }
152
153
    public function getRootDir()
154
    {
155
        if ($this->rootDir === null) {
0 ignored issues
show
Deprecated Code introduced by
The property Symfony\Component\HttpKernel\Kernel::$rootDir has been deprecated with message: since Symfony 4.2

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
156
            $this->rootDir = sys_get_temp_dir() . '/sf_kernel_' . md5(mt_rand());
0 ignored issues
show
Deprecated Code introduced by
The property Symfony\Component\HttpKernel\Kernel::$rootDir has been deprecated with message: since Symfony 4.2

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
157
        }
158
159
        return $this->rootDir;
0 ignored issues
show
Deprecated Code introduced by
The property Symfony\Component\HttpKernel\Kernel::$rootDir has been deprecated with message: since Symfony 4.2

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
160
    }
161
}
162
163
class ImportMappingTestFooBundle extends Bundle
164
{
165
    public function getPath()
166
    {
167
        return sys_get_temp_dir() . '/import_mapping_bundle';
168
    }
169
}
170