UserChangePasswordCommand::execute()   B
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 40
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
dl 0
loc 40
rs 8.5806
c 2
b 1
f 1
cc 4
eloc 26
nc 3
nop 2
1
<?php
2
3
	namespace Vivait\AuthBundle\Command;
4
5
	use Vivait\AuthBundle\Entity\User;
6
	use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
7
	use Symfony\Component\Console\Input\InputArgument;
8
	use Symfony\Component\Console\Input\InputInterface;
9
	use Symfony\Component\Console\Output\OutputInterface;
10
11
	class UserChangePasswordCommand extends ContainerAwareCommand {
12
13
		protected function configure() {
14
			$this
15
				->setName('auth:user:resetpassword')
16
				->setDescription('Reset a user password')
17
				->addArgument('username', InputArgument::REQUIRED, 'Username of the User?')
18
				->addArgument('password', InputArgument::OPTIONAL, 'New Password?');
19
		}
20
21
22
		protected function execute(InputInterface $input, OutputInterface $output) {
23
			$username   = $input->getArgument('username');
24
			$password   = $input->getArgument('password');
25
26
			#find user
27
			$user = $this->getContainer()->get('doctrine')
28
			             ->getRepository('VivaitAuthBundle:User')
29
			             ->findOneBy(array('username' => $username));
30
31
			if(!$user) {
32
				$output->writeln(sprintf("Error: Could not find user with username: %s", $username));
33
				return null;
34
			}
35
36
			if(!$password) {
37
				$alphabet = "abcdefghjkmnpqrstuwxyzABCDEFGHJKMNPQRSTUWXYZ23456789";
38
				$password = '';
39
				$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
40
				for ($i = 0; $i < 8; $i++) {
41
					$n = rand(0, $alphaLength);
42
					$password[$i] = $alphabet[$n];
43
				}
44
			}
45
46
			$factory = $this->getContainer()->get('security.encoder_factory');
47
			$encoder = $factory->getEncoder($this);
48
49
			$user->newSalt();
50
			$user->setPassword($encoder->encodePassword($password, $user->getSalt()));
51
52
			$em = $this->getContainer()->get('doctrine')->getManager();
53
			$em->persist($user);
54
			$em->flush();
55
56
			$output->writeln(sprintf("Password for: %s has been reset to: %s",
57
			                         $user->getUsername(),
58
			                         $password
59
			                 ));
60
61
		}
62
	}