Completed
Push — master ( 50eeb9...9e0ccd )
by Michael
02:32
created

Projects::getOrganizationProjects()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 2
nop 1
dl 0
loc 13
ccs 6
cts 6
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace BabDev\Transifex\Connector;
4
5
use BabDev\Transifex\ApiConnector;
6
use Psr\Http\Message\ResponseInterface;
7
8
/**
9
 * Transifex API Projects class.
10
 *
11
 * @link http://docs.transifex.com/api/projects/
12
 */
13
final class Projects extends ApiConnector
14
{
15
    /**
16
     * Build the data array to send with create and update requests.
17
     *
18
     * @param array $options Optional additional params to send with the request
19
     *
20
     * @return array
21
     */
22 8
    private function buildProjectRequest(array $options): array
23
    {
24 8
        $data = [];
25
26
        // Valid options to check
27
        $validOptions = [
28 8
            'long_description',
29
            'private',
30
            'homepage',
31
            'trans_instructions',
32
            'tags',
33
            'maintainers',
34
            'team',
35
            'auto_join',
36
            'license',
37
            'fill_up_resources',
38
            'repository_url',
39
            'organization',
40
            'archived',
41
            'type',
42
        ];
43
44
        // Loop through the valid options and if we have them, add them to the request data
45 8
        foreach ($validOptions as $option) {
46 8
            if (isset($options[$option])) {
47 6
                $data[$option] = $options[$option];
48
            }
49
        }
50
51
        // Set the license if present
52 8
        if (isset($options['license'])) {
53 4
            $this->checkLicense($options['license']);
54 2
            $data['license'] = $options['license'];
55
        }
56
57 6
        return $data;
58
    }
59
60
    /**
61
     * Checks that a license is an accepted value.
62
     *
63
     * @param string $license The license to check
64
     *
65
     * @throws \InvalidArgumentException
66
     */
67 4
    private function checkLicense(string $license): void
68
    {
69 4
        $accepted = ['proprietary', 'permissive_open_source', 'other_open_source'];
70
71
        // Ensure the license option is an allowed value
72 4
        if (!\in_array($license, $accepted)) {
73 2
            throw new \InvalidArgumentException(
74 2
                \sprintf(
75 2
                    'The license %s is not valid, accepted license values are %s',
76 2
                    $license,
77 2
                    \implode(', ', $accepted)
78
                )
79
            );
80
        }
81 2
    }
82
83
    /**
84
     * Create a project.
85
     *
86
     * @param string $name           The name of the project
87
     * @param string $slug           The slug for the project
88
     * @param string $description    A description of the project
89
     * @param string $sourceLanguage The source language code for the project
90
     * @param array  $options        Optional additional params to send with the request
91
     *
92
     * @return ResponseInterface
93
     *
94
     * @throws \InvalidArgumentException
95
     */
96 4
    public function createProject(
97
        string $name,
98
        string $slug,
99
        string $description,
100
        string $sourceLanguage,
101
        array $options = []
102
    ): ResponseInterface {
103
        // Build the request data.
104 4
        $data = \array_merge(
105
            [
106 4
                'name'                 => $name,
107 4
                'slug'                 => $slug,
108 4
                'description'          => $description,
109 4
                'source_language_code' => $sourceLanguage,
110
            ],
111 4
            $this->buildProjectRequest($options)
112
        );
113
114
        // Check mandatory fields.
115 3
        if (!isset($data['license']) || \in_array($data['license'], ['permissive_open_source', 'other_open_source'])) {
116 3
            if (!isset($data['repository_url'])) {
117 1
                throw new \InvalidArgumentException(
118 1
                    'If a project is denoted either as permissive_open_source or other_open_source, the field repository_url is mandatory and should contain a link to the public repository of the project to be created.'
119
                );
120
            }
121
        }
122
123 2
        $request = $this->createRequest('POST', $this->createUri('/api/2/projects/'));
124 2
        $request = $request->withBody($this->streamFactory->createStream(\json_encode($data)));
125 2
        $request = $request->withHeader('Content-Type', 'application/json');
126
127 2
        return $this->client->sendRequest($request);
128
    }
129
130
    /**
131
     * Delete a project.
132
     *
133
     * @param string $slug The slug for the resource
134
     *
135
     * @return ResponseInterface
136
     */
137 2
    public function deleteProject(string $slug): ResponseInterface
138
    {
139 2
        return $this->client->sendRequest($this->createRequest('DELETE', $this->createUri("/api/2/project/$slug")));
140
    }
141
142
    /**
143
     * Get a list of projects belonging to an organization.
144
     *
145
     * @return ResponseInterface
146
     */
147 4
    public function getOrganizationProjects(string $organization): ResponseInterface
148
    {
149
        // This API endpoint uses the newer `api.transifex.com` subdomain, only change if the default www was given
150 4
        $currentBaseUri = $this->getOption('base_uri');
151
152 4
        if (!$currentBaseUri || $currentBaseUri === 'https://www.transifex.com') {
153 4
            $this->setOption('base_uri', 'https://api.transifex.com');
154
        }
155
156
        try {
157 4
            return $this->client->sendRequest($this->createRequest('GET', $this->createUri("/organizations/$organization/projects/")));
158
        } finally {
159 4
            $this->setOption('base_uri', $currentBaseUri);
160
        }
161
    }
162
163
    /**
164
     * Get information about a project.
165
     *
166
     * @param string $project The project to retrieve details for
167
     * @param bool   $details True to retrieve additional project details
168
     *
169
     * @return ResponseInterface
170
     */
171 2
    public function getProject(string $project, bool $details = false): ResponseInterface
172
    {
173 2
        $uri = $this->createUri("/api/2/project/$project/");
174
175 2
        if ($details) {
176 2
            $uri = $uri->withQuery('details');
177
        }
178
179 2
        return $this->client->sendRequest($this->createRequest('GET', $uri));
180
    }
181
182
    /**
183
     * Get a list of projects the user is part of.
184
     *
185
     * @return ResponseInterface
186
     */
187 3
    public function getProjects(): ResponseInterface
188
    {
189 3
        return $this->client->sendRequest($this->createRequest('GET', $this->createUri('/api/2/projects/')));
190
    }
191
192
    /**
193
     * Update a project.
194
     *
195
     * @param string $slug    The slug for the project
196
     * @param array  $options Additional params to send with the request
197
     *
198
     * @return ResponseInterface
199
     *
200
     * @throws \RuntimeException
201
     */
202 4
    public function updateProject(string $slug, array $options): ResponseInterface
203
    {
204 4
        $data = $this->buildProjectRequest($options);
205
206
        // Make sure we actually have data to send
207 3
        if (empty($data)) {
208 1
            throw new \RuntimeException('There is no data to send to Transifex.');
209
        }
210
211 2
        $request = $this->createRequest('PUT', $this->createUri("/api/2/project/$slug/"));
212 2
        $request = $request->withBody($this->streamFactory->createStream(\json_encode($data)));
213 2
        $request = $request->withHeader('Content-Type', 'application/json');
214
215 2
        return $this->client->sendRequest($request);
216
    }
217
}
218