1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Godsgood33\Php_Db; |
4
|
|
|
|
5
|
|
|
use InvalidArgumentException; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Class to store field values |
9
|
|
|
* |
10
|
|
|
* @property string $field |
11
|
|
|
* The database field name |
12
|
|
|
* @property string $table |
13
|
|
|
* The database table link |
14
|
|
|
* @property string $alias |
15
|
|
|
* The field alias if desired |
16
|
|
|
* |
17
|
|
|
* @author Ryan Prather <[email protected]> |
18
|
|
|
*/ |
19
|
|
|
class DBField |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* Class properties |
23
|
|
|
* |
24
|
|
|
* @var array |
25
|
|
|
*/ |
26
|
|
|
private array $data = [ |
27
|
|
|
'field' => '', |
28
|
|
|
'table' => '', |
29
|
|
|
'alias' => '', |
30
|
|
|
]; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Constructor |
34
|
|
|
* |
35
|
|
|
* @param string $field |
36
|
|
|
* The parameter field name to return |
37
|
|
|
* @param string $table |
38
|
|
|
* The parameter representing the table (can be an alias) |
39
|
|
|
* @param string $alias |
40
|
|
|
* The parameter representing the alias the field should be known as (e.g. " `name` AS 'full_name'") |
41
|
|
|
* |
42
|
|
|
* @throws InvalidArgumentException |
43
|
|
|
*/ |
44
|
|
|
public function __construct(string $field = '*', string $table = '', string $alias = '') |
45
|
|
|
{ |
46
|
|
|
if (preg_match("/[^A-Za-z0-9_\*]/", $field)) { |
47
|
|
|
throw new InvalidArgumentException("Invalid field name $field"); |
48
|
|
|
} elseif (preg_match("/[^A-Za-z0-9_]/", $table)) { |
49
|
|
|
throw new InvalidArgumentException("Invalid table name $table"); |
50
|
|
|
} elseif (preg_match("/[^A-Za-z0-9_]/", $alias)) { |
51
|
|
|
throw new InvalidArgumentException("Invalid alias $alias"); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$this->data['field'] = $field; |
55
|
|
|
$this->data['table'] = $table; |
56
|
|
|
$this->data['alias'] = $alias; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Magic method to turn the class into a string |
61
|
|
|
* |
62
|
|
|
* @return string |
63
|
|
|
*/ |
64
|
|
|
public function __toString(): string |
65
|
|
|
{ |
66
|
|
|
$ret = ($this->data['table'] ? $this->data['table'].'.' : ''). |
67
|
|
|
($this->data['field'] == '*' ? $this->data['field'] : "`{$this->data['field']}`"). |
68
|
|
|
($this->data['alias'] ? " AS '{$this->data['alias']}'" : ""); |
69
|
|
|
|
70
|
|
|
return $ret; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|