Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
st0nebridge committed Jun 25, 2020
0 parents commit 5451ee5
Show file tree
Hide file tree
Showing 7 changed files with 343 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Techster Dynamics

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
147 changes: 147 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
# Google Cloud Storage Meta Bucket for PHP
A simple GCP storage bucket wrapper to automatically set metadata on uploaded files.

Metadata reference: https://cloud.google.com/storage/docs/metadata

Created for use with other libraries that may not allow you to configure the metadata (eg Cache-Control) for storage bucket objects.

Works with:
- https://github.com/1up-lab/OneupFlysystemBundle
- https://github.com/dustin10/VichUploaderBundle (using Flysystem)
- https://github.com/liip/LiipImagineBundle (using Flysystem)

### Installation

Requires: https://github.com/googleapis/google-cloud-php-storage

To begin, install the preferred dependency manager for PHP, [Composer](https://getcomposer.org/).

Install the wrapper:

```sh
$ composer require techdyn/google-storage-meta-bucket
```

### Sample

```php
require 'vendor/autoload.php';

use TechDyn\GoogleStorageMetaBucket\Storage\ProxyStorageClient;

$storage = new ProxyStorageClient(); // ProxyStorageClient extends Google\Cloud\Storage\StorageClient;

$bucket = $storage->bucket('my_bucket'); // MetaBucket extends Google\Cloud\Storage\Bucket

// https://cloud.google.com/storage/docs/metadata
$bucket->setOption('cacheControl', 'no-cache, max-age=60'); // $name uses metadata field written as camelCase

// Upload a file to the bucket.
$bucket->upload(
fopen('/data/file.txt', 'r')
);
```

### Symfony & Flysystem

```yaml
# services.yaml

parameters:

gcp_client_options:
projectId: 'gcp-project-id'
keyFilePath: '%kernel.project_dir%/config/gcp/service.json' # Optional - if not configured externally

gcp_storage_bucket: 'name-of-bucket'

services:

google_cloud_storage.client:
class: TechDyn\GoogleStorageMetaBucket\Storage\ProxyStorageClient
arguments: ['%gcp_client_options%']

google_cloud_storage.bucket:
class: TechDyn\GoogleStorageMetaBucket\Storage\MetaBucket
factory: ['@google_cloud_storage.client', bucket]
arguments: ['%gcp_storage_bucket%']
calls:
- method: setOption
arguments:
- 'cacheControl'
- 'no-cache, max-age=60'
```
##### Flysystem
Using: https://github.com/1up-lab/OneupFlysystemBundle
```yaml
# packages/oneup_flysystem.yaml

# Read the documentation: https://github.com/1up-lab/OneupFlysystemBundle/tree/master/Resources/doc/index.md
oneup_flysystem:
adapters:
gcp_storage_adapter:
googlecloudstorage:
client: google_cloud_storage.client
bucket: google_cloud_storage.bucket
prefix: ~

filesystems:
gcp_storage_fs:
adapter: gcp_storage_adapter
mount: gcp_storage_fs
```
##### Vich Uploader
Using: https://github.com/dustin10/VichUploaderBundle
```yaml
# packages/vich_uploader.yaml

vich_uploader:
db_driver: orm
storage: flysystem
mappings:
uploaded_images:
uri_prefix: 'https://%gcp_storage_bucket%.storage.googleapis.com' # https://name-of-bucket.storage.googleapis.com or your custom domain
upload_destination: gcp_storage_fs
namer: vich_uploader.namer_uniqid
inject_on_load: false
delete_on_update: true
delete_on_remove: true
```
##### Liip Imagine
Using: https://github.com/liip/LiipImagineBundle
```yaml
# packages/liip_imagine.yaml

# See dos how to configure the bundle: https://symfony.com/doc/current/bundles/LiipImagineBundle/basic-usage.html
liip_imagine:
driver: "gd" # valid drivers options include "gd" or "gmagick" or "imagick"

loaders:
gcp_loader:
flysystem:
filesystem_service: oneup_flysystem.gcp_storage_fs_filesystem

data_loader: gcp_loader
resolvers:
gcp_cache:
flysystem:
root_url: 'https://%gcp_storage_bucket%.storage.googleapis.com'
filesystem_service: oneup_flysystem.gcp_storage_fs_filesystem

filter_sets:
thumb_default:
data_loader: gcp_loader
cache: gcp_cache
quality: 75
filters:
downscale: { max: [64, 64], mode: outbound }
```
50 changes: 50 additions & 0 deletions Storage/MetaBucket.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace TechDyn\GoogleStorageMetaBucket\Storage;

use Google\Cloud\Storage\Bucket;
use Google\Cloud\Storage\Connection\ConnectionInterface;
use Google\Cloud\Storage\StorageObject;
use Psr\Http\Message\StreamInterface;

class MetaBucket extends Bucket
{
protected $metadata;

/**
* MetaBucket constructor.
* @param ConnectionInterface $connection
* @param $name
* @param array $info
*/
public function __construct(ConnectionInterface $connection, $name, array $info = [])
{
parent::__construct($connection, $name, $info);

$this->metadata = [];
}

/**
* @param StreamInterface|resource|string|null $data
* @param array $options
* @return StorageObject
*/
public function upload($data, array $options = [])
{
$metadata = $this->metadata ? [ 'metadata' => $this->metadata ] : [];

return parent::upload($data, array_replace_recursive($metadata, $options));
}

/**
* @param string $name
* @param $value
* @return $this
*/
public function setOption(string $name, $value)
{
$this->metadata[$name] = $value;

return $this;
}
}
29 changes: 29 additions & 0 deletions Storage/ProxyStorageClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace TechDyn\GoogleStorageMetaBucket\Storage;

use Google\Cloud\Storage\StorageClient;
use TechDyn\GoogleStorageMetaBucket\Traits\VarThiefTrait;

class ProxyStorageClient extends StorageClient
{
use VarThiefTrait;

/**
* @param string $name
* @param bool $userProject
* @return MetaBucket
*/
public function bucket($name, $userProject = false)
{
if (!$userProject) {
$userProject = null;
} elseif (!is_string($userProject)) {
$userProject = $this->stealParentVar('projectId'); // private inherited variable
}

return new MetaBucket($this->connection, $name, [
'requesterProjectId' => $userProject
]);
}
}
57 changes: 57 additions & 0 deletions Tools/ReflectionTools.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace TechDyn\GoogleStorageMetaBucket\Tools;

use Closure;

class ReflectionTools
{
private static $__reflectedProps = [];

/**
* @param $object
* @param string|array $variable - returns array if array specified
* @param string $className
* @param bool|array $exec
* @return mixed|null
*/
public static function stealVariable(&$object, $variable, string $className, $exec = false)
{
$cacheKey = ((false !== $exec ? "e#" : "s#") . spl_object_hash($object) . "#{$variable}");
if (!isset(self::$__reflectedProps[$cacheKey]))
{
self::$__reflectedProps[$cacheKey] = Closure::bind(function () use ($object, $variable, $exec)
{
$vars = is_array($variable) ? $variable : [ $variable ];
$execParams = is_array($exec) ? $exec : [];

$output = [];
foreach($vars as $v)
{
if (property_exists($object, $v) &&
(false === $exec || ($exec && is_callable($object->$v))))
{
$output[$v] =
$exec ?
$object->$v(...$execParams[$v]) :
$object->$v;
}
}

return
is_array($variable) ?
$output :
reset($output);

}, null, $className);
}

if (!empty($__reflectedProps[$cacheKey]) &&
is_callable(self::$__reflectedProps[$cacheKey]))
{
return self::$__reflectedProps[$cacheKey]();
}

return null;
}
}
25 changes: 25 additions & 0 deletions Traits/VarThiefTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace TechDyn\GoogleStorageMetaBucket\Traits;

use TechDyn\GoogleStorageMetaBucket\Tools\ReflectionTools;

trait VarThiefTrait
{
private static $__reflectionParentClass = null;

/**
* @param string $variableName
* @param bool|array $exec
* @return mixed|null
*/
private function stealParentVar(string $variableName, $exec = false)
{
return ReflectionTools::stealVariable(
$this,
$variableName,
self::$__reflectionParentClass ?: get_parent_class($this),
$exec
);
}
}
14 changes: 14 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "techdyn/google-storage-meta-bucket",
"description": "A simple GCP storage bucket wrapper to automatically set metadata (cache-control, etc) on uploaded files.",
"license": "MIT",
"require": {
"php": "^7.2",
"google/cloud-storage": "^1.0"
},
"autoload": {
"psr-4": {
"TechDyn\\GoogleStorageMetaBucket\\": ""
}
}
}

0 comments on commit 5451ee5

Please sign in to comment.