Skip to content

Commit

Permalink
add test for xml processor
Browse files Browse the repository at this point in the history
  • Loading branch information
MathiasReker committed Dec 31, 2024
1 parent 9a4ff95 commit e695970
Show file tree
Hide file tree
Showing 36 changed files with 418 additions and 36 deletions.
10 changes: 5 additions & 5 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@

$finder = PhpCsFixer\Finder::create()
->ignoreDotFiles(false)
->in([__DIR__])
;

->in([__DIR__]);
$config = new PhpCsFixer\Config();
$config->setRiskyAllowed(true)
->setRules([
Expand Down Expand Up @@ -65,9 +63,11 @@
'@Symfony' => true,
'@Symfony:risky' => true,
'concat_space' => ['spacing' => 'one'],

// Disable rule causing issues
'multiline_whitespace_before_semicolons' => false,
])
->setFinder($finder)
->setLineEnding(\PHP_EOL)
;
->setLineEnding(PHP_EOL);

return $config;
10 changes: 5 additions & 5 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ parameters:
customRulesetUsed: true
fileExtensions:
- php
exceptions:
check:
missingCheckedExceptionInThrows: true
tooWideThrowType: true
implicitThrows: false
shipmonkRules:
forbidCheckedExceptionInCallable:
allowedCheckedExceptionCallables:
'PHPUnit\Framework\MockObject\Builder\InvocationMocker::willReturnCallback': 0
includes:
- vendor/symplify/phpstan-rules/config/code-complexity-rules.neon
- vendor/symplify/phpstan-rules/config/naming-rules.neon
Expand Down
4 changes: 4 additions & 0 deletions src/Commands/SvgOptimizerCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,8 @@ private static function getVersionFromPackageJson(): ?string

/**
* Runs the SVG optimization process.
*
* @throws \UnexpectedValueException
*/
public function run(): void
{
Expand All @@ -222,6 +224,8 @@ public function run(): void
* Processes all SVG files in a directory.
*
* @param string $directoryPath The path to the directory containing the SVG files
*
* @throws \UnexpectedValueException
*/
private function processDirectory(string $directoryPath): void
{
Expand Down
4 changes: 4 additions & 0 deletions src/Services/Data/MetaData.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ public function __construct(
* Converts the metadata to a value object.
*
* @return MetaDataValueObject The value object representing the metadata
*
* @throws \DivisionByZeroError If the original size is 0
*/
public function toValueObject(): MetaDataValueObject
{
Expand All @@ -69,6 +71,8 @@ private function calculateSavedBytes(): int
* Calculates the percentage of bytes saved through optimization.
*
* @return float The percentage of bytes saved
*
* @throws \DivisionByZeroError If the original size is 0
*/
private function calculateSavedPercentage(): float
{
Expand Down
5 changes: 3 additions & 2 deletions src/Services/Providers/AbstractProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ final public function optimize(\DOMDocument $domDocument): self

/**
* Get metadata about the optimization.
*
* @throws \InvalidArgumentException
* @throws \DivisionByZeroError
*/
#[\Override]
final public function getMetaData(): MetaDataValueObject
Expand Down Expand Up @@ -126,8 +129,6 @@ final public function saveToFile(string $path): self
* Ensures that the directory for the output file exists. Creates it if necessary.
*
* @param string $directoryPath The directory path to check/create
*
* @throws IOException If the directory cannot be created
*/
private function ensureDirectoryExists(string $directoryPath): bool
{
Expand Down
6 changes: 6 additions & 0 deletions src/Services/Providers/FileProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,17 @@
use DOMDocument;
use MathiasReker\PhpSvgOptimizer\Exception\FileNotFoundException;
use MathiasReker\PhpSvgOptimizer\Exception\IOException;
use MathiasReker\PhpSvgOptimizer\Exception\XmlProcessingException;

final class FileProvider extends AbstractProvider
{
/**
* FileProvider constructor.
*
* @param string $inputFile The path to the input SVG file
*
* @throws FileNotFoundException
* @throws IOException
*/
public function __construct(private readonly string $inputFile)
{
Expand Down Expand Up @@ -53,6 +57,8 @@ public function getInputContent(): string

/**
* Load the input file into a DOMDocument instance.
*
* @throws XmlProcessingException
*/
#[\Override]
public function loadContent(): \DOMDocument
Expand Down
3 changes: 3 additions & 0 deletions src/Services/Providers/StringProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace MathiasReker\PhpSvgOptimizer\Services\Providers;

use DOMDocument;
use MathiasReker\PhpSvgOptimizer\Exception\XmlProcessingException;

final class StringProvider extends AbstractProvider
{
Expand All @@ -27,6 +28,8 @@ public function __construct(protected string $inputContent)

/**
* Load the input string into a DOMDocument instance.
*
* @throws XmlProcessingException
*/
#[\Override]
public function loadContent(): \DOMDocument
Expand Down
1 change: 1 addition & 0 deletions src/Services/Rules/ConvertEmptyTagsToSelfClosing.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace MathiasReker\PhpSvgOptimizer\Services\Rules;

use DOMDocument;
use MathiasReker\PhpSvgOptimizer\Contracts\Services\Rules\SvgOptimizerRuleInterface;
use MathiasReker\PhpSvgOptimizer\Exception\XmlProcessingException;
use MathiasReker\PhpSvgOptimizer\Services\Util\XmlProcessor;
Expand Down
34 changes: 17 additions & 17 deletions src/Services/Rules/RemoveUnnecessaryWhitespace.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,45 +76,45 @@ public function optimize(\DOMDocument $domDocument): void
}

/**
* Remove unnecessary whitespace inside attribute values.
* Remove all whitespace inside style attribute values.
*
* This method processes the SVG content to trim and reduce whitespace
* within attribute values.
* This method processes the SVG content to remove all whitespace within
* style attribute values, which helps to compact the style definitions.
*
* @param string $content The SVG content to process
*
* @return string The processed SVG content with reduced whitespace in attribute values
* @return string The processed SVG content with whitespace removed from style attributes
*/
private function removeAttributeValueWhitespace(string $content): string
private function removeStyleAttributeWhitespace(string $content): string
{
return preg_replace_callback(
self::ATTRIBUTE_VALUE_REGEX,
self::STYLE_ATTRIBUTE_REGEX,
static fn (array $matches): string => \sprintf(
'%s="%s"',
$matches[1],
preg_replace(self::WHITESPACE_REGEX, ' ', trim($matches[2]))
'style="%s"',
rtrim(str_replace(' ', '', $matches[1]), ';')
),
$content
) ?? $content;
}

/**
* Remove all whitespace inside style attribute values.
* Remove unnecessary whitespace inside attribute values.
*
* This method processes the SVG content to remove all whitespace within
* style attribute values, which helps to compact the style definitions.
* This method processes the SVG content to trim and reduce whitespace
* within attribute values.
*
* @param string $content The SVG content to process
*
* @return string The processed SVG content with whitespace removed from style attributes
* @return string The processed SVG content with reduced whitespace in attribute values
*/
private function removeStyleAttributeWhitespace(string $content): string
private function removeAttributeValueWhitespace(string $content): string
{
return preg_replace_callback(
self::STYLE_ATTRIBUTE_REGEX,
self::ATTRIBUTE_VALUE_REGEX,
static fn (array $matches): string => \sprintf(
'style="%s"',
rtrim(str_replace(' ', '', $matches[1]), ';')
'%s="%s"',
$matches[1],
preg_replace(self::WHITESPACE_REGEX, ' ', trim($matches[2]))
),
$content
) ?? $content;
Expand Down
8 changes: 8 additions & 0 deletions src/Services/SvgOptimizerService.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
namespace MathiasReker\PhpSvgOptimizer\Services;

use MathiasReker\PhpSvgOptimizer\Contracts\Services\Providers\SvgProviderInterface;
use MathiasReker\PhpSvgOptimizer\Exception\FileNotFoundException;
use MathiasReker\PhpSvgOptimizer\Exception\IOException;
use MathiasReker\PhpSvgOptimizer\Exception\SvgValidationException;
use MathiasReker\PhpSvgOptimizer\Models\SvgOptimizer;
use MathiasReker\PhpSvgOptimizer\Services\Providers\FileProvider;
use MathiasReker\PhpSvgOptimizer\Services\Providers\StringProvider;
Expand Down Expand Up @@ -76,6 +79,9 @@ public static function fromString(string $content): self
* @param string $filePath The path to the SVG file
*
* @return static The SvgOptimizerService instance configured for file-based SVG content
*
* @throws FileNotFoundException If the specified file does not exist
* @throws IOException If the file content cannot be read
*/
public static function fromFile(string $filePath): self
{
Expand All @@ -88,6 +94,8 @@ public static function fromFile(string $filePath): self
* If no rules have been added, a default set of rules will be applied.
*
* @return $this The SvgOptimizerService instance
*
* @throws SvgValidationException If the SVG content is invalid
*/
public function optimize(): self
{
Expand Down
4 changes: 3 additions & 1 deletion src/Services/Util/DomDocumentWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ private function removeLineFeedsAndTabs(string $content): string
*
* @return \DOMDocument Returns the loaded DOMDocument
*
* @throws \RuntimeException If the XML file cannot be loaded
* @throws XmlProcessingException If the XML file cannot be loaded
*/
public function loadFromFile(string $filePath): \DOMDocument
{
Expand Down Expand Up @@ -121,6 +121,8 @@ private function createDomDocument(): \DOMDocument
* @param string $xmlContent The XML content as a string
*
* @return \DOMDocument Returns the loaded DOMDocument
*
* @throws XmlProcessingException If the XML content cannot be loaded
*/
public function loadFromString(string $xmlContent): \DOMDocument
{
Expand Down
10 changes: 5 additions & 5 deletions src/Services/Util/XmlProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
use MathiasReker\PhpSvgOptimizer\Exception\XmlProcessingException;
use MathiasReker\PhpSvgOptimizer\Services\Validators\SvgValidator;

final readonly class XmlProcessor
readonly class XmlProcessor
{
private SvgValidator $svgValidator;

Expand All @@ -31,12 +31,12 @@ public function __construct()
* function to optimize the SVG, checks the callback's result type, validates the
* optimized content, and loads the content back into the DOMDocument.
*
* @param \DOMDocument $domDocument The DOMDocument containing the SVG content to be processed.
* @param callable $callback A callable function that will be applied to optimize the SVG content.
* @param \DOMDocument $domDocument the DOMDocument containing the SVG content to be processed
* @param callable $callback a callable function that will be applied to optimize the SVG content
*
* @return string The optimized SVG content.
* @return string the optimized SVG content
*
* @throws XmlProcessingException If any error occurs while processing, validating, or loading the XML content.
* @throws XmlProcessingException if any error occurs while processing, validating, or loading the XML content
*/
public function process(\DOMDocument $domDocument, callable $callback): string
{
Expand Down
2 changes: 1 addition & 1 deletion src/Services/Validators/SvgValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

namespace MathiasReker\PhpSvgOptimizer\Services\Validators;

final class SvgValidator
class SvgValidator
{
/**
* Regular expression to match the XML declaration.
Expand Down
9 changes: 9 additions & 0 deletions tests/Unit/Services/Data/MetaDataTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ final class MetaDataTest extends TestCase

private const float EXPECTED_SAVED_PERCENTAGE = 20.0;

/**
* @throws \InvalidArgumentException
*/
public function testConstructorInvalidOriginalSize(): void
{
$this->expectException(\InvalidArgumentException::class);
Expand All @@ -42,6 +45,10 @@ public function testConstructorInvalidOriginalSize(): void
new MetaData(self::ZERO_SIZE, self::OPTIMIZED_SIZE);
}

/**
* @throws \InvalidArgumentException
* @throws \DivisionByZeroError
*/
public function testToValueObject(): void
{
$metaData = new MetaData(self::ORIGINAL_SIZE, self::OPTIMIZED_SIZE);
Expand All @@ -55,6 +62,7 @@ public function testToValueObject(): void

/**
* @throws \ReflectionException
* @throws \InvalidArgumentException
*/
public function testCalculateSavedBytes(): void
{
Expand All @@ -70,6 +78,7 @@ public function testCalculateSavedBytes(): void

/**
* @throws \ReflectionException
* @throws \InvalidArgumentException
*/
public function testCalculateSavedPercentage(): void
{
Expand Down
Loading

0 comments on commit e695970

Please sign in to comment.