Completed
Push — develop ( 6a168f...92c47e )
by
unknown
12:16
created

ImportController   B

Complexity

Total Complexity 39

Size/Duplication

Total Lines 243
Duplicated Lines 3.7 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 6
Bugs 2 Features 1
Metric Value
wmc 39
c 6
b 2
f 1
lcom 1
cbo 12
dl 9
loc 243
rs 8.2857

2 Methods

Rating   Name   Duplication   Size   Complexity  
A attachDefaultListeners() 9 9 1
F saveAction() 0 221 38

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * YAWIK
5
 *
6
 * @filesource
7
 * @copyright (c) 2013-2015 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\Status;
17
use Organizations\Entity\Employee;
18
use Zend\Json\Json;
19
use Zend\Mvc\Controller\AbstractActionController;
20
use Zend\View\Model\JsonModel;
21
use Zend\Stdlib\Parameters;
22
use Core\Entity\PermissionsInterface;
23
use Jobs\Listener\Events\JobEvent;
24
use Jobs\Listener\Response\JobResponse;
25
26
/**
27
 *
28
 *
29
 */
30
class ImportController extends AbstractActionController
31
{
32
33
    /**
34
     * attaches further Listeners for generating / processing the output
35
     * @return $this
36
     */
37 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...
38
    {
39
        parent::attachDefaultListeners();
40
        $serviceLocator  = $this->getServiceLocator();
41
        $defaultServices = $serviceLocator->get('DefaultListeners');
42
        $events          = $this->getEventManager();
43
        $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...
44
        return $this;
45
    }
46
47
    /**
48
     * api-interface for transferring jobs
49
     * @return JsonModel
50
     */
51
    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...
52
    {
53
54
        $services = $this->getServiceLocator();
55
        $config   = $services->get('Config');
0 ignored issues
show
Unused Code introduced by
$config is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
56
        
57
        if (true) { // && isset($config['debug']) && isset($config['debug']['import.job']) && $config['debug']['import.job']) {
0 ignored issues
show
Bug introduced by
Avoid IF statements that are always true or false
Loading history...
Unused Code Comprehensibility introduced by
81% 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...
58
            // Test
59
            $this->request->setMethod('post');
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 setMethod() 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...
60
            $params = new Parameters(
61
                array(
62
                'applyId' => '71022',
63
                'company' => 'Holsten 4',
64
                'companyId' => '1745',
65
                'contactEmail' => '[email protected]',
66
                'title' => 'Fuhrparkleiter/-in MODs',
67
                'location' => 'Bundesland, Bayern, DE',
68
                'link' => 'http://anzeigen.jobsintown.de/job/1/79161.html',
69
                'datePublishStart' => '2013-11-15',
70
                'status' => 'active',
71
                'reference' => '2130010128',
72
                'atsEnabled' => '1',
73
                'uriApply' => 'http://mw2.yawik.org/de/apply/129145',
74
                'logoRef' => 'http://anzeigen.jobsintown.de/companies/logo/image-id/3263',
75
                'publisher' => 'http://anzeigen.jobsintown.de/feedbackJobPublish/' . '2130010128',
76
                'imageUrl' => 'http://th07.deviantart.net/fs71/PRE/i/2014/230/5/8/a_battle_with_the_elements_by_lordljcornellphotos-d7vns0p.jpg',
77
                'locations' => '[{"country":"Deutschland","city":null,"region":"Mecklenburg-Vorpommern","coordinates":["13.2555","53.5476"]}]',
78
79
                )
80
            );
81
            $this->getRequest()->setPost($params);
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 setPost() 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...
82
        }
83
84
        $params          = $this->params();
85
        $p               = $params->fromPost();
86
        $user            = $services->get('AuthenticationService')->getUser();
87
        $repositories    = $services->get('repositories');
88
        $repositoriesJob = $repositories->get('Jobs/Job');
89
        $log             = $services->get('Core/Log');
90
91
        $result = array('token' => session_id(), 'isSaved' => false, 'message' => '', 'portals' => array());
92
        try {
93
            if (isset($user) && !empty($user->login)) {
94
                $formElementManager = $services->get('FormElementManager');
95
                $form               = $formElementManager->get('Jobs/Import');
96
                $id                 = $params->fromPost('id'); // determine Job from Database
97
                $entity             = null;
98
                $createdJob         = true;
99
100
                if (empty($id)) {
101
                    $applyId = $params->fromPost('applyId');
102
                    if (empty($applyId)) {
103
                        // new Job (propably this branch is never used since all Jobs should have an apply-Id)
104
                        $entity = $repositoriesJob->create();
105
                    } else {
106
                        $entity = $repositoriesJob->findOneBy(array("applyId" => (string) $applyId));
107
                        if (!isset($entity)) {
108
                            // new Job (the more likely branch)
109
                            $entity =$repositoriesJob->create(array("applyId" => (string) $applyId));
110
                        } else {
111
                            $createdJob = false;
112
                        }
113
                        $entity->setid('test');
114
                    }
115
                } else {
116
                    $repositoriesJob->find($id);
117
                    $createdJob = false;
118
                }
119
                //$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...
120
                $form->bind($entity);
121
                if ($this->request->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...
122
                    $loginSuffix                   = '';
123
                    $event                         = $this->getEvent();
124
                    $loginSuffixResponseCollection = $this->getEventManager()->trigger('login.getSuffix', $event);
125
                    if (!$loginSuffixResponseCollection->isEmpty()) {
126
                        $loginSuffix = $loginSuffixResponseCollection->last();
127
                    }
128
                    $params                        = $this->getRequest()->getPost();
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 getPost() 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...
129
                    $params->datePublishStart      = \Datetime::createFromFormat("Y-m-d", $params->datePublishStart);
130
                    $result['post']                = $_POST;
131
                    $form->setData($params);
132
                    if ($form->isValid()) {
133
                        $entity->setStatus($params['status']);
134
                        /*
135
                         * Search responsible user via contactEmail
136
                         */
137
                        $users = $repositories->get('Auth/User');
138
                        $responsibleUser = $users->findByEmail($params['contactEmail']);
139
140
                        $entity->setUser($responsibleUser ?: $user);
141
142
                        $group = $user->getGroup($entity->getCompany());
143
                        if ($group) {
144
                            $entity->getPermissions()->grant($group, PermissionsInterface::PERMISSION_VIEW);
145
                        }
146
                        $result['isSaved'] = true;
147
                        $log->info('Jobs/manage/saveJob [user: ' . $user->login . ']:' . var_export($p, true));
148
149
                        if (!empty($params->companyId)) {
150
                            $companyId                = $params->companyId . $loginSuffix;
151
                            $repOrganization          = $repositories->get('Organizations/Organization');
152
                            $hydratorManager          = $services->get('hydratorManager');
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,
159
                                'image'            => $params->logoRef,
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
                            $entityOrganization = $hydrator->hydrate($data, $entityOrganizationFromDB);
164
                            if ($responsibleUser && $user !== $responsibleUser) {
165
                                $entityOrganization->getEmployees()->add(new Employee($responsibleUser));
166
                            }
167
                            $repositories->store($entityOrganization);
168
                            $entity->setOrganization($entityOrganization);
169
170
                        } else {
171
                            $result['message'] = '';
172
                        }
173
174
                        if (!empty($params->locations)) {
175
                            $locations = \Zend\Json\Json::decode($params->locations, \Zend\Json\Json::TYPE_ARRAY);
176
                            $jobLocations = $entity->getLocations();
177
                            $jobLocations->clear();
178
                            foreach ($locations as $locData) {
179
                                $location = new Location();
180
                                $coords = array_map(function($i) { return (float) $i; }, $locData['coordinates']);
181
                                $location->setCountry($locData['country'])
182
                                         ->setRegion($locData['region'])
183
                                         ->setCity($locData['city'])
184
                                         ->setCoordinates(new Point($coords));
185
186
                                $jobLocations->add($location);
187
                            }
188
                        }
189
                        $repositoriesJob->store($entity);
190
                        $id = $entity->getId();
191
                        if (!empty($id)) {
192
                            $jobEvent = $services->get('Jobs/Event');
193
                            $jobEvent->setJobEntity($entity);
194
195
                            $extra = [];
196
                            foreach (array('channels', 'positions', 'branches', 'keywords', 'description') as $paramName) {
197
                                $data = $params->get($paramName);
198
                                if ($data) {
199
                                    $data = Json::decode($data, Json::TYPE_ARRAY);
200
                                    if ('channels' == $paramName) {
201
                                        foreach (array_keys($data) as $portalName) {
202
                                            $jobEvent->addPortal($portalName);
203
                                        }
204
                                    }
205
206
                                    $extra[$paramName] = $data;
207
                                }
208
                            }
209
                            $jobEvent->setParam('extraData', $extra);
210
211
                            if ($createdJob || True) {
212
                                /* @var $jobEvents \Zend\EventManager\EventManager */
213
                                $jobEvents = $services->get('Jobs/Events');
214
                                $jobEvent->setName(JobEvent::EVENT_JOB_ACCEPTED)
215
                                         ->setTarget($this);
216
                                $responses = $jobEvents->trigger($jobEvent);
0 ignored issues
show
Documentation introduced by
$jobEvent is of type object|array, but the function expects a string|object<Zend\EventManager\EventInterface>.

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...
217
                                foreach ($responses as $response) {
218
                                    // responses from the portals
219
                                    // @TODO, put this in some conclusion and meaningful messages
220
                                    if (!empty($response)) {
221
                                        if ($response instanceof JobResponse) {
222
                                            if (!array_key_exists('log', $result)) {
223
                                                $result['log'] = '';
224
                                            }
225
                                            //$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...
226
                                            //$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...
227
                                            $status = $response->getStatus();
228
                                            $portal = $response->getPortal();
229
                                            if (empty($portal)) {
230
                                                throw new \RuntimeException('Publisher-Events (internal error): There is an unregistered publisher listening');
231
                                            }
232
                                            switch ($status) {
233
                                                case JobResponse::RESPONSE_FAIL:
234
                                                case JobResponse::RESPONSE_NOTIMPLEMENTED:
235
                                                case JobResponse::RESPONSE_ERROR:
236
                                                    $result['isSaved'] = false;
237
                                                    break;
238
                                                case JobResponse::RESPONSE_DENIED:
239
                                                case JobResponse::RESPONSE_OK:
240
                                                case JobResponse::RESPONSE_OKANDSTOP:
241
                                                case JobResponse::RESPONSE_DEPRECATED:
242
                                                    break;
243
                                            }
244
                                            if (array_key_exists($portal, $result['portals'])) {
245
                                                throw new \RuntimeException('Publisher-Events (internal error): There are two publisher registered for ' . $portal);
246
                                            }
247
                                            $result['portals'][$portal] = $status;
248
                                        } else {
249
                                            throw new \RuntimeException('Publisher-Events (internal error): Response must be from the class Jobs\Listener\Response\JobResponse');
250
                                        }
251
                                    } else {
252
                                        throw new \RuntimeException('Publisher-Events (internal error): Response must be set');
253
                                    }
254
                                }
255
                            }
256
                        }
257
                    } else {
258
                        $log->info('Jobs/manage/saveJob [error: ' . $form->getMessages() . ']:' . var_export($p, true));
259
                        $result['valid Error'] = $form->getMessages();
260
                    }
261
                }
262
            } else {
263
                $log->info('Jobs/manage/saveJob [error: session lost]:' . var_export($p, true));
264
                $result['message'] = 'session_id is lost';
265
            }
266
        } catch (\Exception $e) {
267
            $result['message'] = 'exception occured: ' . $e->getMessage();
268
        }
269
        //$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...
270
        return new JsonModel($result);
271
    }
272
}
273