ClassifyRequest::getData()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

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