summaryrefslogtreecommitdiffstats
path: root/library/Director/Application/Dependency.php
blob: 0100e69faf2560302379d75b4ea6a97cbad491fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php

namespace Icinga\Module\Director\Application;

class Dependency
{
    /** @var string */
    protected $name;

    /** @var string|null */
    protected $installedVersion;

    /** @var bool|null */
    protected $enabled;

    /** @var string */
    protected $operator;

    /** @var string */
    protected $requiredVersion;

    /** @var string */
    protected $requirement;

    /**
     * Dependency constructor.
     * @param string $name         Usually a module name
     * @param string $requirement  e.g. >=1.7.0
     * @param string $installedVersion
     * @param bool $enabled
     */
    public function __construct($name, $requirement, $installedVersion = null, $enabled = null)
    {
        $this->name = $name;
        $this->setRequirement($requirement);
        if ($installedVersion !== null) {
            $this->setInstalledVersion($installedVersion);
        }
        if ($enabled !== null) {
            $this->setEnabled($enabled);
        }
    }

    public function setRequirement($requirement)
    {
        if (preg_match('/^([<>=]+)\s*v?(\d+\.\d+\.\d+)$/', $requirement, $match)) {
            $this->operator = $match[1];
            $this->requiredVersion = $match[2];
            $this->requirement = $requirement;
        } else {
            throw new \InvalidArgumentException("'$requirement' is not a valid version constraint");
        }
    }

    /**
     * @return bool
     */
    public function isInstalled()
    {
        return $this->installedVersion !== null;
    }

    /**
     * @return string|null
     */
    public function getInstalledVersion()
    {
        return $this->installedVersion;
    }

    /**
     * @param string $version
     */
    public function setInstalledVersion($version)
    {
        $this->installedVersion = ltrim($version, 'v'); // v0.6.0 VS 0.6.0
    }

    /**
     * @return bool
     */
    public function isEnabled()
    {
        return $this->enabled === true;
    }

    /**
     * @param bool $enabled
     */
    public function setEnabled($enabled = true)
    {
        $this->enabled = $enabled;
    }

    public function isSatisfied()
    {
        if (! $this->isInstalled() || ! $this->isEnabled()) {
            return false;
        }

        return version_compare($this->installedVersion, $this->requiredVersion, $this->operator);
    }

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

    public function getRequirement()
    {
        return $this->requirement;
    }
}