Lifecycle.php 14.7 KB
Newer Older
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
<?php
/**
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Google\Cloud\Storage;

use Google\Cloud\Core\Timestamp;

/**
 * Object Lifecycle Management supports common use cases like setting a Time to
 * Live (TTL) for objects, archiving older versions of objects, or "downgrading"
 * storage classes of objects to help manage costs.
 *
 * This builder does not execute any network requests and is intended to be used
 * in combination with either
 * {@see Google\Cloud\Storage\StorageClient::createBucket()}
 * or {@see Google\Cloud\Storage\Bucket::update()}.
 *
 * Example:
 * ```
 * // Access a builder preconfigured with rules already existing on a given
 * // bucket.
 * use Google\Cloud\Storage\StorageClient;
 *
 * $storage = new StorageClient();
 * $bucket = $storage->bucket('my-bucket');
 * $lifecycle = $bucket->currentLifecycle();
 * ```
 *
 * ```
 * // Or get a fresh builder by using the static factory method.
 * use Google\Cloud\Storage\Bucket;
 *
 * $lifecycle = Bucket::lifecycle();
 * ```
 *
 * @see https://cloud.google.com/storage/docs/lifecycle Object Lifecycle Management API Documentation
 */
class Lifecycle implements \ArrayAccess, \IteratorAggregate
{
    /**
     * @var array
     */
    private $lifecycle;

    /**
     * @param array $lifecycle [optional] A lifecycle configuration. Please see
     *        [here](https://cloud.google.com/storage/docs/json_api/v1/buckets#lifecycle)
     *        for the expected structure.
     */
    public function __construct(array $lifecycle = [])
    {
        $this->lifecycle = $lifecycle;
    }

    /**
     * Adds an Object Lifecycle Delete Rule.
     *
     * Example:
     * ```
     * $lifecycle->addDeleteRule([
     *     'age' => 50,
     *     'isLive' => true
     * ]);
     * ```
     *
     * @param array $condition {
     *     The condition(s) where the rule will apply.
     *
     *     @type int $age Age of an object (in days). This condition is
     *           satisfied when an object reaches the specified age.
     *     @type \DateTimeInterface|string $createdBefore This condition is
     *           satisfied when an object is created before midnight of the
     *           specified date in UTC. If a string is given, it must be a date
     *           in RFC 3339 format with only the date part (for instance,
     *           "2013-01-15").
     *     @type \DateTimeInterface|string $customTimeBefore This condition is
     *           satisfied when the custom time on an object is before this date
     *           in UTC. If a string is given, it must be a date in RFC 3339
     *           format with only the date part (for instance, "2013-01-15").
     *     @type int $daysSinceCustomTime Number of days elapsed since the
     *           user-specified timestamp set on an object. The condition is
     *           satisfied if the days elapsed is at least this number. If no
     *           custom timestamp is specified on an object, the condition does
     *           not apply.
     *     @type int $daysSinceNoncurrentTime Number of days elapsed since the
     *           noncurrent timestamp of an object. The condition is satisfied
     *           if the days elapsed is at least this number. This condition is
     *           relevant only for versioned objects. The value of the field
     *           must be a nonnegative integer. If it's zero, the object version
     *           will become eligible for Lifecycle action as soon as it becomes
     *           noncurrent.
     *     @type bool $isLive Relevant only for versioned objects. If the value
     *           is `true`, this condition matches live objects; if the value is
     *           `false`, it matches archived objects.
     *     @type string[] $matchesStorageClass Objects having any of the storage
     *           classes specified by this condition will be matched. Values
     *           include `"MULTI_REGIONAL"`, `"REGIONAL"`, `"NEARLINE"`,
     *           `"ARCHIVE"`, `"COLDLINE"`, `"STANDARD"`, and
     *           `"DURABLE_REDUCED_AVAILABILITY"`.
     *     @type \DateTimeInterface|string $noncurrentTimeBefore This condition
     *           is satisfied when the noncurrent time on an object is before
     *           this timestamp. This condition is relevant only for versioned
     *           objects. If a string is given, it must be a date in RFC 3339
     *           format with only the date part (for instance, "2013-01-15").
     *     @type int $numNewerVersions Relevant only for versioned objects. If
     *           the value is N, this condition is satisfied when there are at
     *           least N versions (including the live version) newer than this
     *           version of the object.
     *     @type string[] $matchesPrefix Objects having names which start with
     *           values specified by this condition will be matched.
     *     @type string[] $matchesSuffix Objects having names which end with
     *           values specified by this condition will be matched.
     * }
     * @return Lifecycle
     */
    public function addDeleteRule(array $condition)
    {
        $this->lifecycle['rule'][] = [
            'action' => [
                'type' => 'Delete'
            ],
            'condition' => $this->formatCondition($condition)
        ];

        return $this;
    }

    /**
     * Adds an Object Lifecycle Set Storage Class Rule.
     *
     * Example:
     * ```
     * $lifecycle->addSetStorageClassRule('COLDLINE', [
     *     'age' => 50,
     *     'isLive' => true
     * ]);
     * ```
     *
     * ```
     * // Using customTimeBefore rule with an object's custom time setting.
     * $lifecycle->addSetStorageClassRule('NEARLINE', [
     *     'customTimeBefore' => (new \DateTime())->add(
     *         \DateInterval::createFromDateString('+10 days')
     *     )
     * ]);
     *
     * $bucket->update(['lifecycle' => $lifecycle]);
     *
     * $object = $bucket->object($objectName);
     * $object->update([
     *     'metadata' => [
     *         'customTime' => '2020-08-17'
     *     ]
     * ]);
     * ```
     *
     * @param string $storageClass The target storage class. Values include
     *        `"MULTI_REGIONAL"`, `"REGIONAL"`, `"NEARLINE"`, `"COLDLINE"`,
     *        `"STANDARD"`, and `"DURABLE_REDUCED_AVAILABILITY"`.
     * @param array $condition {
     *     The condition(s) where the rule will apply.
     *
     *     @type int $age Age of an object (in days). This condition is
     *           satisfied when an object reaches the specified age.
     *     @type \DateTimeInterface|string $createdBefore This condition is
     *           satisfied when an object is created before midnight of the
     *           specified date in UTC. If a string is given, it must be a date
     *           in RFC 3339 format with only the date part (for instance,
     *           "2013-01-15").
     *     @type \DateTimeInterface|string $customTimeBefore This condition is
     *           satisfied when the custom time on an object is before this date
     *           in UTC. If a string is given, it must be a date in RFC 3339
     *           format with only the date part (for instance, "2013-01-15").
     *     @type int $daysSinceCustomTime Number of days elapsed since the
     *           user-specified timestamp set on an object. The condition is
     *           satisfied if the days elapsed is at least this number. If no
     *           custom timestamp is specified on an object, the condition does
     *           not apply.
     *     @type int $daysSinceNoncurrentTime Number of days elapsed since the
     *           noncurrent timestamp of an object. The condition is satisfied
     *           if the days elapsed is at least this number. This condition is
     *           relevant only for versioned objects. The value of the field
     *           must be a nonnegative integer. If it's zero, the object version
     *           will become eligible for Lifecycle action as soon as it becomes
     *           noncurrent.
     *     @type bool $isLive Relevant only for versioned objects. If the value
     *           is `true`, this condition matches live objects; if the value is
     *           `false`, it matches archived objects.
     *     @type string[] $matchesStorageClass Objects having any of the storage
     *           classes specified by this condition will be matched. Values
     *           include `"MULTI_REGIONAL"`, `"REGIONAL"`, `"NEARLINE"`,
     *           `"ARCHIVE"`, `"COLDLINE"`, `"STANDARD"`, and
     *           `"DURABLE_REDUCED_AVAILABILITY"`.
     *     @type \DateTimeInterface|string $noncurrentTimeBefore This condition
     *           is satisfied when the noncurrent time on an object is before
     *           this timestamp. This condition is relevant only for versioned
     *           objects. If a string is given, it must be a date in RFC 3339
     *           format with only the date part (for instance, "2013-01-15").
     *     @type int $numNewerVersions Relevant only for versioned objects. If
     *           the value is N, this condition is satisfied when there are at
     *           least N versions (including the live version) newer than this
     *           version of the object.
     *     @type string[] $matchesPrefix Objects having names which start with
     *           values specified by this condition will be matched.
     *     @type string[] $matchesSuffix Objects having names which end with
     *           values specified by this condition will be matched.
     * }
     * @return Lifecycle
     */
    public function addSetStorageClassRule($storageClass, array $condition)
    {
        $this->lifecycle['rule'][] = [
            'action' => [
                'type' => 'SetStorageClass',
                'storageClass' => $storageClass
            ],
            'condition' => $this->formatCondition($condition)
        ];

        return $this;
    }

    /**
     * Clear all Object Lifecycle rules or rules of a certain action type.
     *
     * Example:
     * ```
     * // Remove all rules.
     * $lifecycle->clearRules();
     * ```
     *
     * ```
     * // Remove all "Delete" based rules.
     * $lifecycle->clearRules('Delete');
     * ```
     *
     * ```
     * // Clear any rules which have an age equal to 50.
     * $lifecycle->clearRules(function (array $rule) {
     *     return $rule['condition']['age'] === 50
     *         ? false
     *         : true;
     * });
     * ```
     *
     * @param string|callable $action [optional] If a string is provided, it
     *        must be the name of the type of rule to remove (`SetStorageClass`
     *        or `Delete`). All rules of this type will then be cleared. When
     *        providing a callable you may define a custom route for how you
     *        would like to remove rules. The provided callable will be run
     *        through
     *        [array_filter](http://php.net/manual/en/function.array-filter.php).
     *        The callable's argument will be a single lifecycle rule as an
     *        associative array. When returning true from the callable the rule
     *        will be preserved, and if false it will be removed.
     *        **Defaults to** `null`, clearing all assigned rules.
     * @return Lifecycle
     * @throws \InvalidArgumentException If a type other than a string or
     *         callabe is provided.
     */
    public function clearRules($action = null)
    {
        if (!$action) {
            $this->lifecycle = [];
            return $this;
        }

        if (!is_string($action) && !is_callable($action)) {
            throw new \InvalidArgumentException(
                sprintf(
                    'Expected either a string or callable, instead got \'%s\'.',
                    gettype($action)
                )
            );
        }

        if (isset($this->lifecycle['rule'])) {
            if (is_string($action)) {
                $action = function ($rule) use ($action) {
                    return $rule['action']['type'] !== $action;
                };
            }

            $this->lifecycle['rule'] = array_filter(
                $this->lifecycle['rule'],
                $action
            );

            if (!$this->lifecycle['rule']) {
                $this->lifecycle = [];
            }
        }

        return $this;
    }

    /**
     * @access private
     * @return \Generator
     */
    #[\ReturnTypeWillChange]
    public function getIterator()
    {
        if (!isset($this->lifecycle['rule'])) {
            return;
        }

        foreach ($this->lifecycle['rule'] as $rule) {
            yield $rule;
        }
    }

    /**
     * @access private
     * @return array
     */
    public function toArray()
    {
        return $this->lifecycle;
    }

    /**
     * @access private
     * @param string $offset
     * @param mixed $value
     */
    #[\ReturnTypeWillChange]
    public function offsetSet($offset, $value)
    {
        $this->lifecycle['rule'][$offset] = $value;
    }

    /**
     * @access private
     * @param string $offset
     * @return bool
     */
    #[\ReturnTypeWillChange]
    public function offsetExists($offset)
    {
        return isset($this->lifecycle['rule'][$offset]);
    }

    /**
     * @access private
     * @param string $offset
     */
    #[\ReturnTypeWillChange]
    public function offsetUnset($offset)
    {
        unset($this->lifecycle['rule'][$offset]);
    }

    /**
     * @access private
     * @param string $offset
     * @return mixed
     */
    #[\ReturnTypeWillChange]
    public function offsetGet($offset)
    {
        return isset($this->lifecycle['rule'][$offset])
            ? $this->lifecycle['rule'][$offset]
            : null;
    }

    /**
     * Apply condition-specific formatting rules (such as date formatting) to
     * conditions.
     *
     * @param array $condition
     * @return array
     */
    private function formatCondition(array $condition)
    {
        $rfc339DateFields = [
            'createdBefore',
            'customTimeBefore',
            'noncurrentTimeBefore'
        ];

        foreach ($rfc339DateFields as $field) {
            if (isset($condition[$field]) && $condition[$field] instanceof \DateTimeInterface) {
                $condition[$field] = $condition[$field]->format('Y-m-d');
            }
        }

        return $condition;
    }
}