QueryableTrait.php 2.37 KB
<?php

namespace ServiceCore\Infrastructure\Domain\Repository;

use ApiQL\ApiQL;
use Doctrine\DBAL\FetchMode;

/**
 * Trait QueryableTrait
 *
 * @package ServiceCore\Infrastructure\Domain\Repository
 */
trait QueryableTrait
{
    /**
     * @param array $payload
     *
     * @return array
     */
    public function get(array $payload = []): array
    {
        $query = $this->queryBuilder
            ->from($this->tableName)
        ;
        
        if (property_exists($this, 'ordered') && $this->ordered == true) {
            $query->orderBy('row_order');
        }

        $apiQL = new ApiQL($payload, $query);
        $apiQL->execute();

        $result = $query->execute()->fetchAll(FetchMode::ASSOCIATIVE);
        
        $result = $this->decodeParameters($result);
        
        return $result;
    }

    /**
     * @param int $id
     *
     * @return array|null
     */
    public function getById(int $id): ?array
    {
        $query = $this->queryBuilder
            ->select('*')
            ->from($this->tableName)
            ->where('id = :id')
            ->setParameter('id', $id)
        ;

        $result = $query->execute()->fetch(FetchMode::ASSOCIATIVE);
        
        $result = $this->decodeParameters($result);

        return $result ? $result : null;
    }

    /**
     * @param string $guid
     *
     * @return array|null
     */
    public function getByGuid(string $guid): ?array
    {
        $query = $this->queryBuilder
            ->select('*')
            ->from($this->tableName)
            ->where('guid = :guid')
            ->setParameter('guid', $guid)
        ;

        $result = $query->execute()->fetch(FetchMode::ASSOCIATIVE);
        
        $result = $this->decodeParameters($result);

        return $result ? $result : null;
    }
    
    /**
     * @param mixed $result
     *
     * @return mixed
     */
    public function decodeParameters($result)
    {
        if (is_array($result) && !empty($result)) {
            if (isset($result[0]) && isset($result[0]['properties'])) {
                foreach ($result as $index => $value) {
                    $result[$index]['properties'] = json_decode($value['properties'], true);
                }
            } elseif (isset($result['properties'])) {
                $result['properties'] = json_decode($result['properties'], true);
            }
        }
        
        return $result;
    }
}