Conditions | 11 |
Paths | 18 |
Total Lines | 49 |
Code Lines | 26 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php |
||
20 | public function onFlush(OnFlushEventArgs $args) |
||
21 | { |
||
22 | $em = $args->getEntityManager(); |
||
23 | $uow = $em->getUnitOfWork(); |
||
24 | |||
25 | foreach ($uow->getScheduledEntityUpdates() as $entity) { |
||
26 | if (!$entity instanceof Ticket) { |
||
27 | return; |
||
28 | } |
||
29 | |||
30 | if (!key_exists('status', $uow->getEntityChangeSet($entity))) { |
||
31 | return; |
||
32 | } |
||
33 | |||
34 | $ticket = $entity; |
||
35 | } |
||
36 | |||
37 | $oldStatus = $uow->getEntityChangeSet($ticket)['status'][0]; |
||
|
|||
38 | $newStatus = $uow->getEntityChangeSet($ticket)['status'][1]; |
||
39 | |||
40 | if (!in_array($newStatus, Ticket::getStatuses())) { |
||
41 | throw new \InvalidArgumentException("Invalid ticket status"); |
||
42 | } |
||
43 | |||
44 | if ($oldStatus === Ticket::STATUS_PAID) { |
||
45 | throw new TicketStatusConflictException("Invalid status. Ticket already paid."); |
||
46 | } |
||
47 | |||
48 | $user = $this->tokenStorage->getToken()->getUser(); |
||
49 | |||
50 | /** @var CustomerOrder $order */ |
||
51 | $order = $em->getRepository('AppBundle:CustomerOrder')->findOpenedCustomerOrder($user); |
||
52 | |||
53 | /** |
||
54 | * Creating order if isn't exist |
||
55 | */ |
||
56 | if (!$order) { |
||
57 | $order = new CustomerOrder($user); |
||
58 | $ticketMetadata = $em->getClassMetadata(CustomerOrder::class); |
||
59 | $em->persist($order); |
||
60 | $uow->computeChangeSet($ticketMetadata, $order); |
||
61 | } |
||
62 | |||
63 | if ($oldStatus === Ticket::STATUS_FREE && $newStatus === Ticket::STATUS_BOOKED) { |
||
64 | $ticket->setCustomerOrder($order); |
||
65 | } elseif ($oldStatus === Ticket::STATUS_BOOKED && $newStatus === Ticket::STATUS_FREE) { |
||
66 | $ticket->setCustomerOrder(null); |
||
67 | } |
||
68 | } |
||
69 | } |
||
70 |
If you define a variable conditionally, it can happen that it is not defined for all execution paths.
Let’s take a look at an example:
In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.
Available Fixes
Check for existence of the variable explicitly:
Define a default value for the variable:
Add a value for the missing path: