|
- <?php
-
- declare(strict_types=1);
-
- namespace App\Controllers;
-
- use App\Repositories\CustomerRepository;
- use App\Repositories\CustomerTypeRepository;
- use Core\Controller;
- use Core\Request;
- use Core\Response;
-
- class CustomerApiController extends Controller
- {
- public function customers(): Response
- {
- $request = Request::capture();
- $customerTypeId = (int) ($request->input('customer_type_id') ?? 0);
-
- $repo = new CustomerRepository(database());
- $rows = $customerTypeId > 0
- ? $repo->allByTypeWithType($customerTypeId)
- : $repo->allWithType();
-
- return $this->json(array_map([$this, 'formatCustomer'], $rows));
- }
-
- public function customer(string $id): Response
- {
- $repo = new CustomerRepository(database());
- $row = $repo->findWithType((int) $id);
-
- if ($row === null) {
- return Response::json(['error' => 'Not found'], 404);
- }
-
- return $this->json($this->formatCustomer($row));
- }
-
- public function customerTypes(): Response
- {
- $repo = new CustomerTypeRepository(database());
- $rows = $repo->allOrderedByName();
-
- $data = array_map(static function (array $row): array {
- $attributes = [];
- if (!empty($row['attributes'])) {
- $attributes = json_decode((string) $row['attributes'], true) ?? [];
- }
-
- return [
- 'id' => (int) $row['id'],
- 'name' => (string) $row['name'],
- 'api_match_field' => (string) ($row['api_match_field'] ?? ''),
- 'attributes' => $attributes,
- ];
- }, $rows);
-
- return $this->json($data);
- }
-
- private function formatCustomer(array $row): array
- {
- $attributeValues = [];
- if (!empty($row['attribute_values'])) {
- $attributeValues = json_decode((string) $row['attribute_values'], true) ?? [];
- }
-
- return [
- 'id' => (int) $row['id'],
- 'customer_type_id' => (int) $row['customer_type_id'],
- 'customer_type_name' => (string) ($row['customer_type_name'] ?? ''),
- 'attribute_values' => $attributeValues,
- ];
- }
- }
|