77use ApiPlatform \Doctrine \Common \State \PersistProcessor ;
88use ApiPlatform \Metadata \Operation ;
99use ApiPlatform \State \ProcessorInterface ;
10+ use App \BookRepository \BookRepositoryInterface ;
1011use App \Entity \Book ;
1112use Symfony \Component \DependencyInjection \Attribute \Autowire ;
12- use Symfony \Component \HttpFoundation \Request ;
13- use Symfony \Component \Serializer \Encoder \DecoderInterface ;
14- use Symfony \Contracts \HttpClient \HttpClientInterface ;
13+ use Symfony \Component \HttpKernel \Exception \NotFoundHttpException ;
1514
1615/**
1716 * @implements ProcessorInterface<Book, Book>
2423 public function __construct (
2524 #[Autowire(service: PersistProcessor::class)]
2625 private ProcessorInterface $ persistProcessor ,
27- private HttpClientInterface $ client ,
28- private DecoderInterface $ decoder ,
26+ private BookRepositoryInterface $ bookRepository ,
2927 ) {
3028 }
3129
@@ -34,27 +32,17 @@ public function __construct(
3432 */
3533 public function process (mixed $ data , Operation $ operation , array $ uriVariables = [], array $ context = []): Book
3634 {
37- $ book = $ this ->getData ($ data ->book );
38- $ data ->title = $ book ['title ' ];
39-
40- $ data ->author = null ;
41- if (isset ($ book ['authors ' ][0 ]['key ' ])) {
42- $ author = $ this ->getData ('https://openlibrary.org ' . $ book ['authors ' ][0 ]['key ' ] . '.json ' );
43- if (isset ($ author ['name ' ])) {
44- $ data ->author = $ author ['name ' ];
45- }
35+ $ book = $ this ->bookRepository ->find ($ data ->book );
36+
37+ // this should never happen
38+ if (!$ book instanceof Book) {
39+ throw new NotFoundHttpException ();
4640 }
4741
42+ $ data ->title = $ book ->title ;
43+ $ data ->author = $ book ->author ;
44+
4845 // save entity
4946 return $ this ->persistProcessor ->process ($ data , $ operation , $ uriVariables , $ context );
5047 }
51-
52- private function getData (string $ uri ): array
53- {
54- return $ this ->decoder ->decode ($ this ->client ->request (Request::METHOD_GET , $ uri , [
55- 'headers ' => [
56- 'Accept ' => 'application/json ' ,
57- ],
58- ])->getContent (), 'json ' );
59- }
6048}
0 commit comments