Skip to content

Commit 267c04c

Browse files
committed
Create a custom action
1 parent 5d0649e commit 267c04c

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

src/AppBundle/Action/BuyBook.php

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
namespace AppBundle\Action;
4+
5+
use AppBundle\Entity\Book;
6+
use Psr\Log\LoggerInterface;
7+
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
8+
use Symfony\Component\HttpFoundation\Request;
9+
10+
class BuyBook
11+
{
12+
private $logger;
13+
14+
public function __construct(LoggerInterface $logger)
15+
{
16+
$this->logger = $logger;
17+
}
18+
19+
/**
20+
* @Route(
21+
* "/books/{id}/buy",
22+
* name="book_buy",
23+
* methods={"POST"},
24+
* defaults={"_api_resource_class"=Book::class, "_api_item_operation_name"="buy"}
25+
* )
26+
*/
27+
public function __invoke(Book $book, Request $request)
28+
{
29+
$this->logger->info('The user wants to buy a book', [
30+
'uuid' => $book->getUuid(),
31+
'name' => $book->getName(),
32+
'contexts' => $request->getContent(),
33+
]);
34+
35+
$book->setName($book->getName() . ' (Bought)');
36+
37+
return $book;
38+
}
39+
}

src/AppBundle/Entity/Book.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@
88
use ApiPlatform\Core\Annotation\ApiResource;
99

1010
/**
11-
* @ApiResource
11+
* @ApiResource(itemOperations={
12+
* "get"={"method"="GET"},
13+
* "buy"={"route_name"="book_buy"}
14+
* })
1215
*
1316
* @ORM\Entity
1417
*/
@@ -33,7 +36,7 @@ class Book
3336
/**
3437
* @ORM\OneToMany(targetEntity="Review", mappedBy="book")
3538
*
36-
* @var Review[]
39+
* @var Collection
3740
*/
3841
private $reviews;
3942

0 commit comments

Comments
 (0)