View source
<?php
namespace Drupal\janrain_capture;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use GuzzleHttp\Client;
use Drupal\Core\File\FileSystemInterface;
class ScreenLoaderManager {
const CACHE_DIR = 'public://janrain_capture_screens/cache';
const ALLOWED_SCREENS = [
'signin',
'edit-profile',
'public-profile',
'forgot',
'verify',
];
const ALLOWED_TYPES = [
'js',
'html',
];
protected $path;
protected $logger;
protected $httpClient;
public function __construct(ConfigFactoryInterface $configFactory, LoggerChannelFactoryInterface $logger_factory, Client $client, FileSystemInterface $file_system) {
$this->path = rtrim($configFactory
->get('janrain_capture.settings')
->get('screens.folder'), '/');
$this->logger = $logger_factory
->get('janrain_capture');
$this->httpClient = $client;
$this->fileSystem = $file_system;
}
public function isRemote() {
return strpos($this->path, 'http') === 0;
}
public function getScreen($name, $type) {
if (!in_array($name, static::ALLOWED_SCREENS) || !in_array($type, static::ALLOWED_TYPES)) {
return '';
}
$file_name = static::buildPath($this
->isRemote() ? static::CACHE_DIR : $this->path, $name, $type);
if (!is_readable($file_name)) {
$this->logger
->error('Unable to read @filename', [
'@filename' => $file_name,
]);
return '';
}
return file_get_contents($file_name);
}
public function updateRemoteScreens() {
$cache_directory = static::CACHE_DIR;
$success = $this->fileSystem
->prepareDirectory($cache_directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
if (!$success) {
$this->logger
->error('Failed to create screen cache directory: @directory', [
'@directory' => $cache_directory,
]);
return;
}
foreach (static::ALLOWED_SCREENS as $name) {
foreach (static::ALLOWED_TYPES as $type) {
$screen_source = static::buildPath($this->path, $name, $type);
$screen_destination = static::buildPath($cache_directory, $name, $type);
$response = $this->httpClient
->get($screen_source);
if ($response
->getStatusCode() !== 200) {
$this->logger
->error('Error during retrieving Janrain remote screen (@url)', [
'@url' => $screen_source,
]);
continue;
}
$success_file_save = $this->fileSystem
->saveData($response
->getBody(), $screen_destination, FileSystemInterface::EXISTS_REPLACE);
if ($success_file_save === FALSE) {
$this->logger
->error('Failed to write @screenDest', [
'@screenDest' => $screen_destination,
]);
}
}
}
}
protected static function buildPath($path, $name, $type) {
return sprintf('%s/%s.%s', $path, $name, $type);
}
}