Completed
Push — master ( f7aa2f...852d76 )
by Sébastien
04:02
created

Config::getJavaBin()   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 33
    public function __construct(array $config)
74
    {
75 33
        if (!isset($config['port'])) {
76 3
            throw new Exception\InvalidArgumentException("Error missing required 'port' in config");
77 30
        } 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 29
        $port = $config['port'];
81
        // Substitute magic vars is deprecated and will be removed in v1.0.0
82 29
        $config = array_merge(
83 29
                        $this->getDefaultConfig($port),
84 29
                        $this->substitutePlaceholders($config, $port));
85 29
        $this->checkConfig($config);
86 28
        $this->config = $config;
87 28
    }
88
89
    /**
90
     * Return port on which standalone server listens
91
     * @return int
92
     */
93 19
    public function getPort()
94
    {
95 19
        return $this->config['port'];
96
    }
97
98
    /**
99
     * Return jar file of the server
100
     * @return string
101
     */
102 19
    public function getServerJar()
103
    {
104 19
        return $this->config['server_jar'];
105
    }
106
107
108
    /**
109
     * Return java binary
110
     * @return string
111
     */
112 19
    public function getJavaBin()
113
    {
114 19
        return $this->config['java_bin'];
115
    }
116
117
    /**
118
     * Return log file
119
     * @return string
120
     */
121 19
    public function getLogFile()
122
    {
123 19
        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 19
    public function getClasspaths()
131
    {
132 19
        return $this->config['classpaths'];
133
    }
134
135
    /**
136
     * Return pid file where to store process id
137
     * @return string
138
     */
139 23
    public function getPidFile()
140
    {
141 23
        return $this->config['pid_file'];
142
    }
143
144
145
    /**
146
     * Return standalone server threads
147
     *
148
     * @return int|string
149
     */
150 16
    public function getThreads()
151
    {
152 16
        return $this->config['threads'];
153
    }
154
155
    /**
156
     * Return standalone configuration
157
     *
158
     * @return array
159
     */
160 5
    public function toArray()
161
    {
162 5
        return $this->config;
163
    }
164
165
    /**
166
     * Return standalone configuration
167
     * @deprecated use toArray() instead
168
     * @return array
169
     */
170 4
    public function getConfig()
171
    {
172 4
        return $this->toArray();
173
    }
174
175
176
    /**
177
     * Return default configuration options
178
     * @param int $port
179
     * @return array
180
     */
181 29
    protected function getDefaultConfig($port)
182
    {
183 29
        return $this->substitutePlaceholders($this->default_config, $port);
184
    }
185
186
    /**
187
     * Substitute the placeholder {tcp_port} and {base_dir}
188
     * from a config array
189
     *
190
     * @param array $configArray associative array
191
     * @return array
192
     */
193 29
    protected function substitutePlaceholders(array $configArray, $port)
194
    {
195 29
        $substituted = [];
196 29
        $base_dir = $this->getBaseDir();
197
198 29
        foreach ($configArray as $key => $value) {
199 29
            $tmp = str_replace('{base_dir}', $base_dir, $value);
200 29
            $tmp = str_replace('{tcp_port}', $port, $tmp);
201 29
            $substituted[$key] = $tmp;
202 29
        }
203 29
        return $substituted;
204
    }
205
206
    /**
207
     * Return pjbserver-tools installation base directory
208
     *
209
     * @throws Exception\RuntimeException
210
     * @return string
211
     */
212 29
    public function getBaseDir()
213
    {
214
        // Four levels back.
215 29
        $ds  = DIRECTORY_SEPARATOR;
216 29
        $dir = __DIR__ . "$ds..$ds..$ds..$ds..$ds";
217 29
        $base_dir = realpath($dir);
218 29
        if (!$base_dir) {
219
            $message = "Cannot resolve project base directory.";
220
            throw new Exception\RuntimeException($message);
221
        }
222 29
        return $base_dir;
223
    }
224
225
    /**
226
     * Check configuration parameters
227
     * @throws Exception\InvalidArgumentException
228
     * @param array $config
229
     */
230 29
    protected function checkConfig(array $config)
231
    {
232
        // Step 1: all required options
233 29
        $required = ['port', 'server_jar', 'log_file', 'pid_file', 'threads'];
234 29
        foreach ($required as $option) {
235 29
            if (!isset($config[$option]) || $config[$option] == '') {
236
                throw new Exception\InvalidArgumentException("Missing resuired configuration option: '$option''");
237
            }
238 29
        }
239
240
        // Step 2: server_jar file must exists
241 29
        if (!is_file($config['server_jar']) || !is_readable($config['server_jar'])) {
242 1
            throw new Exception\InvalidArgumentException("Server jar file not exists or unreadable. server-jar: '" . $config['server_jar'] ."'");
243
        }
244
245
        // Step 3: log and pid file should be creatable
246 28
        $temp_required_files = ['log_file', 'pid_file'];
247 28
        foreach ($temp_required_files as $option) {
248 28
            $file = $config[$option];
249 28
            $info = pathinfo($file);
250 28
            $dirname = $info['dirname'];
251 28
            if (!is_dir($dirname) || $dirname == ".") {
252
                $msg = "Option '$option' refer to an invalid or non-existent directory ($file)";
253
                throw new Exception\InvalidArgumentException($msg);
254
            }
255 28
            if (is_dir($file)) {
256
                $msg = "Option '$option' does not refer to a file but an existing directory ($file)";
257
                throw new Exception\InvalidArgumentException($msg);
258
            }
259 28
            if (file_exists($file) && !is_writable($file)) {
260
                $msg = "File specified in '$option' is not writable ($file)";
261
                throw new Exception\InvalidArgumentException($msg);
262
            }
263 28
        }
264
265
        // Step 4: Threads must be numeric greater than 0
266
267 28
        $threads = $config['threads'];
268
269 28
        if (!preg_match('/^([0-9])+$/', $threads) || $threads <= 0) {
270 1
            $msg = "Parameter 'threads' must be valid integer greater than 0";
271 1
            throw new Exception\InvalidArgumentException($msg);
272
        }
273
274
        // Step 5: Java must be callable
275
276
        // @todo, many options exists
277
278
        // Step 6: Check classpaths autoload
279 28
        if (isset($config['classpaths'])) {
280 28
            if (!is_array($config['classpaths'])) {
281 1
                $msg = "Option 'classpaths' mus be a php array.";
282 1
                throw new Exception\InvalidArgumentException($msg);
283
            }
284 28
            foreach ($config['classpaths'] as $classpath) {
285 27
                if (preg_match('/\*\.jar$/', $classpath)) {
286
                    // Check if directory exists
287 27
                    $directory = preg_replace('/\*\.jar$/', '', $classpath);
288 27
                    if (!is_dir($directory) || !is_readable($directory)) {
289 1
                        $msg = "Classpath error, the directory of '$classpath' does not exists or is not readable";
290 1
                        throw new Exception\InvalidArgumentException($msg);
291
                    }
292 27
                } elseif (preg_match('/\.jar$/', $classpath)) {
293
                    // Check if file exists
294 1
                    if (!is_file($classpath) || !is_readable($classpath)) {
295 1
                        $msg = "Classpath error, the file '$classpath' does not exists or is not readable";
296 1
                        throw new Exception\InvalidArgumentException($msg);
297
                    }
298
                } else {
299 1
                    $msg = "Error in classpath, files to import must end by .jar extension ($classpath)";
300 1
                    throw new Exception\InvalidArgumentException($msg);
301
                }
302 28
            }
303 28
        }
304 28
    }
305
}
306