Commit | Line | Data |
---|---|---|
44d399bc S |
1 | <?php |
2 | /** | |
3 | * Zend Framework (http://framework.zend.com/) | |
4 | * | |
5 | * @link http://github.com/zendframework/zf2 for the canonical source repository | |
6 | * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) | |
7 | * @license http://framework.zend.com/license/new-bsd New BSD License | |
8 | */ | |
9 | ||
10 | namespace Zend\Mvc\View\Http; | |
11 | ||
12 | use Zend\EventManager\AbstractListenerAggregate; | |
13 | use Zend\EventManager\EventManagerInterface as Events; | |
14 | use Zend\Mvc\MvcEvent; | |
15 | use Zend\Stdlib\ArrayUtils; | |
16 | use Zend\View\Model\ViewModel; | |
17 | ||
18 | class CreateViewModelListener extends AbstractListenerAggregate | |
19 | { | |
20 | /** | |
21 | * {@inheritDoc} | |
22 | */ | |
23 | public function attach(Events $events, $priority = 1) | |
24 | { | |
25 | $this->listeners[] = $events->attach(MvcEvent::EVENT_DISPATCH, [$this, 'createViewModelFromArray'], -80); | |
26 | $this->listeners[] = $events->attach(MvcEvent::EVENT_DISPATCH, [$this, 'createViewModelFromNull'], -80); | |
27 | } | |
28 | ||
29 | /** | |
30 | * Inspect the result, and cast it to a ViewModel if an assoc array is detected | |
31 | * | |
32 | * @param MvcEvent $e | |
33 | * @return void | |
34 | */ | |
35 | public function createViewModelFromArray(MvcEvent $e) | |
36 | { | |
37 | $result = $e->getResult(); | |
38 | if (!ArrayUtils::hasStringKeys($result, true)) { | |
39 | return; | |
40 | } | |
41 | ||
42 | $model = new ViewModel($result); | |
43 | $e->setResult($model); | |
44 | } | |
45 | ||
46 | /** | |
47 | * Inspect the result, and cast it to a ViewModel if null is detected | |
48 | * | |
49 | * @param MvcEvent $e | |
50 | * @return void | |
51 | */ | |
52 | public function createViewModelFromNull(MvcEvent $e) | |
53 | { | |
54 | $result = $e->getResult(); | |
55 | if (null !== $result) { | |
56 | return; | |
57 | } | |
58 | ||
59 | $model = new ViewModel; | |
60 | $e->setResult($model); | |
61 | } | |
62 | } |