Roave / StrictPhp

:no_entry_sign: :sparkles: :heavy_exclamation_mark: AOP-based strict type checks for PHP
MIT License
261 stars 8 forks source link

array_map(): An error occurred while invoking the map callback #52

Open janwalther opened 9 years ago

janwalther commented 9 years ago

I only tried to reproduce the examples given in the StrictPHP readme. Here is my code:

// index.php
<?php
require __DIR__.'/../vendor/autoload.php';

\StrictPhp\StrictPhpKernel::bootstrap([
                                          'debug' => true,
                                          // change this if you use this tool on multiple projects:
                                          'cacheDir' => sys_get_temp_dir(),
                                          'includePaths' => [
                                              __DIR__,
                                          ],
                                      ]);

$obj = new limetec\Test();
$obj->dummyReturn(2);

// separate file Test.php
<?php
namespace limetec;

class Test {
    /**
     * @return string
     */
    public function dummyReturn ($value) {
        return $value;
    }
}

I get the following error:

PHP Warning:  array_map(): An error occurred while invoking the map callback in /home/jan/PhpstormProjects/strictphptest/vendor/roave/strict-php/src/StrictPhp/TypeChecker/ApplyTypeChecks.php on line 79

When I call $obj->dummyReturn("2") everything works fine.

Am I doing something wrong? I would have expected a more readable exception message.

Ocramius commented 9 years ago

@janwalther the exception messages should actually be nicer, but that's not scheduled for 1.0 yet (probably going to be 2.0).

If we manage to restrict StrictPhp to PHP 7.0+ only, then we can redesign the type checkers to actually throw TypeError instances, so that would look better.

Sadly, array_map() behaves weirdly by implicitly try-catching around a exceptions (and throwing warning, sigh).

If you look further in the stack, you'll see the actual failure (currently a stupid throw new Exception('nope'))

janwalther commented 9 years ago

I could introduce a new InvalidTypeException (which extends \ErrorException to be compatible with the current implementation) and give more readable exception messages instead of "nope". Are you interested?

Instead of array_map you could use a foreach loop and wrap the try-catch around this. Or is this not possible in this case?

Ocramius commented 9 years ago

I could introduce a new InvalidTypeException (which extends \ErrorException to be compatible with the current implementation) and give more readable exception messages instead of "nope". Are you interested?

It's more interesting to see what we can do with PHP7 throwable types (you can experiment with that)

Instead of array_map you could use a foreach loop and wrap the try-catch around this. Or is this not possible in this case?

@janwalther it is possible, yes