ICanBoogie/View v0.5.0
  • Namespace
  • Class

Namespaces

  • ICanBoogie
    • View
      • View

Classes

  • View

Interfaces

  • Exception

Traits

  • ControllerBindings
  • ViewBindings
  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 
<?php

/*
 * This file is part of the ICanBoogie package.
 *
 * (c) Olivier Laviale <olivier.laviale@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ICanBoogie\View;

use ICanBoogie\Events;
use ICanBoogie\OffsetNotDefined;
use ICanBoogie\PropertyNotDefined;
use ICanBoogie\PrototypeTrait;
use ICanBoogie\Render\TemplateName;
use ICanBoogie\Render\TemplateNotFound;
use ICanBoogie\Routing\Controller;

/**
 * A view.
 *
 * @property-read Controller $controller The controller invoking the view.
 * @property-read array $variables The variables to pass to the template.
 * @property mixed $content The content of the view.
 * @property string $layout The name of the layout that should decorate the content.
 * @property string $template The name of the template that should render the content.
 * @property-read callable[] $layout_resolvers @internal
 * @property-read callable[] $template_resolvers @internal
 */
class View implements \ArrayAccess
{
    const TEMPLATE_TYPE_VIEW = 1;
    const TEMPLATE_TYPE_LAYOUT = 2;
    const TEMPLATE_TYPE_PARTIAL = 3;

    const TEMPLATE_PREFIX_VIEW = '';
    const TEMPLATE_PREFIX_LAYOUT = '@';
    const TEMPLATE_PREFIX_PARTIAL = '_';

    static private $template_type_name = [

        self::TEMPLATE_TYPE_VIEW => "template",
        self::TEMPLATE_TYPE_LAYOUT => "layout",
        self::TEMPLATE_TYPE_PARTIAL=> "partial"

    ];

    static private $template_prefix = [

        self::TEMPLATE_TYPE_VIEW => self::TEMPLATE_PREFIX_VIEW,
        self::TEMPLATE_TYPE_LAYOUT => self::TEMPLATE_PREFIX_LAYOUT,
        self::TEMPLATE_TYPE_PARTIAL=> self::TEMPLATE_PREFIX_PARTIAL

    ];

    use PrototypeTrait;
    use ViewBindings;

    /**
     * @var Controller
     */
    private $controller;

    /**
     * @see $controller
     *
     * @return Controller
     */
    protected function get_controller()
    {
        return $this->controller;
    }

    /**
     * View's variables.
     *
     * @var array
     */
    private $variables = [];

    /**
     * @see $variables
     *
     * @return array
     */
    protected function get_variables()
    {
        return $this->variables;
    }

    /**
     * @see $content
     *
     * @return mixed
     */
    protected function get_content()
    {
        return isset($this->variables['content']) ? $this->variables['content'] : null;
    }

    /**
     * @see $content
     *
     * @param mixed $content
     */
    protected function set_content($content)
    {
        $this->variables['content'] = $content;
    }

    private $decorators = [];

    /**
     * Return the name of the template.
     *
     * The template name is resolved as follows:
     *
     * - The `template` property of the route.
     * - The `template` property of the controller.
     * - The `{$controller->name}/{$controller->action}`, if the controller has an `action`
     * property.
     *
     * @return string|null
     */
    protected function lazy_get_template()
    {
        $controller = $this->controller;

        foreach ($this->template_resolvers as $provider)
        {
            try
            {
                return $provider($controller);
            }
            catch (PropertyNotDefined $e)
            {
                #
                # Resolver failed, we continue with the next.
                #
            }

        }

        return null;
    }

    /**
     * Returns an array of callable used to resolve the {@link $template} property.
     *
     * @return callable[]
     *
     * @internal
     */
    protected function get_template_resolvers()
    {
        return [

            function ($controller) {

                return $controller->route->template;

            },

            function ($controller) {

                return $controller->template;

            },

            function ($controller) {

                return $controller->name . "/" . $controller->action;

            }

        ];
    }

    /**
     * Returns the name of the layout.
     *
     * The layout name is resolved as follows:
     *
     * - The `layout` property of the route.
     * - The `layout` property of the controller.
     * - If the identifier of the route starts with "admin:", "admin" is returned.
     * - If the route pattern is "/" and a "home" layout template is available, "home" is returned.
     * - If the "@page" template is available, "page" is returned.
     * - "default" is returned.
     *
     * @return string
     */
    protected function lazy_get_layout()
    {
        $controller = $this->controller;

        foreach ($this->layout_resolvers as $resolver)
        {
            try
            {
                return $resolver($controller);
            }
            catch (PropertyNotDefined $e)
            {
                #
                # Resolver failed, we continue with the next.
                #
            }

        }

        if (strpos($controller->route->id, "admin:") === 0)
        {
            return 'admin';
        }

        if ($controller->route->pattern == "/" && $this->resolve_template('home', self::TEMPLATE_PREFIX_LAYOUT))
        {
            return 'home';
        }

        if ($this->resolve_template('page', self::TEMPLATE_PREFIX_LAYOUT))
        {
            return 'page';
        }

        return 'default';
    }

    /**
     * Returns an array of callable used to resolve the {@link $template} property.
     *
     * @return callable[]
     *
     * @internal
     */
    protected function get_layout_resolvers()
    {
        return [

            function ($controller) {

                return $controller->route->layout;

            },

            function ($controller) {

                return $controller->layout;

            }

        ];
    }

    /**
     * An event hook is attached to the `action` event of the controller for late rendering,
     * which only happens if the response is `null`.
     *
     * @param Controller $controller The controller that invoked the view.
     */
    public function __construct(Controller $controller)
    {
        $this->controller = $controller;

        Events::get()->attach_to($controller, function (Controller\ActionEvent $event, Controller $target) {

            $this->on_action($event);

        });
    }

    /**
     * @inheritdoc
     */
    public function offsetExists($offset)
    {
        return array_key_exists($offset, $this->variables);
    }

    /**
     * @inheritdoc
     *
     * @throws OffsetNotDefined if the offset is not defined.
     */
    public function offsetGet($offset)
    {
        if (!$this->offsetExists($offset))
        {
            throw new OffsetNotDefined([ $offset, $this ]);
        }

        return $this->variables[$offset];
    }

    /**
     * @inheritdoc
     */
    public function offsetSet($offset, $value)
    {
        $this->variables[$offset] = $value;
    }

    /**
     * @inheritdoc
     */
    public function offsetUnset($offset)
    {
        unset($this->variables[$offset]);
    }

    /**
     * Add a path to search for templates.
     *
     * @param string $path
     * @param int $weight
     */
    public function add_path($path, $weight=0)
    {
        $this->template_resolver->add_path($path, $weight);
    }

    /**
     * Resolve a template pathname from its name and type.
     *
     * @param string $name Name of the template.
     * @param string $prefix Template prefix.
     * @param array $tries Reference to an array where tried path are collected.
     *
     * @return string|false
     */
    protected function resolve_template($name, $prefix, &$tries = [])
    {
        $tries = $tries ?: [];

        if ($prefix)
        {
            $name = TemplateName::from($name);
            $name = $name->with_prefix($prefix);
        }

        $resolver = $this->template_resolver;

        return $resolver->resolve($name, $this->engines->extensions, $tries);
    }

    /**
     * Add a template to decorate the content with.
     *
     * @param string $template Name of the template.
     */
    public function decorate_with($template)
    {
        $this->decorators[] = $template;
    }

    /**
     * Decorate the content.
     *
     * @param mixed $content The content to decorate.
     *
     * @return mixed
     */
    protected function decorate($content)
    {
        $decorators = array_reverse($this->decorators);

        foreach ($decorators as $template)
        {
            $content = $this->render_with_template($content, $template, self::TEMPLATE_TYPE_LAYOUT);
        }

        return $content;
    }

    /**
     * Render the view.
     *
     * @return string
     */
    public function render()
    {
        $steps = [

            [ $this->template, self::TEMPLATE_TYPE_VIEW ],
            [ $this->layout, self::TEMPLATE_TYPE_LAYOUT ]

        ];

        $content = $this->content;

        foreach ($steps as list($template, $type))
        {
            if (!$template)
            {
                continue;
            }

            $content = $this->render_with_template($content, $template, $type);
        }

        return $this->decorate($content);
    }

    /**
     * Renders the content using a template.
     *
     * @param mixed $content The content to render.
     * @param string $template Name of the template.
     * @param string $type Type of the template.
     *
     * @return string
     */
    protected function render_with_template($content, $template, $type)
    {
        $pathname = $this->resolve_template($template, self::$template_prefix[$type], $tries);

        if (!$pathname)
        {
            $type_name = self::$template_type_name[$type];

            throw new TemplateNotFound("There is no $type_name matching <q>$template</q>.", $tries);
        }

        list($thisArg, $variables) = $this->prepare_engine_args($content, $type);

        return $this->engines->render($pathname, $thisArg, $variables);
    }

    /**
     * Prepares engine arguments.
     *
     * @param mixed $content
     * @param string $type
     *
     * @return array
     */
    protected function prepare_engine_args($content, $type)
    {
        $variables = $this->variables;

        if ($type == self::TEMPLATE_TYPE_LAYOUT)
        {
            $variables['content'] = $content;

            return [ $this, $variables ];
        }

        $variables['view'] = $this;

        return [ $content, $variables ];
    }

    /**
     * Renders the view on `Controller::action` event.
     *
     * **Note:** The view is not rendered if the event's response is defined, which is the case
     * when the controller obtained a result after its execution.
     *
     * @param Controller\ActionEvent $event
     */
    protected function on_action(Controller\ActionEvent $event)
    {
        if ($event->result !== null)
        {
            return;
        }

        new View\BeforeRender($this);

        $event->result = $this->render();
    }
}
ICanBoogie/View v0.5.0 API documentation generated by ApiGen