Completed
Push — develop ( 864a1a...718342 )
by
unknown
06:53
created

ImportController::saveAction()   F

Complexity

Conditions 42
Paths > 20000

Size

Total Lines 232
Code Lines 151

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 232
rs 2
c 0
b 0
f 0
cc 42
eloc 151
nc 650212
nop 0

How to fix   Long Method    Complexity   

Long Method

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:

1
<?php
2
3
/**
4
 * YAWIK
5
 *
6
 * @filesource
7
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
8
 * @license   MIT
9
 */
10
11
/** ActionController of Core */
12
namespace Jobs\Controller;
13
14
use Geo\Entity\Geometry\Point;
15
use Jobs\Entity\Location;
16
use Jobs\Entity\TemplateValues;
17
use Organizations\Entity\Employee;
18
use Psr\Container\ContainerInterface;
19
use Zend\Json\Json;
20
use Zend\Mvc\Controller\AbstractActionController;
21
use Zend\ServiceManager\ServiceManager;
22
use Zend\View\Model\JsonModel;
23
use Core\Entity\PermissionsInterface;
24
use Jobs\Listener\Events\JobEvent;
25
use Jobs\Listener\Response\JobResponse;
26
27
/**
28
 *
29
 *
30
 */
31
class ImportController extends AbstractActionController
32
{
33
34
    /**
35
     *
36
     *
37
     * @var ServiceManager
38
     */
39
    private $serviceLocator;
40
    public static function factory(ContainerInterface $container, $requestedName, array $options = null)
41
    {
42
        $controller = new self();
43
        $controller->serviceLocator = $container;
0 ignored issues
show
Documentation Bug introduced by
$container is of type object<Psr\Container\ContainerInterface>, but the property $serviceLocator was declared to be of type object<Zend\ServiceManager\ServiceManager>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
44
45
        return $controller;
46
    }
47
48
    /**
49
     * api-interface for transferring jobs
50
     * @return JsonModel
51
     */
52
    public function saveAction()
0 ignored issues
show
Coding Style introduced by
saveAction uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
53
    {
54
        $services = $this->serviceLocator;
55
56
        /* @var \Zend\Http\PhpEnvironment\Request $request */
57
        $request = $this->getRequest();
58
59
        $params          = $this->params();
60
        $p               = $params->fromPost();
61
        /* @var \Auth\Entity\User $user */
62
        $user            = $services->get('AuthenticationService')->getUser();
63
        $repositories    = $services->get('repositories');
64
        /* @var \Jobs\Repository\Job $repositoriesJob */
65
        $repositoriesJob = $repositories->get('Jobs/Job');
66
        $log             = $services->get('Core/Log');
67
68
        $result = array('token' => session_id(), 'isSaved' => false, 'message' => '', 'portals' => array());
69
        try {
70
            if (isset($user) && !empty($user->getLogin())) {
71
                $formElementManager = $services->get('FormElementManager');
72
                /* @var \Jobs\Form\Import $form */
73
                $form               = $formElementManager->get('Jobs/Import');
74
                $id                 = $params->fromPost('id'); // determine Job from Database
75
                /* @var \Jobs\Entity\Job $entity */
76
                $entity             = null;
77
                $createdJob         = true;
78
79
                if (empty($id)) {
80
                    $applyId = $params->fromPost('applyId');
81
                    if (empty($applyId)) {
82
                        $entity = $repositoriesJob->create();
83
                    } else {
84
                        $entity = $repositoriesJob->findOneBy(array("applyId" => (string) $applyId));
85
                        if (!isset($entity)) {
86
                            // new Job (the more likely branch)
87
                            $entity =$repositoriesJob->create(array("applyId" => (string) $applyId));
88
                        } else {
89
                            $createdJob = false;
90
                        }
91
                    }
92
                } else {
93
                    $repositoriesJob->find($id);
94
                    $createdJob = false;
95
                }
96
                //$services->get('repositories')->get('Jobs/Job')->store($entity);
0 ignored issues
show
Unused Code Comprehensibility introduced by
83% 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...
97
                $form->bind($entity);
98
                if ($request->isPost()) {
99
                    $loginSuffix                   = '';
100
                    $event                         = $this->getEvent();
101
                    $event->setName('login.getSuffix');
102
                    $loginSuffixResponseCollection = $this->getEventManager()->triggerEvent($event);
103
                    if (!$loginSuffixResponseCollection->isEmpty()) {
104
                        $loginSuffix = $loginSuffixResponseCollection->last();
105
                    }
106
                    $params                        = $request->getPost();
107
                    $params->datePublishStart      = \Datetime::createFromFormat("Y-m-d", $params->datePublishStart);
0 ignored issues
show
Bug introduced by
Accessing datePublishStart on the interface Zend\Stdlib\ParametersInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
108
                    $result['post']                = $_POST;
109
                    $form->setData($params);
110
                    if ($form->isValid()) {
111
112
                        if (isset($params['description'])) {
113
                            $templateValues = new TemplateValues();
114
                            $description = Json::decode($params->description);
0 ignored issues
show
Bug introduced by
Accessing description on the interface Zend\Stdlib\ParametersInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
115
                            $entity->setTemplateValues($templateValues->setDescription(strip_tags($description)));
116
                        }
117
118
                        $entity->setStatus($params['status']);
119
                        /*
120
                         * Search responsible user via contactEmail
121
                         * @var \Auth\Repository\User $users
122
                         */
123
                        $users = $repositories->get('Auth/User');
124
                        $responsibleUser = $users->findByEmail($params['contactEmail']);
125
126
                        $entity->setUser($responsibleUser ?: $user);
127
128
                        $group = $user->getGroup($entity->getCompany());
129
                        if ($group) {
130
                            $entity->getPermissions()->grant($group, PermissionsInterface::PERMISSION_VIEW);
131
                        }
132
                        $result['isSaved'] = true;
133
                        $log->info('Jobs/manage/saveJob [user: ' . $user->getLogin() . ']:' . var_export($p, true));
134
135
                        if (!empty($params->companyId)) {
0 ignored issues
show
Bug introduced by
Accessing companyId on the interface Zend\Stdlib\ParametersInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
136
                            $companyId                = $params->companyId . $loginSuffix;
0 ignored issues
show
Bug introduced by
Accessing companyId on the interface Zend\Stdlib\ParametersInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
137
                            $repOrganization          = $repositories->get('Organizations/Organization');
138
                            $hydratorManager          = $services->get('HydratorManager');
139
                            /* @var \Organizations\Entity\Hydrator\OrganizationHydrator $hydrator */
140
                            $hydrator                 = $hydratorManager->get('Hydrator\Organization');
141
                            $entityOrganizationFromDB = $repOrganization->findbyRef($companyId);
142
                            //$permissions              = $entityOrganizationFromDB->getPermissions();
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
143
                            $data = array(
144
                                'externalId'      => $companyId,
145
                                'organizationName' => $params->company,
0 ignored issues
show
Bug introduced by
Accessing company on the interface Zend\Stdlib\ParametersInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
146
                                'image'            => $params->logoRef,
0 ignored issues
show
Bug introduced by
Accessing logoRef on the interface Zend\Stdlib\ParametersInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
147
                                'user'            => $user
148
                            );
149
                            //$permissions->grant($user, PermissionsInterface::PERMISSION_CHANGE);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
150
151
                            $entityOrganization = $hydrator->hydrate($data, $entityOrganizationFromDB);
152
153
                            if ($params->companyUrl) {
0 ignored issues
show
Bug introduced by
Accessing companyUrl on the interface Zend\Stdlib\ParametersInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
154
                                $entityOrganization->getContact()->setWebsite($params->companyUrl);
0 ignored issues
show
Bug introduced by
Accessing companyUrl on the interface Zend\Stdlib\ParametersInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
155
                            }
156
157
                            if ($responsibleUser && $user !== $responsibleUser) {
158
                                /*
159
                                 * We cannot use custom collections yet
160
                                 * @todo if we updated Mongo ODM to >1.0.5, we must move this to
161
                                 *       a custom collection class
162
                                 */
163
                                $employees = $entityOrganization->getEmployees();
164
                                $contained = false;
165
                                /*
166
                                 * this is o(n) and should propably be optimized when the custom collection is created.
167
                                 * It's not very performant to load the whole user entity, when all we need is the ID.
168
                                 * Maybe store the id as reference in the Employees Entity.
169
                                 */
170
                                foreach ($employees as $employee) {
171
                                    if ($employee->getUser()->getId() == $responsibleUser->getId()) {
172
                                        $contained = true;
173
                                        break;
174
                                    }
175
                                }
176
                                if (!$contained) {
177
                                    $employees->add(new Employee($responsibleUser));
178
                                }
179
                            }
180
                            $repositories->store($entityOrganization);
181
                            $entity->setOrganization($entityOrganization);
182
                        } else {
183
                            $result['message'] = '';
184
                        }
185
186
                        if (!empty($params->locations)) {
0 ignored issues
show
Bug introduced by
Accessing locations on the interface Zend\Stdlib\ParametersInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
187
                            $locations = \Zend\Json\Json::decode($params->locations, \Zend\Json\Json::TYPE_ARRAY);
0 ignored issues
show
Bug introduced by
Accessing locations on the interface Zend\Stdlib\ParametersInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
188
                            $jobLocations = $entity->getLocations();
189
                            $jobLocations->clear();
190
                            foreach ($locations as $locData) {
191
                                $location = new Location();
192
                                $coords = array_map(function ($i) { return (float) $i; }, $locData['coordinates']);
193
                                $location->setCountry($locData['country'])
194
                                         ->setRegion($locData['region'])
195
                                         ->setCity($locData['city'])
196
                                         ->setCoordinates(new Point($coords));
197
198
                                $jobLocations->add($location);
199
                            }
200
                        }
201
                        $repositoriesJob->store($entity);
202
                        $id = $entity->getId();
203
                        if (!empty($id)) {
204
                            $jobEvent = $services->get('Jobs/Event');
205
                            $jobEvent->setJobEntity($entity);
206
207
                            $extra = [];
208
                            foreach (array('channels', 'positions', 'branches', 'keywords', 'description') as $paramName) {
209
                                $data = $params->get($paramName);
210
                                if ($data) {
211
                                    $data = Json::decode($data, Json::TYPE_ARRAY);
212
                                    if ('channels' == $paramName) {
213
                                        foreach (array_keys($data) as $portalName) {
214
                                            $jobEvent->addPortal($portalName);
215
                                        }
216
                                    }
217
218
                                    $extra[$paramName] = $data;
219
                                }
220
                            }
221
                            $jobEvent->setParam('extraData', $extra);
222
223
                            if ($createdJob || true) {
224
                                /* @var $jobEvents \Zend\EventManager\EventManager */
225
                                $jobEvents = $services->get('Jobs/Events');
226
                                $jobEvent->setName(JobEvent::EVENT_JOB_ACCEPTED);
227
                                $jobEvent->setTarget($this);
228
                                $responses = $jobEvents->triggerEvent($jobEvent);
229
                                foreach ($responses as $response) {
230
                                    // responses from the portals
231
                                    // @TODO, put this in some conclusion and meaningful messages
232
                                    if (!empty($response)) {
233
                                        if ($response instanceof JobResponse) {
234
                                            if (!array_key_exists('log', $result)) {
235
                                                $result['log'] = '';
236
                                            }
237
                                            //$message = $response->getMessage();
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
238
                                            //$result['log'] .= $response->getMessage() . PHP_EOL;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
239
                                            $status = $response->getStatus();
240
                                            $portal = $response->getPortal();
241
                                            if (empty($portal)) {
242
                                                throw new \RuntimeException('Publisher-Events (internal error): There is an unregistered publisher listening');
243
                                            }
244
                                            switch ($status) {
245
                                                case JobResponse::RESPONSE_FAIL:
246
                                                case JobResponse::RESPONSE_NOTIMPLEMENTED:
247
                                                case JobResponse::RESPONSE_ERROR:
248
                                                    $result['isSaved'] = false;
249
                                                    break;
250
                                                case JobResponse::RESPONSE_DENIED:
251
                                                case JobResponse::RESPONSE_OK:
252
                                                case JobResponse::RESPONSE_OKANDSTOP:
253
                                                case JobResponse::RESPONSE_DEPRECATED:
254
                                                    break;
255
                                            }
256
                                            if (array_key_exists($portal, $result['portals'])) {
257
                                                throw new \RuntimeException('Publisher-Events (internal error): There are two publisher registered for ' . $portal);
258
                                            }
259
                                            $result['portals'][$portal] = $status;
260
                                        } else {
261
                                            throw new \RuntimeException('Publisher-Events (internal error): Response must be from the class Jobs\Listener\Response\JobResponse');
262
                                        }
263
                                    } else {
264
                                        throw new \RuntimeException('Publisher-Events (internal error): Response must be set');
265
                                    }
266
                                }
267
                            }
268
                        }
269
                    } else {
270
                        $log->info('Jobs/manage/saveJob [error: ' . $form->getMessages() . ']:' . var_export($p, true));
271
                        $result['valid Error'] = $form->getMessages();
272
                    }
273
                }
274
            } else {
275
                $log->info('Jobs/manage/saveJob [error: session lost]:' . var_export($p, true));
276
                $result['message'] = 'session_id is lost';
277
            }
278
        } catch (\Exception $e) {
279
            $result['message'] = 'exception occured: ' . $e->getMessage();
280
        }
281
        //$services->get('Core/Log')->info('Jobs/manage/saveJob result:' . PHP_EOL . var_export($p, True));
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...
282
        return new JsonModel($result);
283
    }
284
}
285