Completed
Push — master ( 34fefe...4d65b3 )
by Sébastien
03:46
created

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