Completed
Pull Request — develop (#462)
by ANTHONIUS
08:03
created

ProfileController   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 118
Duplicated Lines 19.49 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 8
dl 23
loc 118
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 1
A indexAction() 23 23 1
C detailAction() 0 50 7

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
 * @license MIT
8
 * @copyright  2013 - 2017 Cross Solution <http://cross-solution.de>
9
 */
10
11
namespace Organizations\Controller;
12
13
14
use Auth\Exception\UnauthorizedAccessException;
15
use Core\Entity\Exception\NotFoundException;
16
use Jobs\Repository\Job as JobRepository;
17
use Organizations\Entity\Organization;
18
use Organizations\Repository\Organization as OrganizationRepository;
19
use Zend\Http\Response;
20
use Zend\I18n\Translator\TranslatorInterface;
21
use Zend\Mvc\Controller\AbstractActionController;
22
use Zend\View\Model\ViewModel;
23
use Organizations\ImageFileCache\Manager as ImageFileCacheManager;
24
25
/**
26
 * Class ProfileController
27
 *
28
 * @author Anthonius Munthi <[email protected]>
29
 * @package Organizations\Controller
30
 * @since 0.30.1
31
 */
32
class ProfileController extends AbstractActionController
33
{
34
    /**
35
     * @var OrganizationRepository
36
     */
37
    private $repo;
38
39
    /**
40
     * @var JobRepository
41
     */
42
    private $jobRepo;
43
44
    /**
45
     * @var TranslatorInterface
46
     */
47
    private $translator;
48
49
    /**
50
     * @var ImageFileCacheManager
51
     */
52
    private $imageFileCacheManager;
53
54
    public function __construct(
55
        OrganizationRepository $repo,
56
        JobRepository $jobRepository,
57
        TranslatorInterface $translator,
58
        ImageFileCacheManager $imageFileCacheManager
59
    )
60
    {
61
        $this->repo = $repo;
62
        $this->translator = $translator;
63
        $this->imageFileCacheManager = $imageFileCacheManager;
64
        $this->jobRepo = $jobRepository;
65
    }
66
67
    /**
68
     * List organization
69
     *
70
     * @return ViewModel
71
     */
72 View Code Duplication
    public function indexAction()
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...
73
    {
74
75
        $result = $this->pagination([
0 ignored issues
show
Documentation Bug introduced by
The method pagination does not exist on object<Organizations\Con...ller\ProfileController>? Since you implemented __call, maybe consider adding a @method annotation.

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

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

class ParentClass {
    private $data = array();

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

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

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
76
            'paginator' => [
77
                'Organizations/Organization',
78
                'as' => 'organizations',
79
                'params' => [
80
                    'type' => 'profile',
81
                ]
82
            ],
83
            'form' => [
84
                'Core/Search',
85
                [
86
                    'text_name' => 'text',
87
                    'text_placeholder' => /*@translate*/ 'Search for organizations',
88
                    'button_element' => 'text',
89
                ],
90
                'as' => 'form'
91
            ]
92
        ]);
93
        return new ViewModel($result);
94
    }
95
96
    /**
97
     * @return array|ViewModel
98
     */
99
    public function detailAction()
100
    {
101
        $translator      = $this->translator;
102
        $repo            = $this->repo;
103
        $id              = $this->params('id');
104
105
        if(is_null($id)){
106
            $this->getResponse()->setStatusCode(Response::STATUS_CODE_404);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Stdlib\ResponseInterface as the method setStatusCode() does only exist in the following implementations of said interface: Zend\Http\PhpEnvironment\Response, Zend\Http\Response, Zend\Http\Response\Stream.

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...
107
            return [
108
                'message' => $translator->translate('Can not access profile page without id'),
109
                'exception' => new \InvalidArgumentException('Null Organization Profile Id')
110
            ];
111
        }
112
113
        $organization = $repo->find($id);
114
        if(!$organization instanceof Organization){
115
            throw new NotFoundException($id);
116
        }
117
118
        if(
119
            Organization::PROFILE_DISABLED == $organization->getProfileSetting()
120
            || is_null($organization->getProfileSetting())
121
        ){
122
            throw new UnauthorizedAccessException(/*@translate*/ 'This Organization Profile is disabled');
123
        }
124
125
        $result = $this->pagination([
0 ignored issues
show
Documentation Bug introduced by
The method pagination does not exist on object<Organizations\Con...ller\ProfileController>? Since you implemented __call, maybe consider adding a @method annotation.

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

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

class ParentClass {
    private $data = array();

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

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

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
126
            'params' => [
127
                'Organization_Jobs',[
128
                    'organization_id' => $organization->getId()
129
                ]
130
            ],
131
            'paginator' => ['as' => 'jobs','Organizations/ListJob'],
132
        ]);
133
134
        if(
135
            Organization::PROFILE_ACTIVE_JOBS == $organization->getProfileSetting()
136
        ){
137
            /* @var \Zend\Paginator\Paginator $paginator */
138
            $paginator = $result['jobs'];
139
            $count = $paginator->getTotalItemCount();
140
            if(0===$count){
141
                throw new UnauthorizedAccessException(/*@translate*/ 'This Organization Profile is disabled');
142
            }
143
        }
144
        $result['organization'] = $organization;
145
        $result['organizationImageCache'] = $this->imageFileCacheManager;
146
147
        return new ViewModel($result);
148
    }
149
}
150