Completed
Push — develop ( 18f015...6c5b6e )
by Mathias
09:41 queued 05:06
created

ProfileController::detailAction()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 58

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 58
rs 7.983
c 0
b 0
f 0
cc 7
nc 6
nop 0

How to fix   Long Method   

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
 * @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
    /**
55
     * @var array
56
     */
57
    private $options = [
58
        'count' => 10,
59
    ];
60
61
    public function __construct(
62
        OrganizationRepository $repo,
63
        JobRepository $jobRepository,
64
        TranslatorInterface $translator,
65
        ImageFileCacheManager $imageFileCacheManager,
66
        $options
67
    )
68
    {
69
        $this->repo = $repo;
70
        $this->translator = $translator;
71
        $this->imageFileCacheManager = $imageFileCacheManager;
72
        $this->jobRepo = $jobRepository;
73
        $this->options = $options;
74
    }
75
76
    /**
77
     * List organization
78
     *
79
     * @return ViewModel
80
     */
81
    public function indexAction()
82
    {
83
84
        $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...
85
            'params' => ['Organizations_Profile',[
86
                    'q',
87
                    'count' => $this->options['count'],
88
                    'page' => 1,
89
                ]
90
            ],
91
            'paginator' => [
92
                'Organizations/Organization',
93
                'as' => 'organizations',
94
                'params' => [
95
                    'type' => 'profile',
96
                ]
97
            ],
98
            'form' => [
99
                'Core/Search',
100
                'as' => 'form',
101
            ]
102
        ]);
103
104
        $organizationImageCache = $this->imageFileCacheManager;
105
        $result['organizationImageCache'] = $organizationImageCache;
106
107
        return new ViewModel($result);
108
    }
109
110
    /**
111
     * @return array|ViewModel
112
     */
113
    public function detailAction()
114
    {
115
        $translator      = $this->translator;
116
        $repo            = $this->repo;
117
        $id              = $this->params('id');
118
119
        if(is_null($id)){
120
            $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...
121
            return [
122
                'message' => $translator->translate('Can not access profile page without id'),
123
                'exception' => new \InvalidArgumentException('Null Organization Profile Id')
124
            ];
125
        }
126
127
        $organization = $repo->find($id);
128
        if(!$organization instanceof Organization){
129
            throw new NotFoundException($id);
130
        }
131
132
        if(
133
            Organization::PROFILE_DISABLED == $organization->getProfileSetting()
134
            || is_null($organization->getProfileSetting())
135
        ){
136
            return $this->disabledProfileViewModel($organization);
137
        }
138
139
        $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...
140
            'params' => [
141
                'Organization_Jobs',[
142
                    'q',
143
                    'organization_id' => $id,
144
                    'count' => $this->options['count'],
145
                    'page' => 1,
146
                ],
147
            ],
148
            'paginator' => [
149
                'as' => 'jobs',
150
                'Organizations/ListJob',
151
            ],
152
        ]);
153
154
        if(
155
            Organization::PROFILE_ACTIVE_JOBS == $organization->getProfileSetting()
156
        ){
157
            /* @var \Zend\Paginator\Paginator $paginator */
158
            $paginator = $result['jobs'];
159
            $count = $paginator->getTotalItemCount();
160
            if(0===$count){
161
                return $this->disabledProfileViewModel($organization);
162
            }
163
        }
164
        $result['organization'] = $organization;
165
        $result['organizationImageCache'] = $this->imageFileCacheManager;
166
167
        /* @var \Zend\Mvc\Controller\Plugin\Url $url */
168
        $result['paginationControlRoute'] = 'lang/organizations/profileDetail';
169
        return new ViewModel($result);
170
    }
171
172
    private function disabledProfileViewModel($organization)
173
    {
174
        $model = new ViewModel([
175
            'organization' => $organization,
176
        ]);
177
        $model->setTemplate('organizations/profile/disabled');
178
179
        return $model;
180
    }
181
}
182