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 
<?php
/* --------------------------------------------------------------
   CustomerJsonSerializer.inc.php 2016-09-09
   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 CustomerJsonSerializer
 *
 * This class will serialize and deserialize a customer 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 CustomerJsonSerializer extends AbstractJsonSerializer
{
    /**
     * Serialize customer object to json string.
     *
     * Important:
     * Password value will not be included in the serialized object.
     *
     * @param CustomerInterface $object Contains the customer 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 customer records
     *                                  together and not one by one.
     *
     * @return string|array Returns the json encoded customer (string) or an array that can be easily encoded into a
     *                      JSON string.
     * @throws InvalidArgumentException If the provided object type is invalid.
     */
    public function serialize($object, $encode = true)
    {
        if(!is_a($object, 'CustomerInterface'))
        {
            throw new InvalidArgumentException('Invalid argument provided, CustomerInterface object required: '
                                               . get_class($object));
        }

        $address = $object->getDefaultAddress();

        $customer = array(
                'id'              => ($object->getId() !== null) ? (int)(string)$object->getId() : null,
                'number'          => ($object->getCustomerNumber()
                                      !== null) ? (string)$object->getCustomerNumber() : null,
                'gender'          => ($object->getGender() !== null) ? (string)$object->getGender() : null,
                'firstname'       => ($object->getFirstname() !== null) ? (string)$object->getFirstname() : null,
                'lastname'        => ($object->getLastname() !== null) ? (string)$object->getLastname() : null,
                'dateOfBirth'     => ($object->getDateOfBirth() !== null) ? $object->getDateOfBirth()
                                                                                   ->format('Y-m-d') : null,
                'vatNumber'       => ($object->getVatNumber() !== null) ? (string)$object->getVatNumber() : null,
                'vatNumberStatus' => ($object->getVatNumberStatus() !== null) ? $object->getVatNumberStatus() : null,
                'telephone'       => ($object->getTelephoneNumber()
                                      !== null) ? (string)$object->getTelephoneNumber() : null,
                'fax'             => ($object->getFaxNumber() !== null) ? (string)$object->getFaxNumber() : null,
                'email'           => ($object->getEmail() !== null) ? (string)$object->getEmail() : null,
                'statusId'        => ($object->getStatusId() !== null) ? $object->getStatusId() : null,
                'isGuest'         => $object->isGuest(),
                'addressId'       => ($address !== null) ? (int)(string)$address->getId() : null,
                'addonValues'     => ($object->getAddonValues()->count()) ? $object->getAddonValues()->getArray() : null
        );

        return ($encode === true) ? $this->jsonEncode($customer) : $customer;
    }


    /**
     * Deserialize customer JSON string.
     *
     * @param string $string     JSON string that contains the data of the customer.
     * @param object $baseObject (optional) If provided, this will be the base object to be updated
     *                           and no new instance will be created.
     *
     * @return CustomerInterface Returns the deserialized Customer 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);
        }

        $customerFactory = MainFactory::create('CustomerFactory');

        if(!$baseObject)
        {
            $customer = $customerFactory->createCustomer();
        }
        else
        {
            $customer = $baseObject;
        }

        // Parse Main Information

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

        if($json->number !== null)
        {
            $customer->setCustomerNumber(MainFactory::create('CustomerNumber', $json->number));
        }

        if($json->gender !== null)
        {
            $customer->setGender(MainFactory::create('CustomerGender', $json->gender));
        }

        if($json->firstname !== null)
        {
            $customer->setFirstname(MainFactory::create('CustomerFirstname', $json->firstname));
        }

        if($json->lastname !== null)
        {
            $customer->setLastname(MainFactory::create('CustomerLastname', $json->lastname));
        }

        if($json->dateOfBirth !== null)
        {
            $customer->setDateOfBirth(MainFactory::create('DateTime', $json->dateOfBirth));
        }

        if($json->vatNumber !== null)
        {
            $customer->setVatNumber(MainFactory::create('CustomerVatNumber', $json->vatNumber));
        }

        if($json->vatNumberStatus !== null)
        {
            $customer->setVatNumberStatus((int)$json->vatNumberStatus);
        }

        if($json->telephone !== null)
        {
            $customer->setTelephoneNumber(MainFactory::create('CustomerCallNumber', $json->telephone));
        }

        if($json->fax !== null)
        {
            $customer->setFaxNumber(MainFactory::create('CustomerCallNumber', $json->fax));
        }

        if($json->email !== null)
        {
            $customer->setEmail(MainFactory::create('CustomerEmail', $json->email));
        }
        
        if($json->password !== null)
        {
            /** @var AuthService $authService */
            $authService    = StaticGXCoreLoader::getService('Auth');
            $hashedPassword = $authService->getHash(new StringType($json->password));
            
            $customer->setPassword(MainFactory::create('CustomerHashedPassword',
                                                       new NonEmptyStringType($hashedPassword)));
        }

        if($json->statusId !== null)
        {
            $customer->setStatusId((int)$json->statusId);
        }

        if($json->isGuest !== null)
        {
            $customer->setGuest((bool)$json->isGuest);
        }

        if($json->addressId !== null)
        {
            $addressService = StaticGXCoreLoader::getService('AddressBook');
            $address        = $addressService->findAddressById(new IdType((int)$json->addressId));
            if($address !== null) // it is possible that the given address ID does not exist
            {
                $customer->setDefaultAddress($address);
            }
        }
        
        if($json->addonValues !== null)
        {
            $customer->addAddonValues(MainFactory::create('KeyValueCollection',
                                                          json_decode(json_encode($json->addonValues), true)));
        }

        // Returned deserialized Customer object.
        return $customer;
    }
}