Spamworldpro Mini Shell
Spamworldpro


Server : Apache
System : Linux server2.corals.io 4.18.0-348.2.1.el8_5.x86_64 #1 SMP Mon Nov 15 09:17:08 EST 2021 x86_64
User : corals ( 1002)
PHP Version : 7.4.33
Disable Function : exec,passthru,shell_exec,system
Directory :  /home/corals/old/app/code/Cnc/Catalog/Setup/Patch/Data/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/corals/old/app/code/Cnc/Catalog/Setup/Patch/Data/UpdateCustomTablesAttributesData.php
<?php
/**
 * Copyright (c) 2020 Kaliop Digital Commerce (https://digitalcommerce.kaliop.com) All Rights Reserved.
 * https://opensource.org/licenses/OSL-3.0  Open Software License (OSL 3.0)
 * Cnc
 * Radosław Stępień <[email protected]> <[email protected]>
 */
namespace Cnc\Catalog\Setup\Patch\Data;

use Cnc\Catalog\Model\AvailabilityFactory;
use Cnc\Catalog\Model\GuaranteeDurationFactory;
use Cnc\Catalog\Model\GuaranteeTypeFactory;
use Cnc\Catalog\Model\Manufacturer;
use Cnc\Catalog\Model\ManufacturerFactory;
use Cnc\Catalog\Model\ResourceModel\Availability as AvailabilityResource;
use Cnc\Catalog\Model\ResourceModel\Availability\CollectionFactory as AvailabilityCollectionFactory;
use Cnc\Catalog\Model\ResourceModel\GuaranteeDuration as GuaranteeDurationResource;
use Cnc\Catalog\Model\ResourceModel\GuaranteeDuration\CollectionFactory as GuaranteeDurationCollectionFactory;
use Cnc\Catalog\Model\ResourceModel\GuaranteeType as GuaranteeTypeResource;
use Cnc\Catalog\Model\ResourceModel\GuaranteeType\CollectionFactory as GuaranteeTypeCollectionFactory;
use Cnc\Catalog\Model\ResourceModel\Manufacturer as ManufacturerResource;
use Cnc\Catalog\Model\ResourceModel\Manufacturer\CollectionFactory as ManufacturerCollectionFactory;
use Cnc\Catalog\Model\ResourceModel\StateOfWear as StateOfWearResource;
use Cnc\Catalog\Model\ResourceModel\StateOfWear\CollectionFactory as StateOfWearCollectionFactory;
use Cnc\Catalog\Model\StateOfWearFactory;
use DateTime;
use Exception;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\SampleData\FixtureManager;
use Psr\Log\LoggerInterface;

class UpdateCustomTablesAttributesData implements DataPatchInterface
{
    const FILES_TO_IMPORT = [
        self::FIXTURE_STATE_OF_WEAR_DATA_FILE_PATH,
        self::FIXTURE_MANUFACTURER_DATA_FILE_PATH,
        self::FIXTURE_GUARANTEE_DURATION_DATA_FILE_PATH,
        self::FIXTURE_GUARANTEE_TYPE_DATA_FILE_PATH
    ];

    //Files names for import
    const FIXTURE_STATE_OF_WEAR_DATA_FILE_PATH = 'Cnc_Catalog::fixtures/etats.csv';
    const FIXTURE_MANUFACTURER_DATA_FILE_PATH = 'Cnc_Catalog::fixtures/manufacturers.csv';
    const FIXTURE_GUARANTEE_DURATION_DATA_FILE_PATH = 'Cnc_Catalog::fixtures/garanties.csv';
    const FIXTURE_GUARANTEE_TYPE_DATA_FILE_PATH = 'Cnc_Catalog::fixtures/types.csv';

    //Prefixes for each import file data columns
    const IMPORT_FILES_PREFIXES = [
        self::FIXTURE_STATE_OF_WEAR_DATA_FILE_PATH => 'etats_',
        self::FIXTURE_MANUFACTURER_DATA_FILE_PATH => 'manufacturers_',
        self::FIXTURE_GUARANTEE_DURATION_DATA_FILE_PATH => 'garanties_',
        self::FIXTURE_GUARANTEE_TYPE_DATA_FILE_PATH => 'types_',
    ];

    //common columns names for all files
    const NAME_COLUMN = 'name';
    const IMAGE_COLUMN = 'image';
    const CREATED_COLUMN = 'date_added';
    const UPDATED_COLUMN = 'last_modified';
    const COUNTRY_COLUMN = 'country';

    /**
     * @var FixtureManager
     */
    private $fixtureManager;

    /**
     * @var File
     */
    private $file;

    /**
     * @var StateOfWearCollectionFactory
     */
    private $stateOfWearCollectionFactory;

    /**
     * @var ManufacturerCollectionFactory
     */
    private $manufacturerCollectionFactory;

    /**
     * @var GuaranteeDurationCollectionFactory
     */
    private $guaranteeDurationCollectionFactory;

    /**
     * @var GuaranteeTypeCollectionFactory
     */
    private $guaranteeTypeCollectionFactory;

    /**
     * @var StateOfWearResource
     */
    private $stateOfWearResource;

    /**
     * @var ManufacturerResource
     */
    private $manufacturerResource;

    /**
     * @var GuaranteeDurationResource
     */
    private $guaranteeDurationResource;

    /**
     * @var GuaranteeTypeResource
     */
    private $guaranteeTypeResource;

    /**
     * @var StateOfWearFactory
     */
    private $stateOfWearModelFactory;

    /**
     * @var ManufacturerFactory
     */
    private $manufacturerModelFactory;

    /**
     * @var GuaranteeDurationFactory
     */
    private $guaranteeDurationModelFactory;

    /**
     * @var GuaranteeTypeFactory
     */
    private $guaranteeTypeModelFactory;

    /**
     * @var LoggerInterface
     */
    private $logger;

    private $currentObject;
    private $currentModel;
    private $currentResourceModel;
    private $currentCollection;
    private $prefix;
    private $data;

    /**
     * UpdateAvailabilityData constructor.
     * @param FixtureManager $fixtureManager
     * @param File $file
     * @param StateOfWearCollectionFactory $stateOfWearCollectionFactory
     * @param ManufacturerCollectionFactory $manufacturerCollectionFactory
     * @param GuaranteeDurationCollectionFactory $guaranteeDurationCollectionFactory
     * @param GuaranteeTypeCollectionFactory $guaranteeTypeCollectionFactory
     * @param StateOfWearResource $stateOfWearResource
     * @param ManufacturerResource $manufacturerResource
     * @param GuaranteeDurationResource $guaranteeDurationResource
     * @param GuaranteeTypeResource $guaranteeTypeResource
     * @param StateOfWearFactory $stateOfWearModelFactory
     * @param ManufacturerFactory $manufacturerModelFactory
     * @param GuaranteeDurationFactory $guaranteeDurationModelFactory
     * @param GuaranteeTypeFactory $guaranteeTypeModelFactory
     * @param LoggerInterface $logger
     */
    public function __construct(
        FixtureManager $fixtureManager,
        File $file,
        StateOfWearCollectionFactory $stateOfWearCollectionFactory,
        ManufacturerCollectionFactory $manufacturerCollectionFactory,
        GuaranteeDurationCollectionFactory $guaranteeDurationCollectionFactory,
        GuaranteeTypeCollectionFactory $guaranteeTypeCollectionFactory,
        StateOfWearResource $stateOfWearResource,
        ManufacturerResource $manufacturerResource,
        GuaranteeDurationResource $guaranteeDurationResource,
        GuaranteeTypeResource $guaranteeTypeResource,
        StateOfWearFactory $stateOfWearModelFactory,
        ManufacturerFactory $manufacturerModelFactory,
        GuaranteeDurationFactory $guaranteeDurationModelFactory,
        GuaranteeTypeFactory $guaranteeTypeModelFactory,
        LoggerInterface $logger
    ) {
        $this->fixtureManager = $fixtureManager;
        $this->file = $file;
        $this->stateOfWearCollectionFactory = $stateOfWearCollectionFactory;
        $this->manufacturerCollectionFactory = $manufacturerCollectionFactory;
        $this->guaranteeDurationCollectionFactory = $guaranteeDurationCollectionFactory;
        $this->guaranteeTypeCollectionFactory = $guaranteeTypeCollectionFactory;
        $this->stateOfWearResource = $stateOfWearResource;
        $this->manufacturerResource = $manufacturerResource;
        $this->guaranteeDurationResource = $guaranteeDurationResource;
        $this->guaranteeTypeResource = $guaranteeTypeResource;
        $this->stateOfWearModelFactory = $stateOfWearModelFactory;
        $this->manufacturerModelFactory = $manufacturerModelFactory;
        $this->guaranteeDurationModelFactory = $guaranteeDurationModelFactory;
        $this->guaranteeTypeModelFactory = $guaranteeTypeModelFactory;
        $this->logger = $logger;
    }

    /**
     * Get array of patches that have to be executed prior to this.
     *
     * Example of implementation:
     *
     * [
     *      \Vendor_Name\Module_Name\Setup\Patch\Patch1::class,
     *      \Vendor_Name\Module_Name\Setup\Patch\Patch2::class
     * ]
     */
    public static function getDependencies()
    {
        return [];
    }

    /**
     * Get aliases (previous names) for the patch.
     */
    public function getAliases()
    {
        return [];
    }

    /**
     * Run code inside patch
     * If code fails, patch must be reverted, in case when we are speaking about schema - then under revert
     * means run PatchInterface::revert()
     *
     * If we speak about data, under revert means: $transaction->rollback()
     */
    public function apply()
    {
        try {
            foreach (self::FILES_TO_IMPORT as $fileName) {
                $this->data = [];

                $fileToOpen = $this->fixtureManager->getFixture($fileName);
                $file = $this->file->fileOpen($fileToOpen, "r");
                $header = $this->file->fileGetCsv($file, 0, ",");

                while ($row = $this->file->fileGetCsv($file, 0, ",")) {
                    $this->data[] = array_filter(array_combine($header, $row));
                }

                $this->getCurrentObjects($fileName);
                $this->prefix = self::IMPORT_FILES_PREFIXES[$fileName];

                $this->removeData();
                $this->importData();
            }
        } catch (Exception $e) {
            $this->logger->critical($e->getMessage());
        }
    }

    /**
     * Remove old data to have clear table before import new data
     */
    public function removeData()
    {
        $items = $this->currentCollection->getItems();
        if (count($items)) {
            foreach ($items as $item) {
                try {
                    $item->delete();
                } catch (Exception $e) {
                    $this->logger->critical($e->getMessage());
                    $this->logger->critical(var_export($item->getId(), true));
                }
            }
        }
    }

    /**
     * Map current object data and proceed to save in table
     * @throws Exception
     */
    public function importData()
    {
        foreach ($this->data as $item) {
            $this->currentObject['name'] = $this->getNameField($item);
            $this->currentObject['image'] = $this->getImageField($item);
            $this->currentObject['created_at'] = $this->getCreatedAtField($item);
            $this->currentObject['last_update'] = $this->getUpdatedAtField($item);
            if ($this->prefix == 'manufacturers_') {
                $this->currentObject['country'] = $this->getCountryField($item);
            }
            $this->createNew();
        }
    }

    /**
     * Save data into corresponding table
     */
    public function createNew()
    {
        try {
            $model = $this->currentModel->create();
            $model->setName($this->currentObject['name']);
            $model->setImage($this->currentObject['image']);
            $model->setCreatedAt($this->currentObject['created_at']);
            $model->setLastUpdate($this->currentObject['last_update']);
            if ($model instanceof Manufacturer) {
                $model->setCountry($this->currentObject['country']);
            }
            $this->currentResourceModel->save($model);
        } catch (Exception $e) {
            $this->logger->critical($e->getMessage());
        }
    }

    /**
     * Set needed objects instances
     * @param $fileName
     */
    public function getCurrentObjects($fileName)
    {
        switch ($fileName) {
            case (self::FIXTURE_STATE_OF_WEAR_DATA_FILE_PATH):
                $this->currentCollection = $this->stateOfWearCollectionFactory->create();
                $this->currentModel = $this->stateOfWearModelFactory;
                $this->currentResourceModel = $this->stateOfWearResource;
                break;
            case (self::FIXTURE_MANUFACTURER_DATA_FILE_PATH):
                $this->currentCollection = $this->manufacturerCollectionFactory->create();
                $this->currentModel = $this->manufacturerModelFactory;
                $this->currentResourceModel = $this->manufacturerResource;
                break;
            case (self::FIXTURE_GUARANTEE_DURATION_DATA_FILE_PATH):
                $this->currentCollection = $this->guaranteeDurationCollectionFactory->create();
                $this->currentModel = $this->guaranteeDurationModelFactory;
                $this->currentResourceModel = $this->guaranteeDurationResource;
                break;
            case (self::FIXTURE_GUARANTEE_TYPE_DATA_FILE_PATH):
                $this->currentCollection = $this->guaranteeTypeCollectionFactory->create();
                $this->currentModel = $this->guaranteeTypeModelFactory;
                $this->currentResourceModel = $this->guaranteeTypeResource;
                break;
        }
    }

    /**
     * @param $item
     * @return mixed
     * @throws Exception
     */
    public function getNameField($item)
    {
        if (array_key_exists($this->prefix . self::NAME_COLUMN, $item)) {
            return $item[$this->prefix . self::NAME_COLUMN];
        } else {
            $this->logger->critical('Name field is required');
            return false;
        }
    }

    /**
     * @param $item
     * @return string|null
     */
    public function getImageField($item)
    {
        return array_key_exists($this->prefix . self::IMAGE_COLUMN, $item)
            ? $item[$this->prefix . self::IMAGE_COLUMN]
            : null;
    }

    /**
     * @param $item
     * @return DateTime
     */
    public function getCreatedAtField($item)
    {
        return (array_key_exists(self::CREATED_COLUMN, $item)
            && $item[self::CREATED_COLUMN] != 'NULL')
            ? $item[self::CREATED_COLUMN]
            : new DateTime();
    }

    /**
     * @param $item
     * @return string|null
     */
    public function getUpdatedAtField($item)
    {
        return (array_key_exists(self::UPDATED_COLUMN, $item)
            && $item[self::UPDATED_COLUMN] != 'NULL')
        ? $item[self::UPDATED_COLUMN]
        : null;
    }

    /**
     * @param $item
     * @return string
     */
    public function getCountryField($item)
    {
        return array_key_exists(self::COUNTRY_COLUMN, $item)
            ? $item[self::COUNTRY_COLUMN]
            : 'FR';
    }
}

Spamworldpro Mini