<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use App\Entity\Access;
use App\Entity\Institute;
use App\Entity\Municipal;
use App\Entity\User;
use App\Service\Doctrine\Migrations\AwareHasherInterface;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20221221105531 extends AbstractMigration implements ContainerAwareInterface, AwareHasherInterface
{
private UserPasswordHasherInterface $hasher;
private EntityManagerInterface $em;
private User $adminUser;
public function setContainer(ContainerInterface $container = null)
{
$this->em = $container->get('doctrine.orm.entity_manager');
}
public function setHasher(UserPasswordHasherInterface $hasher): void
{
$this->hasher = $hasher;
}
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TABLE access (id SERIAL NOT NULL, user_id INT NOT NULL, municipal_id INT DEFAULT NULL, institute_id INT DEFAULT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE INDEX IDX_6692B54A76ED395 ON access (user_id)');
$this->addSql('CREATE INDEX IDX_6692B547A79FFCF ON access (municipal_id)');
$this->addSql('CREATE INDEX IDX_6692B54697B0F4C ON access (institute_id)');
$this->addSql('COMMENT ON TABLE access IS \'Внутренний портал. Какой пользователь к какой сущности привязан.\'');
$this->addSql('ALTER TABLE access ADD CONSTRAINT FK_6692B54A76ED395 FOREIGN KEY (user_id) REFERENCES "user" (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('ALTER TABLE access ADD CONSTRAINT FK_6692B547A79FFCF FOREIGN KEY (municipal_id) REFERENCES municipal (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('ALTER TABLE access ADD CONSTRAINT FK_6692B54697B0F4C FOREIGN KEY (institute_id) REFERENCES institute (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
$republicInstitutes = [
'ГАУ РСШОР по фехтованию',
'ГАУ РСШОР по фехтованию',
'ГБУ РСШОР по фигурному катанию на коньках и шорт-треку',
'ГАУ РСШОР по шахматам, шашкам, го им. Р.Г.Нежметдинова',
'ГАУ РСШОР "Батыр"',
'ГБУ РСШ по конному спорту',
'ГАУ РСШ по борьбе',
'ГБУ РСШОР по стендовой и пулевой стрельбе',
'ГАУ РСШОР "Динамо"',
'ГБУ РСШОР по водным видам спорта "Акватика"',
'ГБУ РСШОР по водным видам спорта "Акватика"',
'ГБУ "РСАШ"',
'ГБУ РСШ по зимним видам спорта "Барс"',
'ГБУ РСШ по бадминтону им. Ф.Г.Валеева',
'ГБУ РСШ по бадминтону им. Ф.Г.Валеева',
'ГБУ РСШ по регби',
];
foreach ($republicInstitutes as $republicInstitute) {
$sql = sprintf("INSERT INTO institute (created_by_id, name) VALUES (1, '%s')", $republicInstitute);
$this->addSql($sql);
}
}
/**
* @throws \Exception
*/
public function postUp(Schema $schema): void
{
$this->adminUser = $this->em->getRepository(User::class)->findOneBy(['email' => $_ENV['SUPERUSER_EMAIL']]);
try {
$this->em->beginTransaction();
$this->makeMunicipalUsers();
$this->makeRepublicUsers();
$this->em->commit();
} catch (\Exception $exception) {
$this->em->rollback();
throw $exception;
}
}
private function makeMunicipalUsers()
{
$municipals = $this->getMunicipals();
foreach ($municipals as $municipal) {
$user = $this->makeUser('municipal_' . $municipal->getId());
$access = new Access();
$access->setUser($user);
$access->setMunicipal($municipal);
$this->em->persist($access);
}
$this->em->flush();
}
private function makeRepublicUsers()
{
$institutes = $this->getRepublicInstitutes();
foreach ($institutes as $institute) {
$user = $this->makeUser('institute' . $institute->getId());
$access = new Access();
$access->setUser($user);
$access->setInstitute($institute);
$this->em->persist($access);
}
$this->em->flush();
}
private function makeUser(string $userName): User
{
$user = new User();
$user->setEmail($userName . '@etton.ru');
$user->setFirstName($userName);
$user->setSecondName($userName);
$user->setLastName($userName);
$user->addRole(User::ROLE_MUNICIPAL_OFFICER);
$user->setCreatedBy($this->adminUser);
$user->setCreatedAt(new \DateTime());
$password = $this->hasher->hashPassword($user, $userName);
$user->setPassword($password);
$this->em->persist($user);
return $user;
}
/**
* @return Municipal[]
*/
private function getMunicipals(): array
{
return $this->em->createQueryBuilder()
->select('m')
->from(Municipal::class, 'm')
->orderBy('m.id')
->getQuery()
->getResult();
}
/**
* @return Institute[]
*/
private function getRepublicInstitutes(): array
{
return $this->em->createQueryBuilder()
->select('i')
->from(Institute::class, 'i')
->where('i.municipal IS NULL')
->orderBy('i.id')
->getQuery()
->getResult();
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE access DROP CONSTRAINT FK_6692B54A76ED395');
$this->addSql('ALTER TABLE access DROP CONSTRAINT FK_6692B547A79FFCF');
$this->addSql('ALTER TABLE access DROP CONSTRAINT FK_6692B54697B0F4C');
$this->addSql('DROP TABLE access');
}
}