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

use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Tools\SchemaTool;

class SchemaCreator
{

    /**
     * @var AbstractSchemaManager
     */
    private $schemaManager;

    /**
     * @var SchemaTool
     */
    private $schemaTool;

    public function __construct(AbstractSchemaManager $schemaManager, SchemaTool $schemaTool)
    {
        $this->schemaManager = $schemaManager;
        $this->schemaTool = $schemaTool;
    }

    /**
     * Creates the tables corresponding to each ClassMetadata item in $classMetadataItems, unless a table with a
     * corresponding name already exists. If that is the case, does nothing (even if class metadata has changed).
     *
     * @param array<ClassMetadata> $classMetadata
     * @return void
     */
    public function createSchemaUnlessTableExists(array $classMetadataItems)
    {
        // We will only create schemas for those entity classes for which no correspondingly named tables exist.
        $classMetadataItems = array_filter($classMetadataItems, function (ClassMetadata $classMetadataItem) {
            return !$this->tableExistsForClassMetadata($classMetadataItem);
        });
        $this->schemaTool->createSchema($classMetadataItems);
    }

    private function tableExistsForClassMetadata(ClassMetadata $classMetadata)
    {
        return $this->schemaManager->tablesExist([$classMetadata->getTableName()]);
    }
}
