Completed
Push — develop ( c635bd...85470e )
by
unknown
17:23 queued 09:19
created

ManageController::changeStatus()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 16
rs 9.4285
cc 3
eloc 10
nc 4
nop 2
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
7
 * @license   MIT
8
 */
9
10
/** ActionController of Core */
11
namespace Cv\Controller;
12
13
use Geo\Form\GeoText;
14
use Zend\Mvc\Controller\AbstractActionController;
15
use Zend\View\Model\JsonModel;
16
use Core\Form\SummaryFormInterface;
17
use Auth\Entity\User;
18
use Cv\Entity\Cv;
19
use Cv\Entity\Contact;
20
21
/**
22
 * Main Action Controller for the application.
23
 * Responsible for displaying the home site.
24
 *
25
 */
26
class ManageController extends AbstractActionController
27
{
28
29
    /**
30
     * attaches further Listeners for generating / processing the output
31
     * @return $this
32
     */
33 View Code Duplication
    public function attachDefaultListeners()
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...
34
    {
35
        parent::attachDefaultListeners();
36
        $serviceLocator  = $this->serviceLocator;
37
        $defaultServices = $serviceLocator->get('DefaultListeners');
38
        $events          = $this->getEventManager();
39
        $events->attach($defaultServices);
0 ignored issues
show
Documentation introduced by
$defaultServices is of type object|array, but the function expects a string.

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...
40
        return $this;
41
    }
42
    
43
    public function formAction()
44
    {
45
        $serviceLocator = $this->serviceLocator;
46
        $repositories = $serviceLocator->get('repositories');
47
        /* @var $cvRepository \Cv\Repository\Cv */
48
        $cvRepository = $repositories->get('Cv/Cv');
49
        $user = $this->auth()->getUser();
0 ignored issues
show
Documentation Bug introduced by
The method auth does not exist on object<Cv\Controller\ManageController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
50
        /* @var $cv Cv */
51
        $cv = $cvRepository->findDraft($user);
52
        $params = $this->params();
53
        
54
        if (empty($cv)) {
55
            // create draft CV
56
            $cv = $cvRepository->create();
57
            $cv->setIsDraft(true);
58
            $cv->setContact($user->getRole() == User::ROLE_USER ? $user->getInfo() : new Contact());
59
            $cv->setUser($user);
60
            $repositories->store($cv);
61
        }
62
        
63
        if (($status = $params->fromQuery('status')) != '') {
64
            return $this->changeStatus($cv, $status);
0 ignored issues
show
Compatibility introduced by
$cv of type object<Core\Entity\EntityInterface> is not a sub-type of object<Cv\Entity\Cv>. It seems like you assume a concrete implementation of the interface Core\Entity\EntityInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
65
        }
66
        
67
        /* @var $container \Core\Form\Container */
68
        $container = $serviceLocator->get('FormElementManager')
69
            ->get('CvContainer')
70
            ->setEntity($cv);
71
72
        // process post method
73
        if ($this->getRequest()->isPost()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Stdlib\RequestInterface as the method isPost() does only exist in the following implementations of said interface: Zend\Http\PhpEnvironment\Request, Zend\Http\Request.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
74
            $form = $container->getForm($params->fromQuery('form'));
75
76
            if ($form) {
77
                $form->setData(array_merge(
78
                    $params->fromPost(),
79
                    $params->fromFiles()
80
                ));
81
                
82
                if (!$form->isValid()) {
83
                    return new JsonModel([
84
                        'valid' => false,
85
                        'errors' => $form->getMessages()
86
                    ]);
87
                }
88
                /*
89
                 * @todo This is a workaround for GeoJSON data insertion
90
                 * until we figured out, what we really want it to be.
91
                 */
92
                $formId = $params->fromQuery('form');
93 View Code Duplication
                if ('preferredJob' == $formId) {
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...
94
                    $locElem = $form->getBaseFieldset()->get('geo-location');
95
                    if ($locElem instanceof GeoText) {
96
                        $loc = $locElem->getValue('entity');
97
                        $locations = $cv->getPreferredJob()->getDesiredLocations();
98
                        if (count($locations)) {
99
                            $locations->clear();
100
                        }
101
                        $locations->add($loc);
102
                        $cv->getPreferredJob()->setDesiredLocation($locElem->getValue());
103
                    }
104
                }
105
106
                $repositories->store($cv);
107
                
108
                if ($form instanceof SummaryFormInterface) {
109
                    $form->setRenderMode(SummaryFormInterface::RENDER_SUMMARY);
110
                    $viewHelper = 'summaryform';
111
                } else {
112
                    $viewHelper = 'form';
113
                }
114
                
115
                // render form
116
                $content = $serviceLocator->get('ViewHelperManager')
117
                    ->get($viewHelper)
118
                    ->__invoke($form);
119
                
120
                return new JsonModel([
121
                    'valid' => true,
122
                    'content' => $content
123
                ]);
124
            } elseif (($action = $params->fromQuery('action')) !== null) {
125
                return new JsonModel($container->executeAction($action, $params->fromPost()));
126
            }
127
        }// end of process post method
128
        else {
129
            $locElem = $container->getForm('preferredJob')->getBaseFieldset()->get('geo-location');
130
            if ($locElem instanceof GeoText) {
131
                $loc = $cv->getPreferredJob()->getDesiredLocations();
132
                if (count($loc)) {
133
                    $locElem->setValue($loc->first());
134
                }
135
            }
136
        }
137
138
        return [
139
            'container' => $container,
140
            'cv' => $cv
141
        ];
142
    }
143
144
    /**
145
     *
146
     * @param Cv $cv
147
     * @param string $status
148
     * @return \Zend\Http\Response
149
     */
150
    protected function changeStatus(Cv $cv, $status)
151
    {
152
        if ($status != $cv->getStatus()) {
153
            try {
154
                $cv->setStatus($status);
155
                
156
                $this->notification()->success(
0 ignored issues
show
Documentation Bug introduced by
The method notification does not exist on object<Cv\Controller\ManageController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
157
                    /*@translate*/ 'Status has been successfully changed');
158
            } catch (\DomainException $e) {
159
                $this->notification()->error(
0 ignored issues
show
Documentation Bug introduced by
The method notification does not exist on object<Cv\Controller\ManageController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
160
                    /*@translate*/ 'Invalid status');
161
            }
162
        }
163
        
164
        return $this->redirect()->refresh();
165
    }
166
}
167