webmozarts / assert

Assertions to validate method input/output with nice error messages.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Inconsistency between Assert::alpha and Assert::alnum

zerkms opened this issue · comments

The documentation states

alpha($value, $message = '') | Check that a string contains letters only
alnum($value, $message = '') | Check that a string contains letters and digits only

But then implementations are:

    public static function alpha($value, $message = '')
    {
        static::string($value);

        $locale = \setlocale(LC_CTYPE, 0);
        \setlocale(LC_CTYPE, 'C');
        $valid = !\ctype_alpha($value);
        \setlocale(LC_CTYPE, $locale);

        if ($valid) {
            static::reportInvalidArgument(\sprintf(
                $message ?: 'Expected a value to contain only letters. Got: %s',
                static::valueToString($value)
            ));
        }
    }

    public static function alnum($value, $message = '')
    {
        $locale = \setlocale(LC_CTYPE, 0);
        \setlocale(LC_CTYPE, 'C');
        $valid = !\ctype_alnum($value);
        \setlocale(LC_CTYPE, $locale);

        if ($valid) {
            static::reportInvalidArgument(\sprintf(
                $message ?: 'Expected a value to contain letters and digits only. Got: %s',
                static::valueToString($value)
            ));
        }
    }

Note that alpha accepts mixed and checks if it's a string explicitly, but alnum expects it's a string already and does not make a runtime check.

I think both documentation and implementation should be changed to be consistent.

Indeed, would be helpful if milestone was added here then.

ctype is funny in that it just returns false if the entered value is not a string. Even an object that could be cast to a string is not.

So the end result should be the same (except for integers between -128 and 255)

Yep, but isn't the general idea behind assertion libraries (in general) is: we pass you any arbitrary rubbish and if it's not what we expect - throw.

As of now - if you want to check it's an alnum in a variable - you must assert it's a string first.