everycheck / api-rest-utils
Installs: 1 521
Dependents: 1
Suggesters: 0
Security: 0
Stars: 1
Watchers: 2
Forks: 0
Open Issues: 0
Requires
- symfony/symfony: 3.4.*
Requires (Dev)
- php: >=5.5.9
- doctrine/doctrine-bundle: ^1.6
- doctrine/orm: ^2.5
- jms/serializer-bundle: ^1.0 | ^2.0
- sensio/distribution-bundle: ^5.0.19
- sensio/framework-extra-bundle: ^5.0.0
- symfony/monolog-bundle: ^3.1.0
- symfony/polyfill-apcu: ^1.0
README
Some basic utils we use in every api rest project under symfony
Response builder
For now there is one class responsible for building different kind of response needed by an api rest.
All methode return a Symfony\Component\HttpFoundation\Response
, with json content.
usage
public function getAction($id) { $response = new ResponseBuilder($this->get('jms_serializer')); $entity = $this->getDoctrine()->getManager()->getRepository(Entity::class)->find($id); if(empty($entity)) return $response->notFound(); return $response->ok($entities); }
Response available
- json
- empty
- notFound
- ok
- created
- deleted
- conflict
- forbiddenRoute
- forbiddenAcl
- forbidden
- badRequest
- formError for parsing symfony form error
- unauthorized
Configuring headers
Use the addHeaders
method :
public function getAction($id) { $response = new ResponseBuilder($this->get('jms_serializer')); $entity = $this->getDoctrine()->getManager()->getRepository(Entity::class)->find($id); if(empty($entity)) return $response->notFound(); return $response->addHeaders('X-something','some-value')->ok($entities); }
Find paginated with filter and order by
Another common thing required is a find all entity matching certain filter and ordered by some criteria
Just add the trait in your repository like this :
<?php namespace ACMEBundle\Repository; use EveryCheck\ApiRest\Utils\PaginatedRepositoryTrait; class PostRepository extends \Doctrine\ORM\EntityRepository { use PaginatedRepositoryTrait; const BASE_QUERY_NAME = 'post'; const LEFT_JOIN_ALIAS_LIST = [ 'post.author' => 'author', 'post.responses' => 'response', ]; const FILTER_OPTION = [ ['filterOn'=>'author.username' , 'filterName' => 'username' , 'filterKind'=>'like' ], ['filterOn'=>'response.message' , 'filterName' => 'response_message' , 'filterKind'=>'like' ], ['filterOn'=>'response.date' , 'filterName' => 'date' , 'filterKind'=>'greaterThan' ], ]; }
Here an exaple where you enable search on 3 fields on left join. You can also order by those fields.
Controler side :
/** * @Route("/posts", name="get_post_list", methods={"GET"}) */ public function getPostListAction(Request $request) { $posts = $this->getEntityManager()->getRepository(Post::class)->findPaginatedFromRequest($request); return $this->getResponseBuilder()->ok($posts); }
Response example :
{ "limit": 10, "offset": 0, "count": 1, "entities": [ { "message":"something", "author":{ "username":"someone" }, "responses":[ { "message":"something else", "author":{ "username":"someone_else" } } ] } ] }
Easy ?