From cc7db34c9662963dd732c14725dcef5bd596f7aa Mon Sep 17 00:00:00 2001 From: Anton Komarev Date: Mon, 16 Oct 2023 22:28:01 +0300 Subject: [PATCH] Tweak code --- composer.json | 9 +++++- src/Calculator/SvgTextSizeCalculator.php | 41 +++++++++++++++++------- 2 files changed, 37 insertions(+), 13 deletions(-) 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); } }