Optional type PHP hint / unit testing or static analysis check?

PHP type hints do not support scalar variable [1], such as int or string

However, we found that it is still very useful to annotate the type (int or string) in our function during continuous integration to detect errors, for example.

I am currently using a type method

function foo($s) {
    //assert( is_string($s), 'not a string' );
    ...
}

During unit testing and in development mode, approval will be uncommented to identify potential errors.

I am looking to see if there is a better way to do this.

[1] http://www.php.net/manual/en/language.oop5.typehinting.php

+4
source share
3 answers

An interesting and elegant solution would be AOP. You can remove all statements from your code and start using standard phpdocs as follows:

/**
* @param string $s
*/
function foo($s) {
    ...
}

Then, during unit testing and in development mode, you use the AOP framework, like this one: http://go.aopphp.com/blog/2013/02/11/aspect-oriented-framework-for-php/

From their documentation:

... using 10-20 lines of code, we can intercept all the public, protected and static methods in all classes of the application ...

You would use it to intercept all methods on the fly, read attributes, get a ReflectionMethod object, comment on parsing type and check execution. It sounds complicated, but it's pretty easy to do.

: PHP ( ), () .

+4

, "typecheck.php" :

   assert_string($s) {  
      assert( is_string($), 'not a string');
   }

   assert_int($i) { 
     assert( is_int($i), 'not an integer);
   }

   ... lots more type checks as appropriate ...

"" "typecheck.php" - :

    require("typecheck.php");
    ...
    function foo($s) {
       assert_string($s); 
    ...

. , , , ; , , , .

; :

     assert_integer_range($i, $l, $u) {
         assert_int($i);
         assert($i>=$l);
         assert($i<=$u);
    }

     bar($n) {
         assert_integer_range($n,1,10);
     ...

, , , , .

assert_xxx , , . "typecheck.php" , , . , .

- , .

+1

, .

, :

/**
 * This function sets InternalVariable to be $s
 * @param string $s
 */
function foo($s) 
{
    ...
}

PHP_CodeSniffer, , Docblocks , , .

PHPUnit assert , - .

class FOO_TEST
{
    public function test_foo()
    {
        $TestObject = new FOO_CLASS();
        $TestObject->Foo(1);
        $this->assertTrue( is_string($TestObject->InternalString, 'Foo should have accepted a string') );
    }
}

, , , , .

PHP, SPL- PHP

/**
 * This function sets InternalVariable to be $s
 * @param SplString $s
 */
function foo(SplString $s) 
{
    ...
}

Now it will also give confirmation of compilation time.

-1
source

Source: https://habr.com/ru/post/1546453/


All Articles