<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonCommon\Classes\Installation\AttributeConfiguration;

use Doctrine\ORM\EntityManager;

class UninstallationHelper
{
    /**
     * @var EntityManager $entityManager
     */
    private $entityManager;

    /**
     * @param EntityManager $entityManager
     */
    public function __construct(EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * Removes all Shopware\Models\Attribute\Configuration entities whose table and column names
     * match the ones given in the $configurationNames array. This array must have the following form:
     *
     *  $configurationNames = array(
     *      'a_table_name' = array(
     *          'a_column_name',
     *          'another_column_name'
     *      )
     *  );
     *
     * If called in a Shopware environment < 5.2, this method does nothing, since the attribute configuration is
     * not yet available.
     *
     * @param array $configurationNames
     */
    public function removeAttributeConfigurationsIfExist(array $configurationNames)
    {
        if (!class_exists('Shopware\\Models\\Attribute\\Configuration')) {
            return;
        }

        $filterParams = [];
        foreach ($configurationNames as $tableName => $columnNames) {
            $filterParams['tableName'] = $tableName;
            foreach ($columnNames as $columnName) {
                $filterParams['columnName'] = $columnName;
                $configuration = $this->entityManager->getRepository('Shopware\\Models\\Attribute\\Configuration')->findOneBy($filterParams);
                if ($configuration) {
                    $this->entityManager->remove($configuration);
                }
            }
        }
        $this->entityManager->flush();
    }
}
