Skip to content

Commit

Permalink
Tweak code
Browse files Browse the repository at this point in the history
  • Loading branch information
antonkomarev committed Oct 16, 2023
1 parent 1252cc6 commit cc7db34
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 13 deletions.
9 changes: 8 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down Expand Up @@ -69,5 +74,7 @@
"branch-alias": {
"dev-master": "2.x-dev"
}
}
},
"minimum-stability": "dev",
"prefer-stable": true
}
41 changes: 29 additions & 12 deletions src/Calculator/SvgTextSizeCalculator.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@

namespace PUGX\Poser\Calculator;

use Cog\SvgFont\Font;
use Cog\SvgFont\Parser\SimpleXmlSvgFontFileParser;
use Cog\Unicode\UnicodeString;

/**
* @author Anton Komarev <[email protected]>
*/
Expand All @@ -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);
}
}

0 comments on commit cc7db34

Please sign in to comment.