11<?php namespace PerspectiveApi ;
22
33use GuzzleHttp \Client ;
4+ use GuzzleHttp \Exception \ClientException ;
45
56class CommentsClient {
67 const API_URL = 'https://commentanalyzer.googleapis.com/v1alpha1 ' ;
@@ -19,8 +20,20 @@ public function __construct(string $token) {
1920 $ this ->token = $ token ;
2021 }
2122
22- public function analyze (array $ fields ): CommentsResponse {
23- return $ this ->request ('analyze ' , []);
23+ public function analyze (): CommentsResponse {
24+ $ data = [];
25+ $ fields = [
26+ 'comment ' , 'languages ' , 'requestedAttributes ' , 'context ' , 'spanAnnotations ' , 'doNotStore ' , 'clientToken ' ,
27+ 'sessionId '
28+ ];
29+
30+ foreach ($ fields AS $ field ) {
31+ if (isset ($ this ->{$ field })) {
32+ $ data [$ field ] = $ this ->{$ field };
33+ }
34+ }
35+
36+ return $ this ->request ('analyze ' , $ data );
2437 }
2538
2639 public function suggestScore () {
@@ -68,21 +81,21 @@ public function communityId() {
6881 }
6982
7083 protected function request (string $ method , array $ data ): CommentsResponse {
71- $ fields = 'attributeScores,detectedLanguages,languages ' ;
7284 $ client = new Client (['defaults ' => [
7385 'headers ' => ['content-type ' => 'application/json ' , 'Accept ' => 'application/json ' ],
7486 ]]);
75- $ response = $ client ->post (self ::API_URL ."/comments: {$ method }?key= {$ this ->token }&fields= " .$ fields , [
76- 'json ' => [
77- 'comment ' => $ this ->comment ,
78- 'languages ' => $ this ->languages ,
79- 'requestedAttributes ' => $ this ->requestedAttributes ,
80- 'context ' => $ this ->context ,
81- 'spanAnnotations ' => $ this ->spanAnnotations ,
82- 'doNotStore ' => $ this ->doNotStore ,
83- 'clientToken ' => $ this ->clientToken ,
84- 'sessionId ' => $ this ->sessionId
85- ]]);
87+
88+ try {
89+ $ response = $ client ->post (self ::API_URL ."/comments: {$ method }?key= {$ this ->token }" , ['json ' => $ data ]);
90+ } catch (ClientException $ e ) {
91+ $ error = json_decode ($ e ->getResponse ()->getBody (), true );
92+
93+ if (isset ($ error ['error ' ])) {
94+ throw new CommentsException ($ error ['error ' ]['message ' ], $ error ['error ' ]['code ' ]);
95+ } else {
96+ throw $ e ;
97+ }
98+ }
8699
87100 $ result = json_decode ($ response ->getBody (), true );
88101
0 commit comments