chill-bundles/src/Bundle/ChillMainBundle/Command/LoadCountriesCommand.php
2021-11-30 13:54:58 +01:00

103 lines
2.8 KiB
PHP

<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Command;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Intl\Intl;
class LoadCountriesCommand extends Command
{
private $availableLanguages;
/**
* @var EntityManager
*/
private $entityManager;
/**
* LoadCountriesCommand constructor.
*
* @param $availableLanguages
*/
public function __construct(EntityManager $entityManager, $availableLanguages)
{
$this->entityManager = $entityManager;
$this->availableLanguages = $availableLanguages;
parent::__construct();
}
public static function prepareCountryList($languages)
{
$regionBundle = Intl::getRegionBundle();
$countries = [];
foreach ($languages as $language) {
$countries[$language] = $regionBundle->getCountryNames($language);
}
$countryEntities = [];
foreach ($countries[$languages[0]] as $countryCode => $name) {
$names = [];
foreach ($languages as $language) {
$names[$language] = $countries[$language][$countryCode];
}
$country = new \Chill\MainBundle\Entity\Country();
$country->setName($names)->setCountryCode($countryCode);
$countryEntities[] = $country;
}
return $countryEntities;
}
/**
* (non-PHPdoc).
*
* @see \Symfony\Component\Console\Command\Command::configure()
*/
protected function configure()
{
$this->setName('chill:main:countries:populate')
->setDescription('Load or update countries in db. This command does not delete existing countries, ' .
'but will update names according to available languages');
}
/**
* (non-PHPdoc).
*
* @see \Symfony\Component\Console\Command\Command::execute()
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$countries = static::prepareCountryList($this->availableLanguages);
$em = $this->entityManager;
foreach ($countries as $country) {
$countryStored = $em->getRepository('ChillMainBundle:Country')
->findOneBy(['countryCode' => $country->getCountryCode()]);
if (null === $countryStored) {
$em->persist($country);
} else {
$countryStored->setName($country->getName());
}
}
$em->flush();
}
}