gcs-8.x-1.0-alpha3/gcs.module
gcs.module
<?php
use Drupal\Core\Block\BlockPluginInterface;
/**
* @file
*/
use Google\Cloud\Storage\StorageClient;
/**
* Implements hook_block_view_alter().
*
* Ideally, all items on the front-end in public:// will be called from a
* block, one way or another. This little alter will ensure that all content
* within a block is filtered for this site's file directory and rewritten to
* pull the images from Google Images.
*/
function gcs_block_view_alter(array &$build, BlockPluginInterface $block) {
$build['#pre_render'][] = 'gcs_block_prerender';
}
/**
* Callback for the function above.
*/
function gcs_block_prerender(array $build) {
if(isset($build['content']['#markup']) && $build['content']['#markup']) {
$config = \Drupal::config('gcs.settings');
$bucket_name = 'https://storage.googleapis.com/' . $config->get('gcs.bucket_name') . '/';
// Look for anything that looks like a local path to our files directory.
$base_file_path = addcslashes(parse_url(file_create_url('public://'))['path'], '/');
$host = \Drupal::request()->getHost();
// Kill anything local.
$pattern = [
'/("|\'|\()' . $base_file_path . '/im',
'/("|\'|\()http:\/\/' . $host . $base_file_path . '/im',
'/("|\'|\()https:\/\/' . $host . $base_file_path . '/im',
];
if(is_string($build['content']['#markup']))
$build['content']['#markup'] = preg_replace($pattern, '\1' . $bucket_name, $build['content']['#markup']);
else {
$content = preg_replace($pattern, '\1' . $bucket_name, $build['content']['#markup']->__toString());
$build['content']['#markup'] = $build['content']['#markup']->create($content);
}
}
return $build;
}
/**
* This is a placeholder for now.
*/
function gcs_sample() {
$config = \Drupal::config('gcs.settings');
require 'vendor/autoload.php';
$storage = new StorageClient([
'projectId' => $config->get('gcs.project_id'),
]);
$bucket = $storage->bucket($config->get('gcs.bucket_name'));
// Upload a file to the bucket.
$bucket->upload(
fopen('/data/file.txt', 'r')
);
// Using Predefined ACLs to manage object permissions, you may
// upload a file and give read access to anyone with the URL.
$bucket->upload(
fopen('/data/file.txt', 'r'),
[
'predefinedAcl' => 'publicRead'
]
);
// Download and store an object from the bucket locally.
$object = $bucket->object('file_backup.txt');
$object->downloadToFile('/data/file_backup.txt');
$storage->registerStreamWrapper();
$contents = file_get_contents('gs://' . $config->get('gcs.bucket_name') . '/file_backup.txt');
}
