<?php

namespace AppBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;

class MailArrayToStringTransformer implements DataTransformerInterface
{
    /**
     * Transforms an array of mails to a string.
     *
     * @param array $mails Array keys = mail addresses; array values = mail labels
     * @return string Comma-separated string of mail adresses in the following format: john.snow@got.com, Sansa Stark <sansa.stark@got.com>
     */
    public function transform($mails): string
    {
        if (empty($mails)) {
            $mails = '';
        } else {
            foreach ($mails as $address => $label) {
                if (is_string($label)) {
                    $mails[$address] = $label . ' <' . $address . '>';
                } else { // Otherwise the value is the mail address
                    $mails[$address] = $address;
                }
            }

            $mails = join(', ', $mails);
        }

        return $mails;
    }

    /**
     * Transforms a string of mails to an array.
     *
     * @param  string $mails
     * @return array
     */
    public function reverseTransform($mails): array
    {
        $mailsArray = [];

        if (!empty($mails)) {
            $mails = explode(', ', $mails);

            foreach ($mails as $mail) {
                // $mail must be in one of the two following format:
                // john.snow@got.com
                // John Snow <john.snow@got.com>
                
                if ('>' === substr($mail, -1)) { // Last character of the mail is a close angle bracket
                    list($mailLabel, $mailAddress) = preg_grep('^(.*)[[:space:]]<(.*)>$', $mail);
                    $mailsArray[$mailLabel] = $mailAddress;
                } else {
                    $mailsArray[$mailAddress] = null;
                }
            }
        }

        return $mailsArray;
    }
}
