110 lines
2.5 KiB
PHP
110 lines
2.5 KiB
PHP
|
<?php
|
||
|
|
||
|
namespace Shikiryu\WebGobbler;
|
||
|
|
||
|
class Pool
|
||
|
{
|
||
|
protected $file_list = [];
|
||
|
|
||
|
/**
|
||
|
* @var \Shikiryu\WebGobbler\Collector[]
|
||
|
*/
|
||
|
protected $collectors = [];
|
||
|
|
||
|
/**
|
||
|
* @var string
|
||
|
*/
|
||
|
protected $pool_directory;
|
||
|
|
||
|
/**
|
||
|
* @var int
|
||
|
*/
|
||
|
protected $nb_images = 0;
|
||
|
|
||
|
/**
|
||
|
* Pool constructor.
|
||
|
*
|
||
|
* @param array $config
|
||
|
*/
|
||
|
public function __construct(array $config)
|
||
|
{
|
||
|
$collectors = [];
|
||
|
if (array_key_exists('collectors', $config)) {
|
||
|
$collectors = $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 = $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 = $config['nb_images']; // FIXME
|
||
|
|
||
|
$this->prepareCollectors();
|
||
|
}
|
||
|
|
||
|
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;
|
||
|
}
|
||
|
|
||
|
private function prepareCollectors()
|
||
|
{
|
||
|
foreach ($this->collectors as $collector) {
|
||
|
$directory = $collector->getPoolDirectory();
|
||
|
$images = glob($directory.'/*.{jpg,gif,png}', GLOB_BRACE);
|
||
|
if (count($images) < $this->nb_images) {
|
||
|
$collector->getRandomImages($this->nb_images - count($images));
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|