WebCollage/src/Pool.php

137 lines
3.2 KiB
PHP

<?php
namespace Shikiryu\WebGobbler;
class Pool
{
/**
* @var string[]
*/
protected $file_list = [];
/**
* @var \Shikiryu\WebGobbler\Collector[]
*/
protected $collectors = [];
/**
* @var string
*/
protected $pool_directory;
/**
* @var int
*/
protected $nb_images = 0;
/**
* @var \Shikiryu\WebGobbler\Config
*/
protected $config;
/**
* Pool constructor.
*
* @param array $config
*/
public function __construct(Config $config)
{
$this->config = $config;
$pool_config = $config->get('pool');
$collectors = [];
if (array_key_exists('collectors', $pool_config)) {
$collectors = $pool_config['collectors'];
}
$all_collectors = Collector::getAllCollectors($this);
if (empty($collectors)) {
$this->collectors = $all_collectors;
} else {
foreach ($all_collectors as $collector) {
if (in_array($collector->getName(), $collectors, true)) {
$this->collectors[] = $collector;
}
}
}
$pool_dir = $pool_config['directory'];
if (!is_dir($pool_dir) && !mkdir($pool_dir) && !is_dir($pool_dir)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $pool_dir));
}
$this->pool_directory = $pool_dir;
$this->nb_images = $pool_config['nb_images'];
$this->prepareCollectors();
}
public function getConfig()
{
return $this->config;
}
/**
* @return string
*/
public function getPoolDirectory()
{
return $this->pool_directory;
}
/**
* @return string
*/
public function getImage()
{
$images = $this->getFileList();
$index = array_rand($images);
$image = $images[$index];
unset($this->file_list[$index]);
return $image;
}
/**
* @return array
*/
private function getFileList()
{
if (!empty($this->file_list)) {
return $this->file_list;
}
$file_list = [];
foreach ($this->collectors as $collector) {
$directory = $collector->getPoolDirectory();
$file_list = array_merge($file_list, glob($directory.'/*.{jpg,gif,png}', GLOB_BRACE));
}
$this->file_list = $file_list;
return $file_list;
}
/**
* Check if collector folder exists or create it
*
* Download images if configured to
*/
private function prepareCollectors()
{
foreach ($this->collectors as $collector) {
$directory = $collector->getPoolDirectory();
if (!is_dir($directory) && !mkdir($directory) && !is_dir($directory)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $directory));
}
if ($this->config->get('pool.pre_download', false) === true) {
$images = glob($directory . '/*.{jpg,gif,png}', GLOB_BRACE);
if (count($images) < $this->nb_images) {
$collector->getRandomImages($this->nb_images - count($images));
}
}
}
}
}