diff --git a/.env.example b/.env.example index 71b434e8..5ea8b32b 100644 --- a/.env.example +++ b/.env.example @@ -2,7 +2,7 @@ APP_NAME=rinha-de-backend APP_ENV=dev DB_DRIVER=mysql -DB_HOST=localhost +DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=opencodeco DB_USERNAME=root diff --git a/app/Controller/PersonController.php b/app/Controller/PersonController.php index 856d21d8..dcc4ac41 100644 --- a/app/Controller/PersonController.php +++ b/app/Controller/PersonController.php @@ -21,8 +21,9 @@ final class PersonController { public function create(PersonRequest $request, ResponseInterface $response): MessageResponseInterface { - $person = $request->validated(); - + $person = $request->toPerson(); + $person->saveOrFail(); + return $response->json($person)->withStatus(201); } diff --git a/app/Model/Person.php b/app/Model/Person.php new file mode 100644 index 00000000..8bfeb4b5 --- /dev/null +++ b/app/Model/Person.php @@ -0,0 +1,39 @@ + '[]', + ]; +} diff --git a/app/Request/PersonRequest.php b/app/Request/PersonRequest.php index 4e0217ae..bc262256 100644 --- a/app/Request/PersonRequest.php +++ b/app/Request/PersonRequest.php @@ -12,6 +12,8 @@ namespace App\Request; +use App\Model\Person; +use Hyperf\Codec\Json; use Hyperf\Validation\Request\FormRequest; final class PersonRequest extends FormRequest @@ -34,6 +36,20 @@ public function rules(): array 'apelido' => 'required|max:32', 'nome' => 'required|max:100', 'nascimento' => 'required|date_format:Y-m-d', + 'stack' => 'array' ]; } + + public function toPerson(): Person + { + $data = $this->validated(); + + return Person::create([ + 'id' => random_bytes(16), + 'nick' => $data['apelido'], + 'name' => $data['nome'], + 'birth' => $data['nascimento'], + 'stack' => Json::encode($data['stack'] ?? null), + ]); + } } diff --git a/test/Cases/CreatePersonTest.php b/test/Cases/CreatePersonTest.php index dd298a68..2833fbee 100644 --- a/test/Cases/CreatePersonTest.php +++ b/test/Cases/CreatePersonTest.php @@ -142,7 +142,7 @@ public function testCreatePersonWithInvalidBirthDate(): void assertSame(422, $response->getStatusCode()); } - public function testCreatePerson(): void + public function testCreatePersonWithNullStack(): void { /** @var Response $response */ $response = $this->request('POST', '/pessoas', [ @@ -158,4 +158,22 @@ public function testCreatePerson(): void assertSame(201, $response->getStatusCode(), $response->getBody()->getContents()); } + + public function testCreatePersonWithSomeStack(): void + { + /** @var Response $response */ + $response = $this->request('POST', '/pessoas', [ + 'headers' => [ + 'Content-Type' => 'application/json', + ], + 'json' => [ + 'apelido' => 'opencodeco', + 'nome' => 'OpenCodeCo', + 'nascimento' => '2023-07-01', + 'stack' => ['PHP', 'Swoole', 'Hyperf'], + ], + ]); + + assertSame(201, $response->getStatusCode(), $response->getBody()->getContents()); + } }