1: <?php
2:
3: namespace Charcoal\Source\Database;
4:
5: use \DomainException;
6:
7:
8: use \Charcoal\Source\Order;
9: use \Charcoal\Source\Database\DatabaseFilter;
10:
11: 12: 13:
14: class DatabaseOrder extends Order
15: {
16: 17: 18: 19: 20: 21:
22: public function sql()
23: {
24: $mode = $this->mode();
25: switch ($mode) {
26: case self::MODE_RANDOM:
27: return $this->byRandom();
28:
29: case self::MODE_VALUES:
30: return $this->byValues();
31:
32: case self::MODE_CUSTOM:
33: return $this->byCustom();
34: }
35:
36: $property = $this->property();
37: if (empty($property)) {
38: throw new DomainException(
39: 'Property can not be empty.'
40: );
41: }
42:
43: return sprintf('`%1$s` %2$s', $property, $mode);
44: }
45:
46: 47: 48: 49: 50:
51: private function byRandom()
52: {
53: return 'RAND()';
54: }
55:
56: 57: 58: 59: 60:
61: private function byCustom()
62: {
63: $sql = $this->string();
64: if ($sql) {
65: return $sql;
66: }
67: }
68:
69: 70: 71: 72: 73: 74:
75: private function byValues()
76: {
77: $values = $this->values();
78: if (empty($values)) {
79: throw new DomainException(
80: 'Values can not be empty.'
81: );
82: }
83:
84: $property = $this->property();
85: if (empty($property)) {
86: throw new DomainException(
87: 'Property can not be empty.'
88: );
89: }
90:
91: $values = array_filter($values, 'is_scalar');
92: $values = array_map(
93: function ($val) {
94: if (!is_numeric($val)) {
95: $val = htmlspecialchars($val, ENT_QUOTES);
96: $val = sprintf('"%s"', $val);
97: }
98:
99: return $val;
100: },
101: $values
102: );
103:
104: return sprintf('FIELD(`%1$s`, %2$s)', $property, implode(',', $values));
105: }
106: }
107: