Completed
Push — master ( 36f253...f7aa2f )
by Sébastien
04:00
created

Config::getPort()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
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
        'classpaths' => [],
32
        'threads' => 50
33
    ];
34
35
    /**
36
     * Internal configuration array
37
     * @var array
38
     */
39
    protected $config;
40
41
42
    /**
43
     * Constructor
44
     *
45
     * <code>
46
     *
47
     * $params = [
48
     *      // Port (required)
49
     *      'port' => 8089,
50
     *
51
     *      // Classpath autoloads (optional)
52
     *      'classpaths' => [
53
     *          '/my/path/to_specific/jar_file.jar',
54
     *          '/my/path/to_all_jars/*.jar'
55
     *      ],
56
     *
57
     *      'threads' => 50,
58
     *
59
     *      // Defaults (optional)
60
     *      'java_bin'   => 'java',
61
     *      'server_jar' => '{base_dir}/resources/pjb621_standalone/JavaBridge.jar',
62
     *      'log_file'   => '{base_dir}/var/pjbserver-port{tcp_port}.log',
63
     *      'pid_file'   => '{base_dir}/var/pjbserver-port{tcp_port}.pid'
64
     *
65
     * ];
66
     * $config = new StandaloneServer\Config($params);
67
     * </code>
68
     *
69
     * @throws Exception\InvalidArgumentException
70
     * @param array $config
71
     *
72
     */
73 31
    public function __construct(array $config)
74
    {
75 31
        if (!isset($config['port'])) {
76 3
            throw new Exception\InvalidArgumentException("Error missing required 'port' in config");
77 28
        } elseif (!filter_var($config['port'], FILTER_VALIDATE_INT) || $config['port'] < 1) {
78 1
            throw new Exception\InvalidArgumentException("Option 'port' must be numeric greater than 0");
79
        }
80 27
        $port = $config['port'];
81
        // Substitute magic vars is deprecated and will be removed in v1.0.0
82 27
        $config = array_merge(
83 27
                        $this->getDefaultConfig($port),
84 27
                        $this->substitutePlaceholders($config, $port));
85 27
        $this->checkConfig($config);
86 26
        $this->config = $config;
87 26
    }
88
89
    /**
90
     * Return port on which standalone server listens
91
     * @return int
92
     */
93 18
    public function getPort()
94
    {
95 18
        return $this->config['port'];
96
    }
97
98
    /**
99
     * Return jar file of the server
100
     * @return string
101
     */
102 18
    public function getServerJar()
103
    {
104 18
        return $this->config['server_jar'];
105
    }
106
107
108
    /**
109
     * Return java binary
110
     * @return string
111
     */
112 18
    public function getJavaBin()
113
    {
114 18
        return $this->config['java_bin'];
115
    }
116
117
    /**
118
     * Return log file
119
     * @return string
120
     */
121 18
    public function getLogFile()
122
    {
123 18
        return $this->config['log_file'];
124
    }
125
126
    /**
127
     * Return an array containing the java classpath(s) for the server
128
     * @return array
129
     */
130 18
    public function getClasspaths()
131
    {
132 18
        return $this->config['classpaths'];
133
    }
134
135
    /**
136
     * Return pid file where to store process id
137
     * @return string
138
     */
139 21
    public function getPidFile()
140
    {
141 21
        return $this->config['pid_file'];
142
    }
143
144
145
    /**
146
     * Return standalone server threads
147
     *
148
     * @return int|string
149
     */
150 15
    public function getThreads()
151
    {
152 15
        return $this->config['threads'];
153
    }
154
155
    /**
156
     * Return standalone configuration
157
     *
158
     * @return array
159
     */
160 4
    public function getConfig()
161
    {
162 4
        return $this->config;
163
    }
164
165
    /**
166
     * Return default configuration options
167
     * @param int $port
168
     * @return array
169
     */
170 27
    protected function getDefaultConfig($port)
171
    {
172 27
        return $this->substitutePlaceholders($this->default_config, $port);
173
    }
174
175
    /**
176
     * Substitute the placeholder {tcp_port} and {base_dir}
177
     * from a config array
178
     *
179
     * @param array $configArray associative array
180
     * @return array
181
     */
182 27
    protected function substitutePlaceholders(array $configArray, $port)
183
    {
184 27
        $substituted = [];
185 27
        $base_dir = $this->getBaseDir();
186
187 27
        foreach ($configArray as $key => $value) {
188 27
            $tmp = str_replace('{base_dir}', $base_dir, $value);
189 27
            $tmp = str_replace('{tcp_port}', $port, $tmp);
190 27
            $substituted[$key] = $tmp;
191 27
        }
192 27
        return $substituted;
193
    }
194
195
    /**
196
     * Return pjbserver-tools installation base directory
197
     *
198
     * @throws Exception\RuntimeException
199
     * @return string
200
     */
201 27
    public function getBaseDir()
202
    {
203
        // Four levels back.
204 27
        $ds  = DIRECTORY_SEPARATOR;
205 27
        $dir = __DIR__ . "$ds..$ds..$ds..$ds..$ds";
206 27
        $base_dir = realpath($dir);
207 27
        if (!$base_dir) {
208
            $message = "Cannot resolve project base directory.";
209
            throw new Exception\RuntimeException($message);
210
        }
211 27
        return $base_dir;
212
    }
213
214
    /**
215
     * Check configuration parameters
216
     * @throws Exception\InvalidArgumentException
217
     * @param array $config
218
     */
219 27
    protected function checkConfig(array $config)
220
    {
221
        // Step 1: all required options
222 27
        $required = ['port', 'server_jar', 'log_file', 'pid_file', 'threads'];
223 27
        foreach ($required as $option) {
224 27
            if (!isset($config[$option]) || $config[$option] == '') {
225
                throw new Exception\InvalidArgumentException("Missing resuired configuration option: '$option''");
226
            }
227 27
        }
228
229
        // Step 2: server_jar file must exists
230 27
        if (!is_file($config['server_jar']) || !is_readable($config['server_jar'])) {
231 1
            throw new Exception\InvalidArgumentException("Server jar file not exists or unreadable. server-jar: '" . $config['server_jar'] ."'");
232
        }
233
234
        // Step 3: log and pid file should be creatable
235 26
        $temp_required_files = ['log_file', 'pid_file'];
236 26
        foreach ($temp_required_files as $option) {
237 26
            $file = $config[$option];
238 26
            $info = pathinfo($file);
239 26
            $dirname = $info['dirname'];
240 26
            if (!is_dir($dirname) || $dirname == ".") {
241
                $msg = "Option '$option' refer to an invalid or non-existent directory ($file)";
242
                throw new Exception\InvalidArgumentException($msg);
243
            }
244 26
            if (is_dir($file)) {
245
                $msg = "Option '$option' does not refer to a file but an existing directory ($file)";
246
                throw new Exception\InvalidArgumentException($msg);
247
            }
248 26
            if (file_exists($file) && !is_writable($file)) {
249
                $msg = "File specified in '$option' is not writable ($file)";
250
                throw new Exception\InvalidArgumentException($msg);
251
            }
252 26
        }
253
254
        // Step 4: Threads must be numeric greater than 0
255
256 26
        $threads = $config['threads'];
257
258 26
        if (!preg_match('/^([0-9])+$/', $threads) || $threads <= 0) {
259 1
            $msg = "Parameter 'threads' must be valid integer greater than 0";
260 1
            throw new Exception\InvalidArgumentException($msg);
261
        }
262
263
        // Step 5: Java must be callable
264
265
        // @todo, many options exists
266
267
        // Step 6: Check classpaths autoload
268 26
        if (isset($config['classpaths'])) {
269 26
            if (!is_array($config['classpaths'])) {
270 1
                $msg = "Option 'classpaths' mus be a php array.";
271 1
                throw new Exception\InvalidArgumentException($msg);
272
            }
273 26
            foreach ($config['classpaths'] as $classpath) {
274 25
                if (preg_match('/\*\.jar$/', $classpath)) {
275
                    // Check if directory exists
276 25
                    $directory = preg_replace('/\*\.jar$/', '', $classpath);
277 25
                    if (!is_dir($directory) || !is_readable($directory)) {
278 1
                        $msg = "Classpath error, the directory of '$classpath' does not exists or is not readable";
279 1
                        throw new Exception\InvalidArgumentException($msg);
280
                    }
281 25
                } elseif (preg_match('/\.jar$/', $classpath)) {
282
                    // Check if file exists
283 1
                    if (!is_file($classpath) || !is_readable($classpath)) {
284 1
                        $msg = "Classpath error, the file '$classpath' does not exists or is not readable";
285 1
                        throw new Exception\InvalidArgumentException($msg);
286
                    }
287
                } else {
288 1
                    $msg = "Error in classpath, files to import must end by .jar extension ($classpath)";
289 1
                    throw new Exception\InvalidArgumentException($msg);
290
                }
291 26
            }
292 26
        }
293 26
    }
294
}
295