Installer::uninstall()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 16
rs 9.2
cc 4
eloc 10
nc 3
nop 2
1
<?php
2
3
namespace kujaff\VersionsBundle\Service;
4
5
use kujaff\VersionsBundle\Entity\Version;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, kujaff\VersionsBundle\Service\Version.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
6
use kujaff\VersionsBundle\Entity\BundleVersion;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, kujaff\VersionsBundle\Service\BundleVersion.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
7
use kujaff\VersionsBundle\Exception\StructureException;
8
use kujaff\VersionsBundle\Exception\InstallStateException;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use \Symfony\Component\DependencyInjection\ContainerAware;
11
12
class Installer extends ContainerAware
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Component\Depend...njection\ContainerAware has been deprecated with message: since version 2.8, to be removed in 3.0. Use the ContainerAwareTrait instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

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

Loading history...
13
{
14
    /**
15
     * Return tagged services
16
     *
17
     * @param string $bundle
18
     * @param string $tag
19
     * @param $implements Fully qualified interface name must be implemented
20
     * @return array
21
     * @throws StructureException
22
     */
23
    private function getService($bundle, $tag, $implements)
24
    {
25
        $fileName = $this->container->getParameter('kernel.cache_dir') . DIRECTORY_SEPARATOR . 'services.bundle.' . $tag . '.php';
26
        if (file_exists($fileName) === false) {
27
            throw new StructureException('Unable to find service tagged "bundle."' . $tag . '.');
28
        }
29
30
        $serviceIds = require($fileName);
31
        foreach ($serviceIds as $id) {
32
            $service = $this->container->get($id);
33
            if (!$service instanceof $implements) {
34
                throw new StructureException('Service "' . $id . '" must implements ' . $implements . '.');
35
            }
36
            if ($service->getBundleName() == $bundle) {
37
                return $service;
38
            }
39
        }
40
        return false;
41
    }
42
43
    /**
44
     * Get bundle version, assert a version si defined
45
     *
46
     * @param string $bundle
47
     * @return BundleVersion
48
     * @throws StructureException
49
     */
50
    private function getBundleVersion($bundle)
51
    {
52
        $return = $this->container->get('versions.bundle')->getVersion($bundle);
53
        if ($return->getVersion() === null) {
54
            throw new StructureException('Bundle "' . $bundle . '" main class must extends kujaff\VersionsBundle\Model\VersionnedBundle.');
55
        }
56
        return $return;
57
    }
58
59
    /**
60
     * Install
61
     *
62
     * @param string $bundle
63
     * @param boolean $force Force installation
64
     * @param OutputInterface $output
65
     * @return Version
66
     * @throws StructureException
67
     * @throws InstallStateException
68
     */
69
    public function install($bundle, $force = false, $output = null)
70
    {
71
        $manager = $this->container->get('doctrine')->getManager();
72
        if ($force === false) {
73
            $bundleVersion = $this->getBundleVersion($bundle);
74
75
            // already installed
76
            if ($bundleVersion->isInstalled()) {
77
                throw new InstallStateException('Bundle "' . $bundle . '" is already installed.');
78
            }
79
        }
80
81
        if ($output instanceof OutputInterface) {
82
            $output->write('[<comment>' . $bundle . '</comment>] Installing ... ');
83
        }
84
85
        $service = $this->getService($bundle, 'install', 'kujaff\\VersionsBundle\\Model\\Install');
86
        // bundle has a service to do stuff
87
        if ($service !== false) {
88
            $installedVersion = $service->install();
89
            if (!$installedVersion instanceof Version) {
90
                throw new StructureException('Service "' . get_class($service) . '" install method must return an instance of kujaff\VersionsBundle\Entity\Version.');
91
            }
92
            if ($output instanceof OutputInterface) {
93
                $output->writeln('<info>' . $installedVersion->asString() . '</info> installed.');
94
            }
95
96
            if ($force) {
97
                $bundleVersion = $this->getBundleVersion($bundle);
98
            }
99
            $bundleVersion->setInstalledVersion($installedVersion);
0 ignored issues
show
Bug introduced by
The variable $bundleVersion does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
100
            $bundleVersion->setInstallationDate(new \DateTime());
101
            $manager->persist($bundleVersion);
102
            $manager->flush();
103
            return $installedVersion;
104
        }
105
106
        if ($output instanceof OutputInterface) {
107
            $output->writeln('<info>' . $installedVersion->asString() . '</info> installed.');
0 ignored issues
show
Bug introduced by
The variable $installedVersion seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
108
        }
109
110
        // no install service for this bundle, assume we installed the latest version
111
        if ($force) {
112
            $bundleVersion = $this->getBundleVersion($bundle);
113
        }
114
        $bundleVersion->setInstalledVersion($bundleVersion->getVersion());
115
        $bundleVersion->setInstallationDate(new \DateTime());
116
        $manager->persist($bundleVersion);
117
        $manager->flush();
118
        return $bundleVersion->getInstalledVersion();
119
    }
120
121
    /**
122
     * Install all bundle in required order
123
     *
124
     * @param OutputInterface $output
125
     */
126
    public function installAll($output = null)
127
    {
128
        foreach ($this->container->getParameter('versions.installOrder') as $bundle => $options) {
129
            try {
130
                $bundleVersion = $this->getBundleVersion($bundle);
131
            } catch (\Exception $e) {
132
                if ($bundle != 'VersionsBundle') {
133
                    throw $e;
134
                }
135
                $bundleVersion = new BundleVersion('VersionsBundle');
136
            }
137
            if ($bundleVersion->isInstalled() === false) {
138
                $this->install($bundle, $options['force'], $output);
139
            }
140
        }
141
142
        foreach ($this->container->get('versions.bundle')->getBundles() as $bundle) {
143
            $bundleVersion = $this->getBundleVersion($bundle->getName());
144
            if ($bundleVersion->isInstalled() === false) {
145
                $this->install($bundle->getName(), false, $output);
146
            }
147
        }
148
    }
149
150
    /**
151
     * Update a bundle
152
     *
153
     * @param string $bundle Bundle name
154
     * @param Version $version Version to install, null to latest
155
     * @param OutputInterface $output
156
     * @throws InstallStateException
157
     */
158
    public function update($bundle, $version = null, $output = null)
159
    {
160
        $bundleVersion = $this->getBundleVersion($bundle);
161
        if ($bundleVersion->isInstalled() === false) {
162
            throw new InstallStateException('Bundle "' . $bundle . '" is not installed.');
163
        }
164
165
        $version = ($version instanceof Version) ? $version : $bundleVersion->getVersion();
166
167
        // already up to date
168
        if ($this->container->get('versions.version')->compare($bundleVersion->getInstalledVersion(), $version) >= 0) {
169
            return $bundleVersion->getInstalledVersion();
170
        }
171
172
        if ($output instanceof OutputInterface) {
173
            $output->write('[<comment>' . $bundle . '</comment>] Updating from ' . $bundleVersion->getInstalledVersion()->asString() . ' to ' . $version->asString() . ' ... ');
174
        }
175
176
        $service = $this->getService($bundle, 'update', 'kujaff\\VersionsBundle\\Model\\Update');
177
        // an update service has be found
178
        if ($service !== false) {
179
            $installedVersion = $service->update($bundleVersion, $version);
180
181
            // no update service, assume we have updated bundle to the latest version
182
        } else {
183
            $installedVersion = $version;
184
        }
185
186
        if ($output instanceof OutputInterface) {
187
            $output->writeln('<info>' . $installedVersion->asString() . '</info> installed.');
188
        }
189
190
        $bundleVersion->setInstalledVersion($installedVersion);
191
        $bundleVersion->setUpdateDate(new \DateTime());
192
        $this->container->get('doctrine')->getManager()->flush();
193
194
        return $installedVersion;
195
    }
196
197
    /**
198
     * Update all bundles
199
     *
200
     * @param OutputInterface $output
201
     */
202
    public function updateAll($output = null)
203
    {
204
        foreach ($this->container->getParameter('versions.updateOrder') as $order) {
205
            $this->update($order['bundle'], new Version($order['version']), $output);
206
        }
207
208
        foreach ($this->container->get('versions.bundle')->getBundles() as $bundle) {
209
            $this->update($bundle->getName(), null, $output);
210
        }
211
    }
212
213
    /**
214
     * Uninstall
215
     *
216
     * @param string $bundle
217
     * @param boolean $force Force uninstall, although it's not installed
218
     * @throws InstallStateException
219
     */
220
    public function uninstall($bundle, $force = false)
221
    {
222
        $manager = $this->container->get('doctrine')->getManager();
223
        $bundleVersion = $this->getBundleVersion($bundle);
224
        if ($force === false && $bundleVersion->isInstalled() === false) {
225
            throw new InstallStateException('Bundle "' . $bundle . '" is not installed.');
226
        }
227
228
        $service = $this->getService($bundle, 'uninstall', 'kujaff\\VersionsBundle\\Model\\Uninstall');
229
        if ($service !== false) {
230
            $service->uninstall();
231
        }
232
233
        $manager->remove($bundleVersion);
234
        $manager->flush();
235
    }
236
}
237