Passed
Push — master ( a357e7...195a07 )
by Anton
04:22 queued 01:11
created

Query::getString()   D

Complexity

Conditions 9
Paths 12

Size

Total Lines 28
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 4.909
c 0
b 0
f 0
cc 9
eloc 10
nc 12
nop 3
1
<?php
2
3
/**
4
 * @package Framework\DB
5
 * @author Anton Romanov
6
 * @copyright Copyright (c) 2015-2016, Anton Romanov
7
 * @link http://cadmium-cms.com
8
 */
9
10
namespace DB {
11
12
	abstract class Query {
13
14
		protected $query = '';
15
16
		/**
17
		 * Get a field/table name
18
		 */
19
20
		protected function getName(string $name) : string {
21
22
			return preg_replace('/[^a-zA-Z0-9_]/', '_', trim($name));
23
		}
24
25
		/**
26
		 * Get a field value
27
		 */
28
29
		protected function getValue(string $value) : string {
30
31
			return ('\'' . addslashes($value) . '\'');
32
		}
33
34
		/**
35
		 * Get a field sorting direction
36
		 */
37
38
		protected function getDirection(string $direction) : string {
39
40
			return ((strtoupper($direction) !== 'DESC') ? 'ASC' : 'DESC');
41
		}
42
43
		/**
44
		 * Convert a data array to a string
45
		 */
46
47
		protected function getString($source = null, string $pattern = '', string $separator = '') : string {
48
49
			if (!is_array($source)) return (is_scalar($source) ? strval($source) : '');
50
51
			$regexs = ['key' => '/\^([a-z]+)/', 'value' => '/\$([a-z]+)/']; $matches = ['key' => [], 'value' => []];
52
53
			$parsers = ['name' => 'getName', 'value' => 'getValue', 'direction' => 'getDirection']; $output = []; $count = 0;
54
55
			# Parse pattern
56
57
			foreach ($regexs as $name => $regex) preg_match($regex, $pattern, $matches[$name]);
58
59
			# Process replacements
60
61
			foreach ($source as $key => $value) if (is_scalar($value)) {
62
63
				$output[$count] = $pattern; $item = &$output[$count++];
64
65
				foreach ($matches as $name => $match) if (isset($match[1]) && isset($parsers[$match[1]])) {
66
67
					$item = str_replace($match[0], [$this, $parsers[$match[1]]]($$name), $item);
68
				}
69
			};
70
71
			# ------------------------
72
73
			return implode($separator, $output);
74
		}
75
76
		/**
77
		 * Convert the object to a string
78
		 */
79
80
		public function __toString() : string {
81
82
			return $this->query;
83
		}
84
	}
85
}
86