StatementForward::updateStatementForwardQuery()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 5
c 2
b 0
f 0
dl 0
loc 8
rs 9.6111
cc 5
nc 5
nop 2
1
<?php
2
namespace HT2\Integrations\LearningLocker;
3
4
use Guzzle\Exception\RequestException;
0 ignored issues
show
Bug introduced by
The type Guzzle\Exception\RequestException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
5
use Curatr\Services\LearningLocker as LLService;
0 ignored issues
show
Bug introduced by
The type Curatr\Services\LearningLocker was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Lcobucci\JWT\Builder;
7
use Lcobucci\JWT\Signer\Hmac\Sha256;
8
use \Exception;
9
10
class StatementForward extends Connection {
0 ignored issues
show
Bug introduced by
The type HT2\Integrations\LearningLocker\Connection was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
12
  private $statementForward = '/statementforwarding';
13
  private $api = '/api';
14
  private $v2 = '/v2';
15
16
  private $headers = [
17
    'content-type' => 'application/json'
18
  ];
19
20
  /**
21
   * Generate the Query for Learning Locker's
22
   * Statement Forward.
23
   *
24
   * @return  true
25
   * @return  false
26
   */
27
  public function updateStatementForwardQuery($statementForwardId, $isEnabled) {
28
    $query = Query::statementForward($this->org->id);
0 ignored issues
show
Bug introduced by
The type HT2\Integrations\LearningLocker\Query was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
29
    if ($query === false || !$isEnabled) {
30
      $message = $query === false && $isEnabled ? '(No objects)' : null;
31
      return $this->disable($statementForwardId, $message);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->disable($s...entForwardId, $message) could also return false which is incompatible with the documented return type true. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
32
    }
33
    // pass in the query to prevent regeneration in the enable method
34
    return $this->enable($statementForwardId, $query);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->enable($statementForwardId, $query) could also return false which is incompatible with the documented return type true. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
35
  }
36
37
  public static function getSigner() {
38
    return new Sha256;
39
  }
40
41
  public static function getOrgIssuer($org) {
42
    return \Curatr\Helper::getSubdomainURL($org->alias);
0 ignored issues
show
Bug introduced by
The type Curatr\Helper was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
43
  }
44
45
  public static function getOrgSigningKey($org) {
46
    return $org->jwt_secret ?? 'default_key';
47
  }
48
49
  public function createSignedBearer() {
50
    $signer = self::getSigner();
51
    $issuer = self::getOrgIssuer($this->org);
52
    $token = (new Builder())->setIssuer($issuer) // Configures the issuer (iss claim)
53
                        ->setId($this->org->id, true) // Configures the id (jti claim), replicating as a header item
54
                        ->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
55
                        ->sign($signer, self::getOrgSigningKey($this->org))
56
                        ->getToken(); // Retrieves the generated token
57
    return $token->__toString();
58
  }
59
60
  private function title($message = "") {
61
    return trim($this->org->app_name . ' - ' . $this->org->name . ' - Object Completions ' . $message);
62
  }
63
64
  /**
65
   * Enable the Learning Locker Statement Forward.
66
   *
67
   * @param   $statementForwardId
68
   * @return  $response
0 ignored issues
show
Documentation Bug introduced by
The doc comment $response at position 0 could not be parsed: Unknown type name '$response' at position 0 in $response.
Loading history...
69
   */
70
  public function enable($statementForwardId, $query = null) {
71
    $data = [
72
      "active" => true,
73
      "description" => $this->title(),
74
      "query" => $query ?: Query::statementForward($this->org->id),
75
      'configuration' => [
76
        'authType' => 'token',
77
        'secret' => $this->createSignedBearer()
78
      ]
79
    ];
80
    return $this->update($statementForwardId, $data);
81
  }
82
83
  /**
84
   * Disable the Learning Locker Statement Forward.
85
   *
86
   * @param   $id
87
   * @return  $response
0 ignored issues
show
Documentation Bug introduced by
The doc comment $response at position 0 could not be parsed: Unknown type name '$response' at position 0 in $response.
Loading history...
88
   */
89
  public function disable($statementForwardId, $message) {
90
    $message = $message ?? '(Service Disabled)';
91
    $data = array(
92
      "active" => false,
93
      "description" => $this->title($message),
94
      "query" => json_encode(['$comment' => Query::COMMENT, 'disabled' => $message])
95
    );
96
    return $response = $this->update($statementForwardId, $data);
0 ignored issues
show
Unused Code introduced by
The assignment to $response is dead and can be removed.
Loading history...
97
  }
98
99
  /**
100
   * Get the Learning Locker Statement Forward by ID.
101
   *
102
   * @param   $id
103
   * @return  $response
0 ignored issues
show
Documentation Bug introduced by
The doc comment $response at position 0 could not be parsed: Unknown type name '$response' at position 0 in $response.
Loading history...
104
   */
105
  public function check($statementForwardId) {
106
    if (empty($statementForwardId)) return false;
107
    return $this->get($statementForwardId);
108
  }
109
110
  /**
111
   * Get the Learning Locker Statement Forward by ID.
112
   *
113
   * @param   $statementForwardId
114
   * @return  $response
0 ignored issues
show
Documentation Bug introduced by
The doc comment $response at position 0 could not be parsed: Unknown type name '$response' at position 0 in $response.
Loading history...
115
   */
116
  public function get($statementForwardId) {
117
    try {
118
      $url = $this->endpoint . $this->api . $this->v2 . $this->statementForward . '/' . $statementForwardId;
119
      $request = $this->getClient()->get($url, [
120
        'auth' => $this->getAuth(),
121
        'headers' => [
122
          'content-type' => 'application/json'
123
        ],
124
      ]);
125
126
      if($request->getStatusCode() === 404) {
127
        throw new GuzzleHttp\Exception\ClientException('There was a issue connecting to Learning Locker.');
0 ignored issues
show
Bug introduced by
The type HT2\Integrations\Learnin...ception\ClientException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
128
      }
129
      return $request->json();
130
    } catch (Exception $e) {      
131
      if ($e instanceof \GuzzleHttp\Exception\ClientException) {
0 ignored issues
show
Bug introduced by
The type GuzzleHttp\Exception\ClientException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
132
        $responseBody = $e->getResponse()->getBody(true);
0 ignored issues
show
Bug introduced by
The method getResponse() does not exist on Exception. It seems like you code against a sub-type of Exception such as Illuminate\Validation\ValidationException or Illuminate\Http\Exceptions\HttpResponseException. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

132
        $responseBody = $e->/** @scrutinizer ignore-call */ getResponse()->getBody(true);
Loading history...
133
        \Log::error('Error fetching statement forward', [
134
          'id' => $statementForwardId,
135
          'org_id'=>$this->org->id,
136
          'responseBody' => $responseBody
137
        ]);
138
      }
139
      return false;
140
    }
141
  }
142
143
  /**
144
   * Store the Learning Locker Statement Forward.
145
   *
146
   * @param   $data
147
   * @return  $response
0 ignored issues
show
Documentation Bug introduced by
The doc comment $response at position 0 could not be parsed: Unknown type name '$response' at position 0 in $response.
Loading history...
148
   */ 
149
  public function store($data, $startEnabled = true) {
150
    $store = json_encode($data);
151
    try {
152
      $url = $this->endpoint . $this->api . $this->v2 . $this->statementForward;
153
      $request = $this->getClient()->post($url, array(
154
        'auth' => $this->getAuth(),
155
        'headers' => $this->headers,
156
        'body' => $store,
157
      ));
158
      $request = $request->json();
159
      if (isset($request['_id'])) {
160
        return $this->updateStatementForwardQuery($request['_id'], $startEnabled);
161
      }
162
      return false;
163
    } catch (Exception $e) {      
164
      if ($e instanceof \GuzzleHttp\Exception\ClientException) {
165
        $responseBody = $e->getResponse()->getBody(true);
166
        \Log::error('Error creating statement forward', [
167
          'data' => $data,
168
          'org_id'=>$this->org->id,
169
          'responseBody' => $responseBody
170
        ]);
171
      }
172
      return false;
173
    }
174
  }
175
176
  /**
177
   * Update the Learning Locker Statement Forward.
178
   *
179
   * @param   $statementForwardId, $data
0 ignored issues
show
Documentation Bug introduced by
The doc comment $statementForwardId, at position 0 could not be parsed: Unknown type name '$statementForwardId' at position 0 in $statementForwardId,.
Loading history...
180
   * @return  $response
0 ignored issues
show
Documentation Bug introduced by
The doc comment $response at position 0 could not be parsed: Unknown type name '$response' at position 0 in $response.
Loading history...
181
   */
182
  protected function update($statementForwardId, $data) {
183
    if (empty($statementForwardId)) return false;
184
    $update = json_encode($data);
185
    try {
186
      $url = $this->endpoint . $this->api . $this->v2 . $this->statementForward . '/' . $statementForwardId;
187
      $request = $this->getClient()->patch($url, array(
188
        'auth' => $this->getAuth(), 
189
        'headers' => [
190
          'content-type' => 'application/json'
191
        ],
192
        'body' => $update,
193
      ));
194
      return $request->json();
195
    } catch (Exception $e) {      
196
      if ($e instanceof \GuzzleHttp\Exception\ClientException) {
197
        $responseBody = $e->getResponse()->getBody(true);
198
        \Log::error('Error updating statement forward', [
199
          'id' => $statementForwardId,
200
          'data' => $data,
201
          'org_id'=>$this->org->id,
202
          'responseBody' => $responseBody
203
        ]);
204
      }
205
      return false;
206
    }
207
  }
208
209
}
210