aryehraber / statamic-fetch

Statamic v2 Addon — Access content directly as JSON using URL endpoints or via a simple tag.
MIT License
55 stars 8 forks source link

Filter by published/unpublished does not work for localized data #73

Open wanze opened 2 years ago

wanze commented 2 years ago

Description

Fetch returns unpublished content when using filter=published in combination with non-default locale. For example, a call to !/Fetch/collection/project?&limit=6&offset=0&locale=fr&filter=published will return unpublished entries of the project collection for French.

Problem

Fetch::filterData() does not respect localized data. Thus, filtering by published status is always performed on entries of the default locale.

Possible solution

For a quick fix, I extended Fetch::filterData() to localize the data before passing it to Fetch::filterPublished() or Fetch::filterUnpublished().

        if ($this->data instanceof IlluminateCollection) {
            $this->data = $this->data->filter(function ($entry) use ($filter) {
               // START: ADDED CODE
                if ($this->locale && method_exists($entry, 'locale')) {
                    $entry->locale($this->locale);
                }
               // END: ADDED CODE
                return $this->$filter($entry);
            })->filter();
        } else {
            $this->data = $this->$filter($this->data);
        }

Not sure if this fixes it for other data, but it seems to work for collections.

Cheers

aryehraber commented 2 years ago

Hi @wanze, thanks for bringing this to my attention! To be honest, I don't really actively maintain this addon anymore since the release of Statamic 3. I'm happy to merge a PR with this change as at first glance this seems fine to me. Thanks!