Skip to content

Commit

Permalink
Add support for enums in error message (#292)
Browse files Browse the repository at this point in the history
  • Loading branch information
gordinskiy authored Oct 23, 2024
1 parent c4c6fb8 commit f23349f
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Assert.php
Original file line number Diff line number Diff line change
Expand Up @@ -2087,6 +2087,10 @@ protected static function valueToString($value)
return \get_class($value).': '.self::valueToString($value->format('c'));
}

if (\function_exists('enum_exists') && \enum_exists(\get_class($value))) {
return \get_class($value).'::'.$value->name;
}

return \get_class($value);
}

Expand Down
16 changes: 16 additions & 0 deletions tests/AssertTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -833,6 +833,22 @@ public function testResourceOfTypeCustomMessage(): void

Assert::resource(null, 'curl', 'I want a resource of type %2$s. Got: %s');
}

public function testEnumAssertionErrorMessage(): void
{
$enumIntroductionVersion = 80100;

if (PHP_VERSION_ID < $enumIntroductionVersion) {
$this->markTestSkipped(sprintf('This test requires php %s or upper.', $enumIntroductionVersion));
}

require_once 'DummyEnum.php';

$this->expectException('\InvalidArgumentException');
$this->expectExceptionMessage('Expected null. Got: Webmozart\Assert\Tests\TestEnum::CaseName');

Assert::null(TestEnum::CaseName, 'Expected null. Got: %s');
}
}

/**
Expand Down
9 changes: 9 additions & 0 deletions tests/DummyEnum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace Webmozart\Assert\Tests;

// The filename must be different from the class name to be ignored by composer PSR-4 autoloading rules
enum TestEnum
{
case CaseName;
}

0 comments on commit f23349f

Please # to comment.