Skip to content

Instantly share code, notes, and snippets.

@jissereitsma
Created August 16, 2016 09:59
Show Gist options
  • Save jissereitsma/115b62ecb7689b4e5dc7a9aa02fe3c7a to your computer and use it in GitHub Desktop.
Save jissereitsma/115b62ecb7689b4e5dc7a9aa02fe3c7a to your computer and use it in GitHub Desktop.
<?php
/*
* - Switch to composer package
* - Namespacing
* - Use file/handler package
* - Use downloader package
* - Use image creation package
*/
interface ImageGenerator
{
public function getImageUrl();
public function getPrefix();
}
class ThecatapiImageGenerator implements ImageGenerator
{
public function getImageUrl()
{
return 'http://thecatapi.com/api/images/get?format=src&type=png&size=full';
}
public function getPrefix()
{
return 'cats';
}
}
class ImageCreator
{
protected $generator;
protected $baseFolder;
protected $imagesPerFolder = 10;
protected $subfoldersPerFolder = 2;
protected $folderDepth = 2;
public function setGenerator(ImageGenerator $generator)
{
$this->generator = $generator;
}
public function setBaseFolder($folder)
{
$this->baseFolder = $folder;
$this->createFolder($folder);
}
public function createFolder($folder)
{
if (is_dir($folder)) {
return false;
}
echo "creating folder $folder\n";
mkdir($folder);
return true;
}
public function generateSubfolders($folder = null, $depth = 0)
{
if (empty($folder)) {
$folder = $this->baseFolder;
}
if ($depth > $this->folderDepth) {
return false;
}
for ($i = 1; $i <= $this->imagesPerFolder; $i++) {
$newImageName = $folder . '/' . basename($folder) . '-' . $i . '.png';
$this->generateImage($newImageName);
}
for ($i = 1; $i <= $this->subfoldersPerFolder; $i++) {
$newFolderName = $folder . '/' . $this->generator->getPrefix() . '-' . $i;
$this->createFolder($newFolderName);
$this->generateSubfolders($newFolderName, $depth + 1);
}
return false;
}
public function generateImage($imageName)
{
echo "generating image $imageName\n";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->getDownloadUrl());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec ($ch);
curl_close ($ch);
$file = fopen($imageName, "w+");
fputs($file, $data);
fclose($file);
}
public function getDownloadUrl()
{
return $this->generator->getImageUrl();
}
public function setImagesPerFolder($count)
{
$this->imagesPerFolder = (int) $count;
}
public function setFolderDepth($folderDepth)
{
$this->folderDepth = (int) $folderDepth;
}
}
$imageCreator = new ImageCreator;
$imageCreator->setGenerator(new ThecatapiImageGenerator);
$imageCreator->setBaseFolder(__DIR__ . '/tmp');
$imageCreator->setFolderDepth(2);
$imageCreator->setImagesPerFolder(2);
$imageCreator->generateSubfolders();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment