77class AtomxClient extends ApiClient {
88 protected $ apiBase = null ;
99 protected $ id = null ;
10+ protected $ requiresLogin = true ;
1011
1112 /**
1213 * @var AccountStore Store the token for the application
1314 */
1415 private $ accountStore ;
15- private $ shouldSendToken = true ;
1616
1717 function __construct (AccountStore $ accountStore , $ idOrFields = null )
1818 {
@@ -48,23 +48,34 @@ public function setId($id)
4848
4949 protected function handleResponse (Response $ response )
5050 {
51- // TODO: Handle an invalid token/not logged in message
52- return json_decode (parent ::handleResponse ($ response ), true );
51+ $ code = $ response ->getStatusCode ();
52+
53+ if ($ code == 200 ) {
54+ return json_decode ($ response ->getBody ()->getContents (), true );
55+ }
56+
57+ if ($ code == 401 ) {
58+ // Unauthorized, invalidate token
59+ $ this ->accountStore ->storeToken (null );
60+ }
61+
62+ throw new ApiException ('Request failed, received the following status: ' .
63+ $ response ->getStatusCode () . ' Body: ' . $ response ->getBody ()->getContents ());
5364 }
5465
5566 protected function getDefaultOptions ()
5667 {
5768 $ options = parent ::getDefaultOptions ();
5869
59- if ($ this ->shouldSendToken )
60- $ options ['headers ' ] = ['Authorization ' => $ this ->getToken ()];
70+ if ($ this ->requiresLogin )
71+ $ options ['headers ' ] = ['Authorization ' => ' Bearer ' . $ this ->getToken ()];
6172
6273 return $ options ;
6374 }
6475
6576 public function login ()
6677 {
67- $ this ->shouldSendToken = false ;
78+ $ this ->requiresLogin = false ;
6879
6980 try {
7081 $ response = $ this ->postUrl ('login ' , [
@@ -77,17 +88,17 @@ public function login()
7788 throw new ApiException ('Unable to login to API! ' );
7889 }
7990
91+ $ this ->requiresLogin = true ;
92+
8093 if ($ response instanceof Stream) {
8194 $ response = json_decode ($ response ->getContents (), true );
8295 }
8396
84- $ this ->shouldSendToken = true ;
85-
8697 if ($ response ['success ' ] !== true )
8798 throw new ApiException ('Unable to login to API! ' );
8899
89100
90- $ token = ' Bearer ' . $ response ['auth_token ' ];
101+ $ token = $ response ['auth_token ' ];
91102
92103 $ this ->accountStore ->storeToken ($ token );
93104
0 commit comments