<?php
namespace Newland\NeosFiltering\Traits;

/*
 * This file is part of the "neos-filtering" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Doctrine\ORM\Query\Expr;
use Neos\Flow\Persistence\Generic\Qom\Constraint;

/**
 * Trait for filter items that can be configured to combine multiple query items either
 * using AND or using OR.
 */
trait HasCombinationSettings
{
    /** @var string */
    public static $AND = 'AND';

    /** @var string */
    public static $OR = 'OR';

    /** @var string[] */
    protected $allowedCombineOptions = [ 'AND', 'OR' ];

    /** @var string */
    protected $combine;

    public function setCombine(string $combine): void
    {
        $combine = strtoupper($combine);
        if (!in_array($combine, $this->allowedCombineOptions)) {
            throw new \InvalidArgumentException(sprintf(
                'Combine option must be one of [%s]',
                implode(', ', $this->allowedCombineOptions)
            ));
        }

        $this->combine = $combine;
        $this->viewAssignments['combine'] = $combine;
    }

    public function getCombine(): ?string
    {
        return $this->combine;
    }

    /** @return Expr\Base|Constraint|null */
    protected function combineWithCurrentCombinationMethod(Expr $expr, array $parts)
    {
        if (\count($parts) === 0) {
            return null;
        }
        if (\count($parts) === 1) {
            return array_values($parts)[0];
        }

        if ($this->combine === static::$AND) {
            return $expr->andX(...$parts);
        }
        return $expr->orX(...$parts);
    }
}
