1 <?php
2
3 /*
4 * DirectAdmin API Client
5 * (c) Omines Internetbureau B.V. - https://omines.nl/
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10
11 namespace Omines\DirectAdmin\Utility;
12
13 /**
14 * Static helper class for various conversion operations.
15 *
16 * @author Niels Keurentjes <niels.keurentjes@omines.com>
17 */
18 class Conversion
19 {
20 /**
21 * Reduces any input to an ON/OFF value.
22 *
23 * @param mixed $input Data to convert
24 * @param mixed $default Fallback to use if $input is NULL
25 * @return string Either ON or OFF
26 */
27 public static function onOff($input, $default = false)
28 {
29 return self::toBool($input, $default) ? 'ON' : 'OFF';
30 }
31
32 /**
33 * Expands a single option to its unlimited counterpart if NULL or literal 'unlimited'.
34 *
35 * @param array $options Array of options to process
36 * @param string $key Key of the item to process
37 */
38 protected static function processUnlimitedOption(array &$options, $key)
39 {
40 $ukey = "u{$key}";
41 unset($options[$ukey]);
42 if (array_key_exists($key, $options) && ($options[$key] === 'unlimited' || !isset($options[$key]))) {
43 $options[$ukey] = 'ON';
44 }
45 }
46
47 /**
48 * Detects package/domain options that can be unlimited and sets the accordingly.
49 *
50 * @param array $options
51 * @return array Modified array
52 */
53 public static function processUnlimitedOptions(array $options)
54 {
55 foreach (['bandwidth', 'domainptr', 'ftp', 'mysql', 'nemailf', 'nemailml', 'nemailr', 'nemails',
56 'nsubdomains', 'quota', 'vdomains', ] as $key) {
57 self::processUnlimitedOption($options, $key);
58 }
59 return $options;
60 }
61
62 /**
63 * Processes DirectAdmin style encoded responses into a sane array.
64 *
65 * @param string $data
66 * @return array
67 */
68 public static function responseToArray($data)
69 {
70 $unescaped = preg_replace_callback('/&#([0-9]{2})/', function ($val) {
71 return chr($val[1]);
72 }, $data);
73 return \GuzzleHttp\Psr7\parse_query($unescaped);
74 }
75
76 /**
77 * Ensures a DA-style response element is wrapped properly as an array.
78 *
79 * @param mixed $result Messy input
80 * @return array Sane output
81 */
82 public static function sanitizeArray($result)
83 {
84 if (count($result) == 1 && isset($result['list[]'])) {
85 $result = $result['list[]'];
86 }
87 return is_array($result) ? $result : [$result];
88 }
89
90 /**
91 * Converts values like ON, YES etc. to proper boolean variables.
92 *
93 * @param mixed $value Value to be converted
94 * @param mixed $default Value to use if $value is NULL
95 * @return bool
96 */
97 public static function toBool($value, $default = false)
98 {
99 return filter_var(isset($value) ? $value : $default, FILTER_VALIDATE_BOOLEAN);
100 }
101 }
102