view.php 11.9 KB
Newer Older
1
<?php namespace Laravel; use Closure, ArrayAccess;
Taylor Otwell committed
2

3
class View implements ArrayAccess {
4 5

	/**
6
	 * The name of the view.
7
	 *
8
	 * @var string
9
	 */
10
	public $view;
11 12

	/**
13 14 15 16 17 18 19 20
	 * The view data.
	 *
	 * @var array
	 */
	public $data;

	/**
	 * The path to the view on disk.
21 22 23
	 *
	 * @var string
	 */
24
	public $path;
25 26

	/**
27 28 29 30 31 32 33 34
	 * All of the shared view data.
	 *
	 * @var array
	 */
	public static $shared = array();

	/**
	 * All of the registered view names.
35
	 *
36
	 * @var array
37
	 */
38
	public static $names = array();
39 40

	/**
41 42 43 44 45 46 47
	 * The cache content of loaded view files.
	 *
	 * @var array
	 */
	public static $cache = array();

	/**
48 49 50 51 52 53 54
	 * The Laravel view loader event name.
	 *
	 * @var string
	 */
	const loader = 'laravel.view.loader';

	/**
55 56 57 58 59 60 61
	 * The Laravel view engine event name.
	 *
	 * @var string
	 */
	const engine = 'laravel.view.engine';

	/**
62
	 * Create a new view instance.
63
	 *
64 65 66 67 68 69 70 71 72 73 74
	 * <code>
	 *		// Create a new view instance
	 *		$view = new View('home.index');
	 *
	 *		// Create a new view instance of a bundle's view
	 *		$view = new View('admin::home.index');
	 *
	 *		// Create a new view instance with bound data
	 *		$view = new View('home.index', array('name' => 'Taylor'));
	 * </code>
	 *
75 76
	 * @param  string  $view
	 * @param  array   $data
77 78
	 * @return void
	 */
79
	public function __construct($view, $data = array())
80
	{
81 82
		$this->view = $view;
		$this->data = $data;
83 84 85 86 87 88 89 90 91 92 93 94

		// In order to allow developers to load views outside of the normal loading
		// conventions, we'll allow for a raw path to be given in place of the
		// typical view name, giving total freedom on view loading.
		if (starts_with($view, 'path: '))
		{
			$this->path = substr($view, 6);
		}
		else
		{
			$this->path = $this->path($view);
		}
Taylor Otwell committed
95

96
		// If a session driver has been specified, we will bind an instance of the
97
		// validation error message container to every view. If an error instance
98
		// exists in the session, we will use that instance.
99
		if ( ! isset($this->data['errors']))
Taylor Otwell committed
100
		{
101
			if (Session::started() and Session::has('errors'))
Taylor Otwell committed
102
			{
103 104 105 106 107 108
				$this->data['errors'] = Session::get('errors');
			}
			else
			{
				$this->data['errors'] = new Messages;
			}
Taylor Otwell committed
109
		}
110 111 112
	}

	/**
Taylor Otwell committed
113 114 115 116 117
	 * Determine if the given view exists.
	 *
	 * @param  string       $view
	 * @param  boolean      $return_path
	 * @return string|bool
118
	 */
119
	public static function exists($view, $return_path = false)
120
	{
121
		if (starts_with($view, 'name: ') and array_key_exists($name = substr($view, 6), static::$names))
122
		{
123
			$view = static::$names[$name];
124 125
		}
		
126
		list($bundle, $view) = Bundle::parse($view);
127

128
		$view = str_replace('.', '/', $view);
129

130 131 132
		// We delegate the determination of view paths to the view loader event
		// so that the developer is free to override and manage the loading
		// of views in any way they see fit for their application.
133
		$path = Event::until(static::loader, array($bundle, $view));
134

135
		if ( ! is_null($path))
136
		{
137 138
			return $return_path ? $path : true;
		}
Taylor Otwell committed
139

140 141 142 143 144 145 146 147 148 149 150 151 152
		return false;
	}

	/**
	 * Get the path to a given view on disk.
	 *
	 * @param  string  $view
	 * @return string
	 */
	protected function path($view)
	{
		if ($path = $this->exists($view,true))
		{
153
			return $path;
154 155
		}

156
		throw new \Exception("View [$view] doesn't exist.");
157 158 159
	}

	/**
160 161 162 163
	 * Get the path to a view using the default folder convention.
	 *
	 * @param  string  $bundle
	 * @param  string  $view
164
	 * @param  string  $directory
165 166
	 * @return string
	 */
167
	public static function file($bundle, $view, $directory)
168
	{
169
		$directory = str_finish($directory, DS);
170

171
		// Views may have either the default PHP file extension of the "Blade"
172 173
		// extension, so we will need to check for both in the view path
		// and return the first one we find for the given view.
174
		if (file_exists($path = $directory.$view.EXT))
175 176 177
		{
			return $path;
		}
178
		elseif (file_exists($path = $directory.$view.BLADE_EXT))
179 180 181
		{
			return $path;
		}
182 183 184
	}

	/**
185 186
	 * Create a new view instance.
	 *
187 188 189 190
	 * <code>
	 *		// Create a new view instance
	 *		$view = View::make('home.index');
	 *
191 192 193
	 *		// Create a new view instance of a bundle's view
	 *		$view = View::make('admin::home.index');
	 *
194 195 196 197
	 *		// Create a new view instance with bound data
	 *		$view = View::make('home.index', array('name' => 'Taylor'));
	 * </code>
	 *
Taylor Otwell committed
198 199
	 * @param  string  $view
	 * @param  array   $data
200 201
	 * @return View
	 */
202
	public static function make($view, $data = array())
203
	{
204
		return new static($view, $data);
205 206 207
	}

	/**
208
	 * Create a new view instance of a named view.
209
	 *
210
	 * <code>
211 212
	 *		// Create a new named view instance
	 *		$view = View::of('profile');
213
	 *
214 215
	 *		// Create a new named view instance with bound data
	 *		$view = View::of('profile', array('name' => 'Taylor'));
216 217
	 * </code>
	 *
218 219 220 221
	 * @param  string  $name
	 * @param  array   $data
	 * @return View
	 */
222
	public static function of($name, $data = array())
223
	{
224
		return new static(static::$names[$name], $data);
225 226 227
	}

	/**
228 229 230 231 232
	 * Assign a name to a view.
	 *
	 * <code>
	 *		// Assign a name to a view
	 *		View::name('partials.profile', 'profile');
Taylor Otwell committed
233
	 *
234 235 236
	 *		// Resolve an instance of a named view
	 *		$view = View::of('profile');
	 * </code>
237
	 *
238
	 * @param  string  $view
Taylor Otwell committed
239
	 * @param  string  $name
240
	 * @return void
Taylor Otwell committed
241
	 */
242
	public static function name($view, $name)
Taylor Otwell committed
243
	{
244
		static::$names[$name] = $view;
Taylor Otwell committed
245 246 247
	}

	/**
248
	 * Register a view composer with the Event class.
Taylor Otwell committed
249
	 *
250 251 252 253 254 255 256 257
	 * <code>
	 *		// Register a composer for the "home.index" view
	 *		View::composer('home.index', function($view)
	 *		{
	 *			$view['title'] = 'Home';
	 *		});
	 * </code>
	 *
258 259
	 * @param  string|array  $view
	 * @param  Closure       $composer
Taylor Otwell committed
260 261
	 * @return void
	 */
262
	public static function composer($views, $composer)
Taylor Otwell committed
263
	{
264 265 266 267 268 269
		$views = (array) $views;

		foreach ($views as $view)
		{
			Event::listen("laravel.composing: {$view}", $composer);
		}
Taylor Otwell committed
270 271 272
	}

	/**
273
	 * Get the rendered contents of a partial from a loop.
274
	 *
275 276 277 278 279
	 * @param  string  $view
	 * @param  array   $data
	 * @param  string  $iterator
	 * @param  string  $empty
	 * @return string
280
	 */
281
	public static function render_each($view, array $data, $iterator, $empty = 'raw|')
282
	{
283
		$result = '';
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
		// If is actually data in the array, we will loop through the data and
		// append an instance of the partial view to the final result HTML,
		// passing in the iterated value of the data array.
		if (count($data) > 0)
		{
			foreach ($data as $key => $value)
			{
				$with = array('key' => $key, $iterator => $value);

				$result .= render($view, $with);
			}
		}

		// If there is no data in the array, we will render the contents of
		// the "empty" view. Alternative, the "empty view" can be a raw
		// string that is prefixed with "raw|" for convenience.
		else
		{
			if (starts_with($empty, 'raw|'))
			{
				$result = substr($empty, 4);
			}
			else
			{
309
				$result = render($empty);
310 311
			}
		}
312

313
		return $result;
314 315 316
	}

	/**
317
	 * Get the evaluated string content of the view.
Taylor Otwell committed
318
	 *
319
	 * @return string
Taylor Otwell committed
320
	 */
321
	public function render()
Taylor Otwell committed
322
	{
323
		Event::fire("laravel.composing: {$this->view}", array($this));
324

325 326 327
		// If there are listeners to the view engine event, we'll pass them
		// the view so they can render it according to their needs, which
		// allows easy attachment of other view parsers.
328
		if (Event::listeners(static::engine))
329
		{
330
			$result = Event::until(static::engine, array($this));
331

332
			if ( ! is_null($result)) return $result;
333
		}
334 335

		return $this->get();
336 337 338 339 340 341 342 343 344 345
	}

	/**
	 * Get the evaluated contents of the view.
	 *
	 * @return string
	 */
	public function get()
	{
		$__data = $this->data();
346

347 348 349
		// The contents of each view file is cached in an array for the
		// request since partial views may be rendered inside of for
		// loops which could incur performance penalties.
350
		$__contents = $this->load();
351

352
		ob_start() and extract($__data, EXTR_SKIP);
353

354 355
		// We'll include the view contents for parsing within a catcher
		// so we can avoid any WSOD errors. If an exception occurs we
Taylor Otwell committed
356
		// will throw it out to the exception handler.
357
		try
358
		{
359
			eval('?>'.$__contents);
360 361
		}

362 363
		// If we caught an exception, we'll silently flush the output
		// buffer so that no partially rendered views get thrown out
364
		// to the client and confuse the user with junk.
365 366 367 368
		catch (\Exception $e)
		{
			ob_get_clean(); throw $e;
		}
369 370

		return ob_get_clean();
Taylor Otwell committed
371 372 373
	}

	/**
374 375 376 377 378 379 380 381 382 383 384 385
	 * Get the contents of the view file from disk.
	 *
	 * @return string
	 */
	protected function load()
	{
		if (isset(static::$cache[$this->path]))
		{
			return static::$cache[$this->path];
		}
		else
		{
Taylor Otwell committed
386
			return static::$cache[$this->path] = file_get_contents($this->path);
387 388 389 390
		}
	}

	/**
391
	 * Get the array of view data for the view instance.
392
	 *
393
	 * The shared view data will be combined with the view data.
394 395
	 *
	 * @return array
396
	 */
397
	public function data()
398
	{
399
		$data = array_merge($this->data, static::$shared);
Taylor Otwell committed
400

401
		// All nested views and responses are evaluated before the main view.
402
		// This allows the assets used by nested views to be added to the
Taylor Otwell committed
403
		// asset container before the main view is evaluated.
404
		foreach ($data as $key => $value) 
405
		{
406
			if ($value instanceof View or $value instanceof Response)
407
			{
408
				$data[$key] = $value->render();
409
			}
410 411
		}

412
		return $data;
413 414 415
	}

	/**
Taylor Otwell committed
416
	 * Add a view instance to the view data.
417
	 *
418 419
	 * <code>
	 *		// Add a view instance to a view's data
420
	 *		$view = View::make('foo')->nest('footer', 'partials.footer');
421 422 423 424 425
	 *
	 *		// Equivalent functionality using the "with" method
	 *		$view = View::make('foo')->with('footer', View::make('partials.footer'));
	 * </code>
	 *
426 427 428 429 430
	 * @param  string  $key
	 * @param  string  $view
	 * @param  array   $data
	 * @return View
	 */
431
	public function nest($key, $view, $data = array())
432
	{
433
		return $this->with($key, static::make($view, $data));
434 435 436
	}

	/**
437 438
	 * Add a key / value pair to the view data.
	 *
439 440
	 * Bound data will be available to the view as variables.
	 *
441 442 443 444
	 * @param  string  $key
	 * @param  mixed   $value
	 * @return View
	 */
445
	public function with($key, $value = null)
446
	{
447 448 449 450 451 452 453 454 455
		if (is_array($key))
		{
			$this->data = array_merge($this->data, $key);
		}
		else
		{
			$this->data[$key] = $value;
		}

456 457 458 459
		return $this;
	}

	/**
460 461 462 463 464 465
	 * Add a key / value pair to the shared view data.
	 *
	 * Shared view data is accessible to every view created by the application.
	 *
	 * @param  string  $key
	 * @param  mixed   $value
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
	 * @return View
	 */
	public function shares($key, $value)
	{
		static::share($key, $value);
		return $this;
	}

	/**
	 * Add a key / value pair to the shared view data.
	 *
	 * Shared view data is accessible to every view created by the application.
	 *
	 * @param  string  $key
	 * @param  mixed   $value
481
	 * @return void
482
	 */
483
	public static function share($key, $value)
484
	{
485
		static::$shared[$key] = $value;
486 487 488
	}

	/**
489
	 * Implementation of the ArrayAccess offsetExists method.
490
	 */
491
	public function offsetExists($offset)
492
	{
493
		return array_key_exists($offset, $this->data);
494 495 496
	}

	/**
497
	 * Implementation of the ArrayAccess offsetGet method.
498
	 */
499
	public function offsetGet($offset)
500
	{
501
		if (isset($this[$offset])) return $this->data[$offset];
502 503 504
	}

	/**
505
	 * Implementation of the ArrayAccess offsetSet method.
506
	 */
507
	public function offsetSet($offset, $value)
508
	{
509
		$this->data[$offset] = $value;
510 511
	}

512
	/**
513
	 * Implementation of the ArrayAccess offsetUnset method.
514
	 */
515
	public function offsetUnset($offset)
516
	{
517
		unset($this->data[$offset]);
518 519 520
	}

	/**
521 522 523 524
	 * Magic Method for handling dynamic data access.
	 */
	public function __get($key)
	{
525
		return $this->data[$key];
526 527 528 529 530 531 532
	}

	/**
	 * Magic Method for handling the dynamic setting of data.
	 */
	public function __set($key, $value)
	{
533 534 535 536 537 538 539 540 541
		$this->data[$key] = $value;
	}

	/**
	 * Magic Method for checking dynamically-set data.
	 */
	public function __isset($key)
	{
		return isset($this->data[$key]);
542 543 544
	}

	/**
545
	 * Get the evaluated string content of the view.
546
	 *
547
	 * @return string
548
	 */
549
	public function __toString()
550
	{
551
		return $this->render();
552 553
	}

554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
	/**
	 * Magic Method for handling dynamic functions.
	 *
	 * This method handles calls to dynamic with helpers.
	 */
	public function __call($method, $parameters)
	{
		if (strpos($method, 'with_') === 0)
		{
			$key = substr($method, 5);
			return $this->with($key, $parameters[0]);
		}

		throw new \Exception("Method [$method] is not defined on the View class.");
	}

570
}