Completed
Push — develop ( 989a9a...864a1a )
by
unknown
08:17
created

ImportController::factory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 3
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
     * attaches further Listeners for generating / processing the output
50
     * @return $this
51
     */
52 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...
53
    {
54
        parent::attachDefaultListeners();
55
        $serviceLocator  = $this->serviceLocator;
56
        $defaultServices = $serviceLocator->get('DefaultListeners');
57
        $events          = $this->getEventManager();
58
        $events->attach($defaultServices);
0 ignored issues
show
Bug introduced by
The call to attach() misses a required argument $listener.

This check looks for function calls that miss required arguments.

Loading history...
59
        return $this;
60
    }
61
62
    /**
63
     * api-interface for transferring jobs
64
     * @return JsonModel
65
     */
66
    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...
67
    {
68
        $services = $this->serviceLocator;
69
70
        /* @var \Zend\Http\PhpEnvironment\Request $request */
71
        $request = $this->getRequest();
72
73
        $params          = $this->params();
74
        $p               = $params->fromPost();
75
        /* @var \Auth\Entity\User $user */
76
        $user            = $services->get('AuthenticationService')->getUser();
77
        $repositories    = $services->get('repositories');
78
        /* @var \Jobs\Repository\Job $repositoriesJob */
79
        $repositoriesJob = $repositories->get('Jobs/Job');
80
        $log             = $services->get('Core/Log');
81
82
        $result = array('token' => session_id(), 'isSaved' => false, 'message' => '', 'portals' => array());
83
        try {
84
            if (isset($user) && !empty($user->getLogin())) {
85
                $formElementManager = $services->get('FormElementManager');
86
                /* @var \Jobs\Form\Import $form */
87
                $form               = $formElementManager->get('Jobs/Import');
88
                $id                 = $params->fromPost('id'); // determine Job from Database
89
                /* @var \Jobs\Entity\Job $entity */
90
                $entity             = null;
91
                $createdJob         = true;
92
93
                if (empty($id)) {
94
                    $applyId = $params->fromPost('applyId');
95
                    if (empty($applyId)) {
96
                        $entity = $repositoriesJob->create();
97
                    } else {
98
                        $entity = $repositoriesJob->findOneBy(array("applyId" => (string) $applyId));
99
                        if (!isset($entity)) {
100
                            // new Job (the more likely branch)
101
                            $entity =$repositoriesJob->create(array("applyId" => (string) $applyId));
102
                        } else {
103
                            $createdJob = false;
104
                        }
105
                    }
106
                } else {
107
                    $repositoriesJob->find($id);
108
                    $createdJob = false;
109
                }
110
                //$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...
111
                $form->bind($entity);
112
                if ($request->isPost()) {
113
                    $loginSuffix                   = '';
114
                    $event                         = $this->getEvent();
115
                    $loginSuffixResponseCollection = $this->getEventManager()->trigger('login.getSuffix', $event);
116
                    if (!$loginSuffixResponseCollection->isEmpty()) {
117
                        $loginSuffix = $loginSuffixResponseCollection->last();
118
                    }
119
                    $params                        = $request->getPost();
120
                    $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...
121
                    $result['post']                = $_POST;
122
                    $form->setData($params);
123
                    if ($form->isValid()) {
124
125
                        if (isset($params['description'])) {
126
                            $templateValues = new TemplateValues();
127
                            $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...
128
                            $entity->setTemplateValues($templateValues->setDescription(strip_tags($description)));
129
                        }
130
131
                        $entity->setStatus($params['status']);
132
                        /*
133
                         * Search responsible user via contactEmail
134
                         * @var \Auth\Repository\User $users
135
                         */
136
                        $users = $repositories->get('Auth/User');
137
                        $responsibleUser = $users->findByEmail($params['contactEmail']);
138
139
                        $entity->setUser($responsibleUser ?: $user);
140
141
                        $group = $user->getGroup($entity->getCompany());
142
                        if ($group) {
143
                            $entity->getPermissions()->grant($group, PermissionsInterface::PERMISSION_VIEW);
144
                        }
145
                        $result['isSaved'] = true;
146
                        $log->info('Jobs/manage/saveJob [user: ' . $user->getLogin() . ']:' . var_export($p, true));
147
148
                        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...
149
                            $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...
150
                            $repOrganization          = $repositories->get('Organizations/Organization');
151
                            $hydratorManager          = $services->get('hydratorManager');
152
                            /* @var \Organizations\Entity\Hydrator\OrganizationHydrator $hydrator */
153
                            $hydrator                 = $hydratorManager->get('Hydrator/Organization');
154
                            $entityOrganizationFromDB = $repOrganization->findbyRef($companyId);
155
                            //$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...
156
                            $data = array(
157
                                'externalId'      => $companyId,
158
                                '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...
159
                                '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...
160
                                'user'            => $user
161
                            );
162
                            //$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...
163
164
                            $entityOrganization = $hydrator->hydrate($data, $entityOrganizationFromDB);
165
166
                            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...
167
                                $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...
168
                            }
169
170
                            if ($responsibleUser && $user !== $responsibleUser) {
171
                                /*
172
                                 * We cannot use custom collections yet
173
                                 * @todo if we updated Mongo ODM to >1.0.5, we must move this to
174
                                 *       a custom collection class
175
                                 */
176
                                $employees = $entityOrganization->getEmployees();
177
                                $contained = false;
178
                                /*
179
                                 * this is o(n) and should propably be optimized when the custom collection is created.
180
                                 * It's not very performant to load the whole user entity, when all we need is the ID.
181
                                 * Maybe store the id as reference in the Employees Entity.
182
                                 */
183
                                foreach ($employees as $employee) {
184
                                    if ($employee->getUser()->getId() == $responsibleUser->getId()) {
185
                                        $contained = true;
186
                                        break;
187
                                    }
188
                                }
189
                                if (!$contained) {
190
                                    $employees->add(new Employee($responsibleUser));
191
                                }
192
                            }
193
                            $repositories->store($entityOrganization);
194
                            $entity->setOrganization($entityOrganization);
195
                        } else {
196
                            $result['message'] = '';
197
                        }
198
199
                        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...
200
                            $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...
201
                            $jobLocations = $entity->getLocations();
202
                            $jobLocations->clear();
203
                            foreach ($locations as $locData) {
204
                                $location = new Location();
205
                                $coords = array_map(function ($i) { return (float) $i; }, $locData['coordinates']);
206
                                $location->setCountry($locData['country'])
207
                                         ->setRegion($locData['region'])
208
                                         ->setCity($locData['city'])
209
                                         ->setCoordinates(new Point($coords));
210
211
                                $jobLocations->add($location);
212
                            }
213
                        }
214
                        $repositoriesJob->store($entity);
215
                        $id = $entity->getId();
216
                        if (!empty($id)) {
217
                            $jobEvent = $services->get('Jobs/Event');
218
                            $jobEvent->setJobEntity($entity);
219
220
                            $extra = [];
221
                            foreach (array('channels', 'positions', 'branches', 'keywords', 'description') as $paramName) {
222
                                $data = $params->get($paramName);
223
                                if ($data) {
224
                                    $data = Json::decode($data, Json::TYPE_ARRAY);
225
                                    if ('channels' == $paramName) {
226
                                        foreach (array_keys($data) as $portalName) {
227
                                            $jobEvent->addPortal($portalName);
228
                                        }
229
                                    }
230
231
                                    $extra[$paramName] = $data;
232
                                }
233
                            }
234
                            $jobEvent->setParam('extraData', $extra);
235
236
                            if ($createdJob || true) {
237
                                /* @var $jobEvents \Zend\EventManager\EventManager */
238
                                $jobEvents = $services->get('Jobs/Events');
239
                                $jobEvent->setName(JobEvent::EVENT_JOB_ACCEPTED)
240
                                         ->setTarget($this);
241
                                $responses = $jobEvents->trigger($jobEvent);
242
                                foreach ($responses as $response) {
243
                                    // responses from the portals
244
                                    // @TODO, put this in some conclusion and meaningful messages
245
                                    if (!empty($response)) {
246
                                        if ($response instanceof JobResponse) {
247
                                            if (!array_key_exists('log', $result)) {
248
                                                $result['log'] = '';
249
                                            }
250
                                            //$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...
251
                                            //$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...
252
                                            $status = $response->getStatus();
253
                                            $portal = $response->getPortal();
254
                                            if (empty($portal)) {
255
                                                throw new \RuntimeException('Publisher-Events (internal error): There is an unregistered publisher listening');
256
                                            }
257
                                            switch ($status) {
258
                                                case JobResponse::RESPONSE_FAIL:
259
                                                case JobResponse::RESPONSE_NOTIMPLEMENTED:
260
                                                case JobResponse::RESPONSE_ERROR:
261
                                                    $result['isSaved'] = false;
262
                                                    break;
263
                                                case JobResponse::RESPONSE_DENIED:
264
                                                case JobResponse::RESPONSE_OK:
265
                                                case JobResponse::RESPONSE_OKANDSTOP:
266
                                                case JobResponse::RESPONSE_DEPRECATED:
267
                                                    break;
268
                                            }
269
                                            if (array_key_exists($portal, $result['portals'])) {
270
                                                throw new \RuntimeException('Publisher-Events (internal error): There are two publisher registered for ' . $portal);
271
                                            }
272
                                            $result['portals'][$portal] = $status;
273
                                        } else {
274
                                            throw new \RuntimeException('Publisher-Events (internal error): Response must be from the class Jobs\Listener\Response\JobResponse');
275
                                        }
276
                                    } else {
277
                                        throw new \RuntimeException('Publisher-Events (internal error): Response must be set');
278
                                    }
279
                                }
280
                            }
281
                        }
282
                    } else {
283
                        $log->info('Jobs/manage/saveJob [error: ' . $form->getMessages() . ']:' . var_export($p, true));
284
                        $result['valid Error'] = $form->getMessages();
285
                    }
286
                }
287
            } else {
288
                $log->info('Jobs/manage/saveJob [error: session lost]:' . var_export($p, true));
289
                $result['message'] = 'session_id is lost';
290
            }
291
        } catch (\Exception $e) {
292
            $result['message'] = 'exception occured: ' . $e->getMessage();
293
        }
294
        //$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...
295
        return new JsonModel($result);
296
    }
297
}
298