PHP Classes

File: src/Filters/IndexFilter.php

Recommend this page to a friend!
  Classes of Sascha Greuel   PHP JSON Path   src/Filters/IndexFilter.php   Download  
File: src/Filters/IndexFilter.php
Role: Class source
Content type: text/plain
Description: Class source
Class: PHP JSON Path
Query values from data structures like XPATH
Author: By
Last change: [Bug-68] added support for length on array

+ added token value check for length only if named key doesn't exist
+ updated test case to show it working
+ bonus: fixed test case for working length checks on script expressions
Date: 3 years ago
Size: 1,320 bytes
 

Contents

Class file image Download
<?php

/**
 * JSONPath implementation for PHP.
 *
 * @license https://github.com/SoftCreatR/JSONPath/blob/main/LICENSE MIT License
 */

declare(strict_types=1);

namespace
Flow\JSONPath\Filters;

use
Flow\JSONPath\{AccessHelper, JSONPathException};

class
IndexFilter extends AbstractFilter
{
   
/**
     * @inheritDoc
     *
     * @throws JSONPathException
     */
   
public function filter($collection): array
    {
        if (
is_array($this->token->value)) {
           
$result = [];
            foreach (
$this->token->value as $value) {
                if (
AccessHelper::keyExists($collection, $value, $this->magicIsAllowed)) {
                   
$result[] = AccessHelper::getValue($collection, $value, $this->magicIsAllowed);
                }
            }
            return
$result;
        }

        if (
AccessHelper::keyExists($collection, $this->token->value, $this->magicIsAllowed)) {
            return [
               
AccessHelper::getValue($collection, $this->token->value, $this->magicIsAllowed),
            ];
        }

        if (
$this->token->value === '*') {
            return
AccessHelper::arrayValues($collection);
        }

        if (
$this->token->value === 'length') {
            return [
               
count($collection),
            ];
        }

        return [];
    }
}