<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonPickwareMobile\Components\QueryBuilder;

class ScalarValueQueryComponent implements QueryComponent
{
    /**
     * @var mixed
     */
    protected $value;

    /**
     * @param mixed $value
     */
    public function __construct($value)
    {
        $this->value = $value;
    }

    /**
     * @return mixed
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * @param mixed $value
     */
    public function setValue($value)
    {
        $this->value = $value;
    }

    /**
     * @inheritdoc
     */
    public function createQueryString()
    {
        return self::convertToSqlString($this->value);
    }

    /**
     * @inheritdoc
     */
    public function getRequiredTables()
    {
        return [];
    }

    /**
     * @param mixed $value
     * @return string
     */
    private static function convertToSqlString($value)
    {
        if (is_array($value)) {
            // Convert the array values recursively
            $values = array_map(
                [
                    self::class,
                    __FUNCTION__,
                ],
                $value
            );

            return (count($value) > 0) ? sprintf('(%s)', implode(', ', $values)) : '()';
        } elseif (is_bool($value)) {
            return ($value) ? '1' : '0';
        } elseif ($value === null) {
            return 'NULL';
        } elseif (is_int($value)) {
            return $value;
        } elseif (is_float($value)) {
            return sprintf('%F', $value);
        } else {
            // List of escaped characters copied from Zend_Db_Adapter_Abstract::_quote
            return sprintf('\'%s\'', addcslashes($value, "\000\n\r\\'\"\032"));
        }
    }
}
