diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml
index 875db76..79fe0c0 100644
--- a/.github/workflows/php.yml
+++ b/.github/workflows/php.yml
@@ -82,6 +82,7 @@ jobs:
- "8.1"
- "8.2"
- "8.3"
+ - "8.4"
steps:
- name: Configure Git to avoid issues with line endings
diff --git a/.gitignore b/.gitignore
index 02345e7..d48b197 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,6 @@
/vendor
/src/index.php
/.idea
-composer.lock
\ No newline at end of file
+composer.lock
+.php-cs-fixer.cache
+.phpunit.result.cache
\ No newline at end of file
diff --git a/README.md b/README.md
index 8a1faed..e3f1964 100644
--- a/README.md
+++ b/README.md
@@ -21,6 +21,10 @@ install it to you project:
composer require renfordt/larvatar
```
+## Upgrading to 2.0
+
+Version 2.0 brings many breaking changes. Check the [Upgrade Guide](UPGRADING.md) to avoid any issues.
+
## Usage
The general usage is simple. Create a new Larvatar class, insert name and email and the avatar type you wish.
@@ -30,8 +34,17 @@ The general usage is simple. Create a new Larvatar class, insert name and email
use Renfordt\Larvatar\Enum\LarvatarTypes;
use Renfordt\Larvatar\Larvatar;
-$larvatar = new Larvatar('Test Name', 'test@test.com', LarvatarTypes::InitialsAvatar);
+// Larvatar::make($type, $name = '', $email = '')
+$larvatar = Larvatar::make(
+ type: LarvatarTypes::InitialsAvatar,
+ name: 'Test Name'
+ );
+
+// Optional settings
$larvatar->setFont('Roboto,sans-serif', './font/Roboto-bold.ttf');
+$larvatar->setSize(100);
+
+// Get the SVG Code for embedding directly in your page
echo $larvatar->getImageHTML();
// if you need base64 encryption, currently this works only for InitialsAvatar
@@ -40,17 +53,39 @@ echo $larvatar->getImageHTML('base64');
echo $larvatar->getBase64();
```
-There are currently eight different types of avatars available:
+Alternatively you can create an instance of the `Name` class, which provides you more possibilities.
```php
-\Renfordt\Larvatar\Enum\LarvatarTypes::InitialsAvatar; // Microsoft Teams like avatar with initials
-\Renfordt\Larvatar\Enum\LarvatarTypes::Gravatar; // Gravatar
-\Renfordt\Larvatar\Enum\LarvatarTypes::mp; // (Gravatar) MysticPerson, simple cartoon-style silhouette (default)
-\Renfordt\Larvatar\Enum\LarvatarTypes::identicon; // (Gravatar) A geometric pattern based on a email hash
-\Renfordt\Larvatar\Enum\LarvatarTypes::monsterid; // (Gravatar) A generated monster different colors and faces
-\Renfordt\Larvatar\Enum\LarvatarTypes::wavatar; // (Gravatar) generated faces with differing features and backgrounds
-\Renfordt\Larvatar\Enum\LarvatarTypes::retro; // (Gravatar) 8-bit arcade-style pixelated faces
-\Renfordt\Larvatar\Enum\LarvatarTypes::robohash; // (Gravatar) A generated robot with different colors, faces, etc
+$name = \Renfordt\Larvatar\Name::make('Test Name');
+
+$larvatar = Larvatar::make(
+ type: LarvatarTypes::InitialsAvatar,
+ name: $name
+ );
+```
+
+There are currently nine different types of avatars available:
+
+```php
+// 1) Microsoft Teams like avatar with initials
+\Renfordt\Larvatar\Enum\LarvatarTypes::InitialsAvatar;
+// 2) Identicons with more possibilities to adjust
+\Renfordt\Larvatar\Enum\LarvatarTypes::IdenticonLarvatar;
+
+// 3) Gravatar
+\Renfordt\Larvatar\Enum\LarvatarTypes::Gravatar;
+// 4) (Gravatar) MysticPerson, simple cartoon-style silhouette (default)
+\Renfordt\Larvatar\Enum\LarvatarTypes::mp;
+// 5) (Gravatar) A geometric pattern based on an email hash
+\Renfordt\Larvatar\Enum\LarvatarTypes::identicon;
+// 6) (Gravatar) A generated monster different colors and faces
+\Renfordt\Larvatar\Enum\LarvatarTypes::monsterid;
+// 7) (Gravatar) generated faces with differing features and backgrounds
+\Renfordt\Larvatar\Enum\LarvatarTypes::wavatar;
+// 8) (Gravatar) 8-bit arcade-style pixelated faces
+\Renfordt\Larvatar\Enum\LarvatarTypes::retro;
+// 9) (Gravatar) A generated robot with different colors, faces, etc
+\Renfordt\Larvatar\Enum\LarvatarTypes::robohash;
```
## InitialsAvatar
@@ -62,7 +97,10 @@ hexagon and a square. Choose it by using the `setForm()` method. The input is ei
Enum `FormTypes`.
```PHP
-$larvatar = new Larvatar('Your Name', type: LarvatarTypes::InitialsAvatar);
+$larvatar = Larvatar::make(
+ type: LarvatarTypes::InitialsAvatar,
+ name: 'Test Name'
+ );
$larvatar->initialsAvatar->setForm('circle');
$larvatar->initialsAvatar->setForm('square');
$larvatar->initialsAvatar->setForm('hexagon');
@@ -75,7 +113,10 @@ $larvatar->initialsAvatar->setForm(FormTypes::Hexagon);
If you are using the hexagon form, you have additionally the possibility to rotate the form:
```PHP
-$larvatar = new Larvatar('Your Name', type: LarvatarTypes::InitialsAvatar);
+$larvatar = Larvatar::make(
+ type: LarvatarTypes::InitialsAvatar,
+ name: 'Test Name'
+ );
$larvatar->initialsAvatar->setForm(FormTypes::Hexagon);
$larvatar->initialsAvatar->setRotation(30);
```
@@ -88,7 +129,10 @@ and `setTextLightness()`. The parameter is a float with a value range `0` to `1`
is a lighter color.
```PHP
-$larvatar = new Larvatar('Your Name', type: LarvatarTypes::InitialsAvatar);
+$larvatar = Larvatar::make(
+ type: LarvatarTypes::InitialsAvatar,
+ name: 'Test Name'
+ );
$larvatar->initialsAvatar->setBackgroundLightness(0.1);
$larvatar->initialsAvatar->setTextLightness(0.8);
```
@@ -96,7 +140,10 @@ $larvatar->initialsAvatar->setTextLightness(0.8);
Additionally, you can change the offset which will generate a different color.
```PHP
-$larvatar = new Larvatar('Your Name', type: LarvatarTypes::InitialsAvatar);
+$larvatar = Larvatar::make(
+ type: LarvatarTypes::InitialsAvatar,
+ name: 'Test Name'
+ );
$larvatar->initialsAvatar->setOffset(4);
```
@@ -105,6 +152,22 @@ $larvatar->initialsAvatar->setOffset(4);
You can also change the font weight with the method `setFontWeight()`.
```PHP
-$larvatar = new Larvatar('Your Name', type: LarvatarTypes::InitialsAvatar);
+$larvatar = Larvatar::make(
+ type: LarvatarTypes::InitialsAvatar,
+ name: 'Test Name'
+ );
$larvatar->initialsAvatar->setFontWeight('bold');
+```
+
+## Identicons (Larvatar Style)
+
+```PHP
+$larvatar = Larvatar::make(
+ type: LarvatarTypes::IdenticonLarvatar,
+ name: 'Test Name'
+ );
+
+// optional settings
+$larvatar->avatar->setSymmetry(false);
+$larvatar->avatar->setPixels(8);
```
\ No newline at end of file
diff --git a/UPGRADING.md b/UPGRADING.md
new file mode 100644
index 0000000..3a4e4dc
--- /dev/null
+++ b/UPGRADING.md
@@ -0,0 +1,13 @@
+New:
+```php
+$larvatar = Larvatar::make(
+ type: LarvatarTypes::InitialsAvatar,
+ name: 'Test Name'
+ );
+```
+
+
+Old:
+```php
+$larvatar = new Larvatar('Test Name', 'test@test.com', LarvatarTypes::InitialsAvatar);
+```
\ No newline at end of file
diff --git a/avatars.png b/avatars.png
index 0ff54dc..1f4e0e2 100644
Binary files a/avatars.png and b/avatars.png differ
diff --git a/composer.json b/composer.json
index 5d5491d..a8531b8 100644
--- a/composer.json
+++ b/composer.json
@@ -22,17 +22,20 @@
"Renfordt\\Larvatar\\": "src/"
}
},
- "minimum-stability": "dev",
+ "minimum-stability": "stable",
"prefer-stable": true,
"require": {
"php": "^8.1",
"ext-gd": "*",
"meyfa/php-svg": "^0.14.0",
- "renfordt/clamp": "^1.0"
+ "renfordt/clamp": "^1.0",
+ "renfordt/colors": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "^10.5",
- "orchestra/testbench": "^v8.22"
+ "orchestra/testbench": "^v8.22",
+ "friendsofphp/php-cs-fixer": "^3.64",
+ "phpstan/phpstan": "^2.0"
},
"extra": {
"laravel": {
diff --git a/docker-compose.yml b/docker-compose.yml
index b036ab9..8d065b1 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,4 +1,3 @@
-version: "3.7"
services:
php:
build:
diff --git a/src/Avatar.php b/src/Avatar.php
new file mode 100644
index 0000000..5b23735
--- /dev/null
+++ b/src/Avatar.php
@@ -0,0 +1,222 @@
+fontSize;
+ }
+
+ /**
+ * Set the font size.
+ *
+ * @param int $fontSize The font size.
+ * @return void
+ */
+ public function setFontSize(int $fontSize): void
+ {
+ $this->fontSize = $fontSize;
+ }
+
+ /**
+ * Get the font family
+ *
+ * @return string The font family
+ */
+ public function getFontFamily(): string
+ {
+ return $this->fontFamily;
+ }
+
+ /**
+ * Set the font family for the application
+ *
+ * @param string $fontFamily The font family to set
+ * @return void
+ */
+ public function setFontFamily(string $fontFamily): void
+ {
+ $this->fontFamily = $fontFamily;
+ }
+
+ /**
+ * Get the font path
+ *
+ * @return string The font path
+ */
+ public function getFontPath(): string
+ {
+ return $this->fontPath;
+ }
+
+ /**
+ * Set the font path
+ *
+ * @param string $fontPath The path to the font
+ * @return void
+ */
+ public function setFontPath(string $fontPath): void
+ {
+ $this->fontPath = $fontPath;
+ }
+
+ /**
+ * Get the name of the object
+ *
+ * @return Name The name of the object
+ */
+ public function getName(): Name
+ {
+ return $this->name;
+ }
+
+ /**
+ * Set the Name object for the given instance
+ *
+ * @param Name|string $name The Name object or a string of the name
+ *
+ * @return void
+ */
+ public function setName(Name|string $name): void
+ {
+ if (is_string($name)) {
+ $name = Name::make($name);
+ }
+ $this->name = $name;
+ }
+
+ /**
+ * Get the background lightness value
+ *
+ * @return float The background lightness value
+ */
+ public function getBackgroundLightness(): float
+ {
+ return $this->backgroundLightness;
+ }
+
+ /**
+ * Set the background lightness
+ *
+ * @param float $backgroundLightness The background lightness value to set (between 0 and 1)
+ * @return void
+ */
+ public function setBackgroundLightness(float $backgroundLightness): void
+ {
+ $this->backgroundLightness = clamp($backgroundLightness, 0, 1);
+ }
+
+ /**
+ * Get the lightness value of the text
+ *
+ * @return float The lightness value of the text
+ */
+ public function getTextLightness(): float
+ {
+ return $this->textLightness;
+ }
+
+ /**
+ * Set the text lightness value
+ *
+ * @param float $textLightness The text lightness value to be set
+ * @return void
+ */
+ public function setTextLightness(float $textLightness): void
+ {
+ $this->textLightness = clamp($textLightness, 0, 1);
+ }
+
+ /**
+ * Get the font weight
+ *
+ * @return string The font weight
+ */
+ public function getFontWeight(): string
+ {
+ return $this->fontWeight;
+ }
+
+ /**
+ * Set the font weight for the application
+ *
+ * @param string $fontWeight The font weight to set
+ * @return void
+ */
+ public function setFontWeight(string $fontWeight): void
+ {
+ $this->fontWeight = $fontWeight;
+ }
+
+ /**
+ * Get the size of the object
+ *
+ * @return int The size of the object
+ */
+ public function getSize(): int
+ {
+ return $this->size;
+ }
+
+ /**
+ * Set the size of the object
+ *
+ * @param int $size The size to set for the object
+ * @return void
+ */
+ public function setSize(int $size): void
+ {
+ $this->size = $size;
+ }
+
+ /**
+ * Sets the font family and path
+ *
+ * @param string $font The font family
+ * @param string $path The font path
+ *
+ * @return void
+ */
+ public function setFont(string $font, string $path): void
+ {
+ $this->setFontFamily($font);
+ $this->setFontPath($path);
+ }
+
+
+}
diff --git a/src/Color.php b/src/Color.php
deleted file mode 100644
index 0055e71..0000000
--- a/src/Color.php
+++ /dev/null
@@ -1,397 +0,0 @@
-setHex($color);
- break;
- case ColorType::RGB:
- $this->setRGB($color);
- break;
- case ColorType::HSL:
- $this->setHSL($color);
- }
- }
-
- /**
- * Converts a hexadecimal color code to RGB color
- * @param string $hexStr Hexadecimal color code, with or without '#'
- * @return array|int[] Array of red, green, and blue values [0..255]
- * @throws InvalidArgumentException if the provided hex code is invalid
- */
- public static function HexToRGB(string $hexStr): array
- {
- $hexStr = str_replace('#', '', $hexStr);
- $length = strlen($hexStr);
-
- if (!in_array($length, [3, 6]) || preg_match("/^[0-9a-fA-F]+$/", $hexStr) !== 1) {
- throw new InvalidArgumentException('Invalid Hex format.');
- }
-
- $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr);
- if ($length === 6) {
- $colorVal = hexdec($hexStr);
-
- return array(
- 0xFF & ($colorVal >> 0x10),
- 0xFF & ($colorVal >> 0x8),
- 0xFF & $colorVal
- );
- }
-
- return array(
- hexdec(str_repeat(substr($hexStr, 0, 1), 2)),
- hexdec(str_repeat(substr($hexStr, 1, 1), 2)),
- hexdec(str_repeat(substr($hexStr, 2, 1), 2))
- );
- }
-
- /**
- * Convert RGB color to HSL color space.
- *
- * @param int $red The red component of the RGB color (0-255).
- * @param int $green The green component of the RGB color (0-255).
- * @param int $blue The blue component of the RGB color (0-255).
- * @return array An array containing the HSL color values (hue, saturation, lightness).
- */
- public static function RGBToHSL(int $red, int $green, int $blue): array
- {
- list($maxRGB, $minRGB, $chroma, $value, $hue) = self::calculateCVH($red, $green, $blue);
-
- if ($chroma == 0) {
- return array(0, 0, $value);
- }
-
- $lightness = ($maxRGB + $minRGB) / 2;
- $saturation = $chroma / (1 - abs(2 * $value - $chroma - 1));
-
-
- return array(round($hue), round($saturation, 2), round($lightness, 2));
- }
-
- /**
- * Calculate the components Chroma, Value, and Hue based on RGB color.
- *
- * @param int $red The red component of the RGB color (0-255).
- * @param int $green The green component of the RGB color (0-255).
- * @param int $blue The blue component of the RGB color (0-255).
- * @return array An array containing the calculated values (maxRGB, minRGB, chroma, value, hue).
- */
- public static function calculateCVH(int $red, int $green, int $blue): array
- {
- $normalizedRed = $red / 255;
- $normalizedGreen = $green / 255;
- $normalizedBlue = $blue / 255;
-
- $maxRGB = max($normalizedRed, $normalizedGreen, $normalizedBlue);
- $minRGB = min($normalizedRed, $normalizedGreen, $normalizedBlue);
- $chroma = $maxRGB - $minRGB;
- $value = $maxRGB; // also called brightness
- if ($chroma == 0) {
- $hue = 0;
- } elseif ($maxRGB == $normalizedRed) {
- $hue = 60 * (($normalizedGreen - $normalizedBlue) / $chroma);
- } elseif ($maxRGB == $normalizedGreen) {
- $hue = 60 * (2 + ($normalizedBlue - $normalizedRed) / $chroma);
- } else {
- $hue = 60 * (4 + ($normalizedRed - $normalizedGreen) / $chroma);
- }
-
- if ($hue < 0) {
- $hue += 360;
- }
- return array($maxRGB, $minRGB, $chroma, $value, $hue);
- }
-
- /**
- * Convert RGB color to HSV color space.
- *
- * @param int $red The red component of the RGB color (0-255).
- * @param int $green The green component of the RGB color (0-255).
- * @param int $blue The blue component of the RGB color (0-255).
- * @return array An array containing the HSV color values (hue, saturation, value).
- */
- public static function RGBToHSV(int $red, int $green, int $blue): array
- {
- list($maxRGB, $minRGB, $chroma, $value, $hue) = self::calculateCVH($red, $green, $blue);
-
- if ($chroma == 0) {
- return array(0, 0, $value);
- }
-
- $saturation = $chroma / $maxRGB * 100;
-
-
- return array($hue, $saturation, $value);
- }
-
- /**
- * Convert HSV color to RGB color space.
- *
- * @param int $hue The hue component of the HSV color (0-360).
- * @param float $saturation The saturation component of the HSV color (0-1).
- * @param float $value The value component of the HSV color (0-1).
- * @return array An array containing the RGB color values (red, green, blue).
- * @throws InvalidArgumentException if any of the parameters exceed their intended ranges.
- * @throws Exception if RGB calculation is not possible.
- */
- public static function HSVToRGB(int $hue, float $saturation, float $value): array
- {
- self::validateParameters($hue, $saturation, $value);
-
- $chroma = $value * $saturation;
- $hueNormalized = $hue / 60;
- $hMod2 = $hueNormalized - 2 * floor($hueNormalized / 2);
- $secondMax = $chroma * (1 - abs($hMod2 - 1));
-
- list($red, $green, $blue) = self::calculateRGBRange($hueNormalized, $chroma, $secondMax);
-
- return self::finalizeRGBCalculation($red, $green, $blue, $value, $chroma);
- }
-
- private static function validateParameters(int $hue, float $saturation, float $value): void
- {
- if ($hue < 0 || $hue > 360 ||
- $saturation < 0 || $saturation > 1 ||
- $value < 0 || $value > 1) {
- throw new InvalidArgumentException('Parameters exceed their intended ranges.');
- }
- }
-
- /**
- * Calculate the RGB range based on the normalized hue value.
- *
- * @param float $hueNormalized The normalized hue value (0-6).
- * @param float $chroma The chroma value (0 - 360).
- * @param float $secondMax The second maximum value.
- * @return array An array containing the RGB color values.
- */
- private static function calculateRGBRange(float $hueNormalized, float $chroma, float $secondMax): array
- {
- if (0 <= $hueNormalized && $hueNormalized < 1) {
- return [$chroma, $secondMax, 0];
- } elseif (1 <= $hueNormalized && $hueNormalized < 2) {
- return [$secondMax, $chroma, 0];
- } elseif (2 <= $hueNormalized && $hueNormalized < 3) {
- return [0, $chroma, $secondMax];
- } elseif (3 <= $hueNormalized && $hueNormalized < 4) {
- return [0, $secondMax, $chroma];
- } elseif (4 <= $hueNormalized && $hueNormalized < 5) {
- return [$secondMax, 0, $chroma];
- } elseif (5 <= $hueNormalized && $hueNormalized < 6) {
- return [$chroma, 0, $secondMax];
- } else {
- return [];
- }
- }
-
- /**
- * Finalize the RGB color calculation based on the given parameters.
- *
- * @param float $red The red component of the RGB color (0-255).
- * @param float $green The green component of the RGB color (0-255).
- * @param float $blue The blue component of the RGB color (0-255).
- * @param float $value The value component of the RGB color (0-1).
- * @param float $chroma The chroma component of the RGB color (0-1).
- * @param bool $isLightness Flag indicating if the calculation is for lightness.
- * @return array An array containing the finalized RGB color values (red, green, blue).
- */
- private static function finalizeRGBCalculation(
- float $red,
- float $green,
- float $blue,
- float $value,
- float $chroma,
- bool $isLightness = false
- ): array {
- $m = $isLightness ? $value - $chroma / 2 : $value - $chroma;
-
- return array_map(fn($color) => intval(round(($color + $m) * 255)), [$red, $green, $blue]);
- }
-
- /**
- * Convert RGB color to hexadecimal color representation.
- *
- * @param int $red The red component of the RGB color (0-255).
- * @param int $green The green component of the RGB color (0-255).
- * @param int $blue The blue component of the RGB color (0-255).
- * @return string The hexadecimal representation of the RGB color.
- */
- public static function RGBToHex(int $red, int $green, int $blue): string
- {
- $hexr = str_pad(dechex($red), 2, "0", STR_PAD_LEFT);
- $hexg = str_pad(dechex($green), 2, "0", STR_PAD_LEFT);
- $hexb = str_pad(dechex($blue), 2, "0", STR_PAD_LEFT);
- return $hexr.$hexg.$hexb;
- }
-
- /**
- * Convert HSL color to RGB color space.
- *
- * @param int $hue The hue component of the HSL color (0-359).
- * @param float $saturation The saturation component of the HSL color (0-1).
- * @param float $lightness The lightness component of the HSL color (0-1).
- * @return array An array containing the RGB color values (red, green, blue).
- * @throws Exception If RGB calculation is not possible.
- */
- private static function HSLToRGB(int $hue, float $saturation, float $lightness): array
- {
- $chroma = (1 - abs(2 * $lightness - 1)) * $saturation;
- $hueNormalized = $hue / 60;
- $hMod2 = $hueNormalized - 2 * floor($hueNormalized / 2);
- $intermediateValue = $chroma * (1 - abs($hMod2 - 1));
-
- list($red, $green, $blue) = self::calculateRGBRange($hueNormalized, $chroma, $intermediateValue);
-
- if (!isset($red) || !isset($green) || !isset($blue)) {
- throw new Exception('RGB calculation not possible. Check inputs!');
- }
-
- return self::finalizeRGBCalculation($red, $green, $blue, $lightness, $chroma, true);
- }
-
- /**
- * Get the HSL color values of the current object.
- *
- * @return array An array containing the HSL color values (hue, saturation, lightness).
- */
- public function getHSL(): array
- {
- return $this->hsl;
- }
-
- /**
- * Set the HSL color values and update the RGB and hex color values.
- *
- * @param array $color An array containing the HSL color values (hue, saturation, lightness).
- * @return void
- */
- public function setHSL(array $color): void
- {
- $this->hsl = $color;
- $this->rgb = $this->HSLToRGB($color[0], $color[1], $color[2]);
- $this->hex = $this->RGBToHex($this->rgb[0], $this->rgb[1], $this->rgb[2]);
- }
-
- /**
- * Get the RGB color values.
- *
- * @return array An array containing the RGB color values (red, green, blue).
- */
- public function getRGB(): array
- {
- return $this->rgb;
- }
-
- /**
- * Set the RGB color.
- *
- * @param array $color An array containing the RGB color values (red, green, blue).
- * @return void
- */
- public function setRGB(array $color): void
- {
- $this->rgb = $color;
- $this->hex = Color::RGBToHex($color[0], $color[1], $color[2]);
- $this->hsl = Color::RGBToHSL($color[0], $color[1], $color[2]);
- }
-
- /**
- * Get the hexadecimal representation of the color.
- *
- * @return string The hexadecimal string representation of the color.
- */
- public function getHex(): string
- {
- return '#'.$this->hex;
- }
-
- /**
- * Set the hexadecimal color value.
- *
- * @param string $color The hexadecimal color value.
- * @return void
- */
- public function setHex(string $color): void
- {
- if (!preg_match("/#[0-9a-fA-F]{3}/", $color) &&
- !preg_match("/#[0-9a-fA-F]{6}/", $color)) {
- return;
- }
- $color = substr($color, 1);
- $this->hex = $color;
-
- $this->rgb = Color::HexToRGB($this->hex);
- $this->hsl = Color::RGBToHSL($this->rgb[0], $this->rgb[1], $this->rgb[2]);
- }
-
- /**
- * Get a color set based on the HSL color.
- *
- * @param float $darkLightness The lightness value for the dark color (0.0-1.0).
- * @param float $lightLightness The lightness value for the light color (0.0-1.0).
- * @return array An array containing the dark and light color.
- */
- public function getColorSet(float $darkLightness = 0.35, float $lightLightness = 0.8): array
- {
- list($hue, $saturation, $lightness) = $this->hsl;
-
- $dark = new Color(ColorType::HSL, [$hue, $saturation, $darkLightness]);
- $light = new Color(ColorType::HSL, [$hue, $saturation, $lightLightness]);
- return array($dark, $light);
- }
-
- /**
- * Brighten the color by a specified amount.
- *
- * @param int $amount The amount to brighten the color by as a percentage (default: 10).
- * @return void
- */
- public function brighten(int $amount = 10): void
- {
- list($hue, $saturation, $lightness) = $this->hsl;
- $lightness = clamp($lightness + $amount / 100, 0, 1);
- $this->setHSL(array($hue, $saturation, $lightness));
- }
-
- /**
- * Clamp a number between a minimum and maximum value.
- *
- * @param int|float $num The number to clamp.
- * @param int|float $min The minimum value.
- * @param int|float $max The maximum value.
- * @return int|float The clamped number.
- * @deprecated v1.4.0
- */
- private static function clamp(int|float $num, int|float $min, int|float $max): int|float
- {
- return clamp($num, $min, $max);
- }
-
- /**
- * Darken the color by reducing its lightness value.
- *
- * @param int $amount The amount by which to darken the color (0-100).
- * @return void
- */
- public function darken(int $amount = 10): void
- {
- list($hue, $saturation, $lightness) = $this->hsl;
- $lightness = clamp($lightness - $amount / 100, 0, 1);
- $this->setHSL(array($hue, $saturation, $lightness));
- }
-}
diff --git a/src/Enum/LarvatarTypes.php b/src/Enum/LarvatarTypes.php
index f7d3581..a8a1765 100644
--- a/src/Enum/LarvatarTypes.php
+++ b/src/Enum/LarvatarTypes.php
@@ -12,4 +12,5 @@ enum LarvatarTypes: int
case wavatar = 5;
case retro = 6;
case robohash = 7;
-}
\ No newline at end of file
+ case IdenticonLarvatar = 8;
+}
diff --git a/src/Gravatar.php b/src/Gravatar.php
index 4e5dc44..8fc8446 100644
--- a/src/Gravatar.php
+++ b/src/Gravatar.php
@@ -1,97 +1,102 @@
-setEmail($email);
- }
-
- /**
- * Sets the type for the avatar.
- * @param LarvatarTypes $type All enums except LarvatarTypes::InitialsAvatar are allowed
- * @return void
- */
- public function setType(LarvatarTypes $type): void
- {
- if ($type == LarvatarTypes::InitialsAvatar) {
- return;
- }
- $this->type = $type;
- }
-
- /**
- * Sets the email for Gravatar. It is used to gernerate a hash which is passed to the Gravatar API
- * @param string $email
- * @return void
- */
- public function setEmail(string $email): void
- {
- $this->email = $email;
- $this->setHash($email);
- }
-
- /**
- * Sets the size of the Gravatar
- * @param int $size Size in px for the Gravatar
- * @return void
- */
- public function setSize(int $size): void
- {
- $this->size = $size;
- }
-
- /**
- * Generates the hash value for the email address
- * @param $email
- * @return void
- */
- protected function setHash($email): void
- {
- $this->hash = md5(strtolower(trim($email)));
- }
-
- /**
- * Depending on the selected type the missing parameters for Gravatar API will be selected
- * @return string
- * @throws Exception
- */
- protected function getAdditionalParameters(): string
- {
- $link = match($this->type) {
- LarvatarTypes::Gravatar => '?d=',
- LarvatarTypes::mp => '?d=mp&f=y',
- LarvatarTypes::identicon => '?d=identicon&f=y',
- LarvatarTypes::monsterid => '?d=monsterid&f=y',
- LarvatarTypes::wavatar => '?d=wavatar&f=y',
- LarvatarTypes::retro => '?d=retro&f=y',
- LarvatarTypes::robohash => '?d=robohash&f=y',
- LarvatarTypes::InitialsAvatar => throw new Exception('Initials Avatar is not supported for Gravatars.')
- };
- return $link.'&s='.$this->size;
- }
-
- /**
- * Generate the link to the Gravatar
- * @return string
- */
- public function generateGravatarLink(): string
- {
- return 'https://www.gravatar.com/avatar/'.$this->hash.$this->getAdditionalParameters();
- }
-}
+setEmail($email);
+ }
+
+ /**
+ * Sets the email for Gravatar. It is used to gernerate a hash which is passed to the Gravatar API
+ * @param string $email
+ * @return void
+ */
+ public function setEmail(string $email): void
+ {
+ $this->email = $email;
+ $this->setHash($email);
+ }
+
+ /**
+ * Generates the hash value for the email address
+ * @param $email
+ * @return void
+ */
+ protected function setHash(string $email): void
+ {
+ $this->hash = md5(strtolower(trim($email)));
+ }
+
+ /**
+ * Sets the type for the avatar.
+ * @param LarvatarTypes $type All enums except LarvatarTypes::InitialsAvatar are allowed
+ * @return void
+ */
+ public function setType(LarvatarTypes $type): void
+ {
+ if ($type == LarvatarTypes::InitialsAvatar) {
+ return;
+ }
+ $this->type = $type;
+ }
+
+ /**
+ * Sets the size of the Gravatar
+ * @param int $size Size in px for the Gravatar
+ * @return void
+ */
+ public function setSize(int $size): void
+ {
+ $this->size = $size;
+ }
+
+ public function getHTML(): string
+ {
+ return '';
+ }
+
+ /**
+ * Generate the link to the Gravatar
+ * @return string
+ */
+ public function generateGravatarLink(): string
+ {
+ return 'https://www.gravatar.com/avatar/'.$this->hash.$this->getAdditionalParameters();
+ }
+
+ /**
+ * Depending on the selected type the missing parameters for Gravatar API will be selected
+ * @return string
+ * @throws Exception
+ */
+ protected function getAdditionalParameters(): string
+ {
+ $link = match ($this->type) {
+ LarvatarTypes::Gravatar => '?d=',
+ LarvatarTypes::mp => '?d=mp&f=y',
+ LarvatarTypes::identicon => '?d=identicon&f=y',
+ LarvatarTypes::monsterid => '?d=monsterid&f=y',
+ LarvatarTypes::wavatar => '?d=wavatar&f=y',
+ LarvatarTypes::retro => '?d=retro&f=y',
+ LarvatarTypes::robohash => '?d=robohash&f=y',
+ LarvatarTypes::InitialsAvatar => throw new Exception('Initials Avatar is not supported for Gravatars.'),
+ LarvatarTypes::IdenticonLarvatar => throw new \Exception('Larvatars Identicons are not supported for Gravatars.')
+ };
+ return $link.'&s='.$this->size;
+ }
+}
diff --git a/src/Identicon.php b/src/Identicon.php
new file mode 100644
index 0000000..c3702ff
--- /dev/null
+++ b/src/Identicon.php
@@ -0,0 +1,190 @@
+name = $name;
+ }
+
+ public static function make(Name $name): Identicon
+ {
+ return new self($name);
+ }
+
+ /**
+ * Sets the number of pixels.
+ *
+ * @param int $pixels The number of pixels to set.
+ * @return void
+ */
+ public function setPixels(int $pixels): void
+ {
+ $this->pixels = $pixels;
+ }
+
+ /**
+ * Sets the symmetry property of the object.
+ *
+ * @param bool $symmetry The symmetry value to set.
+ * @return void
+ */
+ public function setSymmetry(bool $symmetry): void
+ {
+ $this->symmetry = $symmetry;
+ }
+
+ /**
+ * Returns the HTML representation of the image.
+ *
+ * @param bool $base64 Determines whether the HTML representation should be in base64 format or not.
+ * @return string The HTML representation of the image.
+ */
+ public function getHTML(bool $base64 = false): string
+ {
+ if (!$base64) {
+ return $this->getSVG();
+ }
+
+ return '';
+ }
+
+ /**
+ * Returns the SVG representation of the Identicon .
+ *
+ * @return string The SVG representation of the Identicon.
+ */
+ public function getSVG(): string
+ {
+ $larvatar = new SVG($this->size, $this->size);
+ $doc = $larvatar->getDocument();
+
+ $color = $this->getHSLColor($this->name);
+
+ if ($this->symmetry) {
+ $matrix = $this->generateSymmetricMatrix();
+ } else {
+ $matrix = $this->generateMatrix();
+ }
+
+ foreach ($matrix as $y => $array) {
+ foreach ($array as $x => $value) {
+ if ($value) {
+ $square = new SVGRect(
+ (int)$x * ($this->size / $this->pixels),
+ (int)$y * ($this->size / $this->pixels),
+ (int)$this->size / $this->pixels,
+ (int)$this->size / $this->pixels
+ );
+ $square->setStyle('fill', $color->toHex());
+ $doc->addChild($square);
+ }
+ }
+ }
+
+ return $larvatar;
+ }
+
+ /**
+ * Generate a symmetric identicon matrix based on the provided hash
+ *
+ * @return array The generated symmetric matrix
+ */
+ public function generateSymmetricMatrix(): array
+ {
+ preg_match_all('/(\w)(\w)/', $this->name->getHash(), $chars);
+ $symmetryMatrix = $this->getSymmetryMatrix();
+ $divider = count($symmetryMatrix);
+
+ $matrix = [];
+
+ for ($i = 0; $i < pow($this->pixels, 2); $i++) {
+ $index = (int)($i / 3);
+ $data = $this->convertStrToBool(substr($this->name->getHash(), $i, 1));
+
+ foreach ($symmetryMatrix[$i % $divider] as $item) {
+ $matrix[$index][$item] = $data;
+ }
+ }
+
+ return $matrix;
+ }
+
+ /**
+ * Returns the symmetry matrix.
+ *
+ * @return array The symmetry matrix.
+ */
+ private function getSymmetryMatrix(): array
+ {
+ $items = [];
+ $i = $this->pixels - 1;
+ for ($x = 0; $x <= $i / 2; $x++) {
+ $items[$x] = [$x];
+ if ($x !== $i - $x) {
+ $items[$x][] = $i - $x;
+ }
+ }
+ return $items;
+ }
+
+ /**
+ * Converts a hexadecimal character to a boolean value.
+ *
+ * @param string $char The hexadecimal character to convert.
+ * @return bool The boolean value converted from the hexadecimal character.
+ */
+ private function convertStrToBool(string $char): bool
+ {
+ return (bool)round(hexdec($char) / 10);
+ }
+
+ /**
+ * Generates a matrix based on the given offset value.
+ *
+ * @param int $offset The offset value for generating the matrix. Defaults to 0.
+ * @return array The generated matrix.
+ */
+ private function generateMatrix(int $offset = 0): array
+ {
+ $column = 0;
+ $row = 0;
+ $hash = hash('sha256', $this->name->getHash());
+ $matrix = [];
+ for ($i = 0; $i < pow($this->pixels, 2); $i++) {
+ $matrix[$i % $this->pixels][floor($i / $this->pixels)] =
+ $this->convertStrToBool(substr($hash, $i, 1));
+ if ($column == $this->pixels && $row < $this->pixels) {
+ $row++;
+ $column = -1;
+ }
+ if ($column < $this->pixels) {
+ $column++;
+ }
+ }
+
+ return $matrix;
+ }
+
+ /**
+ * Returns the base64 representation of the SVG image.
+ *
+ * @return string The base64 encoded string representing the SVG image.
+ */
+ public function getBase64(): string
+ {
+ return 'data:image/svg+xml;base64,' . base64_encode($this->getSVG());
+ }
+}
diff --git a/src/InitialsAvatar.php b/src/InitialsAvatar.php
index df53c3b..fc13e15 100644
--- a/src/InitialsAvatar.php
+++ b/src/InitialsAvatar.php
@@ -2,65 +2,131 @@
namespace Renfordt\Larvatar;
-use Renfordt\Larvatar\Enum\ColorType;
+use Renfordt\Colors\HSLColor;
use Renfordt\Larvatar\Enum\FormTypes;
+use Renfordt\Larvatar\Traits\ColorTrait;
use SVG\Nodes\Shapes\SVGCircle;
use SVG\Nodes\Shapes\SVGPolygon;
use SVG\Nodes\Shapes\SVGRect;
use SVG\Nodes\Texts\SVGText;
use SVG\SVG;
-class InitialsAvatar
+use function PHPUnit\Framework\isEmpty;
+
+class InitialsAvatar extends Avatar
{
- private string $fontPath = '';
- private string $fontFamily = '';
- private array $names = [];
- private int $size = 128;
- private int $fontSize = 0;
+ use ColorTrait;
+
private FormTypes $form = FormTypes::Circle;
- private int $rotation;
- private string $fontWeight = 'normal';
- private float $backgroundLightness = 0.8;
- private float $textLightness = 0.35;
+ private int $rotation = 0;
private int $offset = 0;
/**
- * Create an instance of InitialsAvatar
- * @param string $name First and last name or username, seperated by a space
+ * Constructs a new instance of the class.
+ *
+ * @param Name $name The name object to set
+ *
+ * @return void
*/
- public function __construct(string $name = '')
+ public function __construct(Name $name)
{
$this->setName($name);
}
+
+ public static function make(Name|string $name): InitialsAvatar
+ {
+ if (is_string($name)) {
+ $name = Name::make($name);
+ }
+
+ return new self($name);
+ }
+
/**
- * Sets the names for the avatar
- * @param string $name Names seperated by a space for generating the avatar
+ * Sets the form of the application
+ *
+ * @param string|FormTypes $form The form type
* @return void
*/
- public function setName(string $name): void
+ public function setForm(string|FormTypes $form): void
{
- $this->names = explode(' ', $name);
+ if (is_string($form)) {
+ $form = FormTypes::from($form);
+ }
+
+ $this->form = $form;
}
/**
- * Generates an avatar based on the given names and encoding
+ * Sets the rotation angle of the element
*
- * @param array $names An array of names to generate initials from
- * @param string|null $encoding The encoding type for the output ('base64' or null)
+ * @param int $angle The rotation angle value
*
- * @return string The generated avatar in SVG format or the base64-encoded avatar image
+ * @return void
*/
- public function generate(array $names = [], string|null $encoding = null): string
+ public function setRotation(int $angle): void
+ {
+ $this->rotation = $angle;
+ }
+
+ /**
+ * Retrieves the offset of the object
+ *
+ * @return int The offset value
+ */
+ public function getOffset(): int
+ {
+ return $this->offset;
+ }
+
+ /**
+ * Sets the offset for the avatar
+ *
+ * @param int $offset The offset in pixel
+ * @return void
+ */
+ public function setOffset(int $offset): void
+ {
+ $this->offset = $offset;
+ }
+
+ /**
+ * Returns the HTML representation of the code.
+ *
+ * @param bool $base64 Determines if the image source should be in base64 format. Default is false.
+ * @return string The HTML representation of the code.
+ */
+ public function getHTML(bool $base64 = false): string
+ {
+ if (!$base64) {
+ return $this->generate();
+ }
+
+ return '';
+ }
+
+ /**
+ * Generates an SVG representation with initials and shape based on the provided configurations.
+ *
+ * @return string The generated SVG content as a string.
+ */
+ public function generate(): string
{
- $names = $this->getNames($names);
$larvatar = new SVG($this->size, $this->size);
$doc = $larvatar->getDocument();
$this->addFontIfNotEmpty();
- $color = $this->getColor($names);
- list($darkColor, $lightColor) = $color->getColorSet($this->textLightness, $this->backgroundLightness);
+ /**
+ * @var HSLColor $darkColor
+ * @var HSLColor $lightColor
+ */
+ list($darkColor, $lightColor) = $this->getColorSet(
+ $this->name,
+ $this->textLightness,
+ $this->backgroundLightness
+ );
if ($this->form == FormTypes::Circle) {
$halfSize = $this->size / 2;
@@ -71,31 +137,16 @@ public function generate(array $names = [], string|null $encoding = null): strin
$outlineForm = $this->getHexagon($this->size, $lightColor, $this->rotation);
}
+ $initials = $this->getInitials($darkColor);
- $initials = $this->getInitials($names, $darkColor);
-
- $doc->addChild($outlineForm);
+ if (isset($outlineForm)) {
+ $doc->addChild($outlineForm);
+ }
$doc->addChild($initials);
- if ($encoding == 'base64') {
- return 'data:image/svg+xml;base64,'.base64_encode($larvatar);
- }
return $larvatar;
}
- /**
- * Retrieves the names array
- * If the provided $names array is empty,
- * it returns the default names array
- *
- * @param array $names The names array
- * @return array The names array to be returned
- */
- private function getNames(array $names): array
- {
- return empty($names) ? $this->names : $names;
- }
-
/**
* Adds a font if the font path and font family are not empty
* @return void
@@ -107,44 +158,17 @@ private function addFontIfNotEmpty(): void
}
}
- /**
- * Retrieves the color based on the given array of names
- *
- * @param array $names An array of names
- * @return Color The color object with the generated hex color
- */
- private function getColor(array $names): Color
- {
- return new Color(ColorType::Hex, $this->generateHexColor($names, $this->offset));
- }
-
- /**
- * Generates a hex color code based on the names
- * @param array|null $names Array of names used to generate the hex color code.
- * @param int $offset Offset of the hash, similar to a seed
- * @return string Returns a color hash code, e.g. '#123456'
- */
- public function generateHexColor(array $names = null, int $offset = 0): string
- {
- if ($names == null) {
- $names = $this->names;
- }
- $name = implode(' ', $names);
- $hash = md5($name);
- return '#'.substr($hash, $offset, 6);
- }
-
/**
* Get a circle SVG element
*
* @param float $halfSize Half of the size of the circle
- * @param Color $lightColor The light color to fill the circle with
+ * @param HSLColor $lightColor The light color to fill the circle with
* @return SVGCircle The circle SVG element
*/
- private function getCircle(float $halfSize, Color $lightColor): SVGCircle
+ private function getCircle(float $halfSize, HSLColor $lightColor): SVGCircle
{
$circle = new SVGCircle($halfSize, $halfSize, $halfSize);
- $circle->setStyle('fill', $lightColor->getHex());
+ $circle->setStyle('fill', $lightColor->toHex());
return $circle;
}
@@ -153,14 +177,14 @@ private function getCircle(float $halfSize, Color $lightColor): SVGCircle
* Get a square SVGRect
*
* @param float $size Half of the square size
- * @param Color $lightColor The color of the square
+ * @param HSLColor $lightColor The color of the square
*
* @return SVGRect The generated square SVGRect object
*/
- private function getSquare(float $size, Color $lightColor): SVGRect
+ private function getSquare(float $size, HSLColor $lightColor): SVGRect
{
$square = new SVGRect(0, 0, $size, $size);
- $square->setStyle('fill', $lightColor->getHex());
+ $square->setStyle('fill', $lightColor->toHex());
return $square;
}
@@ -168,10 +192,11 @@ private function getSquare(float $size, Color $lightColor): SVGRect
* Get a polygon shape
*
* @param float $size The size of the polygon
- * @param Color $lightColor The light color to fill the polygon
+ * @param HSLColor $lightColor The light color to fill the polygon
+ * @param int $rotation
* @return SVGPolygon The polygon shape with the specified size and color
*/
- private function getHexagon(float $size, Color $lightColor, int $rotation = 0): SVGPolygon
+ private function getHexagon(float $size, HSLColor $lightColor, int $rotation = 0): SVGPolygon
{
$rotation = pi() / 180 * $rotation;
@@ -182,29 +207,28 @@ private function getHexagon(float $size, Color $lightColor, int $rotation = 0):
}
$polygon = new SVGPolygon($edgePoints);
- $polygon->setStyle('fill', $lightColor->getHex());
+ $polygon->setStyle('fill', $lightColor->toHex());
return $polygon;
}
/**
- * Generates initials for the given names and returns SVGText object
- * @param array $names List of names
- * @param Color $darkColor Dark color object
- * @return SVGText SVGText object containing the initials
+ * Generates an SVG text element with the initials and formats it with the given dark color and font settings.
+ *
+ * @param HSLColor $darkColor The dark color used to fill the text, provided in HSL format and converted to hex.
+ * @return SVGText The SVG text element containing the formatted initials.
*/
- private function getInitials(array $names, Color $darkColor): SVGText
+ private function getInitials(HSLColor $darkColor): SVGText
{
- $initialsText = '';
- foreach ($names as $name) {
- $initialsText .= substr($name, 0, 1);
- }
+ $initialsText = $this->name->getInitials();
+
+ $fontFamily = empty($this->fontFamily) ? 'Segoe UI, Helvetica, sans-serif' : $this->fontFamily;
$initials = new SVGText($initialsText, '50%', '55%');
- $initials->setStyle('fill', $darkColor->getHex());
+ $initials->setStyle('fill', $darkColor->toHex());
$initials->setStyle('text-anchor', 'middle');
$initials->setStyle('dominant-baseline', 'middle');
$initials->setStyle('font-weight', $this->fontWeight);
- $initials->setFontFamily($this->fontFamily);
+ $initials->setFontFamily($fontFamily);
if ($this->fontSize == 0) {
$this->fontSize = $this->calculateFontSize($initialsText);
}
@@ -225,136 +249,12 @@ protected function calculateFontSize(string $initials): int
}
/**
- * Sets the font size for the text
- *
- * @param int $size The font size in pixel
- * @return void
- */
- public function setFontSize(int $size): void
- {
- $this->fontSize = $size;
- }
-
- /**
- * Sets the size of the avatar
- * @param int $size Size in pixel
- * @return void
- */
- public function setSize(int $size): void
- {
- $this->size = $size;
- }
-
- /**
- * Sets the font which shall be used for the avatar
- * @param string $fontFamily Font Family, e.g. 'Roboto'
- * @param string $path Relative path to the true type font with a leading slash, e.g. '/font/Roboto-Bold.ttf'
- * @return void
- */
- public function setFont(string $fontFamily, string $path): void
- {
- $this->fontFamily = $fontFamily;
- $this->fontPath = $path;
- }
-
- /**
- * Sets the form of the application
+ * Returns the base64 encoded string representing the SVG image.
*
- * @param string|FormTypes $form The form type
- * @return void
+ * @return string The base64 encoded string representing the SVG image.
*/
- public function setForm(string|FormTypes $form): void
+ public function getBase64(): string
{
- if (is_string($form)) {
- $form = FormTypes::from($form);
- }
-
- $this->form = $form;
+ return 'data:image/svg+xml;base64,'.base64_encode($this->generate());
}
-
- /**
- * Sets the rotation angle of the element
- *
- * @param int $angle The rotation angle value
- *
- * @return void
- */
- public function setRotation(int $angle): void
- {
- $this->rotation = $angle;
- }
-
- /**
- * Sets the font weight
- * @param string $fontWeight The font weight to set
- * @return void
- */
- public function setFontWeight(string $fontWeight): void
- {
- $this->fontWeight = $fontWeight;
- }
-
- /**
- * Get the lightness of the background color.
- *
- * @return float The lightness value of the background color.
- */
- public function getBackgroundLightness(): float
- {
- return $this->backgroundLightness;
- }
-
- /**
- * Sets the lightness of the background
- *
- * @param float $lightness Lightness value (between 0 and 1)
- * @return void
- */
- public function setBackgroundLightness(float $lightness): void
- {
- $this->backgroundLightness = clamp($lightness, 0, 1);
- }
-
- /**
- * Get the lightness of the text
- *
- * @return float The lightness of the text
- */
- public function getTextLightness(): float
- {
- return $this->textLightness;
- }
-
- /**
- * Sets the lightness of the text
- *
- * @param float $lightness Lightness value ranging from 0 to 1
- * @return void
- */
- public function setTextLightness(float $lightness): void
- {
- $this->textLightness = clamp($lightness, 0, 1);
- }
-
- /**
- * Retrieves the offset of the object
- *
- * @return int The offset value
- */
- public function getOffset(): int
- {
- return $this->offset;
- }
-
- /**
- * Sets the offset for the avatar
- *
- * @param int $offset The offset in pixel
- * @return void
- */
- public function setOffset(int $offset): void
- {
- $this->offset = $offset;
- }
-
}
diff --git a/src/Larvatar.php b/src/Larvatar.php
index 7ca9902..8dfa72a 100644
--- a/src/Larvatar.php
+++ b/src/Larvatar.php
@@ -1,96 +1,105 @@
-name = $name;
- $this->email = $email;
- if (is_int($type)) {
- $this->type = LarvatarTypes::from($type);
- } elseif ($type instanceof LarvatarTypes) {
- $this->type = $type;
- }
-
- if ($this->type == LarvatarTypes::InitialsAvatar) {
- $this->initialsAvatar = new InitialsAvatar($this->name);
- }
- }
-
- /**
- * Generates the HTML or SVG code directly for usage
- * @return string HTML or SVG code
- */
- public function getImageHTML(string $encoding = ''): string
- {
- if ($this->type == LarvatarTypes::InitialsAvatar) {
- if (isset($this->font) && $this->font != '' && $this->fontPath != '') {
- $this->initialsAvatar->setFont($this->font, $this->fontPath);
- }
- $this->initialsAvatar->setSize($this->size);
- if ($encoding == 'base64') {
- return '';
- } else {
- return $this->initialsAvatar->generate();
- }
- }
-
- $gravatar = new Gravatar($this->email);
- $gravatar->setType($this->type);
- $gravatar->setSize($this->size);
-
- return '';
- }
-
- /**
- * Get the base64 string representation of the initials' avatar.
- *
- * @return string The base64 encoded string of the initials' avatar.
- */
- public function getBase64(): string
- {
- return $this->initialsAvatar->generate(encoding: 'base64');
- }
-
- /**
- * Set the font for Initial Avatar
- * @param string $fontFamily Font family of the used font, e.g. 'Roboto'
- * @param string $path Relative path to the true type font file, starting with a /, e.g. '/font/Roboto-Bold.ttf'
- * @return void
- */
- public function setFont(string $fontFamily, string $path): void
- {
- $this->font = $fontFamily;
- $this->fontPath = $path;
- }
-
- /**
- * Sets the size of the object.
- *
- * @param int $size The size of the object.
- * @return void
- */
- public function setSize(int $size): void
- {
- $this->size = $size;
- }
-}
\ No newline at end of file
+name = Name::make($name);
+ } else {
+ $this->name = $name;
+ }
+
+ $this->email = $email;
+ $this->type = $type;
+
+ if ($this->type == LarvatarTypes::InitialsAvatar) {
+ $this->avatar = InitialsAvatar::make($this->name);
+ } elseif ($this->type == LarvatarTypes::IdenticonLarvatar) {
+ $this->avatar = Identicon::make($this->name);
+ }
+ }
+
+ public static function make(
+ LarvatarTypes $type,
+ string|Name $name = '',
+ string $email = ''
+ ): Larvatar {
+ return new self($type, $name, $email);
+ }
+
+ /**
+ * Generates the HTML or SVG code directly for usage
+ * @return string HTML or SVG code
+ */
+ public function getImageHTML(bool $base64 = false): string
+ {
+ if ($this->type == LarvatarTypes::InitialsAvatar || $this->type == LarvatarTypes::IdenticonLarvatar) {
+ if (isset($this->font) && $this->font != '' && $this->fontPath != '') {
+ $this->avatar->setFont($this->font, $this->fontPath);
+ }
+ $this->avatar->setSize($this->size);
+ return $this->avatar->getHTML($base64);
+ }
+
+ $gravatar = new Gravatar($this->email);
+ $gravatar->setType($this->type);
+ $gravatar->setSize($this->size);
+
+ return '';
+ }
+
+ /**
+ * Set the font for Initial Avatar
+ * @param string $fontFamily Font family of the used font, e.g. 'Roboto'
+ * @param string $path Relative path to the true type font file, starting with a /, e.g. '/font/Roboto-Bold.ttf'
+ * @return void
+ */
+ public function setFont(string $fontFamily, string $path): void
+ {
+ $this->font = $fontFamily;
+ $this->fontPath = $path;
+ }
+
+ /**
+ * Sets the size of the object.
+ *
+ * @param int $size The size of the object.
+ * @return void
+ */
+ public function setSize(int $size): void
+ {
+ $this->size = $size;
+ }
+
+ /**
+ * Get the base64 string representation of the initials' avatar.
+ *
+ * @return string The base64 encoded string of the initials' avatar.
+ */
+ public function getBase64(): string
+ {
+ return $this->avatar->getBase64();
+ }
+}
diff --git a/src/LarvatarServiceProvider.php b/src/LarvatarServiceProvider.php
index 0172313..d9f25de 100644
--- a/src/LarvatarServiceProvider.php
+++ b/src/LarvatarServiceProvider.php
@@ -6,12 +6,12 @@
class LarvatarServiceProvider extends ServiceProvider
{
- public function boot()
+ public function boot(): void
{
}
- public function register()
+ public function register(): void
{
$this->app->make('Renfordt\Larvatar\Larvatar');
}
-}
\ No newline at end of file
+}
diff --git a/src/Name.php b/src/Name.php
new file mode 100644
index 0000000..a0e48ea
--- /dev/null
+++ b/src/Name.php
@@ -0,0 +1,105 @@
+name = $name;
+ $this->splitNames = explode(' ', $name);
+ $this->hash = $this->hash();
+ }
+
+ /**
+ * Calculates the MD5 hash of the name.
+ *
+ * @return string
+ */
+ private function hash(): string
+ {
+ return md5($this->name);
+ }
+
+ /**
+ * Get the hexadecimal color value
+ *
+ * @param int $offset The starting offset for the substring
+ * @return HexColor The hexadecimal color string
+ */
+ public function getHexColor(int $offset = 0): HexColor
+ {
+ return HexColor::create('#'.substr($this->hash, $offset, 6));
+ }
+
+ /**
+ * Create an instance of the Name class.
+ *
+ * @param string $name The name to be used for creating the Name object.
+ * @return Name The newly created Name object.
+ */
+ public static function make(string $name): Name
+ {
+ return new Name($name);
+ }
+
+ /**
+ * Get the name of the object.
+ *
+ * @return string The name of the object.
+ */
+ public function getName(): string
+ {
+ return $this->name;
+ }
+
+ /**
+ * Get the hash value of the name
+ *
+ * @return string The hashed name.
+ */
+ public function getHash(): string
+ {
+ return $this->hash;
+ }
+
+ /**
+ * Get the initials of the name
+ *
+ * @return string The initials of the name.
+ */
+ public function getInitials(): string
+ {
+ $initials = '';
+ foreach ($this->getSplitNames() as $name) {
+ $initials .= mb_substr($name, 0, 1, 'UTF-8');
+ }
+
+ return $initials;
+ }
+
+ /**
+ * Retrieves the split names.
+ *
+ * @return array The split names.
+ */
+ public function getSplitNames(): array
+ {
+ return $this->splitNames;
+ }
+}
diff --git a/src/Traits/ColorTrait.php b/src/Traits/ColorTrait.php
new file mode 100644
index 0000000..1e6c935
--- /dev/null
+++ b/src/Traits/ColorTrait.php
@@ -0,0 +1,42 @@
+getHexColor();
+
+ $dark = $color->toHSL();
+ $dark->setLightness($textLightness);
+ $light = $color->toHSL();
+ $light->setLightness($backgroundLightness);
+ return [$dark, $light];
+ }
+
+ /**
+ * Converts a hex color to its HSL representation.
+ *
+ * @param Name $name The name object containing the hex color value.
+ * @return HSLColor The HSL color representation of the provided hex color.
+ */
+ public function getHSLColor(Name $name): HSLColor
+ {
+ $color = $name->getHexColor();
+
+ return $color->toHSL();
+ }
+
+}
diff --git a/src/Traits/LarvatarTrait.php b/src/Traits/LarvatarTrait.php
index 8650ef5..990e5b3 100644
--- a/src/Traits/LarvatarTrait.php
+++ b/src/Traits/LarvatarTrait.php
@@ -8,20 +8,20 @@
trait LarvatarTrait
{
/**
- * Retrieves the avatar image HTML based on the provided name, email, avatar type, and encoding.
+ * Generates an avatar image based on the provided parameters.
*
- * @param string $name The name used to generate the avatar.
- * @param string $email The email address used to generate the avatar.
- * @param LarvatarTypes $type The type of avatar to generate. Default is initial avatars.
- * @param string $encoding The encoding type for the avatar image. Default is empty string.
- * @return string The HTML representation of the avatar image.
+ * @param string $name The name to be used for generating the avatar.
+ * @param string $email Optional email to be used for generating the avatar.
+ * @param int $size The size of the avatar image.
+ * @param LarvatarTypes $type The type of avatar to generate.
+ * @param bool $encoding Whether to encode the image in base64.
+ *
+ * @return string The generated avatar image in HTML format.
*/
- public function getAvatar(string $name, string $email = '', int $size = 100, LarvatarTypes $type = LarvatarTypes::InitialsAvatar, string $encoding = ''): string
+ public function getAvatar(string $name, string $email = '', int $size = 100, LarvatarTypes $type = LarvatarTypes::InitialsAvatar, bool $encoding = false): string
{
- $larvatar = new Larvatar($name, $email, $type);
+ $larvatar = new Larvatar($type, $name, $email);
$larvatar->setSize($size);
- $larvatar->setFont('Roboto,sans-serif', '/font/Roboto-Bold.ttf');
- $larvatar->initialsAvatar->setFontWeight('bold');
return $larvatar->getImageHTML($encoding);
}
-}
\ No newline at end of file
+}
diff --git a/tests/AvatarTest.php b/tests/AvatarTest.php
new file mode 100644
index 0000000..13140d4
--- /dev/null
+++ b/tests/AvatarTest.php
@@ -0,0 +1,171 @@
+getMockForAbstractClass(Avatar::class);
+ $mock->setFont($font, $path);
+ $this->assertEquals($font, $mock->getFontFamily());
+ $this->assertEquals($path, $mock->getFontPath());
+ }
+
+ public function fontDataProvider()
+ {
+ return [
+ ['Arial', '/path/to/font.ttf'],
+ ['', '/path/to/font.ttf'],
+ ['Arial', ''],
+ ['@#$%^&*()!', '/path/to/font.ttf'],
+ ['Arial', '/path/to/f@nt!.ttf'],
+ ];
+ }
+
+ /**
+ * Test setting and getting background lightness.
+ *
+ * @dataProvider backgroundLightnessProvider
+ */
+ public function testBackgroundLightnessMethods($input, $expected)
+ {
+ $mock = $this->getMockForAbstractClass(Avatar::class);
+ $mock->setBackgroundLightness($input);
+ $this->assertEquals($expected, $mock->getBackgroundLightness());
+ }
+
+ public function backgroundLightnessProvider()
+ {
+ return [
+ [0.5, 0.5],
+ [-0.5, 0],
+ [1.5, 1],
+ [0, 0],
+ [1, 1],
+ ];
+ }
+
+ /**
+ * Test setting and getting text lightness.
+ *
+ * @dataProvider textLightnessProvider
+ */
+ public function testTextLightnessMethods($input, $expected)
+ {
+ $mock = $this->getMockForAbstractClass(Avatar::class);
+ $mock->setTextLightness($input);
+ $this->assertEquals($expected, $mock->getTextLightness());
+ }
+
+ public function textLightnessProvider()
+ {
+ return [
+ [0, 0],
+ [1, 1],
+ [0.5, 0.5],
+ [-0.1, 0],
+ [1.1, 1],
+ ];
+ }
+
+ /**
+ * Test setting and getting name.
+ *
+ * @dataProvider nameProvider
+ */
+ public function testNameMethods($name, $expected)
+ {
+ $mock = $this->getMockForAbstractClass(Avatar::class);
+ $mock->setName($name);
+ $this->assertEquals($expected, $mock->getName()->getName());
+ }
+
+ public function nameProvider()
+ {
+ return [
+ [new Name('Valid Object'), 'Valid Object'],
+ ['Avatar Name', 'Avatar Name'],
+ ['', ''],
+ ['A!@#avatar%^&*()', 'A!@#avatar%^&*()'],
+ ];
+ }
+
+ /**
+ * Test setting and getting font size.
+ *
+ * @dataProvider fontSizeProvider
+ */
+ public function testFontSizeMethods($input)
+ {
+ $mock = $this->getMockForAbstractClass(Avatar::class);
+ $mock->setFontSize($input);
+ $this->assertEquals($input, $mock->getFontSize());
+ }
+
+ public function fontSizeProvider()
+ {
+ return [
+ [12],
+ [-5],
+ [0],
+ [999999],
+ ];
+ }
+
+ /**
+ * Test setting and getting font weight.
+ *
+ * @dataProvider fontWeightProvider
+ */
+ public function testFontWeightMethods($input)
+ {
+ $mock = $this->getMockForAbstractClass(Avatar::class);
+ $mock->setFontWeight($input);
+ $this->assertEquals($input, $mock->getFontWeight());
+ }
+
+ public function fontWeightProvider()
+ {
+ return [
+ ['normal'],
+ ['bold'],
+ ['100'],
+ ['900'],
+ [''],
+ ['@#$%^&*()!'],
+ ];
+ }
+
+ /**
+ * Test setting and getting size.
+ *
+ * @dataProvider sizeProvider
+ */
+ public function testSizeMethods($input)
+ {
+ $mock = $this->getMockForAbstractClass(Avatar::class);
+ $mock->setSize($input);
+ $this->assertEquals($input, $mock->getSize());
+ }
+
+ public function sizeProvider()
+ {
+ return [
+ [150],
+ [0],
+ [-50],
+ [2000000],
+ ];
+ }
+}
diff --git a/tests/ColorTest.php b/tests/ColorTest.php
deleted file mode 100644
index 0cd65e2..0000000
--- a/tests/ColorTest.php
+++ /dev/null
@@ -1,369 +0,0 @@
-assertEquals($expectedResult, $actualResult, 'Case 1 failed: White');
-
- // Test case 2: black
- $hexColor = '#000000';
- $expectedResult = [0, 0, 0];
- $actualResult = Color::HexToRGB($hexColor);
- $this->assertEquals($expectedResult, $actualResult, 'Case 2 failed: Black');
-
- // Test case 3: Mountain Meadow
- $hexColor = '#11c380';
- $expectedResult = [17, 195, 128];
- $actualResult = Color::HexToRGB($hexColor);
- $this->assertEquals($expectedResult, $actualResult, 'Case 3 failed: Mountain Meadow');
-
- // Test case 4: #8c5a45
- $hexColor = '#8c5a45';
- $expectedResult = [140, 90, 69];
- $actualResult = Color::HexToRGB($hexColor);
- $this->assertEquals($expectedResult, $actualResult, 'Case 4 failed: #8c5a45');
-
- // Test case 4: #8c5a45
- $hexColor = '#345';
- $expectedResult = [51, 68, 85];
- $actualResult = Color::HexToRGB($hexColor);
- $this->assertEquals($expectedResult, $actualResult, 'Case failed: #345');
-
-
- }
-
- /**
- * Tests the RGBToHSL method with a variety of colors.
- *
- * @throws \Exception
- */
- public function testRGBToHSL(): void
- {
- // Test case 1: White
- $rgbColor = [255, 255, 255];
- $expectedResult = [0, 0, 1];
- $actualResult = Color::RGBToHSL($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult);
-
- // Test case 2: Black
- $rgbColor = [0, 0, 0];
- $expectedResult = [0, 0, 0];
- $actualResult = Color::RGBToHSL($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult);
-
- // Test case 3: Red
- $rgbColor = [255, 0, 0];
- $expectedResult = [0, 1, 0.5];
- $actualResult = Color::RGBToHSL($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult);
-
- // Test case 4: Green
- $rgbColor = [0, 255, 0];
- $expectedResult = [120, 1, 0.5];
- $actualResult = Color::RGBToHSL($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult);
-
- // Test case 5: Blue
- $rgbColor = [0, 0, 255];
- $expectedResult = [240, 1, 0.5];
- $actualResult = Color::RGBToHSL($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult);
-
- // Test case 6: Mountain Meadow
- $rgbColor = [17, 195, 128];
- $expectedResult = [157, 0.84, 0.42];
- $actualResult = Color::RGBToHSL($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 6 failed: Mountain Meadow');
-
- // Test case 6: #8c5a45
- $rgbColor = [140, 90, 69];
- $expectedResult = [18, 0.34, 0.41];
- $actualResult = Color::RGBToHSL($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 7 failed: #8c5a45');
- }
-
- /**
- * Tests the RGBToHSV method with a variety of colors.
- *
- * @throws \Exception
- */
- public function testRGBToHSV(): void
- {
- // Test case 1: White
- $rgbColor = [255, 255, 255];
- $expectedResult = [0, 0, 1];
- $actualResult = Color::RGBToHSV($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 1 failed: White');
-
- // Test case 2: Black
- $rgbColor = [0, 0, 0];
- $expectedResult = [0, 0, 0];
- $actualResult = Color::RGBToHSV($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 2 failed: Black');
-
- // Test case 3: Red
- $rgbColor = [255, 0, 0];
- $expectedResult = [0, 100, 1];
- $actualResult = Color::RGBToHSV($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 3 failed: Red');
-
- // Test case 4: Green
- $rgbColor = [0, 255, 0];
- $expectedResult = [120, 100, 1];
- $actualResult = Color::RGBToHSV($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 4 failed: Green');
-
- // Test case 5: Blue
- $rgbColor = [0, 0, 255];
- $expectedResult = [240, 100, 1];
- $actualResult = Color::RGBToHSV($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 5 failed: Blue');
- }
-
- /**
- * Tests the RGBToHex method.
- *
- * @throws \Exception
- */
- public function testRGBToHex(): void
- {
- // Test case 1: White
- $rgbColor = [255, 255, 255];
- $expectedResult = 'ffffff';
- $actualResult = Color::RGBToHex($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 1 failed: White');
-
- // Test case 2: Black
- $rgbColor = [0, 0, 0];
- $expectedResult = '000000';
- $actualResult = Color::RGBToHex($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 2 failed: Black');
-
- // Test case 3: Red
- $rgbColor = [255, 0, 0];
- $expectedResult = 'ff0000';
- $actualResult = Color::RGBToHex($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 3 failed: Red');
-
- // Test case 4: Green
- $rgbColor = [0, 255, 0];
- $expectedResult = '00ff00';
- $actualResult = Color::RGBToHex($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 4 failed: Green');
-
- // Test case 5: Blue
- $rgbColor = [0, 0, 255];
- $expectedResult = '0000ff';
- $actualResult = Color::RGBToHex($rgbColor[0], $rgbColor[1], $rgbColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 5 failed: Blue');
-
- }
-
- /**
- * Tests the HSVToRGB method.
- *
- * @throws \Exception
- */
- public function testHSVToRGB(): void
- {
- // Test case 1: White
- $HSVColor = [0, 0, 1];
- $expectedResult = [255, 255, 255];
- $actualResult = Color::HSVToRGB($HSVColor[0], $HSVColor[1], $HSVColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 1 failed: White');
-
- // Test case 2: Black
- $HSVColor = [0, 0, 0];
- $expectedResult = [0, 0, 0];
- $actualResult = Color::HSVToRGB($HSVColor[0], $HSVColor[1], $HSVColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 2 failed: Black');
-
- // Test case 3: Red
- $HSVColor = [0, 1, 1];
- $expectedResult = [255, 0, 0];
- $actualResult = Color::HSVToRGB($HSVColor[0], $HSVColor[1], $HSVColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 3 failed: Red');
-
- // Test case 4: Green
- $HSVColor = [120, 1, 1];
- $expectedResult = [0, 255, 0];
- $actualResult = Color::HSVToRGB($HSVColor[0], $HSVColor[1], $HSVColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 4 failed: Green');
-
- // Test case 5: Blue
- $HSVColor = [240, 1, 1];
- $expectedResult = [0, 0, 255];
- $actualResult = Color::HSVToRGB($HSVColor[0], $HSVColor[1], $HSVColor[2]);
- $this->assertEquals($expectedResult, $actualResult, 'Case 5 failed: Blue');
- }
-
- /**
- * Tests the calculateCVH method.
- *
- * @throws \Exception
- */
- public function testCalculateCVH(): void
- {
- // Test case 1: RGB (255, 255, 255)
- $expectedResult = [1.0, 1.0, 0, 1.0, 0];
- $actualResult = Color::calculateCVH(255, 255, 255);
- $this->assertEquals($expectedResult, $actualResult, 'Case 1 failed: White');
-
- // Test case 2: RGB (0, 0, 0)
- $expectedResult = [0, 0, 0, 0, 0];
- $actualResult = Color::calculateCVH(0, 0, 0);
- $this->assertEquals($expectedResult, $actualResult, 'Case 2 failed: Black');
-
- // Test case 3: RGB (255, 0, 0)
- $expectedResult = [1.0, 0, 1.0, 1.0, 0];
- $actualResult = Color::calculateCVH(255, 0, 0);
- $this->assertEquals($expectedResult, $actualResult, 'Case 3 failed: Red');
-
- // Test case 4: RGB (0, 255, 0)
- $expectedResult = [1.0, 0, 1.0, 1.0, 120];
- $actualResult = Color::calculateCVH(0, 255, 0);
- $this->assertEquals($expectedResult, $actualResult, 'Case 4 failed: Green');
-
- // Test case 5: RGB (0, 0, 255)
- $expectedResult = [1, 0, 1.0, 1.0, 240];
- $actualResult = Color::calculateCVH(0, 0, 255);
- $this->assertEquals($expectedResult, $actualResult, 'Case 5 failed: Blue');
- }
-
- /**
- * Tests the setHex method in different scenarios.
- *
- * @return void
- */
- public function testSetHex(): void
- {
- $color = new Color(ColorType::RGB, [255, 255, 255]);
-
- $color->setHex('#000000');
- $this->assertEquals([0, 0, 0], $color->getRGB());
- $this->assertEquals('#000000', $color->getHex());
- $this->assertEquals([0, 0, 0], $color->getHSL());
-
- $color->setHex('#FF0000');
- $this->assertEquals([255, 0, 0], $color->getRGB());
- $this->assertEquals('#FF0000', $color->getHex());
- $this->assertEquals([0, 1, 0.5], $color->getHSL());
-
- $color->setHex('#00FF00');
- $this->assertEquals([0, 255, 0], $color->getRGB());
- $this->assertEquals('#00FF00', $color->getHex());
- $this->assertEquals([120, 1, 0.5], $color->getHSL());
-
- $color->setHex('#0000FF');
- $this->assertEquals([0, 0, 255], $color->getRGB());
- $this->assertEquals('#0000FF', $color->getHex());
- $this->assertEquals([240, 1, 0.5], $color->getHSL());
- }
-
- /**
- * Tests the setRGB method in different scenarios.
- *
- * @return void
- */
- public function testSetRGB(): void
- {
- $color = new Color(ColorType::Hex, '#ffffff');
-
- $color->setRGB([0, 0, 0]);
- $this->assertEquals([0, 0, 0], $color->getRGB());
- $this->assertEquals([0, 0, 0], $color->getHSL());
- $this->assertEquals('#000000', $color->getHex());
-
- $color->setRGB([255, 0, 0]);
- $this->assertEquals([255, 0, 0], $color->getRGB());
- $this->assertEquals([0, 1, 0.5], $color->getHSL());
- $this->assertEquals('#ff0000', $color->getHex());
-
- $color->setRGB([0, 255, 0]);
- $this->assertEquals([0, 255, 0], $color->getRGB());
- $this->assertEquals([120, 1, 0.5], $color->getHSL());
- $this->assertEquals('#00ff00', $color->getHex());
-
- $color->setRGB([0, 0, 255]);
- $this->assertEquals([0, 0, 255], $color->getRGB());
- $this->assertEquals([240, 1, 0.5], $color->getHSL());
- $this->assertEquals('#0000ff', $color->getHex());
- }
-
- public function testGetColorSet(): void
- {
- $color = new Color(ColorType::HSL, [240, 0.5, 0.5]);
- list($dark, $light) = $color->getColorSet();
-
- $this->assertEquals([240, 0.5, 0.35], $dark->getHSL());
- $this->assertEquals([240, 0.5, 0.8], $light->getHSL());
- }
-
- public function testBrightenWithoutParameter(): void
- {
- $color = new Color(ColorType::HSL, [240, 0.5, 0.5]);
- $color->brighten();
- $this->assertEquals([240, 0.5, 0.6], $color->getHSL());
- }
-
- public function testBrightenWithParameter(): void
- {
- $color = new Color(ColorType::HSL, [240, 0.5, 0.5]);
- $color->brighten(20);
- $this->assertEquals([240, 0.5, 0.7], $color->getHSL());
- }
-
- public function testBrightenWithOutOfRangeParameter(): void
- {
- $color = new Color(ColorType::HSL, [240, 0.5, 0.5]);
- $color->brighten(120);
- $this->assertEquals([240, 0.5, 1.0], $color->getHSL());
-
- $color->brighten(-120);
- $this->assertEquals([240, 0.5, 0.0], $color->getHSL());
- }
-
- public function testDarkenWithoutParameter(): void
- {
- $color = new Color(ColorType::HSL, [240, 0.5, 0.5]);
- $color->darken();
- $this->assertEquals([240, 0.5, 0.4], $color->getHSL());
- }
-
- public function testDarkenWithParameter(): void
- {
- $color = new Color(ColorType::HSL, [240, 0.5, 0.5]);
- $color->darken(20);
- $this->assertEquals([240, 0.5, 0.3], $color->getHSL());
- }
-
- public function testDarkenWithOutOfRangeParameter(): void
- {
- $color = new Color(ColorType::HSL, [240, 0.5, 0.5]);
- $color->darken(120);
- $this->assertEquals([240, 0.5, 0.0], $color->getHSL());
-
- $color->darken(-120);
- $this->assertEquals([240, 0.5, 1.0], $color->getHSL());
- }
-
-}
diff --git a/tests/GravatarTest.php b/tests/GravatarTest.php
index 1c3d14c..db301fc 100644
--- a/tests/GravatarTest.php
+++ b/tests/GravatarTest.php
@@ -1,4 +1,6 @@
-setType(LarvatarTypes::mp);
- $this->assertEquals(
- 'https://www.gravatar.com/avatar/b58996c504c5638798eb6b511e6f49af?d=mp&f=y&s=100',
- $gravatar->generateGravatarLink()
- );
- }
+ $gravatar = new Gravatar('user@example.com');
+ $gravatar->setType(LarvatarTypes::mp);
+ $this->assertEquals(
+ 'https://www.gravatar.com/avatar/b58996c504c5638798eb6b511e6f49af?d=mp&f=y&s=100',
+ $gravatar->generateGravatarLink()
+ );
+ }
}
diff --git a/tests/IdenticonTest.php b/tests/IdenticonTest.php
new file mode 100644
index 0000000..b3b9178
--- /dev/null
+++ b/tests/IdenticonTest.php
@@ -0,0 +1,524 @@
+setPixels(5);
+
+ // Retrieve the symmetry matrix
+ $symmetryMatrix = $this->invokeMethod($identicon, 'getSymmetryMatrix');
+
+ // Define the expected matrix
+ $expectedMatrix = [
+ [0, 4],
+ [1, 3],
+ [2]
+ ];
+
+ // Assertion
+ $this->assertEquals($expectedMatrix, $symmetryMatrix);
+ }
+
+ /**
+ * Invokes a private or protected method on an object.
+ *
+ * @param object &$object Instantiated object to invoke the method on.
+ * @param string $methodName Method name to invoke.
+ * @param array $parameters Array of parameters to pass into the method.
+ * @return mixed Method return.
+ */
+ protected function invokeMethod(&$object, $methodName, array $parameters = [])
+ {
+ $reflection = new \ReflectionClass($object);
+ $method = $reflection->getMethod($methodName);
+ $method->setAccessible(true);
+
+ return $method->invokeArgs($object, $parameters);
+ }
+
+ /**
+ * Tests the convertStrToBool method with the hexadecimal value '0'.
+ */
+ public function testConvertStrToBoolWithZero()
+ {
+ // Mocking the Name class
+ $nameMock = $this->createMock(Name::class);
+
+ // Creating Identicon
+ $identicon = new Identicon($nameMock);
+
+ // Assertion: Hex '0' should convert to boolean false
+ $result = $this->invokeMethod($identicon, 'convertStrToBool', ['0']);
+ $this->assertFalse($result);
+ }
+
+ /**
+ * Tests the convertStrToBool method with the hexadecimal value 'F'.
+ */
+ public function testConvertStrToBoolWithF()
+ {
+ // Mocking the Name class
+ $nameMock = $this->createMock(Name::class);
+
+ // Creating Identicon
+ $identicon = new Identicon($nameMock);
+
+ // Assertion: Hex 'F' should convert to boolean true
+ $result = $this->invokeMethod($identicon, 'convertStrToBool', ['F']);
+ $this->assertTrue($result);
+ }
+
+ /**
+ * Tests the convertStrToBool method with a mid-range hexadecimal value.
+ */
+ public function testConvertStrToBoolWithEight()
+ {
+ // Mocking the Name class
+ $nameMock = $this->createMock(Name::class);
+
+ // Creating Identicon
+ $identicon = new Identicon($nameMock);
+
+ // Assertion: Hex '8' should convert to boolean true
+ $result = $this->invokeMethod($identicon, 'convertStrToBool', ['8']);
+ $this->assertTrue($result);
+ }
+
+ /**
+ * Tests the convertStrToBool method with a low-range hexadecimal value.
+ */
+ public function testConvertStrToBoolWithFour()
+ {
+ // Mocking the Name class
+ $nameMock = $this->createMock(Name::class);
+
+ // Creating Identicon
+ $identicon = new Identicon($nameMock);
+
+ // Assertion: Hex '4' should convert to boolean false
+ $result = $this->invokeMethod($identicon, 'convertStrToBool', ['4']);
+ $this->assertFalse($result);
+ }
+
+ /**
+ * Tests the getSymmetryMatrix method to handle single pixel cases.
+ */
+ public function testGetSymmetryMatrixHandlesSinglePixel()
+ {
+ // Mocking the Name class
+ $nameMock = $this->createMock(Name::class);
+
+ // Creating Identicon
+ $identicon = new Identicon($nameMock);
+
+ // Set the number of pixels
+ $identicon->setPixels(1);
+
+ // Retrieve the symmetry matrix
+ $symmetryMatrix = $this->invokeMethod($identicon, 'getSymmetryMatrix');
+
+ // Define the expected matrix
+ $expectedMatrix = [
+ [0]
+ ];
+
+ // Assertion
+ $this->assertEquals($expectedMatrix, $symmetryMatrix);
+ }
+
+ /**
+ * Tests the getSymmetryMatrix method to handle even pixel counts.
+ */
+ public function testGetSymmetryMatrixHandlesEvenPixelCount()
+ {
+ // Mocking the Name class
+ $nameMock = $this->createMock(Name::class);
+
+ // Creating Identicon
+ $identicon = new Identicon($nameMock);
+
+ // Set the number of pixels
+ $identicon->setPixels(6);
+
+ // Retrieve the symmetry matrix
+ $symmetryMatrix = $this->invokeMethod($identicon, 'getSymmetryMatrix');
+
+ // Define the expected matrix
+ $expectedMatrix = [
+ [0, 5],
+ [1, 4],
+ [2, 3],
+ ];
+
+ // Assertion
+ $this->assertEquals($expectedMatrix, $symmetryMatrix);
+ }
+
+ /**
+ * Tests the getSVG method to ensure it returns a valid SVG representation with symmetry.
+ */
+ public function testGetSVGWithSymmetry()
+ {
+ // Mocking the Name class
+ $nameMock = $this->createMock(Name::class);
+
+ // Creating Identicon with symmetry
+ $identicon = new Identicon($nameMock);
+ $identicon->setSymmetry(true);
+
+ // Assertion: Check if the output contains expected SVG structure
+ $svgContent = $identicon->getSVG();
+ $this->assertStringContainsString('