Completed
Push — develop ( 725207...6c2664 )
by
unknown
16:33 queued 08:34
created

ManageController::validateCv()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 9
rs 9.2
c 1
b 0
f 0
cc 4
eloc 5
nc 2
nop 1
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 Cv\Entity\CvInterface;
14
use Geo\Form\GeoText;
15
use Zend\Mvc\Controller\AbstractActionController;
16
use Zend\View\Model\JsonModel;
17
use Core\Form\SummaryFormInterface;
18
use Auth\Entity\User;
19
use Cv\Entity\Cv;
20
use Cv\Entity\Contact;
21
22
/**
23
 * Main Action Controller for the application.
24
 * Responsible for displaying the home site.
25
 *
26
 */
27
class ManageController extends AbstractActionController
28
{
29
30
    /**
31
     * attaches further Listeners for generating / processing the output
32
     * @return $this
33
     */
34 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...
35
    {
36
        parent::attachDefaultListeners();
37
        $serviceLocator  = $this->serviceLocator;
38
        $defaultServices = $serviceLocator->get('DefaultListeners');
39
        $events          = $this->getEventManager();
40
        $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...
41
        return $this;
42
    }
43
    
44
    public function formAction()
45
    {
46
        $serviceLocator = $this->serviceLocator;
47
        $repositories = $serviceLocator->get('repositories');
48
        /* @var $cvRepository \Cv\Repository\Cv */
49
        $cvRepository = $repositories->get('Cv/Cv');
50
        $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...
51
        /* @var $cv Cv */
52
        $cv = $this->getCv($cvRepository, $user);
53
        $params = $this->params();
54
        
55
        if (empty($cv)) {
56
            // create draft CV
57
            $cv = $cvRepository->create();
58
            $cv->setIsDraft(true);
59
            $cv->setContact($user->getRole() == User::ROLE_USER ? $user->getInfo() : new Contact());
60
            $cv->setUser($user);
61
            $repositories->store($cv);
62
        }
63
        
64
        if (($status = $params->fromQuery('status')) != '') {
65
            return $this->changeStatus($cv, $status);
66
        }
67
        
68
        /* @var $container \Core\Form\Container */
69
        $container = $serviceLocator->get('FormElementManager')
70
            ->get('CvContainer')
71
            ->setEntity($cv);
72
73
        // process post method
74
        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...
75
            $form = $container->getForm($params->fromQuery('form'));
76
77
            if ($form) {
78
                $form->setData(array_merge(
79
                    $params->fromPost(),
80
                    $params->fromFiles()
81
                ));
82
                
83
                if (!$form->isValid()) {
84
                    return new JsonModel([
85
                        'valid' => false,
86
                        'errors' => $form->getMessages()
87
                    ]);
88
                }
89
                /*
90
                 * @todo This is a workaround for GeoJSON data insertion
91
                 * until we figured out, what we really want it to be.
92
                 */
93
                $formId = $params->fromQuery('form');
94 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...
95
                    $locElem = $form->getBaseFieldset()->get('geo-location');
96
                    if ($locElem instanceof GeoText) {
97
                        $loc = $locElem->getValue('entity');
98
                        $locations = $cv->getPreferredJob()->getDesiredLocations();
99
                        if (count($locations)) {
100
                            $locations->clear();
101
                        }
102
                        $locations->add($loc);
103
                        $cv->getPreferredJob()->setDesiredLocation($locElem->getValue());
104
                    }
105
                }
106
107
                $this->validateCv($cv);
108
109
                $repositories->store($cv);
110
                $viewHelperManager = $serviceLocator->get('ViewHelperManager');
111
                
112 View Code Duplication
                if ('file-uri' === $params->fromPost('return')) {
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...
113
                    $content = $viewHelperManager->get('basepath')
114
                        ->__invoke($form->getHydrator()->getLastUploadedFile()->getUri());
0 ignored issues
show
Bug introduced by
The method getHydrator does only exist in Zend\Form\FormInterface, but not in Core\Form\Container.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
115
                }
116
                else {
117
                    if ($form instanceof SummaryFormInterface) {
118
                        $form->setRenderMode(SummaryFormInterface::RENDER_SUMMARY);
119
                        $viewHelper = 'summaryform';
120
                    } else {
121
                        $viewHelper = 'form';
122
                    }
123
                    
124
                    // render form
125
                    $content = $viewHelperManager->get($viewHelper)
126
                        ->__invoke($form);
127
                }
128
                
129
                return new JsonModel([
130
                    'valid' => true,
131
                    'content' => $content
132
                ]);
133
            } elseif (($action = $params->fromQuery('action')) !== null) {
134
                return new JsonModel($container->executeAction($action, $params->fromPost()));
135
            }
136
        }// end of process post method
137
        else {
138
            $locElem = $container->getForm('preferredJob')->getBaseFieldset()->get('geo-location');
139
            if ($locElem instanceof GeoText) {
140
                $loc = $cv->getPreferredJob()->getDesiredLocations();
141
                if (count($loc)) {
142
                    $locElem->setValue($loc->first());
143
                }
144
            }
145
        }
146
147
        return [
148
            'container' => $container,
149
            'cv' => $cv
150
        ];
151
    }
152
153
    /**
154
     *
155
     * @param Cv $cv
156
     * @param string $status
157
     * @return \Zend\Http\Response
158
     */
159
    protected function changeStatus(Cv $cv, $status)
160
    {
161
        if ($status != $cv->getStatus()) {
162
            try {
163
                $cv->setStatus($status);
164
                
165
                $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...
166
                    /*@translate*/ 'Status has been successfully changed');
167
            } catch (\DomainException $e) {
168
                $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...
169
                    /*@translate*/ 'Invalid status');
170
            }
171
        }
172
        
173
        return $this->redirect()->refresh();
174
    }
175
176
    private function getCv($repository, $user)
177
    {
178
        $id =
179
            $this->params()->fromRoute('id')
180
            ?: ($this->params()->fromQuery('id')
181
                ?: ($this->params()->fromPost('cv')
182
                    ?: null
183
                )
184
            );
185
186
        if ('__my__' == $id) {
187
            return $repository->findOneBy(['user' => $user->getId(), 'isDraft' => null]);
188
        }
189
190
        return $id ? $repository->find($id) : $repository->findDraft($user);
191
    }
192
193
    private function validateCv(Cv $cv)
194
    {
195
        if ($cv->getContact()->getEmail()
196
            && $cv->getPreferredJob()->getDesiredJob()
197
            && count($cv->getPreferredJob()->getDesiredLocations())
198
        ) {
199
            $cv->setIsDraft(false);
200
        }
201
    }
202
}
203