Robohash.php in Avatar Kit 8
File
avatars_robohash/src/Robohash.php
View source
<?php
namespace Drupal\avatars_robohash;
use Drupal\avatars\Exception\AvatarException;
use Drupal\avatars\AvatarBase;
class Robohash extends AvatarBase implements RobohashInterface {
protected $background;
public function __construct() {
$this
->setDimensionConstraints(Robohash::DIMENSION_MINIMUM_WIDTH, Robohash::DIMENSION_MAXIMUM_WIDTH, Robohash::DIMENSION_MINIMUM_HEIGHT, Robohash::DIMENSION_MAXIMUM_HEIGHT);
}
public function getHostName() {
$hostname = parent::getHostName();
return isset($hostname) ? $hostname : $this::ROBOHASH_HOSTNAME;
}
public static function getBackgrounds() {
return [
'transparent' => 'Transparent',
'places' => 'Places',
'patterns' => 'Patterns',
];
}
public static function getBackgroundsMap() {
return [
'transparent' => '',
'places' => 'bg1',
'patterns' => 'bg2',
];
}
public function getBackground() {
return $this->background;
}
public function setBackground($background = NULL) {
if (!array_key_exists($background, $this
->getBackgrounds())) {
throw new AvatarException('Invalid background');
}
$this->background = $background;
return $this;
}
public static function getTypes() {
return [
'robot' => 'Robot',
'monster' => 'Monster',
'robot_head' => 'Robot Head',
];
}
public static function getTypesMap() {
return [
'robot' => 1,
'monster' => 2,
'robot_head' => 3,
];
}
public function setTypeRandom() {
$this->type = 'any';
return $this;
}
public function getUrl() {
$kv = [];
$url = ($this
->isSecure() ? 'https://' : 'http://') . $this
->getHostName() . '/';
$identifier = $this
->getIdentifier();
if (!strlen($identifier)) {
throw new AvatarException('Robohash missing identifier/hash');
}
$url .= $this
->identifierIsPreHashed() ? $identifier : $this
->hashIdentifier($identifier);
$background = $this
->getBackground();
$background_map = $this
->getBackgroundsMap();
if (!empty($background) && $background != key($background_map)) {
$kv['bgset'] = $background_map[$background];
}
$type_map = $this
->getTypesMap();
$type = $this
->getType();
if ($type == 'any') {
$kv['set'] = 'any';
}
elseif (!empty($type) && $type != key($type_map)) {
$kv['set'] = 'set' . $type_map[$type];
}
$width = $this->width;
$height = $this->height;
if (is_numeric($width) && is_numeric($height)) {
$kv['size'] = $width . 'x' . $height;
}
$query = http_build_query($kv);
return !empty($query) ? $url . '?' . $query : $url;
}
}