aboutsummaryrefslogtreecommitdiffstats
path: root/core/namespace/Attribute.php
blob: 69998e08926a6d467ba3e64d945428f5f3770dd5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
abstract class Attribute implements AttributeInterface {

	#===============================================================================
	# Set attribute
	#===============================================================================
	public function set($attribute, $value) {
		return $this->{$attribute} = $value;
	}

	#===============================================================================
	# Get attribute
	#===============================================================================
	public function get($attribute) {
		return $this->{$attribute} ?? NULL;
	}

	#===============================================================================
	# Get array with not FALSE attributes
	#===============================================================================
	protected function getFilteredAttributes(): array {
		return array_filter(get_object_vars($this), function($value) {
			return $value !== FALSE;
		});
	}

	#===============================================================================
	# Insert database item
	#===============================================================================
	public function databaseINSERT(\Database $Database): bool {
		$part[0] = '';
		$part[1] = '';

		$attributes = $this->getFilteredAttributes();

		foreach($attributes as $column => $value) {
			$part[0] .= "{$column},";
			$part[1] .= '?,';
		}

		$part[0] = rtrim($part[0], ',');
		$part[1] = rtrim($part[1], ',');

		$Statement = $Database->prepare('INSERT INTO '.static::TABLE." ({$part[0]}) VALUES ({$part[1]})");
		return $Statement->execute(array_values($attributes));
	}

	#===============================================================================
	# Update database item
	#===============================================================================
	public function databaseUPDATE(\Database $Database): bool {
		$part = '';

		$attributes = $this->getFilteredAttributes();

		foreach($attributes as $column => $value) {
			$part .= "{$column} = ?,";
		}

		$part = rtrim($part, ',');

		$Statement = $Database->prepare('UPDATE '.static::TABLE.' SET '.$part.' WHERE id = '.(int) $this->get('id'));
		return $Statement->execute(array_values($attributes));
	}

	#===============================================================================
	# Delete database item
	#===============================================================================
	public function databaseDELETE(\Database $Database): bool {
		$Statement = $Database->prepare('DELETE FROM '.static::TABLE.' WHERE id = ?');
		return $Statement->execute([$this->get('id')]);
	}
}
?>