<?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\ArticleAttributeElement;

use Doctrine\ORM\EntityManager;

class MigrateHelper
{

    /**
     * @todo Use `\Shopware\Models\Attribute\Configuration::class` once we can depend on PHP >= 5.5.
     */
    const CONFIGURATION_CLASS = 'Shopware\\Models\\Attribute\\Configuration';

    /**
     * @var EntityManager
     */
    private $entityManager;

    public function __construct(EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * Rename any configuration column names to use underscores (_) instead of camel case. Shopware 5.2 migrations
     * did migrate ArticleAttributeElements to Configurations, but did not rename them to match valid column names.
     */
    public function finishArticleAttributeElementsToConfigurationMigration(array $oldElementNames)
    {
        if (!class_exists(static::CONFIGURATION_CLASS)) {
            // Nothing to do for Shopware < 5.2.
            return;
        }

        /** @var $configs \Shopware\Models\Attribute\Configuration[] */
        $configs = $this->entityManager->getRepository(static::CONFIGURATION_CLASS)->findBy([
            'columnName' => $oldElementNames,
            'tableName' => 's_articles_attributes',
        ]);

        if (count($configs) === 0) {
            return;
        }

        foreach ($configs as $config) {
            $config->setColumnName(ConfigurationHelper::transformToColumnName($config->getColumnName()));
            $this->entityManager->persist($config);
        }
        $this->entityManager->flush();
    }
}
