Skip to content

Commit

Permalink
feat: added fruit persist and validation
Browse files Browse the repository at this point in the history
  • Loading branch information
benborla committed Nov 18, 2023
1 parent 87ab3d5 commit 8323e43
Show file tree
Hide file tree
Showing 6 changed files with 275 additions and 3 deletions.
1 change: 1 addition & 0 deletions api/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"symfony/http-client": "6.3.*",
"symfony/mailer": "6.3.*",
"symfony/runtime": "6.3.*",
"symfony/validator": "6.3.*",
"symfony/yaml": "6.3.*"
},
"require-dev": {
Expand Down
176 changes: 175 additions & 1 deletion api/composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions api/config/packages/validator.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
framework:
validation:
email_validation_mode: html5

# Enables validator auto-mapping support.
# For instance, basic validation constraints will be inferred from Doctrine's metadata.
#auto_mapping:
# App\Entity\: []

when@test:
framework:
validation:
not_compromised_password: false
42 changes: 40 additions & 2 deletions api/src/Controller/IndexController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,20 @@
use App\Pagination\Paginator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use App\Repository\FruitRepository;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Fruit;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Doctrine\ORM\EntityManagerInterface;

final class IndexController extends AbstractController
{
public function __construct(private EntityManagerInterface $em)
{
}

#[Route('/', name: 'fruits', methods: ['GET'])]
public function all(Request $request, FruitRepository $fruits): JsonResponse
{
Expand All @@ -30,9 +38,39 @@ public function all(Request $request, FruitRepository $fruits): JsonResponse
}

#[Route('/fruit', name: 'fruit_add', methods: ['POST', 'PUT'])]
public function fruitNew(Request $request)
public function fruitNew(Request $request, ValidatorInterface $validator)
{
// dd($request);
$data = json_decode($request->getContent(), true);

$fruit = new Fruit();
$fruit->setName($data['name'] ?? '')
->setGenus($data['genus'] ?? '')
->setFamily($data['family'] ?? '')
->setFruitOrder($data['fruit_order'] ?? '')
->setCarbohydrates($data['carbohydrates'] ?? 0)
->setFat($data['fat'] ?? 0)
->setProtein($data['protein'] ?? 0)
->setSugar($data['sugar'] ?? 0)
->setCalories($data['calories'] ?? 0)
->setCreatedAt(new \DateTime('now'))
->setUpdatedAt(new \DateTime('now'))
->setSource(Fruit::SOURCE_FROM_APP);

$violations = $validator->validate($fruit);

// @INFO: Return an error upon validator errors
if (count($violations) > 0) {
$errors = [];
foreach ($violations as $violation) {
$errors[$violation->getPropertyPath()][] = $violation->getMessage();
}

return $this->json(['errors' => $errors], Response::HTTP_UNPROCESSABLE_ENTITY);
}
$this->em->persist($fruit);
$this->em->flush();

return new JsonResponse($fruit->toArray());
}

#[Route('/fruit/{id}', name: 'fruit', methods: ['GET', 'POST', 'PUT'])]
Expand Down
34 changes: 34 additions & 0 deletions api/src/Entity/Fruit.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\Repository\FruitRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

#[ORM\Entity(repositoryClass: FruitRepository::class)]
#[ORM\Table(name: 'fruits')]
Expand All @@ -25,15 +26,43 @@ class Fruit
private ?int $id = null;

#[ORM\Column(length: 50)]
#[Assert\NotBlank(message: "Name cannot be blank")]
#[Assert\Length(
min: 4,
max: 50,
minMessage: "Name must be at least 4 characters long.",
maxMessage: "Name cannot be longer than 50 characters."
)]
private ?string $name = null;

#[ORM\Column(length: 20)]
#[Assert\NotBlank(message: "Genus cannot be blank")]
#[Assert\Length(
min: 4,
max: 20,
minMessage: "Genus must be at least 4 characters long.",
maxMessage: "Genus cannot be longer than 20 characters."
)]
private ?string $genus = null;

#[ORM\Column(length: 50)]
#[Assert\NotBlank(message: "Family cannot be blank")]
#[Assert\Length(
min: 4,
max: 50,
minMessage: "Family must be at least 4 characters long.",
maxMessage: "Family cannot be longer than 50 characters."
)]
private ?string $family = null;

#[ORM\Column(length: 30)]
#[Assert\NotBlank(message: "Fruit order cannot be blank")]
#[Assert\Length(
min: 4,
max: 30,
minMessage: "Fruit order must be at least 4 characters long.",
maxMessage: "Fruit order cannot be longer than 30 characters."
)]
private ?string $fruitOrder = null;

#[ORM\Column(nullable: true)]
Expand Down Expand Up @@ -221,4 +250,9 @@ public function setTimestampsOnUpdate(): void
{
$this->updatedAt = new \DateTime('now');
}

public function toArray(): array
{
return get_object_vars($this);
}
}
12 changes: 12 additions & 0 deletions api/symfony.lock
Original file line number Diff line number Diff line change
Expand Up @@ -167,5 +167,17 @@
"config/packages/routing.yaml",
"config/routes.yaml"
]
},
"symfony/validator": {
"version": "6.3",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "5.3",
"ref": "c32cfd98f714894c4f128bb99aa2530c1227603c"
},
"files": [
"config/packages/validator.yaml"
]
}
}

0 comments on commit 8323e43

Please sign in to comment.