A Few Kinks in FilterIterator

After a recent release of Phergie, I came across a few issues stemming partly from odd behavior in the PHP FilterIterator class.

First, bug #52559. At the time, I was trying to troubleshoot why the first element seemed to be skipped during iteration by a subclass of FilterIterator. Not knowing that FilterIterator contained no count() method at the time, I tried calling it to get the number of elements in the original array.

Once I discovered the segfault, I had to come up with a short code sample exposing the bug in order to report it. Tracing that segfault to that method call was a bit tedious, but Xdebug helped. Lesson learned: when a segfault occurs, check calls to all methods of native classes to ensure that they actually exist. The --rc option of the PHP CLI binary is particularly useful for this.

Last, bug #52560. This bug was an indirect cause of the first element being skipped during iteration. What actually happens is that null is returned in place of that element. The bug report goes over this in more detail, but the easiest way to work around this bug is to override the FilterIterator constructor in the subclass and call the rewind() method to explicitly reset the iterator position when the class is instantiated, as shown below.

<?php
class MyFilterIterator extends FilterIterator {
    public function __construct(Iterator $iterator) {
        parent::__construct($iterator);
        $this->rewind();
    }
}

Comments are closed.