Completed
Push — develop ( 4ff741...64bd10 )
by Tom
14:53
created

ClassifyRequest   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 93
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
c 1
b 0
f 0
lcom 1
cbo 8
dl 0
loc 93
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getData() 0 12 2
C sendData() 0 60 9
1
<?php
2
3
namespace Bobbyshaw\WatsonVisualRecognition\Message;
4
5
use GuzzleHttp\Exception\ClientException;
6
use Bobbyshaw\WatsonVisualRecognition\Exceptions\AuthException;
7
use GuzzleHttp\Psr7\MultipartStream;
8
use GuzzleHttp\Psr7\Request;
9
10
/**
11
 * Class ClassifyRequest
12
 * @package Bobbyshaw\WatsonVisualRecognition\Message
13
 */
14
class ClassifyRequest extends AbstractRequest
15
{
16
    const CLASSIFY_PATH = 'classify/';
17
    const ALLOWED_FILE_TYPES = ['.gif', '.jpg', '.png', '.zip'];
18
19
    /**
20
     * Get parameters for classify request
21
     *
22
     * @return array['images_file', 'classifier_ids']
0 ignored issues
show
Documentation introduced by
The doc-type array['images_file', could not be parsed: Expected "]" at position 2, but found "'images_file'". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
23
     *
24
     */
25
    public function getData()
26
    {
27
        $data = parent::getData();
28
29
        $data['images_file'] = $this->getImagesFile();
30
31
        if ($classifierIds = $this->getClassifierIds()) {
32
            $data['classifier_ids'] = $classifierIds;
33
        }
34
35
        return $data;
36
    }
37
38
    /**
39
     * Send Classify HTTP request
40
     *
41
     * @param array $data - array['images_file', 'classifier_ids']
42
     * @return ClassifyResponse
43
     * @throws AuthException
44
     * @throws \Exception
45
     */
46
    public function sendData($data)
47
    {
48
        if (!in_array(substr($data['images_file'], -4), static::ALLOWED_FILE_TYPES)) {
49
            throw new \InvalidArgumentException(
50
                'Image file needs to be one of the following types: ' . implode(', ', static::ALLOWED_FILE_TYPES)
51
            );
52
        }
53
54
        $params = [
55
            [
56
                'name' => 'images_file',
57
                'contents' => fopen($data['images_file'], 'r'),
58
                'filename' => $data['images_file']
59
            ]
60
        ];
61
62
        if (isset($data['classifier_ids'])) {
63
            if (is_array($data['classifier_ids'])) {
64
                $classifierIdParams = [];
65
                foreach ($data['classifier_ids'] as $id) {
66
                    $classifierIdParams[] = ['classifier_id' => $id];
67
                }
68
69
                $params[] = [
70
                    'name' => 'classifier_ids',
71
                    'contents' => json_encode(['classifiers' => $classifierIdParams])
72
                ];
73
            } else {
74
                throw new \InvalidArgumentException('Classifier IDs must be array');
75
            }
76
        }
77
78
        $multipartStream = new MultipartStream($params);
79
80
        $request = new Request(
81
            'POST',
82
            $this->getApiUrl(static::CLASSIFY_PATH) . '?' . http_build_query(['version' => $data['version']]),
83
            ['Authorization' => 'Basic ' . base64_encode($data['username'] . ':' . $data['password'])],
84
            $multipartStream
85
        );
86
87
        try {
88
            $response = $this->httpClient->send($request);
89
90
            if ($response->getStatusCode() != 200) {
91
                $error = $response->getStatusCode() . " Response Received: " . $response->getBody()->getContents();
92
                throw new \Exception($error, $response->getStatusCode());
93
            }
94
        } catch (ClientException $e) {
95
            if ($e->getCode() == 401) {
96
                throw new AuthException('Invalid credentials provided');
97
            } elseif ($e->getCode() == 415) {
98
                throw new \InvalidArgumentException('Unsupported image type');
99
            } else {
100
                throw $e;
101
            }
102
        }
103
104
        return $this->response = new ClassifyResponse($this, $response->getBody());
105
    }
106
}
107