7
7
use ApiPlatform \Doctrine \Common \State \PersistProcessor ;
8
8
use ApiPlatform \Metadata \Operation ;
9
9
use ApiPlatform \State \ProcessorInterface ;
10
+ use App \BookRepository \BookRepositoryInterface ;
10
11
use App \Entity \Book ;
11
12
use 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 ;
15
14
16
15
/**
17
16
* @implements ProcessorInterface<Book, Book>
24
23
public function __construct (
25
24
#[Autowire(service: PersistProcessor::class)]
26
25
private ProcessorInterface $ persistProcessor ,
27
- private HttpClientInterface $ client ,
28
- private DecoderInterface $ decoder ,
26
+ private BookRepositoryInterface $ bookRepository ,
29
27
) {
30
28
}
31
29
@@ -34,27 +32,17 @@ public function __construct(
34
32
*/
35
33
public function process (mixed $ data , Operation $ operation , array $ uriVariables = [], array $ context = []): Book
36
34
{
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 ();
46
40
}
47
41
42
+ $ data ->title = $ book ->title ;
43
+ $ data ->author = $ book ->author ;
44
+
48
45
// save entity
49
46
return $ this ->persistProcessor ->process ($ data , $ operation , $ uriVariables , $ context );
50
47
}
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
- }
60
48
}
0 commit comments