diff --git a/phpcs.xml b/phpcs.xml index 97b6c7e..7a34bf7 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -3,67 +3,82 @@ src/ - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - - - - - - - - - - - + + + + + + + + + + + + - + @@ -71,7 +86,39 @@ - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */database/migrations/* + + diff --git a/src/BaseEnum.php b/src/BaseEnum.php index e38fc3f..1706223 100644 --- a/src/BaseEnum.php +++ b/src/BaseEnum.php @@ -2,16 +2,12 @@ namespace Kwaadpepper\Enum; -use BadMethodCallException; -use JsonSerializable; use Kwaadpepper\Enum\Exceptions\DuplicateDefinitionException; use Kwaadpepper\Enum\Exceptions\DuplicateLabelsException; use Kwaadpepper\Enum\Exceptions\DuplicateValuesException; use Kwaadpepper\Enum\Exceptions\EmptyDefinitionException; use Kwaadpepper\Enum\Exceptions\EnumNotRoutableException; use Kwaadpepper\Enum\Exceptions\UnknownEnumProperty; -use ReflectionClass; -use TypeError; /** * This Base Enum is the class which should @@ -20,18 +16,15 @@ use TypeError; * @property-read int|string $value The enum value, can be string or int * @property-read string $label The enum label, is a string */ -abstract class BaseEnum implements JsonSerializable +abstract class BaseEnum implements \JsonSerializable { - /** - * @var string|int - * @readonly + * @var string|integer */ protected $value; /** * @var string - * @readonly */ protected $label; @@ -42,13 +35,16 @@ abstract class BaseEnum implements JsonSerializable // -- ENUM MAGIC METHODS -- /** - * @param int|string $value - * @param string $label - * @throws TypeError If anything else than string or int is used for value. - * @throws EnumNotRoutableException If provided value are null + * @param integer|string $value + * @param string $label + * @throws \TypeError If anything else than string or int + * is used for value. + * @throws \Kwaadpepper\Enum\Exceptions\EnumNotRoutableException If provided value are null. + * @phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber */ public function __construct($value = null, string $label = null) { + // phpcs:ignore /** * This cannot be allowed, happens with laravel resolver * when using BaseEnum instead of BaseEnumRoutable @@ -62,8 +58,8 @@ abstract class BaseEnum implements JsonSerializable /** * @param string $attribute - * @return int|string - * @throws UnknownEnumProperty + * @return integer|string + * @throws \Kwaadpepper\Enum\Exceptions\UnknownEnumProperty As it could not be found. */ public function __get(string $attribute) { @@ -78,20 +74,22 @@ abstract class BaseEnum implements JsonSerializable /** * @param string $name - * @param array $arguments + * @param array $arguments * @return static - * @throws TypeError If anything else than string or int is used. - * @throws BadMethodCallException If a matching definition cannot be found. - * @throws EnumNotRoutableException If provided value are null + * @throws \TypeError If anything else than string or int is used. + * @throws \BadMethodCallException If a matching definition cannot be found. + * @throws \Kwaadpepper\Enum\Exceptions\EnumNotRoutableException If provided value are null. + * @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceAfterLastUsed */ - // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceAfterLastUsed public static function __callStatic(string $name, array $arguments) { + // phpcs:enable return static::make($name); } /** * Output the value as a string + * * @return string */ public function __toString(): string @@ -149,7 +147,8 @@ abstract class BaseEnum implements JsonSerializable // -- DEFINITON METHODS -- /** - * @return string[]|int[]|Closure + * Get all values + * * @return array | Closure(string):(int|string) */ protected static function values() @@ -158,7 +157,8 @@ abstract class BaseEnum implements JsonSerializable } /** - * @return string[]|Closure + * Get all labels + * * @return array | Closure(string):string */ protected static function labels() @@ -185,21 +185,23 @@ abstract class BaseEnum implements JsonSerializable /** * Parse a value to create its corresponding enumeration value. * - * @param string|int $value + * @param string|integer $value * @return static * @throws TypeError If anything else than string or int is used. - * @throws BadMethodCallException If a matching definition cannot be found. - * @throws EnumNotRoutableException If provided value are null + * @throws \BadMethodCallException If a matching definition cannot be found. + * @throws \Kwaadpepper\Enum\Exceptions\EnumNotRoutableException If provided value are null. + * @phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber */ public static function make($value): BaseEnum { + // phpcs:enable self::assertValidValue($value); $definition = static::findDefinition($value); if ($definition === null) { $enumClass = static::class; - throw new BadMethodCallException( + throw new \BadMethodCallException( "There's no value $value defined for enum $enumClass, consider adding it in the docblock definition." ); } @@ -212,16 +214,19 @@ abstract class BaseEnum implements JsonSerializable return $obj; } - public function equals(BaseEnum ...$others): bool + /** + * Test if an enum values is equal to another + * + * @param \Kwaadpepper\Enum\BaseEnum $other + * @return boolean + */ + public function equals(BaseEnum $other): bool { - foreach ($others as $other) { - // @phpcs:disable PSR2.ControlStructures.ControlStructureSpacing.SpacingAfterOpenBrace - if ( - get_class($this) === get_class($other) - && $this->value === $other->value - ) { - return true; - } + if ( + get_class($this) === get_class($other) + && $this->value === $other->value + ) { + return true; } return false; } @@ -241,7 +246,7 @@ abstract class BaseEnum implements JsonSerializable // -- PRIVATE METHODS -- /** - * @param string|int $input + * @param string|integer $input * @return \Kwaadpepper\Enum\BaseEnumDefinition|null */ private static function findDefinition($input): ?BaseEnumDefinition @@ -255,15 +260,22 @@ abstract class BaseEnum implements JsonSerializable } /** + * Resolve enum defintion + * * @return \Kwaadpepper\Enum\BaseEnumDefinition[] + * @throws \Kwaadpepper\Enum\Exceptions\EmptyDefinitionException If there is any. + * @throws \Kwaadpepper\Enum\Exceptions\DuplicateValuesException If there is any in labels map. + * @throws \Kwaadpepper\Enum\Exceptions\DuplicateValuesException If there is any in values map. + * @phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber */ private static function resolveDefinition(): array { + // phpcs:enable if (isset(self::$definitionCache[static::class])) { return self::$definitionCache[static::class]; } - $reflectionClass = new ReflectionClass(static::class); + $reflectionClass = new \ReflectionClass(static::class); $docComment = $reflectionClass->getDocComment(); preg_match_all('/@method\s+static\s+self\s+([\w_]+)\(\)/', $docComment, $matches); @@ -297,7 +309,9 @@ abstract class BaseEnum implements JsonSerializable throw new DuplicateLabelsException('You have duplicates values in enum labels method.'); } - return self::$definitionCache[static::class] = $definition; + self::$definitionCache[static::class] = $definition; + + return self::$definitionCache[static::class]; } /** @@ -322,13 +336,13 @@ abstract class BaseEnum implements JsonSerializable * * @param mixed $value * @return void - * @throws TypeError If anything else than string or int is used. + * @throws \TypeError If anything else than string or int is used. */ private static function assertValidValue($value): void { if (!(is_string($value) || is_int($value))) { $enumClass = static::class; - throw new TypeError("Only string and integer are allowed values for enum $enumClass."); + throw new \TypeError("Only string and integer are allowed values for enum $enumClass."); } } } diff --git a/src/BaseEnumDefinition.php b/src/BaseEnumDefinition.php index e07d377..fe7d77f 100644 --- a/src/BaseEnumDefinition.php +++ b/src/BaseEnumDefinition.php @@ -8,8 +8,7 @@ namespace Kwaadpepper\Enum; */ class BaseEnumDefinition { - - /** @var string|int */ + /** @var string|integer */ public $value; /** @var string */ @@ -19,9 +18,9 @@ class BaseEnumDefinition private $methodName; /** - * @param string $methodName - * @param string|int $value - * @param string $label + * @param string $methodName + * @param string|integer $value + * @param string $label */ public function __construct(string $methodName, $value, string $label) { @@ -31,8 +30,8 @@ class BaseEnumDefinition } /** - * @param string|int $input - * @return bool + * @param string|integer $input + * @return boolean */ public function equals($input): bool { diff --git a/src/BaseEnumRoutable.php b/src/BaseEnumRoutable.php index 9e2e8cd..4a5bb75 100644 --- a/src/BaseEnumRoutable.php +++ b/src/BaseEnumRoutable.php @@ -29,37 +29,43 @@ abstract class BaseEnumRoutable extends BaseEnum implements UrlRoutable /** * Get the route key for the model. * + * @phpcs:disable Squiz.Commenting.FunctionComment.InvalidNoReturn + * * @return string + * @throws \Kwaadpepper\Enum\Exceptions\NotImplementedException GetRouteKeyName not implemented, + * should not be used. */ public function getRouteKeyName() { + // phpcs:enable // @codeCoverageIgnoreStart - throw new NotImplementedException('getRouteKeyName not implemented, should not be used.'); + throw new NotImplementedException('GetRouteKeyName not implemented, should not be used.'); // @codeCoverageIgnoreEnd } /** * Retrieve the model for a bound value. * - * @param mixed $value - * @param string|null $field + * @param mixed $value + * @param string|null $field * @return \Kwaadpepper\Enum\BaseEnum|null + * @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassAfterLastUsed */ - // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassAfterLastUsed public function resolveRouteBinding($value, $field = null) { - // try to cast numeric value first + // phpcs:enable + // Try to cast numeric value first. try { - // try cast to int + // Try cast to int. $iValue = (is_numeric($value) and floatval(intval($value)) === floatval($value)) ? (int)$value : $value; return static::make($iValue); } catch (BadMethodCallException | EnumNotRoutableException | TypeError $e) { - // try string value after that + // Try string value after that. try { return static::make($value); } catch (BadMethodCallException | EnumNotRoutableException | TypeError $e) { - // could not find a suitable value + // Could not find a suitable value. return null; } } @@ -68,16 +74,21 @@ abstract class BaseEnumRoutable extends BaseEnum implements UrlRoutable /** * Retrieve the child model for a bound value. * - * @param string $childType - * @param mixed $value - * @param string|null $field + * @phpcs:disable Squiz.Commenting.FunctionComment.InvalidNoReturn + * + * @param string $childType + * @param mixed $value + * @param string|null $field * @return \Illuminate\Database\Eloquent\Model|null - * @throws NotImplementedException + * @throws \Kwaadpepper\Enum\Exceptions\NotImplementedException ResolveChildRouteBinding not implemented, + * should not be used. + * @phpcs:disable Squiz.Commenting.FunctionComment.ScalarTypeHintMissing */ public function resolveChildRouteBinding($childType, $value, $field) { + // phpcs:enable // @codeCoverageIgnoreStart - throw new NotImplementedException('resolveChildRouteBinding not implemented, should not be used.'); + throw new NotImplementedException('ResolveChildRouteBinding not implemented, should not be used.'); // @codeCoverageIgnoreEnd } } diff --git a/src/Console/CreateEnum.php b/src/Console/CreateEnum.php index 30d8ce1..701a4e1 100644 --- a/src/Console/CreateEnum.php +++ b/src/Console/CreateEnum.php @@ -7,14 +7,29 @@ use Illuminate\Support\Facades\File; class CreateEnum extends Command { - + /** + * The name and signature of the console command. + * + * @var string + */ protected $signature = 'make:enum'; + /** + * The console command description. + * + * @var string + */ protected $description = 'Create a new enum class'; - // phpcs:ignore Generic.Metrics.CyclomaticComplexity.TooHigh + /** + * Handle the command + * + * @return integer|void + * @phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh + */ public function handle() { + // phpcs:enable $validate = false; $info = [ 'name' => false, @@ -108,6 +123,13 @@ class CreateEnum extends Command $this->info(\sprintf('File generated %s', \app_path("Enums/$name.php"))); } + /** + * Replace the class name + * + * @param string $templateEnum + * @param array $info + * @return void + */ private function replaceClassName(string &$templateEnum, array $info): void { $targetDefinition = "class TemplateEnum"; @@ -116,6 +138,13 @@ class CreateEnum extends Command $templateEnum = str_replace($targetDefinition, $replaceDefinition, $templateEnum); } + /** + * Replace definition + * + * @param string $templateEnum + * @param array $info + * @return void + */ private function replaceDefinition(string &$templateEnum, array $info): void { $targetDefinition = " * ##VALUES\n"; @@ -129,6 +158,13 @@ class CreateEnum extends Command $templateEnum = str_replace($targetDefinition, $replaceDefinition, $templateEnum); } + /** + * Insert lables and values + * + * @param string $templateEnum + * @param array $info + * @return void + */ private function insertLabelsAndValues(string &$templateEnum, array $info): void { $targetDefinition = " // ##OVERRIDE\n"; diff --git a/src/EnumServiceProvider.php b/src/EnumServiceProvider.php index 4721719..329cacb 100644 --- a/src/EnumServiceProvider.php +++ b/src/EnumServiceProvider.php @@ -20,7 +20,7 @@ class EnumServiceProvider extends ServiceProvider __DIR__ . '/../resources/lang' => resource_path('lang/vendor/enum'), ]); - // Register the command if we are using the application via the CLI + // Register the command if we are using the application via the CLI. if ($this->app->runningInConsole()) { $this->commands([ CreateEnum::class, diff --git a/src/Exceptions/DuplicateDefinitionException.php b/src/Exceptions/DuplicateDefinitionException.php index 0da3b63..27a8ed3 100644 --- a/src/Exceptions/DuplicateDefinitionException.php +++ b/src/Exceptions/DuplicateDefinitionException.php @@ -12,5 +12,4 @@ use Exception; */ class DuplicateDefinitionException extends Exception { - // } diff --git a/src/Exceptions/DuplicateLabelsException.php b/src/Exceptions/DuplicateLabelsException.php index 07e2978..bf9316b 100644 --- a/src/Exceptions/DuplicateLabelsException.php +++ b/src/Exceptions/DuplicateLabelsException.php @@ -12,5 +12,4 @@ use Exception; */ class DuplicateLabelsException extends Exception { - // } diff --git a/src/Exceptions/DuplicateValuesException.php b/src/Exceptions/DuplicateValuesException.php index f5cd5ca..3e5ea1b 100644 --- a/src/Exceptions/DuplicateValuesException.php +++ b/src/Exceptions/DuplicateValuesException.php @@ -9,7 +9,7 @@ use Exception; * contain multiple times the same value * * This should only happen if you override the values method - */ class DuplicateValuesException extends Exception + */ +class DuplicateValuesException extends Exception { - // } diff --git a/src/Exceptions/EmptyDefinitionException.php b/src/Exceptions/EmptyDefinitionException.php index c0f008c..c73f866 100644 --- a/src/Exceptions/EmptyDefinitionException.php +++ b/src/Exceptions/EmptyDefinitionException.php @@ -12,5 +12,4 @@ use Exception; */ class EmptyDefinitionException extends Exception { - // } diff --git a/src/Exceptions/EnumNotRoutableException.php b/src/Exceptions/EnumNotRoutableException.php index 6c4c9c6..8c55fd6 100644 --- a/src/Exceptions/EnumNotRoutableException.php +++ b/src/Exceptions/EnumNotRoutableException.php @@ -12,5 +12,4 @@ use Exception; */ class EnumNotRoutableException extends Exception { - // } diff --git a/src/Exceptions/NotImplementedException.php b/src/Exceptions/NotImplementedException.php index 1ca37db..1cdc132 100644 --- a/src/Exceptions/NotImplementedException.php +++ b/src/Exceptions/NotImplementedException.php @@ -11,5 +11,4 @@ use Exception; */ class NotImplementedException extends Exception { - // } diff --git a/src/Exceptions/UnknownEnumClass.php b/src/Exceptions/UnknownEnumClass.php index 09ce7f9..fa71165 100644 --- a/src/Exceptions/UnknownEnumClass.php +++ b/src/Exceptions/UnknownEnumClass.php @@ -6,5 +6,4 @@ use Exception; class UnknownEnumClass extends Exception { - // } diff --git a/src/Exceptions/UnknownEnumProperty.php b/src/Exceptions/UnknownEnumProperty.php index 661db7b..66b9e0c 100644 --- a/src/Exceptions/UnknownEnumProperty.php +++ b/src/Exceptions/UnknownEnumProperty.php @@ -10,9 +10,19 @@ use Exception; */ class UnknownEnumProperty extends Exception { - + /** + * The error message + * + * @var string + */ protected $message; + /** + * Construct the exception. Note: The message is NOT binary safe. + * + * @param string $attribute + * @return void + */ public function __construct(string $attribute) { $this->message = "Unknown attribute $attribute, enumeration only have propeties `label` and `value`."; diff --git a/src/Rules/BaseEnumRule.php b/src/Rules/BaseEnumRule.php index 9c8a7e5..eb2b5a8 100644 --- a/src/Rules/BaseEnumRule.php +++ b/src/Rules/BaseEnumRule.php @@ -8,7 +8,6 @@ use Kwaadpepper\Enum\Exceptions\UnknownEnumClass; abstract class BaseEnumRule implements Rule { - /** @var string $enum */ protected $enumClass; @@ -18,6 +17,7 @@ abstract class BaseEnumRule implements Rule * * @param string $enumClass * @return void + * @throws \Kwaadpepper\Enum\Exceptions\UnknownEnumClass If the class passed is not an enum. */ public function __construct(string $enumClass) { @@ -30,11 +30,13 @@ abstract class BaseEnumRule implements Rule /** * Determine if the validation rule passes. * - * @param string $attribute + * @param string $attribute * @param mixed $value - * @return bool + * @return boolean + * @phpcs:disable Squiz.Commenting.FunctionComment.ScalarTypeHintMissing */ abstract public function passes($attribute, $value): bool; + // phpcs:enable /** * Get the validation error message. diff --git a/src/Rules/EnumIsValidRule.php b/src/Rules/EnumIsValidRule.php index 462eb0f..09e3d44 100644 --- a/src/Rules/EnumIsValidRule.php +++ b/src/Rules/EnumIsValidRule.php @@ -10,19 +10,20 @@ use TypeError; */ class EnumIsValidRule extends BaseEnumRule { - /** * Determine if the validation rule passes. * - * @param string $attribute + * @param string $attribute * @param mixed $value - * @return bool + * @return boolean + * @phpcs:disable Squiz.Commenting.FunctionComment.ScalarTypeHintMissing + * @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed */ - // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed public function passes($attribute, $value): bool { + // phpcs:enable try { - // try cast to int if is int + // Try cast to int if is int. $value = (is_numeric($value) and floatval(intval($value)) === floatval($value)) ? (int)$value : $value; forward_static_call([$this->enumClass, 'make'], $value); diff --git a/src/Traits/CastsEnums.php b/src/Traits/CastsEnums.php index 7b89a76..1604480 100644 --- a/src/Traits/CastsEnums.php +++ b/src/Traits/CastsEnums.php @@ -2,10 +2,8 @@ namespace Kwaadpepper\Enum\Traits; -use BadMethodCallException; use Illuminate\Support\Facades\Log; use Kwaadpepper\Enum\BaseEnum; -use TypeError; /** * @property array $attributes Laravel model attributes @@ -15,15 +13,16 @@ use TypeError; */ trait CastsEnums { - /** * Get a plain attribute (not a relationship). * - * @param string $key + * @param string $key * @return mixed + * @phpcs:disable Squiz.Commenting.FunctionComment.ScalarTypeHintMissing */ public function getAttributeValue($key) { + // phpcs:enable $value = parent::getAttributeValue($key); if ($this->hasEnumCast($key)) { @@ -36,18 +35,20 @@ trait CastsEnums /** * Set a given attribute on the model. * - * @param string $key + * @param string $key * @param mixed $value * @return $this + * @throws \TypeError If cast fails. + * @throws \BadMethodCallException If cast fails. */ - public function setAttribute($key, $value) + public function setAttribute(string $key, $value) { try { if ($enum = $this->castToEnum($key, $value) and $enum instanceof BaseEnum) { $this->attributes[$key] = $enum->value; return $this; } - } catch (TypeError | BadMethodCallException $e) { + } catch (\TypeError | \BadMethodCallException $e) { Log::debug(\sprintf('%s : trait CastEnums error, %s', __CLASS__, $e->getMessage())); if (in_array(config('app.env'), ['debug', 'testing'])) { throw $e; @@ -61,13 +62,15 @@ trait CastsEnums /** * Determine whether an attribute should be cast to a enum. * - * @param string $key - * @return bool + * @param string $key + * @return boolean */ - public function hasEnumCast($key): bool + public function hasEnumCast(string $key): bool { - // This can happen if this trait is added to the model - // but no enum casts have been added yet + /** + * This can happen if this trait is added to the model + * but no enum casts have been added yet. + */ if ($this->enumCasts === null) { return false; } @@ -79,13 +82,13 @@ trait CastsEnums /** * Casts the given key to an enum instance * - * @param string $key + * @param string $key * @param mixed $value * @return \Kwaadpepper\Enum\BaseEnum|mixed|null * @throws TypeError — If anything else than string or int is used. * @throws BadMethodCallException — If a matching definition cannot be found. */ - protected function castToEnum($key, $value) + protected function castToEnum(string $key, $value) { if ( $value === null or @@ -99,7 +102,7 @@ trait CastsEnums $value = $this->castAttribute($key, $value); } - // try cast to int + // Try cast to int. $value = (is_numeric($value) and floatval(intval($value)) === floatval($value)) ? (int)$value : $value; diff --git a/tests/BaseEnumRoutableTest.php b/tests/BaseEnumRoutableTest.php index 45ace2c..227a080 100644 --- a/tests/BaseEnumRoutableTest.php +++ b/tests/BaseEnumRoutableTest.php @@ -16,18 +16,19 @@ use Kwaadpepper\Enum\Tests\Models\Alarm; use Kwaadpepper\Enum\Tests\Models\Journal; use Kwaadpepper\Enum\Tests\Models\Report; use Orchestra\Testbench\TestCase; -use SplFileObject; class BaseEnumRoutableTest extends TestCase { /** * Defines aliases * - * @param [type] $app + * @param \Illuminate\Foundation\Application $app * @return void + * @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing */ protected function getPackageAliases($app) { + // phpcs:enable $app->alias(Alarm::class, 'Alarm'); $app->alias(Journal::class, 'Journal'); $app->alias(Report::class, 'Report'); @@ -40,13 +41,15 @@ class BaseEnumRoutableTest extends TestCase /** * Get package providers. * - * @param \Illuminate\Foundation\Application $app + * @param \Illuminate\Foundation\Application $app * * @return array + * @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing + * @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass */ - // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass protected function getPackageProviders($app) { + // phpcs:enable return [ 'Kwaadpepper\Enum\EnumServiceProvider', ]; @@ -110,12 +113,14 @@ class BaseEnumRoutableTest extends TestCase /** * Define routes setup. * - * @param \Illuminate\Routing\Router $router + * @param \Illuminate\Routing\Router $router * * @return void + * @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing */ protected function defineRoutes($router) { + // phpcs:enable $router->get('/journals/{journal}', function (Journal $journal) { return response()->json([$journal->day]); })->middleware('bindings')->name('journal.view'); @@ -143,6 +148,11 @@ class BaseEnumRoutableTest extends TestCase })->middleware('bindings'); } + /** + * Test route values + * + * @return void + */ public function testRoutesDays() { $response = $this->json('GET', sprintf('/days/%s', Days::none()->value)); @@ -153,6 +163,11 @@ class BaseEnumRoutableTest extends TestCase $response->assertExactJson([Days::mon()]); } + /** + * Test route with example civilities + * + * @return void + */ public function testRoutesCivilities() { $response = $this->json('GET', sprintf('/civilities/%s', ContactFormCivility::mme()->value)); @@ -160,6 +175,11 @@ class BaseEnumRoutableTest extends TestCase $response->assertExactJson([ContactFormCivility::mme()]); } + /** + * Test route with enum as string + * + * @return void + */ public function testRoutesWithEnumIntString() { $response = $this->json('GET', sprintf('/force/%s', ForceStringsFromInteger::valueB()->value)); @@ -167,12 +187,22 @@ class BaseEnumRoutableTest extends TestCase $response->assertExactJson([ForceStringsFromInteger::valueB()]); } + /** + * Test route with enum not found + * + * @return void + */ public function testRoutesWithEnumNotFound() { $response = $this->json('GET', '/force/6'); $response->assertNotFound(); } + /** + * Test routes with enums as pk + * + * @return void + */ public function testRoutesWithEnumAsPrimaryKey() { $response = $this->json('GET', sprintf('/reports/%s', Days::none()->value)); @@ -187,6 +217,11 @@ class BaseEnumRoutableTest extends TestCase $response->assertNotFound(); } + /** + * Test routes with enum as pk without cast enums + * + * @return void + */ public function testRoutesWithEnumAsPrimaryKeyWithoutCastEnums() { $response = $this->json('GET', sprintf('/alarms/%s', Days::none()->value)); @@ -201,9 +236,15 @@ class BaseEnumRoutableTest extends TestCase $response->assertNotFound(); } + /** + * Test routes wit henum as pk without cast enums + * + * ! This test includes getRouteKey method for coverage + * + * @return void + */ public function testRoutesWithEnumAsPrimaryKeyWithoutCastEnumsAndCast() { - // This test includes getRouteKey method for coverage $response = $this->json('GET', \route('journal.view', Days::none())); $response->assertOk(); $response = $this->json('GET', \route('journal.view', Days::mon())); @@ -216,6 +257,11 @@ class BaseEnumRoutableTest extends TestCase $response->assertNotFound(); } + /** + * Test enum is valid rule + * + * @return void + */ public function testRules() { $rule = new EnumIsValidRule(Days::class); @@ -224,24 +270,45 @@ class BaseEnumRoutableTest extends TestCase $this->assertFalse($rule->passes('day', Days::mon())); } + /** + * Test route with enum + * + * @return void + */ public function testRulesRequest() { $response = $this->json('GET', sprintf('/day-validation?day=%s', Days::fri()->value)); $response->assertOk(); } + /** + * Test route fails on non enum + * + * @return void + */ public function testRulesRequestFail() { $response = $this->json('GET', sprintf('/day-validation?day=%s', '"!:')); $response->assertJsonValidationErrors('day'); } + /** + * Test Enum validate enum class on non enum class + * + * @return void + */ public function testRulesRequestInvalid() { $this->expectException(UnknownEnumClass::class); - new EnumIsValidRule(SplFileObject::class); + new EnumIsValidRule(\SplFileObject::class); } + + /** + * Test enum is not routable + * + * @return void + */ public function testNotRoutableEnum() { $response = $this->json('GET', sprintf('/notroutable/%s', '1')); diff --git a/tests/BaseEnumTest.php b/tests/BaseEnumTest.php index df3221b..56fd4e3 100644 --- a/tests/BaseEnumTest.php +++ b/tests/BaseEnumTest.php @@ -19,6 +19,11 @@ use TypeError; class BaseEnumTest extends TestCase { + /** + * Test enum + * + * @return void + */ public function testEnum() { $mon = Days::mon(); @@ -28,13 +33,13 @@ class BaseEnumTest extends TestCase Days::toLabels(); json_encode($tue); - // basic tests + // Basic tests. $this->assertEquals('Monday', $mon->label, 'Days::mon()->value should be equals to `Monday`'); $this->assertEquals(2, $mon->value, 'Days::mon()->value should be equals to `2`'); - $this->assertClassHasAttribute('value', Days::class, 'Days should have a value property'); - $this->assertClassHasAttribute('label', Days::class, 'Days should have a label property'); + $this->assertTrue(\property_exists(Days::class, 'value'), 'Days should have a value property'); + $this->assertTrue(\property_exists(Days::class, 'label'), 'Days should have a label property'); - // undef prop test + // Undef prop test. $exception = null; try { $mon->propthatdontexists; @@ -92,18 +97,32 @@ class BaseEnumTest extends TestCase ); } + /** + * Test cannot assign an enum value + * + * @return void + */ public function testCannotAssignAnEnumValue() { - $this->expectError(); + $this->setUp(); + $this->expectException(\Error::class); $enum = Days::mon(); $enum->value = 'anything'; + $this->tearDown(); } + /** + * Test cannot assign an enum label + * + * @return void + */ public function testCannotAssignAnEnumLabel() { - $this->expectError(); + $this->setUp(); + $this->expectException(\Error::class); $enum = Days::mon(); $enum->label = 'anything'; + $this->tearDown(); } /** @@ -125,6 +144,11 @@ class BaseEnumTest extends TestCase ); } + /** + * Test setting enum value onto model prop + * + * @return void + */ public function testValidEnumSet() { $this->expectNotToPerformAssertions(); @@ -133,6 +157,11 @@ class BaseEnumTest extends TestCase $report->day = Days::mon()->value; } + /** + * Test setting invalid enum value onto model prop + * + * @return void + */ public function testInvalidEnumSet() { $this->expectException(BadMethodCallException::class); @@ -140,6 +169,11 @@ class BaseEnumTest extends TestCase $report->day = Days::mon()->label; } + /** + * Test setting prop enum with float (invalid) + * + * @return void + */ public function testInvalidEnumSetWithFloat() { $this->expectException(TypeError::class); @@ -147,6 +181,11 @@ class BaseEnumTest extends TestCase $report->day = 0.1; } + /** + * Test setting invalid enum prop with object + * + * @return void + */ public function testInvalidEnumSetNotAuthorizedType() { $this->expectException(TypeError::class); @@ -154,6 +193,11 @@ class BaseEnumTest extends TestCase $report->day = new stdClass(); } + /** + * Test setting enum prop with null as valid + * + * @return void + */ public function testInvalidEnumCanSetNull() { $this->expectNotToPerformAssertions(); @@ -161,15 +205,50 @@ class BaseEnumTest extends TestCase $report->day = null; } + /** + * Test enum has duplicated values + * + * @return void + */ public function testDuplicatedValues() { $this->expectException(DuplicateValuesException::class); DuplicatedValues::one(); } + /** + * Test enm has duplicated labels + * + * @return void + */ public function testDuplicatedLabels() { $this->expectException(DuplicateLabelsException::class); DuplicatedLabels::one(); } + + /** + * Setup custom phpunit catch for deprecated error cathing. + * + * @return void + */ + public function setUp(): void + { + set_error_handler( + static function ($errno, $errstr) { + throw new \Exception($errstr, $errno); + }, + E_ALL + ); + } + + /** + * Restore phpunit handler + * + * @return void + */ + public function tearDown(): void + { + restore_error_handler(); + } } diff --git a/tests/Enums/ContactFormCivility.php b/tests/Enums/ContactFormCivility.php index 54b1b5f..18b1ede 100644 --- a/tests/Enums/ContactFormCivility.php +++ b/tests/Enums/ContactFormCivility.php @@ -11,6 +11,11 @@ use Kwaadpepper\Enum\BaseEnumRoutable; */ final class ContactFormCivility extends BaseEnumRoutable { + /** + * Output the value as a string + * + * @return string + */ public function __toString(): string { return (string)$this->label; diff --git a/tests/Enums/Days.php b/tests/Enums/Days.php index db83d77..a4b69be 100644 --- a/tests/Enums/Days.php +++ b/tests/Enums/Days.php @@ -16,6 +16,11 @@ use Kwaadpepper\Enum\BaseEnumRoutable; */ final class Days extends BaseEnumRoutable { + /** + * All values + * + * @return array + */ protected static function values(): array { return [ @@ -30,6 +35,11 @@ final class Days extends BaseEnumRoutable ]; } + /** + * All labels + * + * @return array + */ protected static function labels(): array { return [ @@ -44,6 +54,11 @@ final class Days extends BaseEnumRoutable ]; } + /** + * Output the value as a string + * + * @return string + */ public function __toString(): string { return (string)$this->label; @@ -52,7 +67,7 @@ final class Days extends BaseEnumRoutable /** * Checks if days contain this day * - * @param int $days + * @param integer $days * @return boolean */ public function has(int $days) diff --git a/tests/Enums/DuplicatedLabels.php b/tests/Enums/DuplicatedLabels.php index 0001202..845a0e6 100644 --- a/tests/Enums/DuplicatedLabels.php +++ b/tests/Enums/DuplicatedLabels.php @@ -11,6 +11,11 @@ use Kwaadpepper\Enum\BaseEnumRoutable; */ final class DuplicatedLabels extends BaseEnumRoutable { + /** + * All labels + * + * @return array + */ protected static function labels(): array { return [ diff --git a/tests/Enums/DuplicatedValues.php b/tests/Enums/DuplicatedValues.php index b7a7df8..6578a93 100644 --- a/tests/Enums/DuplicatedValues.php +++ b/tests/Enums/DuplicatedValues.php @@ -11,6 +11,11 @@ use Kwaadpepper\Enum\BaseEnumRoutable; */ final class DuplicatedValues extends BaseEnumRoutable { + /** + * All values + * + * @return array + */ protected static function values(): array { return [ diff --git a/tests/Enums/ForceStringsFromInteger.php b/tests/Enums/ForceStringsFromInteger.php index 53dec4c..07b3c73 100644 --- a/tests/Enums/ForceStringsFromInteger.php +++ b/tests/Enums/ForceStringsFromInteger.php @@ -11,6 +11,11 @@ use Kwaadpepper\Enum\BaseEnumRoutable; */ final class ForceStringsFromInteger extends BaseEnumRoutable { + /** + * All values + * + * @return array + */ protected static function values(): array { return [ diff --git a/tests/Enums/NotRoutableEnum.php b/tests/Enums/NotRoutableEnum.php index 50ec920..5288cd1 100644 --- a/tests/Enums/NotRoutableEnum.php +++ b/tests/Enums/NotRoutableEnum.php @@ -11,6 +11,11 @@ use Kwaadpepper\Enum\BaseEnum; */ final class NotRoutableEnum extends BaseEnum { + /** + * All values + * + * @return array + */ protected static function values(): array { return [ diff --git a/tests/Models/Alarm.php b/tests/Models/Alarm.php index c12a0ec..e48fc1d 100644 --- a/tests/Models/Alarm.php +++ b/tests/Models/Alarm.php @@ -9,14 +9,39 @@ class Alarm extends Model { use CastsEnums; + /** + * Indicates if the model should be timestamped. + * + * @var boolean + */ public $timestamps = false; + /** + * The primary key for the model. + * + * @var string + */ protected $primaryKey = 'day'; + /** + * The "type" of the primary key ID. + * + * @var string + */ protected $keyType = 'int'; + /** + * Indicates if the IDs are auto-incrementing. + * + * @var boolean + */ public $incrementing = false; + /** + * The attributes that are mass assignable. + * + * @var string[] + */ protected $fillable = [ 'day' ]; diff --git a/tests/Models/Journal.php b/tests/Models/Journal.php index f3f8f1b..aa3e0a1 100644 --- a/tests/Models/Journal.php +++ b/tests/Models/Journal.php @@ -10,22 +10,57 @@ class Journal extends Model { use CastsEnums; + /** + * The attributes that are mass assignable. + * + * @var boolean + */ public $timestamps = false; + /** + * The primary key for the model. + * + * @var string + */ protected $primaryKey = 'day'; + /** + * The "type" of the primary key ID. + * + * @var string + */ protected $keyType = 'int'; + /** + * Indicates if the IDs are auto-incrementing. + * + * @var boolean + */ public $incrementing = false; + /** + * The attributes that are mass assignable. + * + * @var string[] + */ protected $fillable = [ 'day' ]; + /** + * The attributes that should be cast. + * + * @var string[] + */ protected $casts = [ 'day' => 'int' ]; + /** + * The attributes that should be to enum. + * + * @var string[] + */ protected $enumCasts = [ 'day' => Days::class ]; diff --git a/tests/Models/Report.php b/tests/Models/Report.php index 763d673..c7cfb2a 100644 --- a/tests/Models/Report.php +++ b/tests/Models/Report.php @@ -10,18 +10,48 @@ class Report extends Model { use CastsEnums; + /** + * Indicates if the model should be timestamped. + * + * @var boolean + */ public $timestamps = false; + /** + * The primary key for the model. + * + * @var string + */ protected $primaryKey = 'day'; + /** + * The "type" of the primary key ID. + * + * @var string + */ protected $keyType = 'int'; + /** + * Indicates if the IDs are auto-incrementing. + * + * @var boolean + */ public $incrementing = false; + /** + * The attributes that are mass assignable. + * + * @var string[] + */ protected $fillable = [ 'day' ]; + /** + * The attributes that should be to enum. + * + * @var string[] + */ protected $enumCasts = [ 'day' => Days::class ]; diff --git a/tests/Requests/PassDayRequest.php b/tests/Requests/PassDayRequest.php index 5e8fcbb..9389f70 100644 --- a/tests/Requests/PassDayRequest.php +++ b/tests/Requests/PassDayRequest.php @@ -11,7 +11,7 @@ class PassDayRequest extends FormRequest /** * Determine if the user is authorized to make this request. * - * @return bool + * @return boolean */ public function authorize() {