PHP code example of theunic / symfony-response-helpers
1. Go to this page and download the library: Download theunic/symfony-response-helpers library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
theunic / symfony-response-helpers example snippets
declare(strict_types=1);
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
final class HomePageController extends AbstractController
{
#[Route("/")]
public function __invoke(): Response
{
return Response\ok("<h1>Hello World!</h1>");
}
}
declare(strict_types=1);
namespace App\Controller\Api;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use App\Repository\UsersRepository;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Routing\Annotation\Route;
final class UsersController extends AbstractController
{
public function __construct(
private readonly UsersRepository $usersRepository,
private readonly ValidatorInterface $validator,
) {
}
#[Route("/api/users/{id}", methods: ["PUT"])]
public function __invoke(int $id, Request $req): JsonResponse
{
$user = $this->usersRepository->find($id);
if (!$user) {
return JsonResponse\notFound(["error" => sprintf("User with id %d was not found", $id)]);
}
$data = json_decode($req->getContent(), associative: true, falgs: JSON_THROW_ON_ERROR);
$constraint = new Assert\Collection([
'username' => new Assert\NotEmpty(),
'email' => [new Assert\NotEmpty(), new Assert\Email()]
]);
$errors = $this->validator->validate($data, $contraint);
if (count($errors) > 0) {
return JsonResponse\badRequest(
array_reduce(
$errors,
static function (array $errors, ContraintViolation $cv): array {
$errors[$cv->getPropertyPath()] = $error->getMessage();
return $errors;
},
[]
)
);
}
return JsonResponse\ok([
"id" => $id,
"username" => $user->getUsername(),
"email" => $user->getEmail()
]);
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.