UserController::indexAction()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 12
rs 9.4285
cc 1
eloc 8
nc 1
nop 0
1
<?php
2
3
	namespace Vivait\AuthBundle\Controller;
4
5
	use Doctrine\ORM\EntityRepository;
6
	use Symfony\Bundle\FrameworkBundle\Controller\Controller;
7
	use Symfony\Component\HttpFoundation\Request;
8
	use Doctrine\ORM\Query;
9
    use Vivait\AuthBundle\Entity\User;
10
11
    class UserController extends Controller {
12
13
		public function indexAction() {
14
			################################################  SETTINGS  ################################################
15
			$twig = 'VivaitAuthBundle:Default:users.html.twig';
16
			############################################################################################################
17
			$db = $this->getDoctrine()
18
			           ->getRepository('VivaitAuthBundle:User')
19
			           ->findAllFull()
20
			           ->getResult();
21
22
			$params = array();
23
			return $this->render($twig, array('db' => $db, 'params' => $params));
24
		}
25
26
		public function editAction(Request $request) {
27
28
			################################################  SETTINGS  ################################################
29
			$name             = 'user';
30
			$repo             = 'VivaitAuthBundle:User';
31
			$formtpl['title'] = 'Add/Edit ' . ucfirst($name);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$formtpl was never initialized. Although not strictly required by PHP, it is generally a good practice to add $formtpl = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
32
			$obj              = new User();
33
			$key              = $request->query->get('id', 0);
34
			$foreign_objs     = array( #	array(
35
			                           #		'repo'   => 'VivaBravoBundle:Product',
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
36
			                           #		'key'    => $request->query->get('pid', 0),
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
37
			                           #		'method' => 'setProduct',
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
38
			                           #		'name'   => 'product'),
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
39
			);
40
			############################################################################################################
41
42 View Code Duplication
			if(!$key) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
43
				### CREATING A NEW OBJECT ###
44
45
				#if there are foreign objects that should be bound to this object, bind them all here
46
				foreach($foreign_objs as $fo) {
47
					$foreign_obj = $this->getDoctrine()
48
					                    ->getRepository($fo['repo'])
49
					                    ->find($fo['key']);
50
					if(!$foreign_obj) {
51
						$this->get('session')->getFlashBag()->add('error', sprintf("Could not find the %s", $fo['name']));
52
						return $this->redirect($request->query->get('parent', $request->request->get('parent', $request->headers->get('referer'))));
53
					}
54
					call_user_func(array($obj, $fo['method'], $foreign_obj));
55
				}
56
			} else {
57
				### EDITING AN EXISTING OBJECT ###
58
				$obj = $this->getDoctrine()
59
				            ->getRepository($repo)
60
				            ->find($key);
61
62
				if(!$obj) {
63
					$this->get('session')->getFlashBag()->add('error', sprintf("Could not find the %s", $name));
64
				}
65
			}
66
67
			if($this->getUser()->getTenants()->count() > 1) {
68
				$tenant_namefield = 'tenantedFullname';
0 ignored issues
show
Unused Code introduced by
$tenant_namefield is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
69
			} else {
70
				$tenant_namefield = 'fullname';
0 ignored issues
show
Unused Code introduced by
$tenant_namefield is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
71
			}
72
73
			##############################################  CREATE FORM  ###############################################
74
75
			$form = $this->createFormBuilder($obj)
76
			             ->add('username', 'text', array('label' => 'Username'))
77
			             ->add('initials', 'text', array('label' => 'Initials'))
78
			             ->add('fullname', 'text', array('label' => 'Full Name'))
79
			             ->add('email', 'email', array('label' => 'Email Address'))
80
			             ->add('password', 'password', array('label' => 'New Password'))
81
			             ->add('active', 'checkbox', array('label' => 'Active'))
82
			             ->add('jobtitle', 'text', array('label' => 'Job Title', 'required' => false))
83
			             ->add('department', 'text', array('label' => 'Department', 'required' => false))
84
			             ->add('location', 'text', array('label' => 'Location', 'required' => false))
85
			             ->add('telephone', 'text', array('label' => 'Telephone', 'required' => false))
86
			             ->add('groups', 'entity', array(
87
					'class'    => 'VivaitAuthBundle:Group',
88
					'property' => 'name',
89
					'multiple' => true,
90
					'required' => true,
91
					'attr'     => array('size' => 15),
92
					'label'    => 'Groups'
93
				))
94
			             ->add('tenants', 'entity', array(
95
					'class'    => 'VivaitAuthBundle:Tenant',
96
					'property' => 'tenant',
97
					'multiple' => true,
98
					'attr'     => array('size' => 15),
99
					'required' => true,
100
					'label'    => 'Tenants'
101
				))
102
			             ->getForm();
103
			############################################################################################################
104
105
			if($request->isMethod('POST')) {
106
				// get a copy of the previous object before fields have been modified
107
				$prevobj = clone $obj;
108
109
				$form->handleRequest($request);
110
				if($form->isValid()) {
111
112
					######  RESET PASSWORD IF NEW PASSWORD IS SET ######
113
					if(strlen($obj->getPassword())) {
114
						# new password set
115
						$obj->newSalt();
116
						$factory  = $this->get('security.encoder_factory');
117
						$encoder  = $factory->getEncoder($this);
118
						$password = $encoder->encodePassword($obj->getPassword(), $obj->getSalt());
119
						$obj->setPassword($password);
120
					} else {
121
						#retain existing password
122
						$obj->setPassword($prevobj->getPassword());
123
					}
124
					####################################################
125
126
127
					$em = $this->getDoctrine()->getManager();
128
					$em->persist($obj);
129
					$em->flush();
130
					$this->get('session')->getFlashBag()->add('success', sprintf('The %s has been %s successfully', $name, $key ? 'modified' : 'created'));
131
					return $this->render('VivaitBootstrapBundle:Default:redirect.html.twig', array('redirect' => $request->query->get('parent', $request->request->get('parent', $request->headers->get('referer')))));
132
				}
133
			}
134
			if(isset($form)) {
135
				$formtpl['form'] = $form->createView();
136
			}
137
			$formtpl['action'] = $this->generateUrl($this->container->get('request')->get('_route'), $request->query->all());
138
139
			return $this->render('VivaitBootstrapBundle:Default:form.html.twig', array(
140
				'form' => array_merge($formtpl, array('parent' => $request->query->get('parent', $request->request->get('parent', $request->headers->get('referer')))))));
141
		}
142
143
144 View Code Duplication
		public function deleteAction(Request $request) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
145
			################################################  SETTINGS  ################################################
146
			$name         = 'user';
147
			$repo         = 'VivaitAuthBundle:User';
148
			$id           = $request->query->get('id', 0);
149
			$msg_notfound = "The $name could not be found";
150
			$msg_success  = "The $name has been removed";
151
			############################################################################################################
152
153
			$obj = $this->getDoctrine()
154
			            ->getRepository($repo)
155
			            ->find($id);
156
157
			if(!$obj) {
158
				$this->get('session')->getFlashBag()->add('error', $msg_notfound);
159
			} else {
160
				$em = $this->getDoctrine()->getManager();
161
				$em->remove($obj);
162
				$em->flush();
163
				$this->get('session')->getFlashBag()->add('success', $msg_success);
164
			}
165
166
			return $this->redirect($request->headers->get('referer'));
167
		}
168
169
		public function impersonateAction(Request $request) {
170
			################################################  SETTINGS  ################################################
171
			$repo = 'VivaitAuthBundle:User';
172
			$twig = 'VivaitAuthBundle:Partials:impersonateuser.html.twig';
173
			############################################################################################################
174
			$db = $this->getDoctrine()
175
			           ->getRepository($repo)
176
			           ->findAll();
177
178
179
180
			$params['parent'] = $request->query->get('parent', $request->request->get('parent', $request->headers->get('referer')));
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
181
			return $this->render($twig, array('db' => $db, 'params' => $params));
182
		}
183
184
185
//		public function twofactorAction(Request $request) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
186
//			################################################  SETTINGS  ################################################
187
//			$name             = 'User';
188
//			$repo             = 'VivaitAuthBundle:User';
189
//			$formtpl['title'] = '2-Factor Authentication';
190
//			$key              = $this->get('security.context')->getToken()->getUser();
191
//			############################################################################################################
192
//
193
//			$obj = $this->getDoctrine()
194
//				->getRepository($repo)
195
//				->find($key);
196
//
197
//			if(!$obj) {
198
//				$this->get('session')->getFlashBag()->add('error', sprintf("Could not find the %s", $name));
199
//			}
200
//
201
//
202
//			$form = $this->createFormBuilder();
203
//			if($obj->getTfkey()) {
204
//				$formtpl['content'] = '2-Factor authentication has been enabled for this account, to disable it click the button below.';
205
//				$form->add('disable', 'submit', array('label' => 'Disable'));
206
//			} else {
207
//				$formtpl['content'] = '2-Factor authentication protects your account by making sure that to access it, you need your username, password and your token generator (typically a mobile device)';
208
//				$form->add('enable', 'submit', array('label' => 'Enable'));
209
//			}
210
//			$form = $form->getForm();
211
//
212
//			if($request->isMethod('POST')) {
213
//				$form->bind($request);
214
//				if($form->isValid()) {
215
//
216
//					if($obj->getTfkey() && $form->get('disable')->isClicked()) {
217
//						$obj->setTfkey(null);
218
//					} else {
219
//
220
//						$bytes = openssl_random_pseudo_bytes(10);
221
//						$string   = bin2hex($bytes);
222
//						$this->get('session')->getFlashBag()->add('success', $string);
223
//						$obj->setTfkey($bytes);
224
//					}
225
//
226
//
227
//					$em = $this->getDoctrine()->getManager();
228
//					$em->persist($obj);
229
//					$em->flush();
230
//					$this->get('session')->getFlashBag()->add('success', sprintf('2-Factor authentication has been %s', $obj->getTfkey() ? 'enabled' : 'disabled'));
231
//					return $this->render('VivaitBootstrapBundle:Default:redirect.html.twig', array('redirect' => $request->query->get('parent', $request->request->get('parent', $request->headers->get('referer')))));
232
//				}
233
//			}
234
//
235
//			if(isset($form)) {
236
//				$formtpl['form'] = $form->createView();
237
//			}
238
//			$formtpl['action'] = $this->generateUrl($this->container->get('request')->get('_route'), $request->query->all());
239
//			return $this->render('VivaitBootstrapBundle:Default:form.html.twig', array('form' => array_merge($formtpl, array('parent' => $request->query->get('parent', $request->request->get('parent', $request->headers->get('referer')))))));
240
//
241
//
242
//		}
243
//
244
//		private static function base32_decode($b32) {
245
//			$lut = array("A" => 0, "B" => 1,
246
//			             "C" => 2, "D" => 3,
247
//			             "E" => 4, "F" => 5,
248
//			             "G" => 6, "H" => 7,
249
//			             "I" => 8, "J" => 9,
250
//			             "K" => 10, "L" => 11,
251
//			             "M" => 12, "N" => 13,
252
//			             "O" => 14, "P" => 15,
253
//			             "Q" => 16, "R" => 17,
254
//			             "S" => 18, "T" => 19,
255
//			             "U" => 20, "V" => 21,
256
//			             "W" => 22, "X" => 23,
257
//			             "Y" => 24, "Z" => 25,
258
//			             "2" => 26, "3" => 27,
259
//			             "4" => 28, "5" => 29,
260
//			             "6" => 30, "7" => 31
261
//			);
262
//
263
//			$b32    = strtoupper($b32);
264
//			$l      = strlen($b32);
265
//			$n      = 0;
266
//			$j      = 0;
267
//			$binary = "";
268
//
269
//			for($i = 0; $i < $l; $i++) {
270
//
271
//				$n = $n << 5;
272
//				$n = $n + $lut[$b32[$i]];
273
//				$j = $j + 5;
274
//
275
//				if($j >= 8) {
276
//					$j = $j - 8;
277
//					$binary .= chr(($n & (0xFF << $j)) >> $j);
278
//				}
279
//			}
280
//
281
//			return $binary;
282
//		}
283
	}
284