Completed
Push — master ( e6b0f2...148d74 )
by Sébastien
03:16
created

Config::checkConfig()   C

Complexity

Conditions 21
Paths 41

Size

Total Lines 64
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 35
CRAP Score 23.8377

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 64
ccs 35
cts 43
cp 0.8139
rs 5.9118
cc 21
eloc 38
nc 41
nop 1
crap 23.8377

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace PjbServer\Tools\StandaloneServer;
4
5
use PjbServer\Tools\Exception;
6
7
/*
8
  java -Djava.awt.headless="true"
9
  -Dphp.java.bridge.threads=50
10
  -Dphp.java.bridge.base=/usr/lib/php/modules
11
  -Dphp.java.bridge.php_exec=/usr/local/bin/php-cgi
12
  -Dphp.java.bridge.default_log_file=
13
  -Dphp.java.bridge.default_log_level=5
14
  -Dphp.java.bridge.daemon="false"
15
  -jar JavaBridge.jar
16
 * sudo netstat -anltp|grep :8089
17
 */
18
19
class Config
20
{
21
22
    /**
23
     * Default configuration options
24
     * @var array
25
     */
26
    protected $default_config = [
27
        'java_bin'   => 'java',
28
        'server_jar' => '{base_dir}/resources/pjb621_standalone/JavaBridge.jar',
29
        'log_file'   => '{base_dir}/var/pjbserver-port{tcp_port}.log',
30
        'pid_file'   => '{base_dir}/var/pjbserver-port{tcp_port}.pid',
31
    ];
32
33
    /**
34
     * Internal configuration array
35
     * @var array
36
     */
37
    protected $config;
38
39
40
    /**
41
     * Constructor
42
     *
43
     * <code>
44
     *
45
     * $params = [
46
     *      // Port (required)
47
     *      'port' => 8089,
48
     *
49
     *      // Classpath autoloads (optional)
50
     *      'classpaths' => [
51
     *          '/my/path/to_specific/jar_file.jar',
52
     *          '/my/path/to_all_jars/*.jar'
53
     *      ],
54
     *
55
     *      // Defaults (optional)
56
     *      'java_bin'   => 'java',
57
     *      'server_jar' => '{base_dir}/resources/pjb621_standalone/JavaBridge.jar',
58
     *      'log_file'   => '{base_dir}/var/pjbserver-port{tcp_port}.log',
59
     *      'pid_file'   => '{base_dir}/var/pjbserver-port{tcp_port}.pid'
60
     *
61
     * ];
62
     * $config = new StandaloneServer\Config($params);
63
     * </code>
64
     *
65
     * @throws Exception\InvalidArgumentException
66
     * @param array $config
67
     *
68
     */
69 20
    public function __construct(array $config)
70
    {
71 20
        if (!isset($config['port'])) {
72 3
            throw new Exception\InvalidArgumentException("Error missing required 'port' in config");
73 17
        } elseif (!filter_var($config['port'], FILTER_VALIDATE_INT) || $config['port'] < 1) {
74 1
            throw new Exception\InvalidArgumentException("Option 'port' must be numeric greater than 0");
75
        }
76 16
        $config = array_merge($this->getDefaultConfig($config['port']), $config);
77 16
        $this->checkConfig($config);
78 15
        $this->config = $config;
79 15
    }
80
81
    /**
82
     * Return port on which standalone server listens
83
     * @return int
84
     */
85 11
    public function getPort()
86
    {
87 11
        return $this->config['port'];
88
    }
89
90
    /**
91
     * Return jar file of the server
92
     * @return string
93
     */
94 11
    public function getServerJar()
95
    {
96 11
        return $this->config['server_jar'];
97
    }
98
99
100
    /**
101
     * Return java binary
102
     * @return string
103
     */
104 11
    public function getJavaBin()
105
    {
106 11
        return $this->config['java_bin'];
107
    }
108
109
    /**
110
     * Return log file
111
     * @return string
112
     */
113 11
    public function getLogFile()
114
    {
115 11
        return $this->config['log_file'];
116
    }
117
118
    /**
119
     *
120
     * @return string
121
     */
122 11
    public function getClasspaths()
123
    {
124 11
        return $this->config['classpaths'];
125
    }
126
127
    /**
128
     * Return pid file where to store process id
129
     * @return string
130
     */
131 13
    public function getPidFile()
132
    {
133 13
        return $this->config['pid_file'];
134
    }
135
136
    /**
137
     * Return standalone configuration
138
     *
139
     * @return array
140
     */
141 2
    public function getConfig()
142
    {
143 2
        return $this->config;
144
    }
145
146
    /**
147
     * Return default configuration options
148
     * @param int $port
149
     * @return array
150
     */
151 16
    protected function getDefaultConfig($port)
152
    {
153 16
        $base_dir = realpath(__DIR__ . '/../../../../');
154 16
        $config = [];
155 16
        foreach ($this->default_config as $key => $value) {
156 16
            $tmp = str_replace('{base_dir}', $base_dir, $value);
157 16
            $tmp = str_replace('{tcp_port}', $port, $tmp);
158 16
            $config[$key] = $tmp;
159 16
        }
160 16
        return $config;
161
    }
162
163
    /**
164
     * Check configuration parameters
165
     * @throws Exception\InvalidArgumentException
166
     * @param array $config
167
     */
168 16
    protected function checkConfig(array $config)
169
    {
170
        // Step 1: all required options
171 16
        $required = ['port', 'server_jar', 'log_file', 'pid_file'];
172 16
        foreach ($required as $option) {
173 16
            if (!isset($config[$option]) || $config[$option] == '') {
174
                throw new Exception\InvalidArgumentException("Missing resuired configuration option: '$option''");
175
            }
176 16
        }
177
178
        // Step 2: server_jar file must exists
179 16
        if (!is_file($config['server_jar']) || !is_readable($config['server_jar'])) {
180 1
            throw new Exception\InvalidArgumentException("Server jar file not exists or unreadable. server-jar: '" . $config['server_jar'] ."'");
181
        }
182
183
        // Step 3: log and pid file should be creatable
184 15
        $temp_required_files = ['log_file', 'pid_file'];
185 15
        foreach ($temp_required_files as $option) {
186 15
            $file = $config[$option];
187 15
            $info = pathinfo($file);
188 15
            $dirname = $info['dirname'];
189 15
            if (!is_dir($dirname) || $dirname == ".") {
190
                $msg = "Option '$option' refer to an invalid or non-existent directory ($file)";
191
                throw new Exception\InvalidArgumentException($msg);
192
            }
193 15
            if (is_dir($file)) {
194
                $msg = "Option '$option' does not refer to a file but an existing directory ($file)";
195
                throw new Exception\InvalidArgumentException($msg);
196
            }
197 15
            if (file_exists($file) && !is_writable($file)) {
198
                $msg = "File specified in '$option' is not writable ($file)";
199
                throw new Exception\InvalidArgumentException($msg);
200
            }
201 15
        }
202
203
        // Step 4: Java must be callable
204
205
        // Step 5: Check classpaths autoload
206 15
        if (isset($config['classpaths'])) {
207 15
            if (!is_array($config['classpaths'])) {
208 1
                $msg = "Option 'classpaths' mus be a php array.";
209 1
                throw new Exception\InvalidArgumentException($msg);
210
            }
211 15
            foreach ($config['classpaths'] as $classpath) {
212 15
                if (preg_match('/\*\.jar$/', $classpath)) {
213
                    // Check if directory exists
214 15
                    $directory = preg_replace('/\*\.jar$/', '', $classpath);
215 15
                    if (!is_dir($directory) || !is_readable($directory)) {
216 1
                        $msg = "Classpath error, the directory of '$classpath' does not exists or is not readable";
217 1
                        throw new Exception\InvalidArgumentException($msg);
218
                    }
219 15
                } elseif (preg_match('/\.jar$/', $classpath)) {
220
                    // Check if file exists
221 1
                    if (!is_file($classpath) || !is_readable($classpath)) {
222 1
                        $msg = "Classpath error, the file '$classpath' does not exists or is not readable";
223 1
                        throw new Exception\InvalidArgumentException($msg);
224
                    }
225
                } else {
226 1
                    $msg = "Error in classpath, files to import must end by .jar extension ($classpath)";
227 1
                    throw new Exception\InvalidArgumentException($msg);
228
                }
229 15
            }
230 15
        }
231 15
    }
232
}
233