Skip to content

Expose "length" filter, make it work with Countable objects - #103

Closed
rundef wants to merge 4 commits into
nette:masterfrom
rundef:master
Closed

Expose "length" filter, make it work with Countable objects#103
rundef wants to merge 4 commits into
nette:masterfrom
rundef:master

Conversation

@rundef

@rundef rundef commented Feb 14, 2016

Copy link
Copy Markdown
Contributor

I needed to count the number of elements in an array ...
I saw that this feature has been talked about in issue #33

I wasn't sure if I should have created a new filter |count for objects only ... Tell me what you think!

Comment thread src/Latte/Runtime/Filters.php Outdated
public static function length($s)
{
return strlen(utf8_decode($s)); // fastest way
return is_string($s) ?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

imho it should be something like

public static function length($s)
{
    if (is_array($s)) {
        return count($s);
    } elseif ($s instanceof \Traversable) {
        return iterator_count($s);
    } else {
        return strlen(utf8_decode($s)): // fastest way
    }
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if (is_array($val) || $val instanceof \Countable)

@xificurk

Copy link
Copy Markdown
Contributor

A test would be nice ;-)

@rundef

rundef commented Feb 14, 2016

Copy link
Copy Markdown
Contributor Author

Thanks for the quick feedback :)

@dg dg closed this in 5d5520a Feb 19, 2016
@dg

dg commented Feb 19, 2016

Copy link
Copy Markdown
Member

Thanks, merged

if (is_array($s) || $s instanceof \Countable) {
return count($s);
} elseif ($s instanceof \Traversable) {
return iterator_count($s);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this (may) mutate the iterator, imo it's best to let decide the programmer.

iterator_count() is not guaranteed to retain the current position of the iterator.
http://php.net/iterator_count

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants