Issue
I'am currently working on a very old Symfony 2.4 project.
I have created a CsvImportCommand file to create adding massive customers with a csv functionality.
I need to set the current logged-in user as the value of my column 'created_by', but i do not know how can i get this information.
I saw that i could get this information in the twig template with app.user
or with get('security.context')->getToken()->getUser()
in a controller file.
But i really do not know how can i retrieve this information in a command file.
Remember, it is a Symfony 2.4 project.
below are my codes, it returns an error : PHP Parse error: syntax error, unexpected '$this' (T_VARIABLE) (on my 2nd line)
class CsvImportCommand extends ContainerAwareCommand
{
private $user = $this->get('security.context')->getToken()->getUser();
private $username = $user->getUsername();
protected function configure()
{
$this
->setName('csv:import')
->setDescription('Import users from CSV file')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$now = new \DateTime();
$output->writeln('<comment>Start:' . $now->format('d-m-Y G:i:s') . '---</comment>');
$this->import($input, $output);
$now = new \DateTime();
$output->writeln('<comment>End:' . $now->format('d-m-Y G:i:s') . '---</comment>');
}
protected function import(InputInterface $input, Outputinterface $output)
{
$data = $this->get($input, $output);
$em = $this->getContainer()->get('doctrine')->getManager();
$em->getConnection()->getConfiguration()->setSQLLogger(null);
$size = count($data);
$batchSize = 20;
$i = 1;
foreach($data as $row) {
$person = $em->getRepository('MyBundle:Person')->findOneBy(array('firstname'=>$row['firstname'], 'lastname'=>$row['lastname']));
if(!$person){
$person = new Person();
$em->persist($person);
}
$person->setIsPrivate($row['is_private']);
$person->setCivility($row['civility']);
$person->setFirstName($row['firstname']);
$person->setLastName($row['lastname']);
$person->setPhoneHome($row['phone_home']);
$person->setMobileHome($row['mobile_home']);
$person->setEmailPro($row['email_pro']);
$person->setEmailHome($row['email_home']);
$person->setCreatedAt(new \DateTime());
$person->setUpdatedAt(new \DateTime());
$person->setCreatedBy($username);
if (($i % $batchSize) === 0) {
$em->flush();
$em->clear();
$now = new \DateTime();
$output->writeln('of users imported... | ' . $now->format('d-m-Y G:i:s'));
}
$i++;
}
$em->flush();
$em->clear();
}
}
Solution
Regarding your error:
you can't use $this in class variables. U have to assign $user in the __construct or u create set-Methods. Something like: setUser.
Regarding security-bundle with commands:
U can't use the security.context because u dont have a user in this section. Maybe u can fake it, but this is not so good.
Answered By - can.duendar
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.