php-src icon indicating copy to clipboard operation
php-src copied to clipboard

Classes extending `IteratorAggregate` can not implement `RecursiveIterator`

Open ghostwriter opened this issue 4 years ago • 8 comments

Description

To recursively iterate over a SplFixedArray, to save memory and improve performance.

Is this intended, or a bug? https://3v4l.org/ufapQ

  • SplFixedArray (extends IteratorAggregate )
  • RecursiveIterator (extends Iterator).

The following code:

<?php
class RecursiveFixedArray extends SplFixedArray implements RecursiveIterator
{
    public function getChildren(): ?RecursiveIterator
    {
        return $this->current();
    }

    public function hasChildren(): bool
    {
        return $this->current() instanceof RecursiveFixedArray;
    }
}

Resulted in this output:

Fatal error: Class RecursiveFixedArray cannot implement both Iterator and IteratorAggregate at the same time

But I expected this output instead:

// No error

PHP Version

8.0.1 - 8.0.16, 8.1.0 - 8.1.3

Operating System

No response

ghostwriter avatar Feb 28 '22 00:02 ghostwriter

Is this intended, or a bug?

Is what intended or a bug?

If you want a "recursive fixed array" based on SplFixedArray then you can override getIterator to return a RecursiveArrayIterator.

damianwadley avatar Feb 28 '22 00:02 damianwadley

Is what intended or a bug?

Is the behavior described above, intended or a bug?

Before PHP 8.0, you did not need to return RecursiveArrayIterator, you only had to implement RecursiveIterator interface.

why doesn't this code work on >= 8.0.x?

  • This behavior is not documented
  • This change in behavior was not discussed or documented

ghostwriter avatar Feb 28 '22 00:02 ghostwriter

There are multiple issues in here that you might be asking about: whether SplFixedArray should be an IteratorAggregate, whether implementing both Iterator and IteratorAggregate is a problem, whether the conflict should be reported as a fatal error... Apparently you asked about the first one.

Yes: as of PHP 8.0, SplFixedArray uses IteratorAggregate instead of Iterator. https://www.php.net/manual/en/migration80.incompatible.php#migration80.incompatible.spl

damianwadley avatar Feb 28 '22 02:02 damianwadley

Implementing both Iterator and IteratorAggregate is a problem, because they are identical behaviors that are interchangeable.

A Fatal error thrown when both Iterator and IteratorAggregate are implemented on the same class is acceptable.

A Fatal error thrown when an IteratorAggregate and an interface that extends Iterator is implemented on the same class is undesired. eg RecursiveIterator

  • why is implementing IteratorAggregate not sufficient for RecursiveIterator's request for an Iterator?
  • was this change in behavior discussed anywhere? to read and learn why this current behavior is preferable.
  • why is this behavior is not documented, if it is in fact the intended behavior? if "help wanted", where can we find instructions on how we can contribute?

If you're willing to discuss, reopen this issue.

ghostwriter avatar Feb 28 '22 04:02 ghostwriter

I don't mind replying but I don't think there's anything actionable here...

Implementing both Iterator and IteratorAggregate is a problem, because they are identical behaviors that are interchangeable.

They aren't identical behaviors. They're both iterable but they go about it two completely different ways: one of them means the object modifies itself during iteration, and the other means the object remains unchanged because it uses a proxy object to handle iteration (which does gets modified).

That self-modification can be a significant problem if you aren't careful. For example, this code

<?php

function print_directory($iterator) {
	foreach ($iterator as $file) {
		if ($file->isDir()) {
			echo "{$file} is dir containing:\n";
			print_directory($file);
		} else {
			echo "{$file} is file\n";
		}
	}
}

$root = new DirectoryIterator(".");
print_directory($root);

?>

may look fine but it will not work because $root, $iterator, and $file are all the same object. Classes using IteratorAggregate don't have that problem (not unless they try to) because the object used for iteration is something separate.

A Fatal error thrown when both Iterator and IteratorAggregate are implemented on the same class is acceptable.

A Fatal error thrown when an IteratorAggregate and an interface that extends Iterator is implemented on the same class is undesired. eg RecursiveIterator

I don't see how you can make the first statement and also make the second statement. Iterator and IteratorAggregate are two separate mechanisms for iteration so it logically does not make sense to support both. It doesn't matter where in the inheritance hierarchy Iterator and IteratorAggregate are introduced, the end result is that the resultant class would have support for both mechanisms. And there's no way to "un-implement" an interface.

why is this behavior is not documented, if it is in fact the intended behavior?

It is documented. I gave you a link to a section in the PHP 8.0 migration guide where one of the bullet points says exactly this happened:

SplFixedArray is now an IteratorAggregate and not an Iterator. SplFixedArray::rewind(), SplFixedArray::current(), SplFixedArray::key(), SplFixedArray::next(), and SplFixedArray::valid() have been removed. In their place, SplFixedArray::getIterator() has been added. Any code which uses explicit iteration over SplFixedArray must now obtain an Iterator through SplFixedArray::getIterator(). This means that SplFixedArray is now safe to use in nested loops.

Note that SplFixedArray's Changelog incorrectly states IteratorAggregate was added in 8.1 (and I created an issue for that), but the most important documentation to check for large changes like this is still the migration guide.

damianwadley avatar Feb 28 '22 05:02 damianwadley

First, thank you for taking the time to answer my questions. You're an amazing human being, thank you. I've learned and corrected some of the things I originally misunderstood.


Iterator and IteratorAggregate are two separate mechanisms for iteration so it logically does not make sense to support both.

Agreed.

They aren't identical behaviors. They're both iterable but they go about it two completely different ways: one of them means the object modifies itself during iteration, and the other means the object remains unchanged because it uses a proxy object to handle iteration (which does gets modified).

I misspoke when I said "they are identical behaviors", I meant, they're both Traversable.

interface Traversable {
}

interface IteratorAggregate extends Traversable {
    /* Methods */
    public getIterator(): Traversable
}

interface Iterator extends Traversable {
    /* Methods */
    public current(): mixed
    public key(): mixed
    public next(): void
    public rewind(): void
    public valid(): bool
}

My understanding was that, IteratorAggregate is an internal decorator/proxy implementation of a Traversable that provides a/n Iterator&Traversable to iterate over. By implementing IteratorAggregate you are implementing a proxy to Iterator.

Is this correct?

If so, RecursiveIterator should accept IteratorAggregate as an Iterator provider.

My question is why IteratorAggregate and RecursiveIterator can not be used together.

  • incorrect abstraction?
  • incorrect implementation?
  • bug?

Fatal error: Class RecursiveFixedArrayProxy cannot implement both Iterator and IteratorAggregate at the same time https://3v4l.org/usWZK

<?php

declare(strict_types=1);

final class RecursiveFixedArrayProxy implements IteratorAggregate, RecursiveIterator
{
    private SplFixedArray $splFixedArray;
    public function __construct(iterable $iterable = [])
    {
        $this->splFixedArray = new SplFixedArray(
            is_countable($iterable) ?
            count($iterable) :
            iterator_count($iterable)
        );

        $offset = 0;
        $size = $this->splFixedArray->count();
        foreach ($iterable as $key => $value) {
            if($offset === $size){
                // resize the SplFixedArray when nessary. (if the iterable passed in via the __construct implements countable differently eg. where count() returns the capacity/size of the iterable)
                $this->splFixedArray->setSize(++$size);
            }
            if(is_array($value)){
                // save arrays as RecursiveFixedArrayProxy
                $this->splFixedArray->offsetSet($offset++, new self($value));
                continue;
            }
            // save all other values as stdClass via Closure
            $this->splFixedArray->offsetSet(
                $offset++,
                (static function(mixed $key = null, mixed $value = null): stdClass{
                    $stdClass = new stdClass();
                    $stdClass->key = $key;
                    $stdClass->value = $value;

                    return $stdClass;
                })($key, $value)
            );
        }
        $this->splFixedArray->setSize($offset);
    }
    // required from IteratorAggregate
    public function getIterator(): Generator
    {
        // to provide a Recursive SplFixedArray implemtation.
        yield from new RecursiveArrayIterator(
            // is this wrong? trying to avoid using arrays, for memory boost
            // avoids: $this->splFixedArray->toArray()
            $this->splFixedArray
        );
    }
    // required from RecursiveIterator
    public function getChildren(): ?RecursiveIterator
    {
        /** @return RecursiveFixedArray */
        return $this->current();
    }
    // required from RecursiveIterator
    public function hasChildren(): bool
    {
        // traverse recursively if *current* is instance of RecursiveFixedArray
        return $this->current() instanceof RecursiveFixedArray;
    }
}

How can you recursively traverse a SplFixedArray (no modification), without having to convert SplFixedArray to an array and relying on RecursiveArrayIterator?

  • extending SplFixedArray & RecursiveIterator causes error
  • using a proxy that implements IteratorAggregate & RecursiveIterator causes error

there's no way to "un-implement" an interface.

we can however refactor the abstraction

// eg. Add interface
interface RecursiveTraversable extends Traversable {
    /* Methods */
    public getChildren(): ?RecursiveTraversable
    public hasChildren(): bool
}
interface RecursiveIterator extends RecursiveTraversable {
    /* Inherited methods */
    public getChildren(): ?RecursiveIterator
    public hasChildren(): bool
    /* Inherited methods */
    public Iterator::current(): mixed
    public Iterator::key(): mixed
    public Iterator::next(): void
    public Iterator::rewind(): void
    public Iterator::valid(): bool
}
// extends RecursiveTraversable instead of Iterator
interface RecursiveIteratorAggregate extends RecursiveTraversable {
    /* Inherited methods */
    public getChildren(): ?RecursiveIterator
    public hasChildren(): bool
    /* Methods */
    public getIterator(): Traversable
}

ghostwriter avatar Feb 28 '22 20:02 ghostwriter

My understanding was that, IteratorAggregate is an internal decorator/proxy implementation of a Traversable that provides a/n Iterator&Traversable to iterate over. By implementing IteratorAggregate you are implementing a proxy to Iterator.

Is this correct?

No, it is not correct. The Traversable interface is internal, the IteratatorAggregate interface is exposed (as is Iterator). But both are interfaces so IteratorAggregate can't be a decorator or proxy or any other implementation.

Therefore, in terms of compatibility for Traversable, it can only be resolved to an Iterator at run-time. And a decorator/proxy implementation exists for Traversable, which is probably the default implementation you're actually looking for: IteratorIterator.

So as with PHP 8 SplFixedArray has changed from Iterator to IteratorAggregate but remains a Traversable you can still have your implementation backwards and forwards compatible by adhering to the Traversable interface instead of Iterator or IteratorAggregate.

From raising the issue here, it looks like that this is already part of your understanding to a certain degree.

However, this does not yet fully resolve your issue as you have found out, that it can't have the concrete Traversable implementation any longer:

  • If it runs on PHP < 8.0 then it needs to implement the Iterator - or -
  • If it runs on PHP >= 8.0 then it needs to have the IteratorAggregate.

But as we did learn, it can't have both. And for sure we don't want to load different classes / definitions under the same name, right?

The resolution is still within understanding the change better. What did happen? Traversable didn't change. This is good as we need it for foreach and similar iteration use. But the way on how the actual iterator is provided did change: From inheritance (extends an Iterator) to aggregation (getIterator() an Iterator).

Now as the subject of the matter, SplFixedArray, changed, anything that extends from it just needs to change, too, it needs to reflect those changes.

And the change is clear: From inheritance to aggregation.

And you already voiced what you're looking for here: A decorator/proxy.

Therefore, may we suggest as (one) resolution: Your subject RecursiveFixedArray representing an SplFixedArray being an Iterator becomes an IteratorIterator:

class RecursiveFixedArray extends IteratorIterator implements RecursiveIterator
{
    protected SplFixedArray $subject;

    public function __construct(int $size = 0) {
        parent::__construct(
            $this->subject = new SplFixedArray($size)
        );
    }

    public function getChildren(): ?self
    {
        if (!$this->hasChildren()) {
            return null;
        }

        $children = new self(0);
        $children->subject = $this->current()->subject;

        return $children;
    }

    public function hasChildren(): bool
    {
        return $this->current() instanceof self;
    }
}

As IteratorIterator proxies all undefined methods to its inner iterator, it is most likely that this already works. A classic refactoring from inheritance to aggregation for a Traversable in PHP.


However, it won't cover your case as a whole I'd assume, because you also raised another "internal interface", not just iteration, so I'd like to add more discussion to it, so it is possible to also decide on the details we may face with design issues:

How can you recursively traverse a SplFixedArray (no modification), without having to convert SplFixedArray to an array and relying on RecursiveArrayIterator?

While the new class already provides recursive iteration (in its RecursiveIterator implementation) and the direct question could be considered answered, I take the term array as a hint that you'd also like to have ArrayAccess (and likely Countable as well as JsonSerializeable) from the original extended SplFixedArray.

These are special interfaces in PHP that need to be implemented in the proxy when needed, aggregation does not maintain these interfaces on the new class automatically (as those are interfaces) and the method forwarding capability of IteratorIterator to the getInnerIterator() is not enough yet (and wouldn't be either for some other reason, but we're dealing with that anyway).

Therefore, to become feature complete the new replacement implementation needs those to be added as well (here only the exemplary count() method):

class RecursiveFixedArray
    extends IteratorIterator
    implements RecursiveIterator,
               ArrayAccess,
               Countable,
               JsonSerializable

{
    protected SplFixedArray $subject;

    public function __construct(int $size = 0) {
        parent::__construct(
            $this->subject = new SplFixedArray($size)
        );
    }

    # ...

    public function count(): int
    {
        return $this->subject->count();
    }

    # ...

This is the same for all proxy methods of these interfaces, I'm pretty sure as you're writing about proxies and decorators, this should be straight forward to grasp.

And details again: When we're talking about backward and forward compatible code, types may change and PHP 8.1 requires attributes to hint, which (gladly!) are backwards compatible to hop over the 7.4 |\ 8.0 |\ 8.1 barriers fatal and warning free.

If everything worked right with the proxying there shouldn't be any fatal errors including those involving the PHP 8 new InternalIterator nor any warnings or notices.

Coming that far, you may ask yourself if that is not repeating what uncovered the flaw in the first place: Not wrapping third-party (internal) code. I'd say yes and no. While the original code sort-of was programmed against interfaces, it was reasonable sane so why not do it again? Additionally, it might be that a whole proxy is not even necessary, therefore the extra overhead of implementing Countable etc. in the proxy may not even be necessary. Even better if only the recursive iterator is needed, and now favoring composition over inheritance as the solution for both new and old code, the more straight forward implementation may be:

class SplFixedArrayRecursiveIterator extends IteratorIterator implements RecursiveIterator
{
    public function __construct(SplFixedArray $traversable) {
        parent::__construct($traversable);
    }

    public function getChildren(): ?self
    {
       return $this->hasChildren() ? new self($this->current()) : null;
    }

    public function hasChildren(): bool
    {
        return $this->current() instanceof SplFixedArray;
    }
}

While it won't act as a full proxy, it would suffice as a recursive iterator for the subject, would have less implementation and would do the really necessary things already.

It may require more refactoring of the existing code as it ain't a full replacement but then on the other hand, when implementing the proxy it may be already useful to implement a full proxy that is as well preferring composition to inheritance and therefore not have it extend IteratorIterator and instead make that one an internal detail as well. As not being an SplFixedArray it would not inherit the original problem after all (and hint: it could use the SplFixedArrayRecursiveIterator as the iterator aggregate if your looking for some refactoring strategies). But if the problem was only on level of recursion, no extended proxy necessary, just an iterator for which the IteratorIterator boilerplate works very well as the replacement from the previous boilerplate inherited from SplFixedArray.

Hope this helps also other stumbling over it and looking into making code more backwards and forward compatible even if such breaking changes may appear as if they could not be solved at all.

TLDR: If you need to deal with the Traversal internal interface from the PHP code side, look at IteratorIterator for an implementation.

hakre avatar Aug 14 '22 12:08 hakre

Wow! @hakre, you're a great educator!

Thank you for taking the time to eloquently describe the issues and providing an incredibly detailed answer, along with beautifully refactored examples.

You are absolutely right, no warnings or notices if the SplFixedArrayRecursiveIterator class extends IteratorIterator and drops IteratatorAggregate . - https://3v4l.org/DsGJO

Totally missed that!


I'll revisit that codebase and play with this.

Thank you both for your help, Have a great week!

ghostwriter avatar Aug 16 '22 18:08 ghostwriter