Completed
Push — develop ( ff69a2...5c149c )
by Carsten
25:49 queued 22:46
created

Index::attachDefaultListeners()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 7
Ratio 100 %

Importance

Changes 0
Metric Value
dl 7
loc 7
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @license    MIT
7
 * @copyright  2013 - 2016 Cross Solution <http://cross-solution.de>
8
 */
9
10
/** */
11
namespace Install\Controller;
12
13
use Core\Service\ClearCacheService;
14
use Zend\Form\FormElementManager\FormElementManagerV3Polyfill as FormElementManager;
15
use Zend\Json\Json;
16
use Zend\ModuleManager\Listener\ListenerOptions;
17
use Zend\Mvc\Controller\AbstractActionController;
18
use Zend\Mvc\MvcEvent;
19
use Zend\Stdlib\ResponseInterface;
20
use Zend\View\Model\ViewModel;
21
22
/**
23
 * Install module main controller.
24
 *
25
 * @author Mathias Gelhausen <[email protected]>
26
 * @todo   write test
27
 * @since  0.20
28
 */
29
class Index extends AbstractActionController
30
{
31
    protected $installForm;
32
33
    /**
34
     * @var ClearCacheService
35
     */
36
    private $cacheService;
37
38
    public function __construct(FormElementManager $formElementManager)
39
    {
40
        $this->installForm = $formElementManager->get('Install/Installation');
41
42
        $config = $formElementManager->getServiceLocator()->get('ApplicationConfig');
43
        $options = new ListenerOptions($config['module_listener_options']);
44
        $this->cacheService = new ClearCacheService($options);
45
    }
46
    
47
    /**
48
     * Hook for custom preDispatch event.
49
     *
50
     * @param MvcEvent $event
51
     */
52
    public function preDispatch(MvcEvent $event)
53
    {
54
        $this->layout()->setVariable('lang', $this->params('lang'));
55
56
        $p       = $this->params()->fromQuery('p');
57
        $request = $this->getRequest();
58
59
        if ($p && $request->isXmlHttpRequest()) {
60
            $routeMatch = $event->getRouteMatch();
61
            $routeMatch->setParam('action', $p);
62
            $response = $this->getResponse();
63
            $response->getHeaders()
64
                     ->addHeaderLine('Content-Type', 'application/json')
65
                     ->addHeaderLine('Content-Encoding', 'utf8');
66
        }
67
    }
68
69
    /**
70
     * Index action.
71
     *
72
     * @return ViewModel
73
     */
74
    public function indexAction()
75
    {
76
        // Clear the user identity, if any. (#370)
77
        if (PHP_SESSION_ACTIVE !== session_status()) {
78
            session_start();
79
        }
80
        session_destroy();
81
82
        $form    = $this->installForm;
83
        $prereqs = $this->plugin('Install/Prerequisites')->check();
84
    
85
        return $this->createViewModel(
86
            array(
87
                'prerequisites' => $prereqs,
88
                'form'          => $form,
89
                'lang'          => $this->params('lang'),
90
            )
91
        );
92
    }
93
94
    /**
95
     * Action to check prerequisites via ajax request.
96
     *
97
     * @return ViewModel|ResponseInterface
98
     */
99
    public function prereqAction()
100
    {
101
        $prereqs = $this->plugin('Install/Prerequisites')->check();
102
103
        $model = $this->createViewModel(array('prerequisites' => $prereqs), true);
104
        $model->setTemplate('install/index/prerequisites.ajax.phtml');
105
106
        return $model;
107
    }
108
109
    /**
110
     * Main working action. Creates the configuration.
111
     *
112
     * @return ResponseInterface|ViewModel
113
     */
114
    public function installAction()
115
    {
116
        $form = $this->installForm;
117
        $form->setData($_POST);
118
119
        if (!$form->isValid()) {
120
            return $this->createJsonResponse(
121
                array(
122
                    'ok'     => false,
123
                    'errors' => $form->getMessages(),
124
                )
125
            );
126
        }
127
128
        $data = $form->getData();
129
130
        try {
131
            $options = [
132
                'connection' => $data['db_conn'],
133
            ];
134
            $userOk = $this->plugin('Install/UserCreator', $options)->process($data['username'], $data['password'], $data['email']);
0 ignored issues
show
Unused Code introduced by
$userOk 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...
135
            $ok = $this->plugin('Install/ConfigCreator')->process($data['db_conn'], $data['email']);
136
        } catch (\Exception $exception) {
137
            /* @TODO: provide a way to handle global error message */
138
            return $this->createJsonResponse([
139
                'ok'        => false,
140
                'errors'    => [
141
                    'global' => [$exception->getMessage()]
142
                ]
143
            ]);
144
        }
145
146
        /*
147
         * Make sure there's no cached config files
148
         */
149
        $this->cacheService->clearCache();
150
151
        $model = $this->createViewModel(array('ok' => $ok), true);
152
        $model->setTemplate('install/index/install.ajax.phtml');
153
154
        return $model;
155
    }
156
157
    /**
158
     * Attaches default listeners to the event manager.
159
     */
160 View Code Duplication
    protected 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...
161
    {
162
        parent::attachDefaultListeners();
163
    
164
        $events = $this->getEventManager();
165
        $events->attach(MvcEvent::EVENT_DISPATCH, array( $this, 'preDispatch' ), 100);
166
    }
167
168
    /**
169
     * Creates a view model
170
     *
171
     * @param array $params
172
     * @param bool  $terminal
173
     *
174
     * @return ViewModel
175
     */
176
    protected function createViewModel(array $params, $terminal = false)
177
    {
178
        if (!isset($params['lang'])) {
179
            $params['lang'] = $this->params('lang');
180
        }
181
182
183
        $model = new ViewModel($params);
184
        $terminal && $model->setTerminal($terminal);
185
186
        return $model;
187
    }
188
189
    /**
190
     * Create a json response object for ajax requests.
191
     *
192
     * @param array $variables
193
     *
194
     * @return \Zend\Stdlib\ResponseInterface
195
     */
196
    protected function createJsonResponse(array $variables)
197
    {
198
        $response = $this->getResponse();
199
        $json     = Json::encode($variables);
200
        $response->setContent($json);
201
202
        return $response;
203
    }
204
}
205