<?php

namespace Comitium5\DesignerBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

/**
 * Class ArrayToStringTransformer
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Form\DataTransformer
 */
class ArrayToStringTransformer implements DataTransformerInterface
{
    /**
     * @var array
     */
    protected $options;

    /**
     * ArrayToStringTransformer constructor.
     * @param array $options
     */
    public function __construct(array $options = [])
    {
        $this->options = array_merge(
            ['glue' => ','],
            $options
        );
    }

    /**
     * @param array $array
     * @return string
     */
    public function transform($array)
    {
        if(null === $array) {
            return '';
        }

        if(!is_array($array)) {
            throw new TransformationFailedException('Is not a valid array');
        }

        return implode($this->options["glue"], $array);
    }

    /**
     * @param string $string
     * @return array
     */
    public function reverseTransform($string)
    {
        $array = explode($this->options["glue"], $string);

        if (isset($this->options["sort"])) {
            sort($array, SORT_STRING);
        }

        return $array;
    }
}
