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 
<?php
/* --------------------------------------------------------------
   OrderRepositoryWriter.inc.php 2018-01-19
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2018 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

MainFactory::load_class('OrderRepositoryWriterInterface');

/**
 * Class OrderRepositoryWriter
 *
 * @category   System
 * @package    Order
 * @subpackage Repositories
 */
class OrderRepositoryWriter implements OrderRepositoryWriterInterface
{
    /**
     * Query builder.
     * @var CI_DB_query_builder
     */
    protected $db;
    
    
    /**
     * OrderRepositoryWriter constructor
     *
     * @param CI_DB_query_builder $db Query builder.
     */
    public function __construct(CI_DB_query_builder $db)
    {
        $this->db = $db;
    }
    
    
    /**
     * Inserts a new order to the orders table.
     *
     * @param OrderInterface $order Order.
     *
     * @return int ID of inserted order.
     */
    public function insert(OrderInterface $order)
    {
        $record = $this->_serializeOrder($order);
        
        // Insert orders_hash
        $record['orders_hash'] = time() + mt_rand();
        
        $this->db->insert('orders', $record);
        
        return $this->db->insert_id();
    }
    
    
    /**
     * Updates an existing order in the orders table.
     *
     * @param OrderInterface $order Order object.
     *
     * @return OrderRepositoryWriter Same instance for method chaining.
     */
    public function update(OrderInterface $order)
    {
        $record = $this->_serializeOrder($order);
        $this->db->update('orders', $record, array('orders_id' => $order->getOrderId()));
    }
    
    
    /**
     * Converts the order to an associative array that is later used to insert/update
     * the values into the database.
     *
     * @param OrderInterface $order The object to be serialized.
     *
     * @return array Contains the orders object matched with their respective db columns.
     */
    protected function _serializeOrder(OrderInterface $order)
    {
        // Find the correct language directory.
        $language = $this->db->get_where('languages', array('code' => strtolower((string)$order->getLanguageCode())))
                             ->row_array();

        // #49270 set payment to "voucher", if payment class is empty
        $payment = $order->getPaymentType()->getPaymentClass();
        $paymentClass = $payment !== '' ? $payment : 'voucher';
        
        $record = array(
            'customers_id'              => $order->getCustomerId(),
            'orders_status'             => $order->getStatusId(),
            'customers_cid'             => (string)$order->getCustomerNumber(),
            'customers_vat_id'          => (string)$order->getVatIdNumber(),
            'customers_status'          => $order->getCustomerStatusInformation()->getStatusId(),
            'customers_status_name'     => $order->getCustomerStatusInformation()->getStatusName(),
            'customers_status_image'    => $order->getCustomerStatusInformation()->getStatusImage(),
            'customers_status_discount' => $order->getCustomerStatusInformation()->getStatusDiscount(),
            'account_type'              => (int)$order->getCustomerStatusInformation()->isGuest(),
            'payment_method'            => $paymentClass, // use module code for method (legacy code)
            'payment_class'             => $paymentClass,
            'shipping_method'           => $order->getShippingType()->getTitle(),
            'shipping_class'            => $order->getShippingType()->getModule(),
            'comments'                  => $order->getComment(),
            'date_purchased'            => $order->getPurchaseDateTime()->format('Y-m-d H:i:s'),
            'last_modified'             => $order->getLastModifiedDateTime()->format('Y-m-d H:i:s'),
            'language'                  => (string)$language['directory'],
            'order_total_weight'        => $order->getTotalWeight(),
            'currency'                  => (string)$order->getCurrencyCode()->getCode(),
            'currency_value'            => (float)$order->getCurrencyCode()->getCurrencyValue(),
            'customers_telephone'       => $order->getCustomerTelephone(),
            'customers_email_address'   => $order->getCustomerEmail()
        );
        
        $customerAddress = $this->_serializeAddressBlock($order->getCustomerAddress(), new StringType('customers'));
        $deliveryAddress = $this->_serializeAddressBlock($order->getDeliveryAddress(), new StringType('delivery'));
        $billingAddress  = $this->_serializeAddressBlock($order->getBillingAddress(), new StringType('billing'));
        
        $record = array_merge($record, $customerAddress, $deliveryAddress, $billingAddress);
        
        return $record;
    }
    
    
    /**
     * Serializes address block.
     *
     * @param AddressBlockInterface $addressBlock  The object to be serialized.
     * @param StringType            $prefix        The address prefix can be one of the "delivery", "billing" and
     *                                             "customers".
     *
     * @return array Array with the address data.
     */
    protected function _serializeAddressBlock(AddressBlockInterface $addressBlock, StringType $prefix)
    {
        $country = $this->db->select('address_format_id')
                            ->get_where('countries', array('countries_id' => $addressBlock->getCountry()->getId()))
                            ->row_array();
        
        $addressPrefix = $prefix->asString() . '_';
        
        $addressBlockArray = array(
            $addressPrefix . 'name'              => (string)$addressBlock->getFirstname() . ' '
                                                    . (string)$addressBlock->getLastname(),
            $addressPrefix . 'firstname'         => (string)$addressBlock->getFirstname(),
            $addressPrefix . 'lastname'          => (string)$addressBlock->getLastname(),
            $addressPrefix . 'gender'            => (string)$addressBlock->getGender(),
            $addressPrefix . 'company'           => (string)$addressBlock->getCompany(),
            $addressPrefix . 'street_address'    => (string)$addressBlock->getStreet(),
            $addressPrefix . 'house_number'      => (string)$addressBlock->getHouseNumber(),
            $addressPrefix . 'additional_info'   => (string)$addressBlock->getAdditionalAddressInfo(),
            $addressPrefix . 'suburb'            => (string)$addressBlock->getSuburb(),
            $addressPrefix . 'city'              => (string)$addressBlock->getCity(),
            $addressPrefix . 'postcode'          => (string)$addressBlock->getPostcode(),
            $addressPrefix . 'state'             => (string)$addressBlock->getCountryZone()->getName(),
            $addressPrefix . 'country'           => (string)$addressBlock->getCountry()->getName(),
            $addressPrefix . 'address_format_id' => (int)$country['address_format_id']
        );
        
        if($prefix->asString() !== 'customers')
        {
            $addressBlockArray[$addressPrefix . 'country_iso_code_2'] = $addressBlock->getCountry()->getIso2();
        }
        
        return $addressBlockArray;
    }
}