-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathProject.php
More file actions
538 lines (479 loc) · 16.6 KB
/
Project.php
File metadata and controls
538 lines (479 loc) · 16.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
<?php
declare(strict_types=1);
namespace Platformsh\Client\Model;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Utils;
use Platformsh\Client\Model\Activities\HasActivitiesInterface;
use Platformsh\Client\Model\Activities\HasActivitiesTrait;
use Platformsh\Client\Model\Invitation\AlreadyInvitedException;
use Platformsh\Client\Model\Invitation\Environment as InvitationEnvironment;
use Platformsh\Client\Model\Invitation\Permission as InvitationPermission;
use Platformsh\Client\Model\Invitation\ProjectInvitation;
use Platformsh\Client\Model\Project\Capabilities;
use Platformsh\Client\Model\Project\Settings;
/**
* A Platform.sh project.
*
* @property-read string $id
* @property-read string $title
* @property-read string $created_at
* @property-read string $updated_at
* @property-read string $owner
* @property-read string $default_branch
* @property-read string $region
*/
class Project extends ApiResourceBase implements HasActivitiesInterface
{
use HasActivitiesTrait;
private ?string $urlViaGateway = null;
/**
* {@inheritDoc}
*
* Project information can come from a number of different places, which
* do not always contain full information about each project. So this
* overrides the Resource constructor to default $full to false.
*/
public function __construct(array $data, $baseUrl = null, ClientInterface $client = null, $full = false)
{
parent::__construct($data, $baseUrl, $client, $full);
}
/**
* Prevent deletion.
*
* @internal
*/
public function delete(): Result
{
throw new \BadMethodCallException('Projects should not be deleted directly. Delete the subscription instead.');
}
/**
* Get the subscription ID for the project.
*
* @todo when APIs are unified, this can be a property
*
* @return string|int
* The ID is a numeric string. Legacy APIs may return an integer.
*/
public function getSubscriptionId(): int|string
{
if (isset($this->data['subscription_id'])) {
return $this->data['subscription_id'];
}
if (isset($this->data['subscription']['license_uri'])) {
return basename($this->data['subscription']['license_uri']);
}
throw new \RuntimeException('Subscription ID not found');
}
/**
* Get the Git URL for the project.
*/
public function getGitUrl(): string
{
$repository = $this->getProperty('repository');
return $repository['url'];
}
/**
* Get the users associated with a project.
*
* @return ProjectAccess[]
*/
public function getUsers(): array
{
return ProjectAccess::getCollection($this->getLink('access'), 0, [], $this->client);
}
/**
* Add a new user to a project.
*
* @param string $user The user's UUID or email address (see $byUuid).
* @param string $role One of ProjectAccess::$roles.
* @param bool $byUuid Set true if $user is a UUID, or false (default) if
* $user is an email address.
*
* @deprecated Users should now be invited via Project::inviteUserByEmail()
*
* @see Project::inviteUserByEmail()
*/
public function addUser(string $user, string $role, bool $byUuid = false): Result
{
trigger_error('Calling Project::addUser() is deprecated; the method will be removed in a future version. Use Project::inviteUserByEmail() instead.', E_USER_DEPRECATED);
$property = $byUuid ? 'user' : 'email';
$body = [
$property => $user,
'role' => $role,
];
return ProjectAccess::create($body, $this->getLink('access'), $this->client);
}
/**
* Set the API gateway URL, e.g. 'https://api.platform.sh'.
*/
public function setApiUrl(string $url): void
{
$projectUrl = Utils::uriFor($url)->withPath('/projects/' . \urlencode($this->id))->__toString();
$this->baseUrl = $this->urlViaGateway = $projectUrl;
}
/**
* Invite a new user to a project using their email address.
*
* This is only possible after setting the API gateway URL. This will be
* the case already if the project was instantiated via a PlatformClient
* method such as PlatformClient::getProject(). Otherwise, use
* Project::setApiUrl() before calling this method.
*
* @param string $email
* The user's email address.
* @param string $role
* The user's role on the project ('viewer' or 'admin').
* @param InvitationEnvironment[] $environments
* Deprecated. A list of environments for the invitation. Replaced by $permissions.
* @param bool $force
* Whether to re-send the invitation, if an invitation has already been sent to the same email address.
* @param InvitationPermission[] $permissions
* A list of permissions for the invitation. Only used if the project role is not 'admin'.
*
* @throws AlreadyInvitedException if there is a pending invitation open with the same details
*@see Project::setApiUrl()
* @see \Platformsh\Client\PlatformClient::getProject()
*
* Normally either a list of $environments should be given, or the project-level $role should be 'admin'.
*/
public function inviteUserByEmail(string $email, string $role, array $environments = [], bool $force = false, array $permissions = []): ProjectInvitation
{
$data = [
'email' => $email,
'role' => $role,
];
if (! empty($permissions)) {
$data['permissions'] = InvitationPermission::listForApi($permissions);
}
if (! empty($environments)) {
$data['environments'] = InvitationEnvironment::listForApi($environments);
}
if ($force) {
$data['force'] = true;
}
$request = new Request('POST', $this->getLink('invitations'), [
'Content-Type' => 'application/json',
], \json_encode($data));
try {
$data = self::send($request, $this->client);
} catch (BadResponseException $e) {
if ($e->getResponse() && $e->getResponse()->getStatusCode() === 409) {
throw new AlreadyInvitedException(
'An invitation has already been created for this email address and role(s)',
$email,
$this,
$role,
$environments,
$permissions
);
}
throw $e;
}
return new ProjectInvitation($data, $this->getLink('invitations'), $this->client);
}
/**
* Get a single environment of the project.
*
* To get the project's default environment, use:
* <code>
* $defaultEnv = $project->getEnvironment($project->default_branch);
* </code>
*
* @param string $id The environment ID.
*/
public function getEnvironment(string $id): false|Environment
{
return Environment::get($id, $this->getLink('environments'), $this->client);
}
/**
* @inheritdoc
*
* The accounts API does not (yet) return HAL links. This is a collection
* of workarounds for that issue.
*/
public function getLink(string $rel, bool $absolute = true): string
{
/**
* Require the API URL to be set for 'invitations' and 'access'.
*
* These endpoints require the external API proxy or gateway, or may
* require it in the future.
*
* The parent method, via self::makeAbsoluteUrl(), ensures an
* appropriate base URL is used otherwise.
*
* @see setApiUrl()
* @see makeAbsoluteUrl()
*/
if ($rel === 'invitations' || $rel === 'access') {
if (! isset($this->urlViaGateway)) {
throw new \RuntimeException('The API gateway URL must be set');
}
}
// Use the HAL links available on the project.
if ($this->hasLink($rel)) {
return parent::getLink($rel, $absolute);
}
// If the 'self' link is not present then this might be a project
// stub with an 'endpoint' property.
if ($rel === 'self') {
return $this->makeAbsoluteUrl($this->getProperty('endpoint'));
}
// If the '#ui' link is not present then this might be a project
// stub with a 'uri' property.
if ($rel === '#ui') {
return $this->getProperty('uri');
}
if ($rel === '#manage-variables') {
return $this->getUri() . '/variables';
}
if ($rel === 'invitations') {
if (! isset($this->urlViaGateway)) {
throw new \RuntimeException('The API gateway URL must be set');
}
return rtrim($this->urlViaGateway, '/') . '/invitations';
}
return $this->getUri() . '/' . ltrim($rel, '#');
}
/**
* Get a list of environments for the project.
*
* @param int $limit
* Limit the number of environments to return.
* @param string|null $type
* Filter by environment type.
* @param bool|null $active
* Filter by environment status (active or not).
*
* @return Environment[]
*/
public function getEnvironments(int $limit = 0, string $type = null, bool $active = null): array
{
$options = [];
if ($type !== null) {
$options['query']['type'] = $type;
}
if ($active !== null) {
$options['query']['active'] = $active ? 'true' : 'false';
}
return Environment::getCollection($this->getLink('environments'), $limit, $options, $this->client);
}
/**
* Get a list of environment types for the project.
*
* @return EnvironmentType[]
*/
public function getEnvironmentTypes(): array
{
return EnvironmentType::getCollection($this->getLink('environment-types'), 0, [], $this->client);
}
/**
* Get an environment type.
*/
public function getEnvironmentType(string $id): false|EnvironmentType
{
return EnvironmentType::get($id, $this->getLink('environment-types'), $this->client);
}
/**
* Get a list of domains for the project.
*
* @return Domain[]
*/
public function getDomains(int $limit = 0): array
{
return Domain::getCollection($this->getLink('domains'), $limit, [], $this->client);
}
/**
* Get a single domain of the project.
*/
public function getDomain(string $name): Domain|false
{
return Domain::get($name, $this->getLink('domains'), $this->client);
}
/**
* Add a domain to the project.
*/
public function addDomain(string $name, array $ssl = []): Result
{
$body = [
'name' => $name,
];
if (! empty($ssl)) {
$body['ssl'] = $ssl;
}
return Domain::create($body, $this->getLink('domains'), $this->client);
}
/**
* Get a list of integrations for the project.
*
* @return Integration[]
*/
public function getIntegrations(int $limit = 0): array
{
return Integration::getCollection($this->getLink('integrations'), $limit, [], $this->client);
}
/**
* Get a single integration of the project.
*/
public function getIntegration(string $id): Integration|false
{
return Integration::get($id, $this->getLink('integrations'), $this->client);
}
/**
* Add an integration to the project.
*/
public function addIntegration(string $type, array $data = []): Result
{
$body = [
'type' => $type,
] + $data;
return Integration::create($body, $this->getLink('integrations'), $this->client);
}
/**
* Returns whether the project is suspended.
*/
public function isSuspended(): bool
{
return ! empty($this->data['subscription']['suspended'])
|| (isset($this->data['status']) && $this->data['status'] === 'suspended');
}
/**
* Get a list of variables.
*
* @return ProjectLevelVariable[]
*/
public function getVariables(int $limit = 0): array
{
return ProjectLevelVariable::getCollection($this->getLink('#manage-variables'), $limit, [], $this->client);
}
/**
* Set a variable.
*
* @param string $name
* The name of the variable to set.
* @param mixed $value
* The value of the variable to set. If non-scalar it will be JSON-encoded automatically.
* @param bool $json
* Whether this variable's value is JSON-encoded.
* @param bool $visibleBuild
* Whether this variable should be exposed during the build phase.
* @param bool $visibleRuntime
* Whether this variable should be exposed during deploy and runtime.
* @param bool $sensitive
* Whether this variable's value should be readable via the API.
*/
public function setVariable(
string $name,
mixed $value,
bool $json = false,
bool $visibleBuild = true,
bool $visibleRuntime = true,
bool $sensitive = false
): Result {
// If $value isn't a scalar, assume it's supposed to be JSON.
if (! is_scalar($value)) {
$value = json_encode($value);
$json = true;
}
$values = [
'value' => $value,
'is_json' => $json,
'visible_build' => $visibleBuild,
'visible_runtime' => $visibleRuntime,
];
if ($sensitive) {
$values['is_sensitive'] = $sensitive;
}
$existing = $this->getVariable($name);
if ($existing) {
return $existing->update($values);
}
$values['name'] = $name;
return ProjectLevelVariable::create($values, $this->getLink('#manage-variables'), $this->client);
}
/**
* Get a single variable.
*
* @param string $id
* The name of the variable to retrieve.
* @return ProjectLevelVariable|false
* The variable requested, or False if it is not defined.
*/
public function getVariable(string $id): false|ProjectLevelVariable
{
return ProjectLevelVariable::get($id, $this->getLink('#manage-variables'), $this->client);
}
/**
* Get a list of certificates associated with this project.
*
* @return Certificate[]
*/
public function getCertificates(): array
{
return Certificate::getCollection($this->getUri() . '/certificates', 0, [], $this->client);
}
/**
* Get a single certificate.
*/
public function getCertificate(string $id): Certificate|false
{
return Certificate::get($id, $this->getUri() . '/certificates', $this->client);
}
/**
* Add a certificate to the project.
*/
public function addCertificate(string $certificate, string $key, array $chain = []): Result
{
$options = [
'key' => $key,
'certificate' => $certificate,
'chain' => $chain,
];
return Certificate::create($options, $this->getUri() . '/certificates', $this->client);
}
/**
* Find the project base URL from another project resource's URL.
*/
public static function getProjectBaseFromUrl(string $url): string
{
if (preg_match('#/api/projects/([^/]+)#', $url, $matches)) {
return Utils::uriFor($url)->withPath('/api/projects/' . $matches[1])->__toString();
}
throw new \RuntimeException('Failed to find project ID from URL: ' . $url);
}
/**
* Clear the project's build cache.
*/
public function clearBuildCache(): Result
{
return $this->runOperation('clear-build-cache');
}
/**
* Returns system information about the project, e.g. the API version.
*/
public function systemInformation(): System|false
{
return System::get($this->getLink('#system'), '', $this->client);
}
/**
* Returns the project's capabilities (features enabled by the billing system).
*/
public function getCapabilities(): Capabilities
{
$request = new Request('GET', $this->getUri() . '/capabilities');
$data = self::send($request, $this->client);
return Capabilities::fromData($data);
}
/**
* Returns the project settings.
*/
public function getSettings(): Settings
{
$url = $this->getUri() . '/settings';
$request = new Request('GET', $this->getUri() . '/settings');
$data = self::send($request, $this->client);
return new Settings($data, $url, $this->client);
}
}