Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

77 рядки
2.2KB

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Controllers;
  4. use App\Repositories\CustomerRepository;
  5. use App\Repositories\CustomerTypeRepository;
  6. use Core\Controller;
  7. use Core\Request;
  8. use Core\Response;
  9. class CustomerApiController extends Controller
  10. {
  11. public function customers(): Response
  12. {
  13. $request = Request::capture();
  14. $customerTypeId = (int) ($request->input('customer_type_id') ?? 0);
  15. $repo = new CustomerRepository(database());
  16. $rows = $customerTypeId > 0
  17. ? $repo->allByTypeWithType($customerTypeId)
  18. : $repo->allWithType();
  19. return $this->json(array_map([$this, 'formatCustomer'], $rows));
  20. }
  21. public function customer(string $id): Response
  22. {
  23. $repo = new CustomerRepository(database());
  24. $row = $repo->findWithType((int) $id);
  25. if ($row === null) {
  26. return Response::json(['error' => 'Not found'], 404);
  27. }
  28. return $this->json($this->formatCustomer($row));
  29. }
  30. public function customerTypes(): Response
  31. {
  32. $repo = new CustomerTypeRepository(database());
  33. $rows = $repo->allOrderedByName();
  34. $data = array_map(static function (array $row): array {
  35. $attributes = [];
  36. if (!empty($row['attributes'])) {
  37. $attributes = json_decode((string) $row['attributes'], true) ?? [];
  38. }
  39. return [
  40. 'id' => (int) $row['id'],
  41. 'name' => (string) $row['name'],
  42. 'api_match_field' => (string) ($row['api_match_field'] ?? ''),
  43. 'attributes' => $attributes,
  44. ];
  45. }, $rows);
  46. return $this->json($data);
  47. }
  48. private function formatCustomer(array $row): array
  49. {
  50. $attributeValues = [];
  51. if (!empty($row['attribute_values'])) {
  52. $attributeValues = json_decode((string) $row['attribute_values'], true) ?? [];
  53. }
  54. return [
  55. 'id' => (int) $row['id'],
  56. 'customer_type_id' => (int) $row['customer_type_id'],
  57. 'customer_type_name' => (string) ($row['customer_type_name'] ?? ''),
  58. 'attribute_values' => $attributeValues,
  59. ];
  60. }
  61. }

Powered by TurnKey Linux.