Repository navigation
Expand file tree
/
Copy pathBlobContainerClient.php
More file actions
435 lines (379 loc) · 15.1 KB
/
Copy pathBlobContainerClient.php
File metadata and controls
435 lines (379 loc) · 15.1 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
<?php
declare(strict_types=1);
namespace AzureOss\Storage\Blob;
use AzureOss\Identity\TokenCredential;
use AzureOss\Storage\Blob\Exceptions\BlobStorageException;
use AzureOss\Storage\Blob\Exceptions\BlobStorageExceptionDeserializer;
use AzureOss\Storage\Blob\Exceptions\InvalidBlobUriException;
use AzureOss\Storage\Blob\Exceptions\UnableToGenerateSasException;
use AzureOss\Storage\Blob\Helpers\BlobUriParserHelper;
use AzureOss\Storage\Blob\Helpers\MetadataHelper;
use AzureOss\Storage\Blob\Models\Blob;
use AzureOss\Storage\Blob\Models\BlobClientOptions;
use AzureOss\Storage\Blob\Models\BlobContainerClientOptions;
use AzureOss\Storage\Blob\Models\BlobContainerProperties;
use AzureOss\Storage\Blob\Models\BlobErrorCode;
use AzureOss\Storage\Blob\Models\BlobInclude;
use AzureOss\Storage\Blob\Models\BlobLeaseClientOptions;
use AzureOss\Storage\Blob\Models\BlobPrefix;
use AzureOss\Storage\Blob\Models\BlockBlobClientOptions;
use AzureOss\Storage\Blob\Models\CreateContainerOptions;
use AzureOss\Storage\Blob\Models\DeleteContainerOptions;
use AzureOss\Storage\Blob\Models\GetBlobsOptions;
use AzureOss\Storage\Blob\Models\GetContainerPropertiesOptions;
use AzureOss\Storage\Blob\Models\PublicAccessType;
use AzureOss\Storage\Blob\Models\RequestConditionSet;
use AzureOss\Storage\Blob\Models\SetContainerMetadataOptions;
use AzureOss\Storage\Blob\Models\TaggedBlob;
use AzureOss\Storage\Blob\Responses\FindBlobsByTagBody;
use AzureOss\Storage\Blob\Responses\ListBlobsResponseBody;
use AzureOss\Storage\Blob\Sas\BlobSasBuilder;
use AzureOss\Storage\Blob\Specialized\BlobLeaseClient;
use AzureOss\Storage\Blob\Specialized\BlockBlobClient;
use AzureOss\Storage\Common\Auth\StorageSharedKeyCredential;
use AzureOss\Storage\Common\Helpers\StorageUriParserHelper;
use AzureOss\Storage\Common\Middleware\ClientFactory;
use AzureOss\Storage\Common\Sas\SasProtocol;
use GuzzleHttp\Client;
use GuzzleHttp\Promise\Create;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Query;
use GuzzleHttp\RequestOptions;
use Psr\Http\Message\UriInterface;
/**
* Provides operations for an Azure Blob Storage container and the blobs within it.
*/
final class BlobContainerClient
{
public const ROOT_BLOB_CONTAINER_NAME = '$root';
public const LOGS_BLOB_CONTAINER_NAME = '$logs';
public const WEB_BLOB_CONTAINER_NAME = '$web';
private readonly Client $client;
public readonly string $containerName;
/**
* @param UriInterface $uri URI of the container, including any SAS query string.
* @param StorageSharedKeyCredential|TokenCredential|null $credential Credential used to authorize requests, or null for anonymous/SAS access.
* @param BlobContainerClientOptions $options Client transport and service-version options.
*
* @throws InvalidBlobUriException When the URI does not identify a container.
*/
public function __construct(
public readonly UriInterface $uri,
public readonly StorageSharedKeyCredential|TokenCredential|null $credential = null,
private readonly BlobContainerClientOptions $options = new BlobContainerClientOptions,
) {
$this->containerName = BlobUriParserHelper::getContainerName($uri);
$this->client = (new ClientFactory)->create($uri, $credential, new BlobStorageExceptionDeserializer, $this->options->httpClientOptions, $this->options->apiVersion);
}
/** Creates a general-purpose client for a blob without making a service request. */
public function getBlobClient(string $blobName): BlobClient
{
return new BlobClient(
$this->getBlobUri($blobName),
$this->credential,
new BlobClientOptions($this->options->httpClientOptions, $this->options->apiVersion),
);
}
/** Creates a block blob client without making a service request. */
public function getBlockBlobClient(string $blobName): BlockBlobClient
{
return new BlockBlobClient(
$this->getBlobUri($blobName),
$this->credential,
new BlockBlobClientOptions($this->options->httpClientOptions, $this->options->apiVersion),
);
}
/** Creates a lease client for this container without making a service request. */
public function getBlobLeaseClient(?string $leaseId = null): BlobLeaseClient
{
return new BlobLeaseClient(
$this->uri,
$this->credential,
$leaseId,
container: true,
options: new BlobLeaseClientOptions($this->options->httpClientOptions, $this->options->apiVersion),
);
}
private function getBlobUri(string $blobName): UriInterface
{
return $this->uri->withPath($this->uri->getPath().'/'.ltrim($blobName, '/'));
}
/**
* Creates the container.
*/
public function create(CreateContainerOptions $options = new CreateContainerOptions): void
{
$this->createAsync($options)->wait();
}
/**
* Asynchronously creates the container.
*/
public function createAsync(CreateContainerOptions $options = new CreateContainerOptions): PromiseInterface
{
$headers = [];
if ($options->publicAccessType !== PublicAccessType::NONE) {
$headers['x-ms-blob-public-access'] = $options->publicAccessType->value;
}
return $this->client->putAsync($this->uri, [
RequestOptions::QUERY => [
'restype' => 'container',
],
RequestOptions::HEADERS => $headers,
]);
}
/**
* Creates the container if it does not already exist.
*/
public function createIfNotExists(CreateContainerOptions $options = new CreateContainerOptions): void
{
$this->createIfNotExistsAsync($options)->wait();
}
/**
* Asynchronously creates the container if it does not already exist.
*/
public function createIfNotExistsAsync(CreateContainerOptions $options = new CreateContainerOptions): PromiseInterface
{
return $this->createAsync($options)
->otherwise(function (mixed $reason) {
$e = Create::exceptionFor($reason);
if ($e instanceof BlobStorageException && $e->errorCode === BlobErrorCode::ContainerAlreadyExists) {
return;
}
throw $e;
});
}
/** Deletes the container. */
public function delete(DeleteContainerOptions $options = new DeleteContainerOptions): void
{
$this->deleteAsync($options)->wait();
}
/** Asynchronously deletes the container. */
public function deleteAsync(DeleteContainerOptions $options = new DeleteContainerOptions): PromiseInterface
{
return $this->client->deleteAsync($this->uri, [
RequestOptions::QUERY => [
'restype' => 'container',
],
RequestOptions::HEADERS => $options->conditions?->toHeaders(
'BlobContainerClient::delete',
RequestConditionSet::DATES_AND_LEASE,
) ?? [],
]);
}
/** Deletes the container if it exists. */
public function deleteIfExists(DeleteContainerOptions $options = new DeleteContainerOptions): void
{
$this->deleteIfExistsAsync($options)->wait();
}
/** Asynchronously deletes the container if it exists. */
public function deleteIfExistsAsync(DeleteContainerOptions $options = new DeleteContainerOptions): PromiseInterface
{
return $this->deleteAsync($options)
->otherwise(function (mixed $reason) {
$e = Create::exceptionFor($reason);
if ($e instanceof BlobStorageException && $e->errorCode === BlobErrorCode::ContainerNotFound) {
return;
}
throw $e;
});
}
/** Determines whether the container exists. */
public function exists(): bool
{
return $this->existsAsync()->wait();
}
/**
* Asynchronously determines whether the container exists.
*
* @return PromiseInterface<bool, \Throwable>
*/
public function existsAsync(): PromiseInterface
{
return $this->client
->headAsync($this->uri, [
RequestOptions::QUERY => [
'restype' => 'container',
],
])
->then(fn () => true)
->otherwise(function (mixed $reason) {
$e = Create::exceptionFor($reason);
if ($e instanceof BlobStorageException && $e->errorCode === BlobErrorCode::ContainerNotFound) {
return false;
}
throw $e;
});
}
/** Gets the container's properties and metadata. */
public function getProperties(GetContainerPropertiesOptions $options = new GetContainerPropertiesOptions): BlobContainerProperties
{
return $this->getPropertiesAsync($options)->wait();
}
/**
* Asynchronously gets the container's properties and metadata.
*
* @return PromiseInterface<BlobContainerProperties, mixed>
*/
public function getPropertiesAsync(GetContainerPropertiesOptions $options = new GetContainerPropertiesOptions): PromiseInterface
{
return $this->client
->headAsync($this->uri, [
RequestOptions::QUERY => [
'restype' => 'container',
],
RequestOptions::HEADERS => $options->conditions?->toHeaders(
'BlobContainerClient::getProperties',
RequestConditionSet::LEASE_ONLY,
) ?? [],
])
->then(BlobContainerProperties::fromResponseHeaders(...));
}
/**
* Replaces all user-defined metadata on the container.
*
* @param array<string, string> $metadata
*/
public function setMetadata(array $metadata, SetContainerMetadataOptions $options = new SetContainerMetadataOptions): void
{
$this->setMetadataAsync($metadata, $options)->wait();
}
/**
* Asynchronously replaces all user-defined metadata on the container.
*
* @param array<string, string> $metadata
*/
public function setMetadataAsync(array $metadata, SetContainerMetadataOptions $options = new SetContainerMetadataOptions): PromiseInterface
{
return $this->client->putAsync($this->uri, [
RequestOptions::QUERY => [
'restype' => 'container',
'comp' => 'metadata',
],
RequestOptions::HEADERS => [
...MetadataHelper::metadataToHeaders($metadata),
...($options->conditions?->toHeaders(
'BlobContainerClient::setMetadata',
RequestConditionSet::MODIFIED_SINCE_AND_LEASE,
) ?? []),
],
]);
}
/**
* Lists blobs in a flat sequence, following continuation markers automatically.
*
* @return \Generator<Blob>
*/
public function getBlobs(?string $prefix = null, GetBlobsOptions $options = new GetBlobsOptions): \Generator
{
$nextMarker = '';
while (true) {
$response = $this->listBlobs($prefix, null, $nextMarker, $options->pageSize, $options->includes);
$nextMarker = $response->nextMarker;
foreach ($response->blobs as $blob) {
yield $blob;
}
if ($nextMarker === '') {
break;
}
}
}
/**
* Lists blobs as a hierarchy of blob items and virtual-directory prefixes.
*
* @return \Generator<Blob|BlobPrefix>
*/
public function getBlobsByHierarchy(?string $prefix = null, string $delimiter = '/', GetBlobsOptions $options = new GetBlobsOptions): \Generator
{
$nextMarker = '';
while (true) {
$response = $this->listBlobs($prefix, $delimiter, $nextMarker, $options->pageSize, $options->includes);
$nextMarker = $response->nextMarker;
foreach ($response->blobs as $blob) {
yield $blob;
}
foreach ($response->blobPrefixes as $blobPrefix) {
yield $blobPrefix;
}
if ($nextMarker === '') {
break;
}
}
}
/**
* @param BlobInclude[] $includes
*/
private function listBlobs(?string $prefix, ?string $delimiter, string $marker, ?int $maxResults, array $includes): ListBlobsResponseBody
{
$response = $this->client->get($this->uri, [
RequestOptions::QUERY => [
'restype' => 'container',
'comp' => 'list',
'prefix' => $prefix,
'marker' => $marker !== '' ? $marker : null,
'delimiter' => $delimiter,
'maxresults' => $maxResults,
'include' => $includes !== []
? implode(',', array_map(static fn (BlobInclude $include): string => $include->value, $includes))
: null,
],
]);
return ListBlobsResponseBody::fromXml(new \SimpleXMLElement($response->getBody()->getContents()));
}
/** Returns whether this client has a shared-key credential capable of signing a container SAS. */
public function canGenerateSasUri(): bool
{
return $this->credential instanceof StorageSharedKeyCredential;
}
/**
* Generates a URI for this container containing a signed service SAS query string.
*
* @throws UnableToGenerateSasException When the client does not have a shared-key credential.
*/
public function generateSasUri(BlobSasBuilder $blobSasBuilder): UriInterface
{
if (! $this->credential instanceof StorageSharedKeyCredential) {
throw new UnableToGenerateSasException;
}
$builder = clone $blobSasBuilder;
if (StorageUriParserHelper::isDevelopmentUri($this->uri)) {
$builder->setProtocol(SasProtocol::HTTPS_AND_HTTP);
}
$sas = $builder
->setContainerName($this->containerName)
->setBlobName(null)
->setSnapshot(null)
->setBlobVersionId(null)
->build($this->credential);
return $this->uri->withQuery(Query::build([
...Query::parse($this->uri->getQuery()),
...Query::parse($sas),
]));
}
/**
* Finds blobs in this container whose index tags match the SQL expression.
*
* @return \Generator<TaggedBlob>
*/
public function findBlobsByTag(string $tagFilterSqlExpression): \Generator
{
$nextMarker = '';
while (true) {
$response = $this->client->get($this->uri, [
RequestOptions::QUERY => [
'restype' => 'container',
'comp' => 'blobs',
'where' => $tagFilterSqlExpression,
'marker' => $nextMarker !== '' ? $nextMarker : null,
],
]);
$body = FindBlobsByTagBody::fromXml(new \SimpleXMLElement($response->getBody()->getContents()));
$nextMarker = $body->nextMarker;
foreach ($body->blobs as $blob) {
yield $blob;
}
if ($nextMarker === '') {
break;
}
}
}
}