|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Ottaviano\Faker; |
| 4 | + |
| 5 | +use Faker\Provider\Base; |
| 6 | + |
| 7 | +class Gravatar extends Base |
| 8 | +{ |
| 9 | + private const MODES = [ |
| 10 | + 'blank', |
| 11 | + 'identicon', |
| 12 | + 'monsterid', |
| 13 | + 'mp', |
| 14 | + 'retro', |
| 15 | + 'robohash', |
| 16 | + 'wavatar', |
| 17 | + ]; |
| 18 | + |
| 19 | + private const URL = 'https://www.gravatar.com/avatar/%s.jpg?d=%s&size=%d'; |
| 20 | + |
| 21 | + public static function gravatarUrl(string $mode = null, string $email = null, int $size = 80): string |
| 22 | + { |
| 23 | + if (!$mode || !in_array($mode, static::MODES, true)) { |
| 24 | + $mode = 'retro'; |
| 25 | + } |
| 26 | + |
| 27 | + $hash = $email ? md5(static::toLower($email)) : static::randomNumber(5, true); |
| 28 | + |
| 29 | + return sprintf(static::URL, $hash, $mode, $size); |
| 30 | + } |
| 31 | + |
| 32 | + public static function gravatar(string $dir = null, string $mode = null, string $email = null, int $size = 80, bool $fullPath = true): ?string |
| 33 | + { |
| 34 | + $dir = $dir ?? sys_get_temp_dir(); |
| 35 | + |
| 36 | + if (!is_dir($dir) || !is_writable($dir)) { |
| 37 | + throw new \InvalidArgumentException(sprintf('Cannot write to directory "%s"', $dir)); |
| 38 | + } |
| 39 | + |
| 40 | + $name = md5(uniqid($_SERVER['SERVER_ADDR'] ?? '', true)); |
| 41 | + $filename = $name.'.jpg'; |
| 42 | + $filepath = $dir.DIRECTORY_SEPARATOR.$filename; |
| 43 | + |
| 44 | + $url = static::gravatarUrl($mode, $email, $size); |
| 45 | + |
| 46 | + // save file |
| 47 | + if (function_exists('curl_exec')) { |
| 48 | + // use cURL |
| 49 | + $fp = fopen($filepath, 'w'); |
| 50 | + $ch = curl_init($url); |
| 51 | + curl_setopt($ch, CURLOPT_FILE, $fp); |
| 52 | + $success = curl_exec($ch) && 200 === curl_getinfo($ch, CURLINFO_HTTP_CODE); |
| 53 | + fclose($fp); |
| 54 | + curl_close($ch); |
| 55 | + |
| 56 | + if (!$success) { |
| 57 | + unlink($filepath); |
| 58 | + |
| 59 | + // could not contact the distant URL or HTTP error - fail silently. |
| 60 | + return null; |
| 61 | + } |
| 62 | + } elseif (ini_get('allow_url_fopen')) { |
| 63 | + copy($url, $filepath); |
| 64 | + } else { |
| 65 | + 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()'); |
| 66 | + } |
| 67 | + |
| 68 | + return $fullPath ? $filepath : $filename; |
| 69 | + } |
| 70 | +} |
0 commit comments