Skip to content

Commit

Permalink
Standin replacement for LoremPixel to Placeholder.com (#11)
Browse files Browse the repository at this point in the history
* Standin replacement for LoremImage to Placeholder.com

* Updated constant and stricter sprintf types

* Removed BC

* Null to empty string if no elements are set

Co-authored-by: Chris Döhring <[email protected]>

Co-authored-by: Chris Döhring <[email protected]>
  • Loading branch information
pimjansen and chris-doehring authored Oct 28, 2020
1 parent 6929a20 commit a23a83b
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 47 deletions.
73 changes: 47 additions & 26 deletions src/Faker/Provider/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,24 @@
*/
class Image extends Base
{
protected static $categories = array(
/** @var string */
public const BASE_URL = 'https://via.placeholder.com';

/**
* @var array
* @deprecated Categories are no longer used as a list in the placeholder API but referenced as string instead
*/
protected static $categories = [
'abstract', 'animals', 'business', 'cats', 'city', 'food', 'nightlife',
'fashion', 'people', 'nature', 'sports', 'technics', 'transport'
);
];

/**
* Generate the URL that will return a random image
*
* Set randomize to false to remove the random GET parameter at the end of the url.
*
* @example 'http://lorempixel.com/640/480/?12345'
* @example 'http://via.placeholder.com/640x480.png/CCCCCC?text=well+hi+there'
*
* @param integer $width
* @param integer $height
Expand All @@ -28,41 +35,55 @@ class Image extends Base
*
* @return string
*/
public static function imageUrl($width = 640, $height = 480, $category = null, $randomize = true, $word = null, $gray = false)
{
$baseUrl = "https://lorempixel.com/";
$url = "{$width}/{$height}/";
public static function imageUrl(
$width = 640,
$height = 480,
$category = null,
$randomize = true,
$word = null,
$gray = false
) {
$size = sprintf('%dx%d.png', $width, $height);

if ($gray) {
$url = "gray/" . $url;
$imageParts = [];
if ($category !== null) {
$imageParts[] = $category;
}

if ($category) {
if (!in_array($category, static::$categories)) {
throw new \InvalidArgumentException(sprintf('Unknown image category "%s"', $category));
}
$url .= "{$category}/";
if ($word) {
$url .= "{$word}/";
}
if ($word !== null) {
$imageParts[] = $word;
}

if ($randomize) {
$url .= '?' . static::randomNumber(5, true);
if ($randomize === true) {
$imageParts[] = Lorem::word();
}

return $baseUrl . $url;
$backgroundColor = $gray === true ? 'CCCCCC' : str_replace('#', '', Color::safeHexColor());

return sprintf(
'%s/%s/%s%s',
self::BASE_URL,
$size,
$backgroundColor,
count($imageParts) > 0 ? '?text=' . urlencode(implode(' ', $imageParts)) : ''
);
}

/**
* Download a remote random image to disk and return its location
*
* Requires curl, or allow_url_fopen to be on in php.ini.
*
* @example '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.jpg'
* @example '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.png'
*/
public static function image($dir = null, $width = 640, $height = 480, $category = null, $fullPath = true, $randomize = true, $word = null, $gray = false)
{
public static function image(
$dir = null,
$width = 640,
$height = 480,
$category = null,
$fullPath = true,
$randomize = true,
$word = null,
$gray = false
) {
$dir = is_null($dir) ? sys_get_temp_dir() : $dir; // GNU/Linux / OS X / Windows compatible
// Validate directory path
if (!is_dir($dir) || !is_writable($dir)) {
Expand All @@ -72,7 +93,7 @@ public static function image($dir = null, $width = 640, $height = 480, $category
// Generate a random filename. Use the server address so that a file
// generated at the same time on a different server won't have a collision.
$name = md5(uniqid(empty($_SERVER['SERVER_ADDR']) ? '' : $_SERVER['SERVER_ADDR'], true));
$filename = $name . '.jpg';
$filename = $name . '.png';
$filepath = $dir . DIRECTORY_SEPARATOR . $filename;

$url = static::imageUrl($width, $height, $category, $randomize, $word, $gray);
Expand Down
52 changes: 31 additions & 21 deletions test/Faker/Provider/ImageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,34 @@ final class ImageTest extends TestCase
{
public function testImageUrlUses640x680AsTheDefaultSize()
{
$this->assertMatchesRegularExpression('#^https://lorempixel.com/640/480/#', Image::imageUrl());
$this->assertMatchesRegularExpression(
'#^https://via.placeholder.com/640x480.png/#',
Image::imageUrl()
);
}

public function testImageUrlAcceptsCustomWidthAndHeight()
{
$this->assertMatchesRegularExpression('#^https://lorempixel.com/800/400/#', Image::imageUrl(800, 400));
$this->assertMatchesRegularExpression(
'#^https://via.placeholder.com/800x400.png/#',
Image::imageUrl(800, 400)
);
}

public function testImageUrlAcceptsCustomCategory()
{
$this->assertMatchesRegularExpression('#^https://lorempixel.com/800/400/nature/#', Image::imageUrl(800, 400, 'nature'));
$this->assertMatchesRegularExpression(
'#^https://via.placeholder.com/800x400.png/[\w]{6}\?text=nature\+.*#',
Image::imageUrl(800, 400, 'nature')
);
}

public function testImageUrlAcceptsCustomText()
{
$this->assertMatchesRegularExpression('#^https://lorempixel.com/800/400/nature/Faker#', Image::imageUrl(800, 400, 'nature', false, 'Faker'));
$this->assertMatchesRegularExpression(
'#^https://via.placeholder.com/800x400.png/[\w]{6}\?text=nature\+Faker#',
Image::imageUrl(800, 400, 'nature', false, 'Faker')
);
}

public function testImageUrlReturnsLinkToRegularImageWhenGrayIsFalse()
Expand All @@ -38,7 +50,10 @@ public function testImageUrlReturnsLinkToRegularImageWhenGrayIsFalse()
false
);

$this->assertSame('https://lorempixel.com/800/400/nature/Faker/', $imageUrl);
$this->assertMatchesRegularExpression(
'#^https://via.placeholder.com/800x400.png/[\w]{6}\?text=nature\+Faker#',
$imageUrl
);
}

public function testImageUrlReturnsLinkToRegularImageWhenGrayIsTrue()
Expand All @@ -52,39 +67,34 @@ public function testImageUrlReturnsLinkToRegularImageWhenGrayIsTrue()
true
);

$this->assertSame('https://lorempixel.com/gray/800/400/nature/Faker/', $imageUrl);
$this->assertMatchesRegularExpression(
'#^https://via.placeholder.com/800x400.png/CCCCCC\?text=nature\+Faker#',
$imageUrl
);
}

public function testImageUrlAddsARandomGetParameterByDefault()
{
$url = Image::imageUrl(800, 400);
$splitUrl = preg_split('/\?/', $url);
$splitUrl = preg_split('/\?text=/', $url);

$this->assertEquals(count($splitUrl), 2);
$this->assertMatchesRegularExpression('#\d{5}#', $splitUrl[1]);
}

public function testUrlWithDimensionsAndBadCategory()
{
$this->expectException(\InvalidArgumentException::class);
Image::imageUrl(800, 400, 'bullhonky');
$this->assertMatchesRegularExpression('#\w*#', $splitUrl[1]);
}

public function testDownloadWithDefaults()
{
$this->markTestSkipped('Skipped due to unstable service prior 1.9.0 release');

$url = "http://lorempixel.com/";
$curlPing = curl_init($url);
$curlPing = curl_init(Image::BASE_URL);
curl_setopt($curlPing, CURLOPT_TIMEOUT, 5);
curl_setopt($curlPing, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curlPing, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlPing, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($curlPing);
$httpCode = curl_getinfo($curlPing, CURLINFO_HTTP_CODE);
curl_close($curlPing);

if ($httpCode < 200 | $httpCode > 300) {
$this->markTestSkipped("LoremPixel is offline, skipping image download");
$this->markTestSkipped("Placeholder.com is offline, skipping image download");
}

$file = Image::image(sys_get_temp_dir());
Expand All @@ -93,9 +103,9 @@ public function testDownloadWithDefaults()
list($width, $height, $type, $attr) = getimagesize($file);
$this->assertEquals(640, $width);
$this->assertEquals(480, $height);
$this->assertEquals(constant('IMAGETYPE_JPEG'), $type);
$this->assertEquals(constant('IMAGETYPE_PNG'), $type);
} else {
$this->assertEquals('jpg', pathinfo($file, PATHINFO_EXTENSION));
$this->assertEquals('png', pathinfo($file, PATHINFO_EXTENSION));
}
if (file_exists($file)) {
unlink($file);
Expand Down

0 comments on commit a23a83b

Please sign in to comment.