CheckServerIdTrait::requireServerId()   A
last analyzed

Complexity

Conditions 3
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 1
nop 1
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Fwolf\Config;
4
5
use Fwolf\Config\Exception\ServerIdNotSet;
6
use Fwolf\Config\Exception\ServerIdProhibited;
7
8
/**
9
 * @copyright   Copyright 2013-2017 Fwolf
10
 * @license     https://opensource.org/licenses/MIT MIT
11
 */
12
trait CheckServerIdTrait
13
{
14
    /**
15
     * Get server id from config
16
     *
17
     * @return string
18
     */
19
    abstract public function getServerId();
20
21
22
    /**
23
     * Check current server id in allowed list
24
     *
25
     * @param   string|int|string[]|int[] $allowedIds
26
     * @return  bool
27
     * @throws  ServerIdNotSet
28
     */
29
    public function isServerIdAllowed($allowedIds)
30
    {
31
        $serverId = $this->getServerId();
32
33
        if (empty($serverId)) {
34
            throw new ServerIdNotSet('Server id not set');
35
        }
36
37
        if (!is_array($allowedIds)) {
38
            $allowedIds = [$allowedIds];
39
        }
40
41
        return in_array($serverId, $allowedIds);
42
    }
43
44
45
    /**
46
     * Limit program can only run on preferred server
47
     *
48
     * @param   string|int|string[]|int[] $allowedIds
49
     * @return  $this
50
     * @throws  ServerIdProhibited
51
     */
52
    public function requireServerId($allowedIds)
53
    {
54
        if (!$this->isServerIdAllowed($allowedIds)) {
55
            $message = 'This program can only run on ' .
56
                (is_array($allowedIds)
57
                    ? 'servers: ' . implode(', ', $allowedIds)
58
                    : 'server ' . $allowedIds);
59
60
            throw new ServerIdProhibited($message);
61
        }
62
63
        return $this;
64
    }
65
}
66