Skip to content

Commit f66a262

Browse files
calebdwCaleb White
and
Caleb White
authored
Add image formats to Faker\Provider\Image (#473)
* Added image formats to `Faker\Provider\Image` * Wrote unit tests for image formats in `Image` * Renamed test * Used Image constants, added test for downloaded image * Fixed `php-cs-fixer` issues Co-authored-by: Caleb White <[email protected]>
1 parent 4e206f8 commit f66a262

File tree

2 files changed

+126
-21
lines changed

2 files changed

+126
-21
lines changed

Diff for: src/Faker/Provider/Image.php

+37-5
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ class Image extends Base
1212
*/
1313
public const BASE_URL = 'https://via.placeholder.com';
1414

15+
public const FORMAT_JPG = 'jpg';
16+
public const FORMAT_JPEG = 'jpeg';
17+
public const FORMAT_PNG = 'png';
18+
1519
/**
1620
* @var array
1721
*
@@ -35,6 +39,7 @@ class Image extends Base
3539
* @param bool $randomize
3640
* @param string|null $word
3741
* @param bool $gray
42+
* @param string $format
3843
*
3944
* @return string
4045
*/
@@ -44,9 +49,21 @@ public static function imageUrl(
4449
$category = null,
4550
$randomize = true,
4651
$word = null,
47-
$gray = false
52+
$gray = false,
53+
$format = 'png'
4854
) {
49-
$size = sprintf('%dx%d.png', $width, $height);
55+
// Validate image format
56+
$imageFormats = static::getFormats();
57+
58+
if (!in_array(strtolower($format), $imageFormats, true)) {
59+
throw new \InvalidArgumentException(sprintf(
60+
'Invalid image format "%s". Allowable formats are: %s',
61+
$format,
62+
implode(', ', $imageFormats)
63+
));
64+
}
65+
66+
$size = sprintf('%dx%d.%s', $width, $height, $format);
5067

5168
$imageParts = [];
5269

@@ -90,7 +107,8 @@ public static function image(
90107
$fullPath = true,
91108
$randomize = true,
92109
$word = null,
93-
$gray = false
110+
$gray = false,
111+
$format = 'png'
94112
) {
95113
$dir = null === $dir ? sys_get_temp_dir() : $dir; // GNU/Linux / OS X / Windows compatible
96114
// Validate directory path
@@ -101,10 +119,10 @@ public static function image(
101119
// Generate a random filename. Use the server address so that a file
102120
// generated at the same time on a different server won't have a collision.
103121
$name = md5(uniqid(empty($_SERVER['SERVER_ADDR']) ? '' : $_SERVER['SERVER_ADDR'], true));
104-
$filename = $name . '.png';
122+
$filename = sprintf('%s.%s', $name, $format);
105123
$filepath = $dir . DIRECTORY_SEPARATOR . $filename;
106124

107-
$url = static::imageUrl($width, $height, $category, $randomize, $word, $gray);
125+
$url = static::imageUrl($width, $height, $category, $randomize, $word, $gray, $format);
108126

109127
// save file
110128
if (function_exists('curl_exec')) {
@@ -136,4 +154,18 @@ public static function image(
136154

137155
return $fullPath ? $filepath : $filename;
138156
}
157+
158+
public static function getFormats(): array
159+
{
160+
return array_keys(static::getFormatConstants());
161+
}
162+
163+
public static function getFormatConstants(): array
164+
{
165+
return [
166+
static::FORMAT_JPG => constant('IMAGETYPE_JPEG'),
167+
static::FORMAT_JPEG => constant('IMAGETYPE_JPEG'),
168+
static::FORMAT_PNG => constant('IMAGETYPE_PNG'),
169+
];
170+
}
139171
}

Diff for: test/Faker/Provider/ImageTest.php

+89-16
Original file line numberDiff line numberDiff line change
@@ -85,35 +85,108 @@ public function testImageUrlAddsARandomGetParameterByDefault()
8585
self::assertMatchesRegularExpression('#\w*#', $splitUrl[1]);
8686
}
8787

88-
public function testDownloadWithDefaults()
88+
public function testImageUrlThrowsExceptionOnInvalidImageFormat()
8989
{
90-
$curlPing = curl_init(Image::BASE_URL);
91-
curl_setopt($curlPing, CURLOPT_TIMEOUT, 5);
92-
curl_setopt($curlPing, CURLOPT_CONNECTTIMEOUT, 5);
93-
curl_setopt($curlPing, CURLOPT_RETURNTRANSFER, true);
94-
curl_setopt($curlPing, CURLOPT_FOLLOWLOCATION, true);
95-
$data = curl_exec($curlPing);
96-
$httpCode = curl_getinfo($curlPing, CURLINFO_HTTP_CODE);
97-
curl_close($curlPing);
90+
$this->expectException(\InvalidArgumentException::class);
91+
Image::imageUrl(
92+
800,
93+
400,
94+
'nature',
95+
false,
96+
'Faker',
97+
true,
98+
'foo'
99+
);
100+
}
98101

99-
if ($httpCode < 200 | $httpCode > 300) {
100-
self::markTestSkipped('Placeholder.com is offline, skipping image download');
102+
public function testImageUrlAcceptsDifferentImageFormats()
103+
{
104+
foreach (Image::getFormats() as $format) {
105+
$imageUrl = Image::imageUrl(
106+
800,
107+
400,
108+
'nature',
109+
false,
110+
'Faker',
111+
true,
112+
$format
113+
);
114+
115+
self::assertMatchesRegularExpression(
116+
"#^https://via.placeholder.com/800x400.{$format}/CCCCCC\?text=nature\+Faker#",
117+
$imageUrl
118+
);
101119
}
120+
}
121+
122+
public function testDownloadWithDefaults()
123+
{
124+
self::checkUrlConnection(Image::BASE_URL);
102125

103126
$file = Image::image(sys_get_temp_dir());
104127
self::assertFileExists($file);
105128

129+
self::checkImageProperties($file, 640, 480, 'png');
130+
}
131+
132+
public function testDownloadWithDifferentImageFormats()
133+
{
134+
self::checkUrlConnection(Image::BASE_URL);
135+
136+
foreach (Image::getFormats() as $format) {
137+
$width = 800;
138+
$height = 400;
139+
$file = Image::image(
140+
sys_get_temp_dir(),
141+
$width,
142+
$height,
143+
'nature',
144+
true,
145+
false,
146+
'Faker',
147+
true,
148+
$format
149+
);
150+
self::assertFileExists($file);
151+
152+
self::checkImageProperties($file, $width, $height, $format);
153+
}
154+
}
155+
156+
private static function checkImageProperties(
157+
string $file,
158+
int $width,
159+
int $height,
160+
string $format
161+
) {
106162
if (function_exists('getimagesize')) {
107-
[$width, $height, $type, $attr] = getimagesize($file);
108-
self::assertEquals(640, $width);
109-
self::assertEquals(480, $height);
110-
self::assertEquals(constant('IMAGETYPE_PNG'), $type);
163+
$imageConstants = Image::getFormatConstants();
164+
[$actualWidth, $actualHeight, $type, $attr] = getimagesize($file);
165+
self::assertEquals($width, $actualWidth);
166+
self::assertEquals($height, $actualHeight);
167+
self::assertEquals($imageConstants[$format], $type);
111168
} else {
112-
self::assertEquals('png', pathinfo($file, PATHINFO_EXTENSION));
169+
self::assertEquals($format, pathinfo($file, PATHINFO_EXTENSION));
113170
}
114171

115172
if (file_exists($file)) {
116173
unlink($file);
117174
}
118175
}
176+
177+
private static function checkUrlConnection(string $url)
178+
{
179+
$curlPing = curl_init($url);
180+
curl_setopt($curlPing, CURLOPT_TIMEOUT, 5);
181+
curl_setopt($curlPing, CURLOPT_CONNECTTIMEOUT, 5);
182+
curl_setopt($curlPing, CURLOPT_RETURNTRANSFER, true);
183+
curl_setopt($curlPing, CURLOPT_FOLLOWLOCATION, true);
184+
$data = curl_exec($curlPing);
185+
$httpCode = curl_getinfo($curlPing, CURLINFO_HTTP_CODE);
186+
curl_close($curlPing);
187+
188+
if ($httpCode < 200 | $httpCode > 300) {
189+
self::markTestSkipped(sprintf('"%s" is offline, skipping test', $url));
190+
}
191+
}
119192
}

0 commit comments

Comments
 (0)