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 272 273 274 275 276 277 278 
<?php

/* --------------------------------------------------------------
   ProductRepositoryDeleter.inc.php 2015-12-08
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2015 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

/**
 * Class ProductRepositoryDeleter
 *
 * @category   System
 * @package    Product
 * @subpackage Repositories
 */
class ProductRepositoryDeleter implements ProductRepositoryDeleterInterface
{
    /**
     * Database connection.
     *
     * @var CI_DB_query_builder
     */
    protected $db;
    
    /**
     * @var \ProductRepositoryDeleteHelper
     */
    protected $deleteHelper;
    
    
    /**
     * ProductRepositoryDeleter constructor.
     *
     * @param CI_DB_query_builder            $db
     * @param \ProductRepositoryDeleteHelper $deleteHelper
     */
    public function __construct(CI_DB_query_builder $db, ProductRepositoryDeleteHelper $deleteHelper)
    {
        $this->db           = $db;
        $this->deleteHelper = $deleteHelper;
    }
    
    
    /**
     * Removes a product by the given product id.
     *
     * @param IdType $productId Id of product entity.
     *
     * @return ProductRepositoryDeleter Same instance for chained method calls.
     */
    public function deleteById(IdType $productId)
    {
        $this->_removeFeatureSetsByProductId($productId)
             ->_removeAdditionalFieldRelationsByProductId($productId)
             ->_removePropertiesByProductId($productId)
             ->_removePersonalOffersByCustomerStatusByProductId($productId)
             ->_removeReviewsByProductId($productId)
             ->_removeRecordsByProductId($productId);

        $this->deleteHelper->productsContent($productId, $this->db, MainFactory::create('ProductsContentFileStorage'),
                                             MainFactory::create('ResponsiveFileManagerConfigurationStorage'))
                           ->resetCategoriesAndAlsoPurchasedCache();
        
        return $this;
    }
    
    
    /**
     * Removes related feature set records by the given product id.
     *
     * @param \IdType $productId Product id of records to be removed.
     *
     * @return $this|ProductRepositoryDeleter Same instance for chained method calls.
     */
    protected function _removeFeatureSetsByProductId(IdType $productId)
    {
        // removal of feature set records
        $featureSets = $this->db->select('feature_set_id')
                                ->from('feature_set_to_products')
                                ->where('products_id', $productId->asInt())
                                ->get()
                                ->result_array();
        $this->db->delete('feature_set_to_products', ['products_id' => $productId->asInt()]);
        foreach($featureSets as $featureSet)
        {
            // check if feature set is used by another product
            $total = (int)$this->db->select('COUNT(*) as total')
                                   ->from('feature_set_to_products')
                                   ->where('feature_set_id', $featureSet['feature_set_id'])
                                   ->get()
                                   ->row_array()['total'];
            
            if($total === 0)
            {
                $this->db->delete([
                                      'feature_index',
                                      'feature_set',
                                      'feature_set_values'
                                  ], ['feature_set_id' => $featureSet['feature_set_id']]);
            }
        }
        
        return $this;
    }
    
    
    /**
     * Removes related additional field records by the given product id.
     *
     * @param \IdType $productId Product id of records to be removed.
     *
     * @return $this|ProductRepositoryDeleter Same instance for chained method calls.
     */
    protected function _removeAdditionalFieldRelationsByProductId(IdType $productId)
    {
        $additionalFields = $this->db->select('additional_field_id')
                                     ->from('additional_fields')
                                     ->where('item_type', 'product')
                                     ->get()
                                     ->result_array();
        array_map(function ($e) use ($productId)
        {
            $additionalFieldId = (int)$e['additional_field_id'];
            // we can use row_array(), because item_id and additional_field_id are unique in combination
            $additionalFieldValueId = (int)$this->db->select('additional_field_value_id')
                                                    ->from('additional_field_values')
                                                    ->where([
                                                                'item_id'             => $productId->asInt(),
                                                                'additional_field_id' => $additionalFieldId
                                                            ])
                                                    ->get()
                                                    ->row_array()['additional_field_value_id'];
            
            $this->db->delete('additional_field_value_descriptions',
                              ['additional_field_value_id' => $additionalFieldValueId]);
            $this->db->delete('additional_field_values', ['additional_field_value_id' => $additionalFieldValueId]);
        }, $additionalFields);
        
        return $this;
    }
    
    
    /**
     * Removes related property records by the given product id.
     *
     * @param \IdType $productId Product id of records to be removed.
     *
     * @return $this|ProductRepositoryDeleter Same instance for chained method calls.
     */
    protected function _removePropertiesByProductId(IdType $productId)
    {
        $combinationIds = array_map(function ($e)
        {
            return (int)$e['products_properties_combis_id'];
        }, $this->db->select('products_properties_combis_id')
                    ->from('products_properties_combis')
                    ->where(['products_id' => $productId->asInt()])
                    ->get()
                    ->result_array());
        foreach($combinationIds as $combinationId)
        {
            $this->db->delete('customers_basket', ['products_id LIKE' => '%x' . $combinationId]);
            $this->deleteHelper->propertyCombinationImages(new IdType($combinationId));
        }
        $propertyTables = [
            'products_properties_combis',
            'products_properties_combis_values',
            'products_properties_index'
        ];
        if (count($combinationIds) > 0)
        {
            foreach($propertyTables as $propertyTable)
            {
                $this->db->where_in('products_properties_combis_id', $combinationIds)->delete($propertyTable);
            }
        }
        
        $joinCondition          = 'a.products_id = b.products_id AND a.properties_values_id = b.properties_values_id AND '
                                  . 'a.properties_id = b.properties_id';
        $propertyAdminSelectIds = array_map(function ($e)
        {
            return (int)$e['products_properties_admin_select_id'];
        }, $this->db->distinct()
                    ->select('a.products_properties_admin_select_id, b.products_id')
                    ->from('products_properties_admin_select a')
                    ->join('products_properties_index AS b', $joinCondition, 'left outer')
                    ->where('b.products_id IS NULL')
                    ->get()
                    ->result_array());
        if(count($propertyAdminSelectIds) > 0)
        {
            $this->db->where_in('products_properties_admin_select_id', implode(',', $propertyAdminSelectIds))
                     ->delete('products_properties_admin_select');
        }
        
        return $this;
    }
    
    
    /**
     * Removes records from all dynamic personal_offer_by_customer_status_ tables by the given product id.
     *
     * @param \IdType $productId Product id of records to be removed.
     *
     * @return $this|ProductRepositoryDeleter Same instance for chained method calls.
     */
    protected function _removePersonalOffersByCustomerStatusByProductId(IdType $productId)
    {
        array_map(function ($e) use ($productId)
        {
            $this->db->delete('personal_offers_by_customers_status_' . (int)$e['customers_status_id'],
                              ['products_id' => $productId->asInt()]);
        }, $this->db->select('customers_status_id')->distinct()->from('customers_status')->get()->result_array());
        
        return $this;
    }
    
    
    /**
     * Removes review records by the given product id.
     *
     * @param \IdType $productId Product id of records to be removed.
     *
     * @return $this|ProductRepositoryDeleter Same instance for chained method calls.
     */
    protected function _removeReviewsByProductId(IdType $productId)
    {
        array_map(function ($e)
        {
            $this->db->delete('reviews_description', ['reviews_id' => (int)$e['reviews_id']]);
        }, $this->db->select('reviews_id')
                    ->from('reviews')
                    ->where(['products_id' => $productId->asInt()])
                    ->get()
                    ->result_array());
        $this->db->delete('reviews', ['products_id' => $productId->asInt()]);
        
        return $this;
    }
    
    
    /**
     * Removes records by products id in all related tables.
     *
     * @param \IdType $productId Product id of records to be removed.
     *
     * @return $this|ProductRepositoryDeleter Same instance for chained method calls.
     */
    protected function _removeRecordsByProductId(IdType $productId)
    {
        $affectedTables = [
            'products',
            'specials',
            'products_content',
            'products_images',
            'products_to_categories',
            'products_description',
            'products_attributes',
            'customers_basket',
            'customers_basket_attributes',
            'gm_prd_img_alt',
            'gm_gmotion',
            'gm_gmotion_products',
            'categories_index',
            'products_quantity_unit',
            'products_google_categories',
            'products_item_codes',
            'products_properties_admin_select'
        ];
        $this->db->delete($affectedTables, ['products_id' => $productId->asInt()]);
        
        return $this;
    }
}