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
10namespace Zend\View\Helper;
11
12use Zend\View\Exception;
13use Zend\View\Model\ModelInterface as Model;
14
15/**
16 * View helper for retrieving layout object
17 */
18class Layout extends AbstractHelper
19{
20    /**
21     * @var ViewModel
22     */
23    protected $viewModelHelper;
24
25    /**
26     * Set layout template or retrieve "layout" view model
27     *
28     * If no arguments are given, grabs the "root" or "layout" view model.
29     * Otherwise, attempts to set the template for that view model.
30     *
31     * @param  null|string $template
32     * @return Layout
33     */
34    public function __invoke($template = null)
35    {
36        if (null === $template) {
37            return $this->getRoot();
38        }
39
40        return $this->setTemplate($template);
41    }
42
43    /**
44     * Get layout template
45     *
46     * @return string
47     */
48    public function getLayout()
49    {
50        return $this->getRoot()->getTemplate();
51    }
52
53    /**
54     * Get the root view model
55     *
56     * @throws Exception\RuntimeException
57     * @return null|Model
58     */
59    protected function getRoot()
60    {
61        $helper = $this->getViewModelHelper();
62
63        if (!$helper->hasRoot()) {
64            throw new Exception\RuntimeException(sprintf(
65                '%s: no view model currently registered as root in renderer',
66                __METHOD__
67            ));
68        }
69
70        return $helper->getRoot();
71    }
72
73    /**
74     * Set layout template
75     *
76     * @param  string $template
77     * @return Layout
78     */
79    public function setTemplate($template)
80    {
81        $this->getRoot()->setTemplate((string) $template);
82        return $this;
83    }
84
85    /**
86     * Retrieve the view model helper
87     *
88     * @return ViewModel
89     */
90    protected function getViewModelHelper()
91    {
92        if (null === $this->viewModelHelper) {
93            $this->viewModelHelper = $this->getView()->plugin('view_model');
94        }
95
96        return $this->viewModelHelper;
97    }
98}
99