Issues (19)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

Controller/CRUDController.php (5 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/*
3
 * Copyright 2016-2018 Arnaud Bienvenu
4
 *
5
 * This file is part of Kyela.
6
7
 * Kyela is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Affero General Public License as published by
9
 * the Free Software Foundation, either version 3 of the License, or
10
 * (at your option) any later version.
11
12
 * Kyela is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU Affero General Public License for more details.
16
17
 * You should have received a copy of the GNU Affero General Public License
18
 * along with Kyela.  If not, see <http://www.gnu.org/licenses/>.
19
 *
20
 */
21
22
namespace Abienvenu\KyelaBundle\Controller;
23
24
use Abienvenu\KyelaBundle\Entity\Entity;
25
use Abienvenu\KyelaBundle\Entity\Poll;
26
use Abienvenu\KyelaBundle\Form\Type\FormActionsType;
27
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
28
use Symfony\Component\Form\FormTypeInterface;
29
use Symfony\Component\HttpFoundation\Request;
30
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
31
32
abstract class CRUDController extends PollSetterController
33
{
34
	// Member variables that must be defined in the custom controller
35
	protected $entityName;
36
	protected $cancelRoute;
37
	protected $successRoute;
38
	protected $deleteRoute;
39
	protected $deleteSuccessRoute;
40
41
	// Methods to be implemented in the custom controller
42
	abstract public function newAction(Request $request);
43
	abstract public function editAction(Request $request, $id);
44
	abstract public function deleteAction(Request $request, $id);
45
46
	/**
47
	 * Adds pollUrl into the parameters if not explicitly set
48
	 *
49
	 * @param string $route
50
	 * @param mixed $parameters
51
	 * @param Boolean $absolute
52
	 */
53
	protected function generateUrlWithPoll($route, $parameters = [], $absolute = UrlGeneratorInterface::ABSOLUTE_PATH)
54
	{
55
		if (!isset($parameters['pollUrl']) && $this->poll)
56
		{
57
			$parameters['pollUrl'] = $this->poll->getUrl();
58
		}
59
		return parent::generateUrl($route, $parameters, $absolute);
0 ignored issues
show
$absolute is of type boolean, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Comprehensibility Bug introduced by
It seems like you call parent on a different method (generateUrl() instead of generateUrlWithPoll()). Are you sure this is correct? If so, you might want to change this to $this->generateUrl().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
60
	}
61
62
	/**
63
	 * Create a form to create a new entity, and create it when the form is submited
64
	 */
65
	protected function doNewAction($formType, Entity $entity, Request $request, $successMessage = null, $extra = [])
66
	{
67
		$form = $this->doCreateCreateForm($formType, $entity, $request->get('_route'), $extra);
68
		if ($request->isMethod('POST'))
69
		{
70
			$form->handleRequest($request);
71
72
			if ($entity instanceof Poll)
73
			{
74
				$this->poll = $entity;
75
			}
76
			else
77
			{
78
				$entity->setPoll($this->poll);
0 ignored issues
show
It seems like you code against a specific sub-type and not the parent class Abienvenu\KyelaBundle\Entity\Entity as the method setPoll() does only exist in the following sub-classes of Abienvenu\KyelaBundle\Entity\Entity: Abienvenu\KyelaBundle\Entity\Choice, Abienvenu\KyelaBundle\Entity\Comment, Abienvenu\KyelaBundle\Entity\Event, Abienvenu\KyelaBundle\Entity\Participant. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
79
			}
80
81 View Code Duplication
			if ($form->get('actions')->has('cancel') && $form->get('actions')->get('cancel')->isClicked()) {
0 ignored issues
show
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...
82
				return $this->redirect($this->generateUrlWithPoll($this->cancelRoute));
83
			}
84
85
			if ($form->isValid()) {
86
				$em = $this->getDoctrine()->getManager();
87
				$em->persist($entity);
88
				$em->flush();
89
90
				if ($successMessage) {
91
					$request->getSession()->getFlashBag()->add('success', $successMessage);
92
				}
93
				return $this->redirect($this->generateUrlWithPoll($this->successRoute));
94
			}
95
		}
96
97
		return [
98
			'poll'   => $this->poll,
99
			'entity' => $entity,
100
			'form'   => $form->createView(),
101
		];
102
	}
103
104
	/**
105
	 * Create a form to edit an entity, and update it when the form is submited
106
	 *
107
	 * @param string $formType
108
	 * @param int $id The entity id
109
	 * @param Request $request
110
	 */
111
	protected function doEditAction($formType, $id, Request $request, $extra = [])
112
	{
113
		$em = $this->getDoctrine()->getManager();
114
115
		/** @var Entity $entity */
116
		$entity = $em->getRepository($this->entityName)->find($id);
117
118
		if (!$entity) {
119
			throw $this->createNotFoundException("Unable to find entity.");
120
		}
121
122
		$deleteForm = $this->createDeleteForm($id);
123
		$editForm = $this->doCreateEditForm($formType, $entity, $request->get('_route'), $extra);
124
		if ($request->isMethod('PUT'))
125
		{
126
			$editForm->handleRequest($request);
127
128 View Code Duplication
			if ($editForm->get('actions')->get('cancel')->isClicked()) {
0 ignored issues
show
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...
129
				$em->refresh($entity);
130
				return $this->redirect($this->generateUrlWithPoll($this->cancelRoute));
131
			}
132
133
			if ($editForm->isValid()) {
134
				$em->flush();
135
				return $this->redirect($this->generateUrlWithPoll($this->successRoute));
136
			}
137
			else {
138
				$em->refresh($entity);
139
			}
140
		}
141
142
		return [
143
			'poll'        => $this->poll,
144
			'entity'      => $entity,
145
			'edit_form'   => $editForm->createView(),
146
			'delete_form' => $deleteForm->createView(),
147
		];
148
	}
149
150
	/**
151
	 * Deletes an entity
152
	 *
153
	 * @param Request $request
154
	 * @param mixed $id The entity id
155
	 *
156
	 */
157
	public function doDeleteAction(Request $request, $id)
158
	{
159
		$form = $this->createDeleteForm($id);
160
		$form->handleRequest($request);
161
162
		if ($form->isValid()) {
163
			$em = $this->getDoctrine()->getManager();
164
			$entity = $em->getRepository($this->entityName)->find($id);
165
166
			if (!$entity) {
167
				throw $this->createNotFoundException('Unable to find entity.');
168
			}
169
170
			$em->remove($entity);
171
			$em->flush();
172
			if ($entity instanceof Poll) {
173
				$this->unsetPoll($request);
174
			}
175
			$flashMessage = $this->get('translator')->trans('deleted');
176
			$request->getSession()->getFlashBag()->add('success', $flashMessage);
177
		}
178
		return $this->redirect($this->generateUrlWithPoll($this->deleteSuccessRoute));
179
	}
180
181
	/**
182
	 * Creates a form to create an entity
183
	 *
184
	 * @param FormTypeInterface $formType The form builder
185
	 * @param Entity $entity The new entity
186
	 * @param string $action The name of the route to the action
187
	 *
188
	 * @return \Symfony\Component\Form\Form The form
189
	 */
190
	protected function doCreateCreateForm($formType, Entity $entity, $action, $extra)
191
	{
192
	    $options = $extra + [
193
			'action' => $this->generateUrlWithPoll($action),
194
			'method' => 'POST',
195
		];
196
		$form = $this->createForm($formType, $entity, $options);
197
198
		$options = [
199
			'buttons' => [
200
				'save' => ['type' => SubmitType::class, 'options' => ['label' => 'create']],
201
			]
202
		];
203
		if (!($entity instanceof Poll))
204
		{
205
			$options['buttons']['cancel'] = ['type' => SubmitType::class, 'options' => ['label' => 'cancel', 'attr' => ['type' => 'default', 'novalidate' => true]]];
206
		}
207
		$form->add('actions', FormActionsType::class, $options);
208
		return $form;
209
	}
210
211
	/**
212
	 * Creates a form to edit an entity
213
	 *
214
	 * @param string $formType The form builder
215
	 * @param Entity $entity The entity to edit
216
	 * @param string $action The name of the route to the action
217
	 *
218
	 * @return \Symfony\Component\Form\Form The form
219
	 */
220
	protected function doCreateEditForm($formType, Entity $entity, $action, $extra = [])
221
	{
222
	    $options = $extra + [
223
			'action' => $this->generateUrlWithPoll($action, ['id' => $entity->getId()]),
224
			'method' => 'PUT',
225
		];
226
		$form = $this->createForm($formType, $entity, $options);
227
228
		$form->add('actions', FormActionsType::class, [
229
			'buttons' => [
230
				'save' => ['type' => SubmitType::class, 'options' => ['label' => 'save']],
231
				'cancel' => ['type' => SubmitType::class, 'options' => ['label' => 'cancel', 'attr' => ['type' => 'default', 'novalidate' => true]]],
232
			]
233
		]);
234
		return $form;
235
	}
236
237
	/**
238
	 * Creates a form to delete an entity by id.
239
	 *
240
	 * @param int $id The entity id
241
	 *
242
	 * @return \Symfony\Component\Form\Form The form
243
	 */
244
	protected function createDeleteForm($id)
245
	{
246
		$t = $this->get('translator');
247
		return $this->createFormBuilder()
248
		            ->setAction($this->generateUrlWithPoll($this->deleteRoute, ['id' => $id]))
249
		            ->setMethod('DELETE')
250
		            ->add('submit', SubmitType::class, ['label' => 'delete', 'attr' => ['type' => 'danger', 'onclick' => "return confirm('{$t->trans("are.you.sure.to.delete")}');"]])
251
		            ->getForm();
252
	}
253
}
254