You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

193 lines
6.0 KiB

2 years ago
  1. <?php
  2. namespace App\Utilities\Helpers;
  3. use Faker\Provider\Base;
  4. class Image extends Base {
  5. /**
  6. * @var string
  7. */
  8. public const BASE_URL = 'https://via.placeholder.com';
  9. public const FORMAT_JPG = 'jpg';
  10. public const FORMAT_JPEG = 'jpeg';
  11. public const FORMAT_PNG = 'png';
  12. /**
  13. * @var array
  14. *
  15. * @deprecated Categories are no longer used as a list in the placeholder API but referenced as string instead
  16. */
  17. protected static $categories = [
  18. 'abstract', 'animals', 'business', 'cats', 'city', 'food', 'nightlife',
  19. 'fashion', 'people', 'nature', 'sports', 'technics', 'transport',
  20. ];
  21. /**
  22. * Generate the URL that will return a random image
  23. *
  24. * Set randomize to false to remove the random GET parameter at the end of the url.
  25. *
  26. * @example 'http://via.placeholder.com/640x480.png/CCCCCC?text=well+hi+there'
  27. *
  28. * @param int $width
  29. * @param int $height
  30. * @param string|null $category
  31. * @param bool $randomize
  32. * @param string|null $word
  33. * @param bool $gray
  34. * @param string $format
  35. *
  36. * @return string
  37. */
  38. public static function imageUrl(
  39. $width = 640,
  40. $height = 480,
  41. $category = null,
  42. $randomize = true,
  43. $word = null,
  44. $gray = false,
  45. $format = 'png'
  46. ) {
  47. trigger_deprecation(
  48. 'fakerphp/faker',
  49. '1.20',
  50. 'Provider is deprecated and will no longer be available in Faker 2. Please use a custom provider instead'
  51. );
  52. // Validate image format
  53. $imageFormats = static::getFormats();
  54. if (!in_array(strtolower($format), $imageFormats, true)) {
  55. throw new \InvalidArgumentException(sprintf(
  56. 'Invalid image format "%s". Allowable formats are: %s',
  57. $format,
  58. implode(', ', $imageFormats)
  59. ));
  60. }
  61. $size = sprintf('%dx%d.%s', $width, $height, $format);
  62. $imageParts = [];
  63. if ($category !== null) {
  64. $imageParts[] = $category;
  65. }
  66. if ($word !== null) {
  67. $imageParts[] = $word;
  68. }
  69. if ($randomize === true) {
  70. $imageParts[] = Lorem::word();
  71. }
  72. $backgroundColor = $gray === true ? 'CCCCCC' : str_replace('#', '', Color::safeHexColor());
  73. return sprintf(
  74. '%s/%s/%s%s',
  75. self::BASE_URL,
  76. $size,
  77. $backgroundColor,
  78. count($imageParts) > 0 ? '?text=' . urlencode(implode(' ', $imageParts)) : ''
  79. );
  80. }
  81. /**
  82. * Download a remote random image to disk and return its location
  83. *
  84. * Requires curl, or allow_url_fopen to be on in php.ini.
  85. *
  86. * @example '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.png'
  87. *
  88. * @return bool|string
  89. */
  90. public static function image(
  91. $dir = null,
  92. $width = 640,
  93. $height = 480,
  94. $category = null,
  95. $fullPath = true,
  96. $randomize = true,
  97. $word = null,
  98. $gray = false,
  99. $format = 'png'
  100. ) {
  101. trigger_deprecation(
  102. 'fakerphp/faker',
  103. '1.20',
  104. 'Provider is deprecated and will no longer be available in Faker 2. Please use a custom provider instead'
  105. );
  106. $dir = null === $dir ? sys_get_temp_dir() : $dir; // GNU/Linux / OS X / Windows compatible
  107. // Validate directory path
  108. if (!is_dir($dir) || !is_writable($dir)) {
  109. throw new \InvalidArgumentException(sprintf('Cannot write to directory "%s"', $dir));
  110. }
  111. // Generate a random filename. Use the server address so that a file
  112. // generated at the same time on a different server won't have a collision.
  113. $name = md5(uniqid(empty($_SERVER['SERVER_ADDR']) ? '' : $_SERVER['SERVER_ADDR'], true));
  114. $filename = sprintf('%s.%s', $name, $format);
  115. $filepath = $dir . DIRECTORY_SEPARATOR . $filename;
  116. $url = static::imageUrl($width, $height, $category, $randomize, $word, $gray, $format);
  117. // save file
  118. if (function_exists('curl_exec')) {
  119. // use cURL
  120. $fp = fopen($filepath, 'w');
  121. $ch = curl_init($url);
  122. curl_setopt($ch, CURLOPT_FILE, $fp);
  123. $success = curl_exec($ch) && curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200;
  124. fclose($fp);
  125. curl_close($ch);
  126. if (!$success) {
  127. unlink($filepath);
  128. // could not contact the distant URL or HTTP error - fail silently.
  129. return false;
  130. }
  131. } elseif (ini_get('allow_url_fopen')) {
  132. // use remote fopen() via copy()
  133. $success = copy($url, $filepath);
  134. if (!$success) {
  135. // could not contact the distant URL or HTTP error - fail silently.
  136. return false;
  137. }
  138. } else {
  139. return new \RuntimeException('The image formatter downloads an image from a remote HTTP server. Therefore, it requires that PHP can request remote hosts, either via cURL or fopen()');
  140. }
  141. return $fullPath ? $filepath : $filename;
  142. }
  143. public static function getFormats(): array
  144. {
  145. trigger_deprecation(
  146. 'fakerphp/faker',
  147. '1.20',
  148. 'Provider is deprecated and will no longer be available in Faker 2. Please use a custom provider instead'
  149. );
  150. return array_keys(static::getFormatConstants());
  151. }
  152. public static function getFormatConstants(): array
  153. {
  154. trigger_deprecation(
  155. 'fakerphp/faker',
  156. '1.20',
  157. 'Provider is deprecated and will no longer be available in Faker 2. Please use a custom provider instead'
  158. );
  159. return [
  160. static::FORMAT_JPG => constant('IMAGETYPE_JPEG'),
  161. static::FORMAT_JPEG => constant('IMAGETYPE_JPEG'),
  162. static::FORMAT_PNG => constant('IMAGETYPE_PNG'),
  163. ];
  164. }
  165. }