Created
January 21, 2015 08:55
-
-
Save kolyadin/c2534e6316c024f89eb4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Popcorn\UserBundle\Command; | |
use Doctrine\DBAL\DriverManager; | |
use Doctrine\ORM\Id\AssignedGenerator; | |
use Doctrine\ORM\Mapping\ClassMetadata; | |
use Doctrine\ORM\QueryBuilder; | |
use Popcorn\GeoBundle\Entity\Country; | |
use Popcorn\ImageBundle\Entity\NullImage; | |
use Popcorn\PersonBundle\Entity\Person; | |
use Popcorn\UserBundle\Entity\Group; | |
use Popcorn\UserBundle\Entity\User; | |
use Popcorn\UserBundle\Entity\UserInfo; | |
use Popcorn\UserBundle\Entity\UserSettings; | |
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; | |
use Symfony\Component\Console\Input\InputArgument; | |
use Symfony\Component\Console\Input\InputInterface; | |
use Symfony\Component\Console\Input\InputOption; | |
use Symfony\Component\Console\Output\OutputInterface; | |
class ImportUserCommand extends ContainerAwareCommand { | |
/** | |
* @see Command | |
*/ | |
protected function configure() { | |
$this | |
->setName('popcorn:import:users') | |
->setDescription('Импорт пользователей'); | |
} | |
/** | |
* @todo Сделать импорт аватарок | |
* @todo Привязать импортированных пользователей к модераторам (сравниить с боевым сайтом) | |
* | |
* @param InputInterface $input | |
* @param OutputInterface $output | |
* | |
* @return void | |
*/ | |
protected function execute(InputInterface $input, OutputInterface $output) { | |
/** @var \Doctrine\ORM\EntityManager $em */ | |
$em = $this->getContainer()->get('doctrine.orm.entity_manager'); | |
/** @var \Doctrine\DBAL\Connection $conn */ | |
$conn = $this->getContainer()->get('doctrine.dbal.default_connection'); | |
$output->write('Подготовка к импорту... '); | |
$this->prepareImport(); | |
$output->writeln('готово'); | |
$users = $this->getUserData(); | |
$output->writeln('Начинается импорт, всего импортируемых пользователей: ' . count($users)); | |
$iteratorCount = 1; | |
foreach ($users as $key => &$table) { | |
$iteratorCount++; | |
$user = (new User()) | |
->setId($table['id']) | |
->setLastActivity($this->convertLastActivity($table['ldate'])) | |
->setEnabled($this->convertEnabled($table)) | |
->setEmail($table['email']) | |
->setPlainPassword($table['pass']) | |
->addGroup($em->getRepository('UserBundle:Group')->findOneBy(['name' => 'user'])) | |
->setNick($table['nick']) | |
->setUsername($table['nick']) | |
->setAvatar(null) | |
->setRating((int)$table['rating']) | |
->setLastLogin(null) | |
->setCreatedAt(new \DateTime($table['regtime'])) | |
->setUserInfo( | |
(new UserInfo()) | |
->setName($table['name']) | |
->setSex($this->convertUserSex((int)$table['sex'])) | |
->setCredo($table['credo']) | |
->setBirthDate($this->convertUserBirthdate($table['birthday'])) | |
->setCountry($this->convertCountry($em, $table['country_id'])) | |
->setCity($this->convertCity($em, $table['city_id'])) | |
->setMarried($this->convertMarried((int)$table['family'])) | |
->setMeetPerson($this->convertMeetPerson($em, $table['meet_actor'])) | |
->setPoints((int)$table['points']) | |
->setActivist($table['activist_now'] == 1) | |
->setActivistCount((int)$table['activist']) | |
) | |
->setUserSettings( | |
(new UserSettings()) | |
->setShowBirthDate($table['show_bd'] == 1) | |
->setDailySubscribe($table['daily_sub'] == 1) | |
->setAlertMessage($table['alert_on_new_mail'] == 1) | |
->setAlertGuestBook($table['alert_on_new_guest_items'] == 1) | |
->setCanInvite($table['can_invite_to_community_groups'] == 1) | |
); | |
$metadata = $em->getClassMetadata(get_class($user)); | |
$metadata->setIdGenerator(new AssignedGenerator()); | |
$metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_NONE); | |
$em->persist($user); | |
$em->flush(); | |
$em->detach($user); | |
$em->clear(); | |
unset($user); | |
unset($metadata); | |
unset($table[$key]); | |
if (($iteratorCount % 100) == 0) { | |
$output->writeln("\t<info>Импортировано пользователей: $iteratorCount, импорт продолжается...</info>"); | |
} | |
} | |
unset($users); | |
$output->writeln('Импорт завершен'); | |
} | |
/** | |
* @param $table | |
* @return bool | |
*/ | |
private function convertEnabled($table) { | |
if ($table['banned'] == 1) { | |
return false; | |
} | |
if ($table['enabled'] == 1) { | |
return true; | |
} | |
return false; | |
} | |
private function convertLastActivity($time) { | |
//Поставим время последней активности год назад, если в базе нет данных | |
if (!$time) { | |
return new \DateTime('-1 year'); | |
} | |
return \DateTime::createFromFormat('U', $time); | |
} | |
/** | |
* @param \Doctrine\ORM\EntityManager $em | |
* @param $personId | |
* @return \Popcorn\PersonBundle\Entity\Person|null | |
*/ | |
private function convertMeetPerson($em, $personId) { | |
if (!$personId) return null; | |
$person = $em->find('PersonBundle:Person', $personId); | |
if ($person) { | |
return $person; | |
} else { | |
return null; | |
} | |
} | |
/** | |
* @param \Doctrine\ORM\EntityManager $em | |
* @param $cityId | |
* @return \Popcorn\GeoBundle\Entity\City|null | |
*/ | |
private function convertCity($em, $cityId) { | |
if (!$cityId) return null; | |
$city = $em->find('GeoBundle:City', $cityId); | |
if ($city) { | |
return $city; | |
} else { | |
return null; | |
} | |
} | |
/** | |
* @param \Doctrine\ORM\EntityManager $em | |
* @param $countryId | |
* @return \Popcorn\GeoBundle\Entity\Country|null | |
*/ | |
private function convertCountry($em, $countryId) { | |
if (!$countryId) return null; | |
$country = $em->find('GeoBundle:Country', $countryId); | |
if ($country) { | |
return $country; | |
} else { | |
return null; | |
} | |
} | |
private function convertMarried($family) { | |
$userMarried = UserInfo::MARRIED_UNKNOWN; | |
switch ($family) { | |
case 1: | |
$userMarried = UserInfo::MARRIED_SINGLE; | |
break; | |
case 2: | |
$userMarried = UserInfo::MARRIED_MARRIED; | |
break; | |
} | |
return $userMarried; | |
} | |
private function convertUserSex($sex) { | |
$userSex = UserInfo::SEX_UNKNOWN; | |
switch ($sex) { | |
case 1: | |
$userSex = UserInfo::SEX_MALE; | |
break; | |
case 2: | |
$userSex = UserInfo::SEX_FEMALE; | |
break; | |
} | |
return $userSex; | |
} | |
/** | |
* @param $birthday | |
* @return \DateTime|null | |
*/ | |
private function convertUserBirthdate($birthday) { | |
$userBirthday = null; | |
if ($birthday) { | |
if (strlen($birthday) < 8) { | |
$userBirthday = null; | |
} else { | |
$y = substr($birthday, 0, 4); | |
$m = substr($birthday, 4, 2); | |
$d = substr($birthday, 6, 2); | |
$userBirthday = new \DateTime("{$y}-{$m}-{$d}"); | |
} | |
} | |
return $userBirthday; | |
} | |
private function getUserEntityTableName() { | |
return $this | |
->getContainer() | |
->get('doctrine.orm.entity_manager') | |
->getClassMetadata('UserBundle:User') | |
->getTableName(); | |
} | |
/** | |
*/ | |
private function prepareImport() { | |
/** | |
* Set foreign_key_checks = 0; | |
* TRUNCATE `popcorn_user`; | |
* TRUNCATE `popcorn_users_to_groups`; | |
* TRUNCATE `popcorn_users_to_statuses`; | |
* TRUNCATE `popcorn_user__group`; | |
* TRUNCATE `popcorn_user__info`; | |
* TRUNCATE `popcorn_user__settings`; | |
* TRUNCATE `popcorn_user__status`; | |
* Set foreign_key_checks = 1; | |
*/ | |
/** @var \Doctrine\ORM\EntityManager $em */ | |
$em = $this->getContainer()->get('doctrine.orm.entity_manager'); | |
$users = $em->createQuery('SELECT u FROM UserBundle:User u'); | |
foreach ($users->iterate() as $row) { | |
$user = $row[0]; | |
$em->remove($user); | |
$em->flush(); | |
$em->detach($user); | |
} | |
$em->createQuery('DELETE FROM UserBundle:Group')->execute(); | |
$group = (new Group('user'))->addRole('ROLE_USER'); | |
$em->persist($group); | |
$group = (new Group('moderator'))->setRoles(['ROLE_USER', 'ROLE_MODERATOR']); | |
$em->persist($group); | |
$group = (new Group('admin'))->setRoles(['ROLE_USER', 'ROLE_MODERATOR', 'ROLE_ADMIN']); | |
$em->persist($group); | |
$em->flush(); | |
$em->detach($group); | |
} | |
private function getUserData() { | |
$conn = $this->getContainer()->get('popcorn.dbal.prod')->getConnection(); | |
$stmt = $conn->prepare('SELECT * FROM popkorn_users WHERE pass != "" LIMIT 100'); | |
$stmt->execute(); | |
$data = $stmt->fetchAll(\PDO::FETCH_ASSOC); | |
return $data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment