1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 
<?php
/* --------------------------------------------------------------
   EmailsJsonSerializer.inc.php 2016-04-15
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2016 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

MainFactory::load_class('AbstractJsonSerializer');

/**
 * Class EmailsJsonSerializer
 *
 * This class will serialize and deserialize an email entity. It can be used into many
 * places where PHP interacts with external requests such as AJAX or API communication.
 *
 * @category   System
 * @package    Extensions
 * @subpackage Serializers
 */
class EmailJsonSerializer extends AbstractJsonSerializer
{
    /**
     * Serialize email object (from Email instance to json string)
     *
     * @param EmailInterface $object    Contains the email data.
     * @param bool           $encode    (optional) Whether to json_encode the result of the method (default true).
     *                                  Sometimes it might be required to encode an array of multiple email records
     *                                  together and not one by one.
     *
     * @return string|array
     */
    public function serialize($object, $encode = true)
    {
        if(!is_a($object, 'EmailInterface'))
        {
            throw new InvalidArgumentException('Invalid argument provided, EmailInterface object required: '
                                               . get_class($object));
        }

        // Main Properties

        $email = array(
                'id'           => ($object->getId()) ? (int)(string)$object->getId() : null,
                'subject'      => ($object->getSubject()) ? (string)$object->getSubject() : null,
                'sender'       => ($object->getSender()) ? $this->_serializeContact($object->getSender()) : null,
                'recipient'    => ($object->getRecipient()) ? $this->_serializeContact($object->getRecipient()) : null,
                'replyTo'      => ($object->getReplyTo()) ? $this->_serializeContact($object->getReplyTo()) : null,
                'contentHtml'  => ($object->getContentHtml()) ? (string)$object->getContentHtml() : null,
                'contentPlain' => ($object->getContentPlain()) ? (string)$object->getContentPlain() : null,
                'isPending'    => $object->isPending(),
                'creationDate' => $object->getCreationDate()->format('Y-m-d H:i:s'),
                'sentDate'     => ($object->getSentDate()) ? $object->getSentDate()->format('Y-m-d H:i:s') : null,
                'bcc'          => array(),
                'cc'           => array(),
                'attachments'  => array()
        );

        // BCC & CC

        foreach($object->getBcc()->getArray() as $contact)
        {
            $email['bcc'][] = $this->_serializeContact($contact);
        }

        foreach($object->getCc()->getArray() as $contact)
        {
            $email['cc'][] = $this->_serializeContact($contact);
        }

        // Attachments

        foreach($object->getAttachments()->getArray() as $attachment)
        {
            $email['attachments'][] = $this->_serializeAttachment($attachment);
        }

        return ($encode) ? $this->jsonEncode($email) : $email;
    }


    /**
     * Deserialize email JSON string.
     *
     * @param string $string     JSON string that contains the data of the email.
     * @param object $baseObject (optional) If provided, this will be the base object to be updated
     *                           and no new instance will be created.
     *
     * @return EmailInterface Returns the deserialized Email object.
     * @throws InvalidArgumentException If the argument is not a string or is empty.
     */
    public function deserialize($string, $baseObject = null)
    {
        if(!is_string($string) || empty($string))
        {
            throw new InvalidArgumentException('Invalid argument provided for deserialization: ' . gettype($string));
        }

        $json = json_decode($string);

        if($json === null && json_last_error() > 0)
        {
            throw new InvalidArgumentException('Provided JSON string is malformed and could not be parsed: ' . $string);
        }

        if(!$baseObject)
        {
            $email = MainFactory::create('Email');
        }
        else
        {
            $email = $baseObject;
        }

        // Deserialize Main Properties

        if($json->id !== null)
        {
            $email->setId(new IdType((int)$json->id));
        }

        if($json->subject !== null)
        {
            $email->setSubject(MainFactory::create('EmailSubject', $json->subject));
        }

        if($json->contentHtml !== null)
        {
            $email->setContentHtml(MainFactory::create('EmailContent', $json->contentHtml));
        }

        if($json->contentPlain !== null)
        {
            $email->setContentPlain(MainFactory::create('EmailContent', $json->contentPlain));
        }

        if($json->isPending !== null)
        {
            $email->setPending((bool)$json->isPending);
        }

        if($json->creationDate !== null)
        {
            $email->setCreationDate(new EmptyDateTime($json->creationDate));
        }

        if($json->sentDate !== null)
        {
            $email->setSentDate(new EmptyDateTime($json->sentDate));
        }

        // Deserialize Contacts

        if($json->sender !== null)
        {
            $sender = $this->_deserializeContact($json->sender, ContactType::SENDER);
            $email->setSender($sender);
        }

        if($json->recipient !== null)
        {
            $recipient = $this->_deserializeContact($json->recipient, ContactType::RECIPIENT);
            $email->setRecipient($recipient);
        }

        if($json->replyTo !== null)
        {
            $replyTo = $this->_deserializeContact($json->replyTo, ContactType::REPLY_TO);
            $email->setReplyTo($replyTo);
        }

        if($json->bcc !== null)
        {
            foreach($json->bcc as $contact)
            {
                $email->getBcc()->add($this->_deserializeContact($contact, ContactType::BCC));
            }
        }

        if($json->cc)
        {
            foreach($json->cc as $contact)
            {
                $email->getCc()->add($this->_deserializeContact($contact, ContactType::CC));
            }
        }

        // Deserialize Attachments 

        if($json->attachments !== null)
        {
            foreach($json->attachments as $attachment)
            {
                $email->getAttachments()->add($this->_deserializeAttachment($attachment));
            }
        }

        return $email;
    }


    /**
     * Serialize EmailContact
     *
     * @param EmailContactInterface $contact
     *
     * @return array
     */
    protected function _serializeContact(EmailContactInterface $contact)
    {
        return array(
                'emailAddress' => ($contact->getEmailAddress()) ? (string)$contact->getEmailAddress() : null,
                'contactName'  => ($contact->getContactName()) ? (string)$contact->getContactName() : null
        );
    }


    /**
     * Deserialize EmailContact
     *
     * @param stdClass $contact
     * @param          $type
     *
     * @return EmailContact
     */
    protected function _deserializeContact(stdClass $contact, $type)
    {
        $emailAddress = ($contact->emailAddress !== null) ? MainFactory::create('EmailAddress',
                                                                                $contact->emailAddress) : null;
        $contactType  = MainFactory::create('ContactType', $type);
        $contactName  = ($contact->contactName !== null) ? MainFactory::create('ContactName',
                                                                               $contact->contactName) : null;

        return MainFactory::create('EmailContact', $emailAddress, $contactType, $contactName);
    }


    /**
     * Serialize EmailAttachment
     *
     * @param EmailAttachmentInterface $attachment
     *
     * @return array
     */
    protected function _serializeAttachment(EmailAttachmentInterface $attachment)
    {
        return array(
                'path' => ($attachment->getPath()) ? (string)$attachment->getPath() : null,
                'name' => ($attachment->getName()) ? (string)$attachment->getName() : null
        );
    }


    /**
     * Deserialize EmailAttachment
     *
     * @param stdClass $attachment
     *
     * @return EmailAttachment
     */
    protected function _deserializeAttachment(stdClass $attachment)
    {
        $path = ($attachment->path !== null) ? MainFactory::create('AttachmentPath', $attachment->path) : null;
        $name = ($attachment->name !== null) ? MainFactory::create('AttachmentName', $attachment->name) : null;

        return MainFactory::create('EmailAttachment', $path, $name);
    }
}