Completed
Push — develop ( ab74f6...880247 )
by
unknown
10:28
created

TemplateController::viewAction()   C

Complexity

Conditions 7
Paths 4

Size

Total Lines 45
Code Lines 27

Duplication

Lines 6
Ratio 13.33 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 6
loc 45
rs 6.7272
cc 7
eloc 27
nc 4
nop 0
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
7
 * @author Mathias Weitz <[email protected]>
8
 * @author Mathias Gelhausen <[email protected]>
9
 * @author Carsten Bleek <[email protected]>
10
 * @author Miroslav Fedeleš <[email protected]>
11
 * @license   MIT
12
 */
13
14
namespace Jobs\Controller;
15
16
use Core\Entity\PermissionsInterface;
17
use Jobs\Entity\Status;
18
use Jobs\Repository;
19
use Zend\Mvc\Controller\AbstractActionController;
20
use Zend\View\Model\ViewModel;
21
use Zend\View\Model\JsonModel;
22
use Zend\Stdlib\AbstractOptions;
23
use Zend\Http\PhpEnvironment\Response;
24
25
/**
26
 * Handles rendering the job in formular and in preview mode
27
 *
28
 * Class TemplateController
29
 * @package Jobs\Controller
30
 */
31
class TemplateController extends AbstractActionController
32
{
33
34
    /**
35
     * @var Repository\Job
36
     */
37
    private $jobRepository;
38
39
    /**
40
     * @var AbstractOptions
41
     */
42
    protected $config;
43
44
    public function __construct(Repository\Job $jobRepository, AbstractOptions $config)
45
    {
46
        $this->jobRepository = $jobRepository;
47
        $this->config = $config;
48
    }
49
50
    /**
51
     * Handles the job opening template in preview mode
52
     *
53
     * @return ViewModel
54
     * @throws \RuntimeException
55
     */
56
    public function viewAction()
57
    {
58
        $id = $this->params()->fromQuery('id');
59
        $response = $this->getResponse();
60
        /* @var \Jobs\Entity\Job $job */
61
        $job = $this->jobRepository->find($id);
62
        
63 View Code Duplication
        if (!$job) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
64
            $response->setStatusCode(Response::STATUS_CODE_404);
65
            return [
66
                'message' => sprintf($this->serviceLocator->get('Translator')->translate('Job with id "%s" not found'), $id)
67
            ];
68
        }
69
        
70
        $mvcEvent             = $this->getEvent();
71
        $applicationViewModel = $mvcEvent->getViewModel();
72
73
        /* @var \Auth\Entity\User $user */
74
        $user = $this->auth()->getUser();
0 ignored issues
show
Documentation Bug introduced by
The method auth does not exist on object<Jobs\Controller\TemplateController>? 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...
75
76
        /* @var \Zend\View\Model\ViewModel $model */
77
        $model = $this->serviceLocator->get('Jobs/viewModelTemplateFilter')->__invoke($job);
78
79
        if (
80
            Status::ACTIVE == $job->getStatus() or
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
81
            $job->getPermissions()->isGranted($user, PermissionsInterface::PERMISSION_VIEW) or
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
82
            $this->auth()->isAdmin()
0 ignored issues
show
Documentation Bug introduced by
The method auth does not exist on object<Jobs\Controller\TemplateController>? 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...
83
        ) {
84
            $applicationViewModel->setTemplate('iframe/iFrameInjection');
85
        }elseif(Status::EXPIRED == $job->getStatus() or  Status::INACTIVE == $job->getStatus()) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
86
            $response->setStatusCode(Response::STATUS_CODE_410);
87
            $model->setTemplate('jobs/error/expired');
88
            $model->setVariables(
89
                [
90
                    'job'=>$job,
91
                    'message', 'the job posting you were trying to open, was inactivated or has expired'
92
                ]
93
            );
94
        } else {
95
            // there is a special handling for 404 in ZF2
96
            $response->setStatusCode(Response::STATUS_CODE_404);
97
            $model->setVariable('message', 'job is not available');
98
        }
99
        return $model;
100
    }
101
102
    /**
103
     * Handles the job opening template in formular mode.
104
     *
105
     * All template forms are sending the ID of a job posting and an identifier of the sending
106
     * form.
107
     *
108
     * @return ViewModel
109
     */
110
    protected function editTemplateAction()
111
    {
112
        $id = $this->params('id');
113
        $formIdentifier=$this->params()->fromQuery('form');
114
        $job = $this->jobRepository->find($id);
115
116
        /** @var \Zend\Http\Request $request */
117
        $request              = $this->getRequest();
118
        $isAjax               = $request->isXmlHttpRequest();
119
        $services             = $this->serviceLocator;
120
        $viewHelperManager    = $services->get('ViewHelperManager');
121
        $mvcEvent             = $this->getEvent();
122
        $applicationViewModel = $mvcEvent->getViewModel();
123
        $forms                = $services->get('FormElementManager');
124
125
        /** @var \Jobs\Form\JobDescriptionTemplate $formTemplate */
126
        $formTemplate         = $forms->get(
127
            'Jobs/Description/Template',
128
            array(
129
            'mode' => $job->id ? 'edit' : 'new'
130
            )
131
        );
132
133
        $formTemplate->setParam('id', $job->id);
134
        $formTemplate->setParam('applyId', $job->applyId);
135
136
        $formTemplate->setEntity($job);
137
138
        if (isset($formIdentifier) && $request->isPost()) {
139
            // at this point the form get instantiated and immediately accumulated
140
141
            $instanceForm = $formTemplate->get($formIdentifier);
142
            if (!isset($instanceForm)) {
143
                throw new \RuntimeException('No form found for "' . $formIdentifier . '"');
144
            }
145
146
            // the id is part of the postData, but it never should be altered
147
            $postData = $request->getPost();
148
149
            unset($postData['id']);
150
            unset($postData['applyId']);
151
152
            $instanceForm->setData($postData);
153
            if ($instanceForm->isValid()) {
154
                $this->serviceLocator->get('repositories')->persist($job);
155
            }
156
        }
157
158
        $model = $services->get('Jobs/ViewModelTemplateFilter')->__invoke($formTemplate);
159
160
        if (!$isAjax) {
161
            $basePath   = $viewHelperManager->get('basepath');
162
            $headScript = $viewHelperManager->get('headscript');
163
            $headScript->appendFile($basePath->__invoke('/Core/js/core.forms.js'));
164
165
            $headStyle = $viewHelperManager->get('headstyle');
166
            $headStyle->prependStyle('form > input {
167
            color: inherit !important; margin:inherit !important;
168
            padding:inherit !important; border:0 !important; cursor:pointer !important; letter-spacing:inherit !important;
169
            line-height: inherit !important;
170
             font-size: inherit !important;
171
}
172
'
173
            );
174
        } else {
175
            return new JsonModel(array('valid' => true));
176
        }
177
        $applicationViewModel->setTemplate('iframe/iFrameInjection');
178
        return $model;
179
    }
180
}
181