|
| 1 | +<?php |
| 2 | +namespace Tqdev\PhpCrudApi\Record; |
| 3 | + |
| 4 | +use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable; |
| 5 | + |
| 6 | +class ColumnIncluder |
| 7 | +{ |
| 8 | + |
| 9 | + private function isMandatory(String $tableName, String $columnName, array $params): bool |
| 10 | + { |
| 11 | + return isset($params['mandatory']) && in_array($tableName . "." . $columnName, $params['mandatory']); |
| 12 | + } |
| 13 | + |
| 14 | + private function select(String $tableName, bool $primaryTable, array $params, String $paramName, |
| 15 | + array $columnNames, bool $include): array{ |
| 16 | + if (!isset($params[$paramName])) { |
| 17 | + return $columnNames; |
| 18 | + } |
| 19 | + $columns = array(); |
| 20 | + foreach (explode(',', $params[$paramName][0]) as $columnName) { |
| 21 | + $columns[$columnName] = true; |
| 22 | + } |
| 23 | + $result = array(); |
| 24 | + foreach ($columnNames as $columnName) { |
| 25 | + $match = isset($columns['*.*']); |
| 26 | + if (!$match) { |
| 27 | + $match = isset($columns[$tableName . '.*']) || isset($columns[$tableName . '.' . $columnName]); |
| 28 | + } |
| 29 | + if ($primaryTable && !$match) { |
| 30 | + $match = isset($columns['*']) || isset($columns[$columnName]); |
| 31 | + } |
| 32 | + if ($match) { |
| 33 | + if ($include || $this->isMandatory($tableName, $columnName, $params)) { |
| 34 | + $result[] = $columnName; |
| 35 | + } |
| 36 | + } else { |
| 37 | + if (!$include || $this->isMandatory($tableName, $columnName, $params)) { |
| 38 | + $result[] = $columnName; |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + return $result; |
| 43 | + } |
| 44 | + |
| 45 | + public function getNames(ReflectedTable $table, bool $primaryTable, array $params): array |
| 46 | + { |
| 47 | + $tableName = $table->getName(); |
| 48 | + $results = $table->columnNames(); |
| 49 | + $results = $this->select($tableName, $primaryTable, $params, 'include', $results, true); |
| 50 | + $results = $this->select($tableName, $primaryTable, $params, 'exclude', $results, false); |
| 51 | + return $results; |
| 52 | + } |
| 53 | + |
| 54 | + public function getValues(ReflectedTable $table, bool $primaryTable, /* object */ $record, array $params): array |
| 55 | + { |
| 56 | + $results = array(); |
| 57 | + $columnNames = $this->getNames($table, $primaryTable, $params); |
| 58 | + foreach ($columnNames as $columnName) { |
| 59 | + if (property_exists($record, $columnName)) { |
| 60 | + $results[$columnName] = $record->$columnName; |
| 61 | + } |
| 62 | + } |
| 63 | + return $results; |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments