Overriding functions incompatibility - php

TL;DR
I want to override offsetSet($index,$value) from ArrayObject like this: offsetSet($index, MyClass $value) but it generates a fatal error ("declaration must be compatible").
What & Why
I'm trying to create an ArrayObject child-class that forces all values to be of a certain object. My plan was to do this by overriding all functions that add values and giving them a type-hint, so you cannot add anything other than values of MyClass
How
First stop: append($value);
From the SPL:
/**
* Appends the value
* #link http://www.php.net/manual/en/arrayobject.append.php
* #param value mixed <p>
* The value being appended.
* </p>
* #return void
*/
public function append ($value) {}
My version:
/**
* #param MyClass $value
*/
public function append(Myclass $value){
parent::append($value);
}
Seems to work like a charm.
You can find and example of this working here
Second stop: offsetSet($index,$value);
Again, from the SPL:
/**
* Sets the value at the specified index to newval
* #link http://www.php.net/manual/en/arrayobject.offsetset.php
* #param index mixed <p>
* The index being set.
* </p>
* #param newval mixed <p>
* The new value for the index.
* </p>
* #return void
*/
public function offsetSet ($index, $newval) {}
And my version:
/**
* #param mixed $index
* #param Myclass $newval
*/
public function offsetSet ($index, Myclass $newval){
parent::offsetSet($index, $newval);
}
This, however, generates the following fatal error:
Fatal error: Declaration of
Namespace\MyArrayObject::offsetSet() must be
compatible with that of ArrayAccess::offsetSet()
You can see a version of this NOT working here
If I define it like this, it is fine:
public function offsetSet ($index, $newval){
parent::offsetSet($index, $newval);
}
You can see a version of this working here
Questions
Why doesn't overriding offsetSet() work with above code, but append() does?
Do I have all the functions that add objects if I add a definition of exchangeArray() next to those of append() and offsetSet()?

abstract public void offsetSet ( mixed $offset , mixed $value )
is declared by the ArrayAccess interface while public void append ( mixed $value ) doesn't have a corresponding interface. Apparently php is more "forgiving"/lax/whatever in the latter case than with interfaces.
e.g.
<?php
class A {
public function foo($x) { }
}
class B extends A {
public function foo(array $x) { }
}
"only" prints a warning
Strict Standards: Declaration of B::foo() should be compatible with A::foo($x)
while
<?php
interface A {
public function foo($x);
}
class B implements A {
public function foo(array $x) { }
}
bails out with
Fatal error: Declaration of B::foo() must be compatible with A::foo($x)

APIs should never be made more specific.
In fact, I consider it a bug that append(Myclass $value) isn't a fatal error. I consider the The fatal error on your offsetSet() as correct.
The reason for this is simple:
function f(ArrayObject $ao) {
$ao->append(5); //Error
}
$ao = new YourArrayObject();
With an append with a type requirement, that will error. Nothing looks wrong with it though. You've effectively made the API more specific, and references to the base class are no longer able to be assumed to have the expected API.
What is basically comes down to is that if an API is made more specific, that sub class is no longer compatible with it's parent class.
This odd disparity can be seen with f: it allows you to pass a Test to it but will then fail on the $ao->append(5) execution. If a echo 'hello world'; were above it, that would execute. I consider that incorrect behavior.
In a language like C++, Java or C#, this is where generics would come into play. In PHP, I'm afraid there's not a pretty solution to this. Run time checks would be nasty and error prone, and rolling your own class would completely obliterate the advantages of having ArrayObject as the base class. Unfortunately, the desire to have ArrayObject as the base class is also the problem here. It stores mixed types, so your subclasses must store mixed types as well.
You could perhaps implement that ArrayAccess interface in your own class and clearly mark that the class is only meant to be used with a certain type of object. That would still be a bit clumsy though, I fear.
Without generics, there's not a way to have a generalized homogeneous container without runtime instanceof-style checks. The only way would be to have a ClassAArrayObject, ClassBArrayObject, etc.

Related

PHP Unit mocked objects types

What is the correct way of setting a type for mocked objects?
Example code:
/**
* #dataProvider getTestDataProvider
* #throws Exception
*/
public function testExampleData(
Request $request,
Response $expected,
SomeClass $someClassMock
): void {
$result = $someClassMock->getData($request);
$this->assertEquals($expected, $result);
}
In this example the type of $someClassMock is class SomeClass. Also there is a type called MockObject which is also working properly, but it messes up the autocompletion of functions inside that class.
Which types should I use on these mocked objects? Real object class or MockObject?
What I do to make sure the auto completion works for the mocked class as well as the MockObject, is tell php that it can be either class. This adds the auto complete for both and also makes it quite understandable for anyone reading the code that it is a mock and what object it is mocking.
In your case it would look like this:
/**
* #dataProvider getTestDataProvider
* #throws Exception
*/
public function testExampleData(
Request $request,
Response $expected,
SomeClass|MockObject $someClassMock // <-- Change made here
): void {
$result = $someClassMock->getData($request);
$this->assertEquals($expected, $result);
}
You will still be passing in the MockObject, but your IDE will not complain about any unknown functions.
EDIT: To make it work with PHP versions before 8, I would suggest something like this (minimal example):
class ExampleTest extends TestCase
{
private someClass | MockObject $someClassMock;
public function setUp(): void
{
$this->someClassMock = $this->createMock(SomeClass::Class);
}
public function testMe()
{
$this->someClassMock->expects($this->once())->method('getData')->willReturn('someStuff');
}
}
In this scenario the variable $someClassMock is declared as both types and you can use it throughout your test with autocompletion for both of them. This should also work with your data provider although you might have to rewrite it slightly. I didn't include it in my example to keep it simple.

PhpStorm not finding methods in objects created by late static binding by parent abstract class

In my PHP application I have a base class for all database objects, which is further extended by specific model classes. It goes on like this (simplified):
abstract class Model extends Collection {
(...)
function __construct(string $primary_key, string $value) {
$data = MysqlDB::instance() -> select(static::TABLE, implode(',', static::COLUMNS), "$primary_key=\"$value\"");
if (count($data) != 1)
throw new ModelException('Select condition uncertain');
parent::__construct($data[0]);
}
public static function getById(string $id) : ?Model {
try {
return new static('id', $id);
} catch (ModelException $e) {
return NULL;
}
}
(...)
}
The point is, I use the getById function on child classes to obtain the needed objects. However, since the return type of getById method is Model, PhpStorm can't figure out what methods the objects has and highlights the ones I use as an error. Consequently, no type-hinting available.
For instance, assuming that final class User extends Model and that class User has method sendNotification, this kind of code:
User::getById($id) -> sendNotification($param1, $param2, ...)
has sendNotification yellowed out as though it did not exist.
I know this isn't that much of an issue, but it's really irritating in terms of that I get distracted by constant redundant warnings and that I can't use type-hinting in such a usage case.
Try with actual PHPDoc for your getById() where you specify dynamic type (e.g. #return static or #return $this).
That's the most common way of providing such "this class and its' children" typehint.
Another possible option is kind of the same .. but using PHP 7.1 functionality (so no PHPDoc blocks).
Try using self as return type instead of Model. I mean here:
public static function getById(string $id) : ?Model {
use this instead:
public static function getById(string $id) : ?self {
But for this one you should use PhpStorm 2017.2 EAP build as 2017.1.x has issues with that (see https://stackoverflow.com/a/44806801/783119 as an example).
There are three ways to achieve this, none of them has anything to do with PHPStorm.
First overwrite the method in every child with the proper return type:
/**
* #return User
*/
public static function getById(string $id) : ?Model { return parent::getById($id); }
Second add all possible children to the return tag of the abstract class.
/**
* #return Model|User|...
*/
public static function getById(string $id) : ?Model { /* ... */ }
Third add a type hint just in place:
/** #var User $user */
$user = User::getById($id);
$user->sendNotification($param1, $param2, ...);
These are not nice and hard to maintain. But there is no "setting" in PHPStorm for that.

How to indicate a parameter that "include trait" in PHPDoc

Recently I ran into an interesting situation when implementing a PHP application using PhpStorm. The following code snippet illustrates the problem.
interface I{
function foo();
}
trait T{
/**
* #return string
*/
public function getTraitMsg()
{
return "I am a trait";
}
}
class A implements I{
use T;
function foo(){}
}
class C implements I{
use T;
function foo(){}
}
class B {
/**
* #param I $input <===Is there anyway to specify that $input use T?
*/
public function doSomethingCool($input){ //An instance of "A" or "C"
$msg = $input -> getTraitMsg(); //Phpstorm freaks out here
}
}
My question is in the comment. How do I indicate that $input parameter implements I and uses T?
It's a lit bit hackly, but you can use class_uses it returns list of used traits. And add T as a #param type in PHPDoc for autocomplete
class B {
/**
* #param I|T $input <===Is there anyway to specify that $input use T?
*/
public function doSomethingCool($input){ //An instance of "A" or "C"
$uses = class_uses(get_class($input));
if (!empty($uses['T'])) {
echo $input->getTraitMsg(); //Phpstorm freaks out here
}
}
}
AFAIK you cannot type hint a trait usage in such way (#param only accepts scalar types or classes/interfaces + some keywords).
The ideal solution for you would be placing getTraitMsg() declaration into I interface.
If this cannot be done .. then you can specify that only instances of A or C can be passed here (as they utilize that trait):
/**
* #param A|C $input
*/
public function doSomethingCool($input)
{
$msg = $input->getTraitMsg(); // PhpStorm is good now
}
If names of such possible classes are unknown in advance (e.g. it's a library code and final classes could be anything in every new project or even added in current project at any time) .. then I suggest to use safeguards, which you should be using with such code anyway (via method_exists()):
/**
* #param I $input
*/
public function doSomethingCool($input)
{
if (method_exists($input, 'getTraitMsg')) {
$msg = $input->getTraitMsg(); // PhpStorm is good now
}
}
Why use safeguard? Because you may pass instance of another class K that implements I but does not use trait T. In such case code without guard will break.
Just to clarify: you could use #param I|T $input to specify that method expects instance that implements I or uses T .. but it's only works for PhpStorm (not sure about other IDEs) -- AFAIK it's not accepted by actual PHPDocumentor and does not seem to fit the PHPDoc proposed standard.
"//Phpstorm freaks out here" -- no, it's not. It just tries to signal you that your code is not correct.
The contract of method doSomethingCool() doesn't require $input to expose any method named getTraitMsg(). The docblock says it should implement interface I but the docblock is not code, it only helps PhpStorm help you with validations and suggestions.
Because you didn't type-hinted the argument $input, the code:
$b = new B();
$b->doSomethingCool(1);
is valid but it crashes as soon as it tries to execute the line $msg = $input -> getTraitMsg();.
If you want to call getTraitMsg() on $input you have to:
declare the type of $input;
make sure the declared type of $input exposes a method named getTraitMsg().
For the first step, your existing code of class B should read:
class B {
/**
* #param I $input
*/
public function doSomethingCool(I $input) {
$msg = $input -> getTraitMsg();
}
}
Please remark the type I in front of argument $input in the parameters list.
The easiest way to accomplish the next step is to declare method getTraitMsg() into the interface I:
interface I {
function foo();
function getTraitMsg();
}
Now, the code:
$b = new B();
$b->doSomethingCool(1);
throws an exception when it reaches the line $b->doSomethingCool(1); (i.e. before entering the function). It is the PHP's way to tell you the method is not invoked with the correct arguments. You have to pass it an object that implements the interface I, no matter if it is of type A or C. It can be of any other type that implements interface I and nobody cares if it uses trait T to implement it or not.

How do I stub this function in PHP

I have the following class I want to test:
<?php
namespace Freya\Component\PageBuilder\FieldHandler;
use Freya\Component\PageBuilder\FieldHandler\IFieldHandler;
/**
* Used to get a set of non empty, false or null fields.
*
* The core purpose is to use this class to determine that A) Advanced Custom Fields is installed
* and B) that we get back a set of fields for a child page.
*
* The cavete here is that this class requires you to have child pages that then have Custom Fields that
* you want to display on each of those pages. getting other page information such as content, title, featured image
* and other meta boxes is left ot the end developer.
*
* #see Freya\Component\PageBuilder\FieldHandler\IFieldHandler
*/
class FieldHandler implements IFieldHandler {
/**
* {#inheritdoc}
*
* #return bool
*/
public function checkForAFC() {
return function_exists("register_field_group");
}
/**
* {#inheritdoc}
*
* #param $childPageID - the id of the child page who may or may not have custom fields.
* #return mixed - Null or Array
*/
public function getFields($childPageId) {
$fieldsForThisPage = get_fields($childPageId);
if (is_array($fieldsForThisPage)) {
foreach ($fieldsForThisPage as $key => $value) {
if ($value === "" || $value === false || $value === null) {
unset($fieldsForThisPage[$key]);
}
}
return $fieldsForThisPage;
}
return null;
}
}
I can test all of this but one thing I want to do is stub the get_fields() function to say you will return this type of array to then be used how ever the rest of the function uses it, which in this case is looping through it.
The part I don't know how to do in php is stub a function that's being called and then say you will return x.
So how do I stub get_fields?
You cen define such function in global namespace. Take a look at the following example:
namespace {
function getFields($pageId) {
return array($pageId);
}
}
namespace MyNamespace {
class MyClass
{
public function foo(){
var_dump(getFields(5));
}
}
$obj = new MyClass();
$obj->foo();
}
And here is the output:
array(1) {
[0]=>
int(5)
}
The only issue is that this function will exist till end of script. To solve this problem you can use the tearDown method together with runkit library:
http://php.net/manual/en/function.runkit-function-remove.php
that allows you to remove user defined functions.
Unfortunatelly this library does not exist on Windows so there you won't be able to remove the definition and may consider running tests in isolation.
Edit:
You can also consider using this library (it also depends on runkit):
https://github.com/tcz/phpunit-mockfunction
You can use a trick here with the unqualified function name get_fields(). Since you don't use the fully qualified function name \get_fields() PHP will first try to find the function in the current namespace and then fall back to the global function name.
For the definition of qualified and unqualified, see: http://php.net/manual/en/language.namespaces.basics.php (it's similar to absolute and relative filenames)
So what you have to do is define the function in the namespace of the class, together with your test case, like this:
namespace Freya\Component\PageBuilder\FieldHandler;
function get_fields()
{
return ['X'];
}
class FieldHandlerTest extends \PHPUnit_Test_Case
{
...
}
Additional notes:
You can do the same with core functions, as described here: http://www.schmengler-se.de/en/2011/03/php-mocking-built-in-functions-like-time-in-unit-tests/
This trick only works with functions, not classes. Classes in the global namespace always must be referenced with leading backslash.

OOP - blank interface

Let's say that I have these two interfaces (PHP syntax)
interface Renderable_Item
{
}
interface Item_Renderer
{
function render(Renderable_Item $item);
}
I have a set of classes that are all same of a kind, but they just have nothing important (in Item_Renderer point of view) in common. All these classes implements Renderable_Item because they all should be renderable by Item_Renderer. So the Renderable_Item interface is just my way to group these classes.
Classes that implement Item_Renderer would have to first detect the concrete type, "downcast" it and then call methods of the concrete class anyway, so the interface has no meaning here, but in my opinion, it just "suits" there
Is there some better approach?
BTW, I am doing a PHP parser written in PHP. (I know there is some PHP parser in PERL and other, but just for fun .. ;))
First, I explode PHP code into structured chunks (classes that implement blank interface "Code_Chunk" (= Renderable_Item, in my example)). This is for example how class representing Assignment expression looks like -
class Assignment implements Expression
{
/**
* #var Variable
*/
private $variable;
/**
* #var Expression
*/
private $variableValue;
/**
* #return Expression
*/
public function getVariableValue()
{
return $this->variableValue;
}
/**
* #param Expression $variableValue
*/
public function setVariableValue($variableValue)
{
$this->variableValue = $variableValue;
}
/**
* #param Variable $variable
*/
public function setVariable(Variable $variable)
{
$this->variable = $variable;
}
/**
* #return Variable
*/
public function getVariable()
{
return $this->variable;
}
}
Interface Expression is by the way just another blank interface extending Code_Chunk, just to distinguish the code chunks that have some value (= expressions) from other.
However, there is nothing common between these classes that I can use except they are all some kind of "code chunk".
After this procedure, I want to rerender the whole parsed code tree, which is basically tons of structured instances of custom classes implementing Code_Chunk. Every Code_Chunk has its own rendering class (implementing Chunk_Renderer (= Item_Renderer)) accepting only that one certain chunk. For example, this is Assignment rendering class
class Assignment_Renderer implements Chunk_Renderer
{
public function render(Code_Chunk $chunk)
{
if(!($chunk instanceof Assignment)){
throw new Unexpected_Chunk_Exception($chunk);
}
/**
* #var $chunk Assignment
*/
$_ = '';
$_ .= $chunk->getVariable()->toString();
$_ .= '=';
$_ .= Chunk_Renderer_Factory::render($chunk->getVariableValue());
return $_;
}
}
Chunk_Renderer_Factory is a class holding all renderer classes as singletons and deciding, which renderer to use on which chunk.

Categories