diff --git a/composer.json b/composer.json index 58a5fe4..48060bb 100644 --- a/composer.json +++ b/composer.json @@ -29,12 +29,17 @@ { "type": "vcs", "url": "https://github.com/JellyBellyDev/phpspec-data-provider-extension" + }, + { + "type": "vcs", + "url": "https://github.com/cybercog/php-svg-font" } ], "require": { "php": ">=7.4", "ext-gd": "*", "ext-simplexml": "*", + "cybercog/php-svg-font": "*", "kartsims/easysvg": "^2.4", "symfony/console": "^4.0|^5.0|^6.0" }, @@ -69,5 +74,7 @@ "branch-alias": { "dev-master": "2.x-dev" } - } + }, + "minimum-stability": "dev", + "prefer-stable": true } diff --git a/src/Calculator/SvgTextSizeCalculator.php b/src/Calculator/SvgTextSizeCalculator.php index da18561..3bc3a03 100644 --- a/src/Calculator/SvgTextSizeCalculator.php +++ b/src/Calculator/SvgTextSizeCalculator.php @@ -11,6 +11,10 @@ namespace PUGX\Poser\Calculator; +use Cog\SvgFont\Font; +use Cog\SvgFont\Parser\SimpleXmlSvgFontFileParser; +use Cog\Unicode\UnicodeString; + /** * @author Anton Komarev */ @@ -25,25 +29,38 @@ class SvgTextSizeCalculator implements TextSizeCalculatorInterface */ public function calculateWidth(string $text, int $size = self::TEXT_SIZE): float { - $font = SvgFont::fromFile(__DIR__ . '/Font/DejaVuSans.svg'); + $font = (new SimpleXmlSvgFontFileParser()) + ->parseFile(__DIR__ . '/DejaVuSans.svg') + ->getById('DejaVuSansBook'); + + $width = $this->computeTextWidth( + $font, + $text, + $size, + ); - $textUnicode = TextUnicodeConverter::convertTextToCodePoints($text); + return \round($width + self::SHIELD_PADDING, 1); + } - $width = 0; - $lineWidth = 0; + private function computeTextWidth( + Font $font, + string $text, + int $fontSize + ): float { + $characterList = UnicodeString::of($text)->characterList(); - foreach ($textUnicode as $unicodeCodePoint) { - if (self::UNICODE_CODE_POINT_LINE_FEED === $unicodeCodePoint) { - $width = \max($width, $lineWidth); - $lineWidth = 0; + $maxLineWidth = $lineWidth = 0; + + foreach ($characterList as $character) { + if ($character->toDecimal() === self::UNICODE_CODE_POINT_LINE_FEED) { + $maxLineWidth = max($maxLineWidth, $lineWidth); + $lineWidth = 0; continue; } - $lineWidth += $font->computeWidth($unicodeCodePoint, $size); + $lineWidth += $font->computeWidth($character, $fontSize); } - $width = \max($width, $lineWidth); - - return \round($width + self::SHIELD_PADDING, 1); + return max($maxLineWidth, $lineWidth); } }