Template.php 17.4 KB
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 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
<?php
namespace FakerPress;

class Template {
	/**
	 * The folders into which we will look for the template.
	 *
	 * @since  0.5.1
	 *
	 * @var array
	 */
	protected $folder = [];

	/**
	 * The origin class for the plugin where the template lives
	 *
	 * @since  0.5.1
	 *
	 * @var object
	 */
	public $origin;

	/**
	 * The local context for templates, mutable on every self::render() call
	 *
	 * @since  0.5.1
	 *
	 * @var array
	 */
	protected $context = [];

	/**
	 * The global context for this instance of templates
	 *
	 * @since  0.5.1
	 *
	 * @var array
	 */
	protected $global = [];

	/**
	 * Allow chaing if class will extract data from the local context
	 *
	 * @since  0.5.1
	 *
	 * @var boolean
	 */
	protected $template_context_extract = false;

	/**
	 * Base template for where to look for template
	 *
	 * @since  0.5.1
	 *
	 * @var array
	 */
	protected $template_base_path;

	/**
	 * Should we use a lookup into the list of folders to try to find the file
	 *
	 * @since  0.5.1
	 *
	 * @var  bool
	 */
	protected $template_folder_lookup = false;

	/**
	 * Configures the class origin plugin path
	 *
	 * @since  0.5.1
	 *
	 * @param  object|string  $origin   The base origin for the templates
	 *
	 * @return self
	 */
	public function set_template_origin( $origin = null ) {
		if ( empty( $origin ) ) {
			$origin = $this->origin;
		}

		if ( is_string( $origin ) ) {
			// Origin needs to be a class with a `instance` method
			if ( class_exists( $origin ) && method_exists( $origin, 'instance' ) ) {
				$origin = call_user_func( [ $origin, 'instance' ] );
			}
		}

		if ( ! is_string( $origin ) ) {
			$this->origin = $origin;
			$this->template_base_path = untrailingslashit( $this->origin->path() );
		} else {
			$this->template_base_path = untrailingslashit( (array) explode( '/', $origin ) );
		}

		return $this;
	}

	/**
	 * Configures the class with the base folder in relation to the Origin
	 *
	 * @since  0.5.1
	 *
	 * @param  array|string   $folder  Which folder we are going to look for templates
	 *
	 * @return self
	 */
	public function set_template_folder( $folder = null ) {
		// Allows configuring a already set class
		if ( ! isset( $folder ) ) {
			$folder = $this->folder;
		}

		// If Folder is String make it an Array
		if ( is_string( $folder ) ) {
			$folder = (array) explode( '/', $folder );
		}

		// Cast as Array and save
		$this->folder = (array) $folder;

		return $this;
	}

	/**
	 * Configures the class with the base folder in relation to the Origin
	 *
	 * @since  0.5.1
	 *
	 * @param  mixed   $use  Should we look for template files in the list of folders
	 *
	 * @return self
	 */
	public function set_template_folder_lookup( $value = true ) {
		$this->template_folder_lookup = fp_is_truthy( $value );

		return $this;
	}

	/**
	 * Configures the class global context
	 *
	 * @since  0.5.1
	 *
	 * @param  array  $context  Default global Context
	 *
	 * @return self
	 */
	public function add_template_globals( $context = [] ) {
		// Cast as Array merge and save
		$this->global = wp_parse_args( (array) $context, $this->global );

		return $this;
	}

	/**
	 * Configures if the class will extract context for template
	 *
	 * @since  0.5.1
	 *
	 * @param  bool  $value  Should we extract context for templates
	 *
	 * @return self
	 */
	public function set_template_context_extract( $value = false ) {
		// Cast as bool and save
		$this->template_context_extract = fp_is_truthy( $value );

		return $this;
	}

	/**
	 * Sets a Index inside of the global or local context
	 * Final to prevent extending the class when the `get` already exists on the child class
	 *
	 * @since  0.5.1
	 *
	 * @see    fp_array_set
	 *
	 * @param  array    $index     Specify each nested index in order.
	 *                             Example: array( 'lvl1', 'lvl2' );
	 * @param  mixed    $default   Default value if the search finds nothing.
	 * @param  boolean  $is_local  Use the Local or Global context
	 *
	 * @return mixed The value of the specified index or the default if not found.
	 */
	final public function get( $index, $default = null, $is_local = true ) {
		$context = $this->get_global_values();

		if ( true === $is_local ) {
			$context = $this->get_local_values();
		}

		/**
		 * Allows filtering the the getting of Context variables, also short circuiting
		 * Following the same strucuture as WP Core
		 *
		 * @since  4.6.2
		 *
		 * @param  mixed    $value     The value that will be filtered
		 * @param  array    $index     Specify each nested index in order.
		 *                             Example: array( 'lvl1', 'lvl2' );
		 * @param  mixed    $default   Default value if the search finds nothing.
		 * @param  boolean  $is_local  Use the Local or Global context
		 * @param  self     $template  Current instance of the Template
		 */
		$value = apply_filters( 'fakerpress_template_context_get', null, $index, $default, $is_local, $this );
		if ( null !== $value ) {
			return $value;
		}

		return fp_array_get( $context, $index, null, $default );
	}

	/**
	 * Sets a Index inside of the global or local context
	 * Final to prevent extending the class when the `set` already exists on the child class
	 *
	 * @since  0.5.1
	 *
	 * @see    fp_array_set
	 *
	 * @param  string|array  $index     To set a key nested multiple levels deep pass an array
	 *                                  specifying each key in order as a value.
	 *                                  Example: array( 'lvl1', 'lvl2', 'lvl3' );
	 * @param  mixed         $value     The value.
	 * @param  boolean       $is_local  Use the Local or Global context
	 *
	 * @return array Full array with the key set to the specified value.
	 */
	final public function set( $index, $value = null, $is_local = true ) {
		if ( true === $is_local ) {
			$this->context = fp_array_set( $this->context, $index, $value );

			return $this->context;
		}

		$this->global = fp_array_set( $this->global, $index, $value );

		return $this->global;
	}

	/**
	 * Merges local and global context, and saves it locally
	 *
	 * @since  0.5.1
	 *
	 * @param  array  $context  Local Context array of data
	 * @param  string $file     Complete path to include the PHP File
	 * @param  array  $name     Template name
	 *
	 * @return array
	 */
	public function merge_context( $context = [], $file = null, $name = null ) {
		// Allow for simple null usage as well as array() for nothing
		if ( is_null( $context ) ) {
			$context = [];
		}

		// Applies local context on top of Global one
		$context = wp_parse_args( (array) $context, $this->global );

		/**
		 * Allows filtering the Local context
		 *
		 * @since  0.5.1
		 *
		 * @param array  $context   Local Context array of data
		 * @param string $file      Complete path to include the PHP File
		 * @param array  $name      Template name
		 * @param self   $template  Current instance of the Template
		 */
		$this->context = apply_filters( 'fakerpress_template_context', $context, $file, $name, $this );

		return $this->context;
	}

	/**
	 * Fetches the path for locating files in the Plugin Folder
	 *
	 * @since  0.5.1
	 *
	 * @return string
	 */
	protected function get_template_plugin_path() {
		// Craft the plugin Path
		$path = array_merge( (array) $this->template_base_path, $this->folder );

		// Implode to avoid Window Problems
		$path = implode( DIRECTORY_SEPARATOR, $path );

		/**
		 * Allows filtering of the base path for templates
		 *
		 * @since  0.5.1
		 *
		 * @param string $path      Complete path to include the base plugin folder
		 * @param self   $template  Current instance of the Template
		 */
		return apply_filters( 'fakerpress_template_plugin_path', $path, $this );
	}

	/**
	 * Fetches the Namespace for the public paths, normally folders to look for
	 * in the theme's directory.
	 *
	 * @since  0.5.1
	 *
	 * @return array
	 */
	protected function get_template_public_namespace() {
		$namespace = [
			'fakerpress',
		];

		if ( ! empty( $this->origin->template_namespace ) ) {
			$namespace[] = $this->origin->template_namespace;
		}

		/**
		 * Allows filtering of the base path for templates
		 *
		 * @since  4.7.20
		 *
		 * @param array  $namespace Which is the namespace we will look for files in the theme
		 * @param self   $template  Current instance of the Template
		 */
		return apply_filters( 'fakerpress_template_public_namespace', $namespace, $this );
	}

	/**
	 * Fetches the path for locating files given a base folder normally theme related
	 *
	 * @since  0.5.1
	 *
	 * @param  mixed  $base  Base path to look into
	 *
	 * @return string
	 */
	protected function get_template_public_path( $base ) {
		// Craft the plugin Path
		$path = array_merge( (array) $base, (array) $this->get_template_public_namespace() );

		// Implode to avoid Window Problems
		$path = implode( DIRECTORY_SEPARATOR, $path );

		/**
		 * Allows filtering of the base path for templates
		 *
		 * @since  0.5.1
		 *
		 * @param string $path      Complete path to include the base public folder
		 * @param self   $template  Current instance of the Template
		 */
		return apply_filters( 'fakerpress_template_public_path', $path, $this );
	}

	/**
	 * Fetches the folders in which we will look for a given file
	 *
	 * @since  0.5.1
	 *
	 * @return array
	 */
	protected function get_template_path_list() {
		$folders = [];

		// Only look into public folders if we tell to use folders
		if ( $this->template_folder_lookup ) {
			$folders[] = [
				'id' => 'child-theme',
				'priority' => 10,
				'path' => $this->get_template_public_path( STYLESHEETPATH ),
			];
			$folders[] = [
				'id' => 'parent-theme',
				'priority' => 15,
				'path' => $this->get_template_public_path( TEMPLATEPATH ),
			];
		}

		$folders[] = [
			'id' => 'plugin',
			'priority' => 20,
			'path' => $this->get_template_plugin_path(),
		];

		/**
		 * Allows filtering of the list of folders in which we will look for the
		 * template given.
		 *
		 * @since  0.5.1
		 *
		 * @param  array  $folders   Complete path to include the base public folder
		 * @param  self   $template  Current instance of the Template
		 */
		$folders = apply_filters( 'fakerpress_template_path_list', $folders, $this );

		uasort( $folders, 'fp_sort_by_priority' );

		return $folders;
	}

	/**
	 * Tries to locate the correct file we want to load based on the Template class
	 * configuration and it's list of folders
	 *
	 * @since  0.5.1
	 *
	 * @param  mixed  $name  File name we are looking for
	 *
	 * @return string
	 */
	public function get_template_file( $name ) {
		// If name is String make it an Array
		if ( is_string( $name ) ) {
			$name = (array) explode( '/', $name );
		}

		$folders = $this->get_template_path_list();

		foreach ( $folders as $folder ) {
			$folder['path'] = trim( $folder['path'] );
			if ( ! $folder['path'] ) {
				continue;
			}

			// Build the File Path
			$file = implode( DIRECTORY_SEPARATOR, array_merge( (array) $folder['path'], $name ) );

			// Append the Extension to the file path
			$file .= '.php';

			// Skip non-existent files
			if ( file_exists( $file ) ) {
				/**
				 * A more Specific Filter that will include the template name
				 *
				 * @since  4.6.2
				 * @since  4.7.20   The $name param no longers contains the extension
				 *
				 * @param string $file      Complete path to include the PHP File
				 * @param array  $name      Template name
				 * @param self   $template  Current instance of the Template
				 */
				return apply_filters( 'fakerpress_template_file', $file, $name, $this );
			}
		}

		// Couldn't find a template on the Stack
		return false;
	}

	/**
	 * A very simple method to include a Template, allowing filtering and additions using hooks.
	 *
	 * @since  0.5.1
	 *
	 * @param string  $name    Which file we are talking about including
	 * @param array   $context Any context data you need to expose to this file
	 * @param boolean $echo    If we should also print the Template
	 *
	 * @return string|false Either the final content HTML or `false` if no template could be found.
	 */
	public function render( $name, $context = [], $echo = true ) {
		// If name is String make it an Array
		if ( is_string( $name ) ) {
			$name = (array) explode( '/', $name );
		}

		// Clean this Variable
		$name = array_map( 'sanitize_title_with_dashes', $name );

		if ( ! empty( $this->origin->template_namespace ) ) {
			$namespace = array_merge( (array) $this->origin->template_namespace, $name );
		} else {
			$namespace = $name;
		}

		// Setup the Hook name
		$hook_name = implode( '/', $namespace );

		// Check if the file exists
		$file = $this->get_template_file( $name );

		// Check if it's a valid variable
		if ( ! $file ) {
			return false;
		}

		// Before we load the file we check if it exists
		if ( ! file_exists( $file ) ) {
			return false;
		}

		ob_start();

		// Merges the local data passed to template to the global scope
		$this->merge_context( $context, $file, $name );

		/**
		 * Fires an Action before including the template file
		 *
		 * @since  0.5.1
		 *
		 * @param string $file      Complete path to include the PHP File
		 * @param array  $name      Template name
		 * @param self   $template  Current instance of the Template
		 */
		do_action( 'fakerpress_template_before_include', $file, $name, $this );

		/**
		 * Fires an Action for a given template name before including the template file
		 *
		 * E.g.:
		 *    `fakerpress_template_before_include:events/blocks/parts/details`
		 *    `fakerpress_template_before_include:events/embed`
		 *    `fakerpress_template_before_include:tickets/login-to-purchase`
		 *
		 * @since  0.5.1
		 *
		 * @param string $file      Complete path to include the PHP File
		 * @param array  $name      Template name
		 * @param self   $template  Current instance of the Template
		 */
		do_action( "fakerpress_template_before_include:$hook_name", $file, $name, $this );

		// Only do this if really needed (by default it wont).
		if ( true === $this->template_context_extract && ! empty( $this->context ) ) {
			// We don't allow Extrating of a variable called $name
			if ( isset( $this->context['name'] ) ) {
				unset( $this->context['name'] );
			}

			// We don't allow the extraction of a variable called `$file`.
			if ( isset( $this->context['file'] ) ) {
				unset( $this->context['file'] );
			}

			// Make any provided variables available in the template variable scope.
			extract( $this->context ); // @codingStandardsIgnoreLine
		}

		include $file;

		/**
		 * Fires an Action after including the template file
		 *
		 * @since  0.5.1
		 *
		 * @param string $file      Complete path to include the PHP File
		 * @param array  $name      Template name
		 * @param self   $template  Current instance of the Template
		 */
		do_action( 'fakerpress_template_after_include', $file, $name, $this );

		/**
		 * Fires an Action for a given template name after including the template file
		 *
		 * E.g.:
		 *    `fakerpress_template_after_include:events/blocks/parts/details`
		 *    `fakerpress_template_after_include:events/embed`
		 *    `fakerpress_template_after_include:tickets/login-to-purchase`
		 *
		 * @since  0.5.1
		 *
		 * @param string $file      Complete path to include the PHP File
		 * @param array  $name      Template name
		 * @param self   $template  Current instance of the Template
		 */
		do_action( "fakerpress_template_after_include:$hook_name", $file, $name, $this );

		// Only fetch the contents after the action
		$html = ob_get_clean();

		/**
		 * Allow users to filter the final HTML
		 *
		 * @since  0.5.1
		 *
		 * @param string $html      The final HTML
		 * @param string $file      Complete path to include the PHP File
		 * @param array  $name      Template name
		 * @param self   $template  Current instance of the Template
		 */
		$html = apply_filters( 'fakerpress_template_html', $html, $file, $name, $this );

		/**
		 * Allow users to filter the final HTML by the name
		 *
		 * E.g.:
		 *    `fakerpress_template_html:events/blocks/parts/details`
		 *    `fakerpress_template_html:events/embed`
		 *    `fakerpress_template_html:tickets/login-to-purchase`
		 *
		 * @since  0.5.1
		 *
		 * @param string $html      The final HTML
		 * @param string $file      Complete path to include the PHP File
		 * @param array  $name      Template name
		 * @param self   $template  Current instance of the Template
		 */
		$html = apply_filters( "fakerpress_template_html:$hook_name", $html, $file, $name, $this );

		if ( $echo ) {
			echo $html;
		}

		return $html;
	}

	/**
	 * Sets a number of values at the same time.
	 *
	 * @since 0.5.1
	 *
	 * @param array $values   An associative key/value array of the values to set.
	 * @param bool  $is_local Whether to set the values as global or local; defaults to local as the `set` method does.
	 *
	 * @see   Template::set()
	 */
	public function set_values( array $values = [], $is_local = true ) {
		foreach ( $values as $key => $value ) {
			$this->set( $key, $value, $is_local );
		}
	}

	/**
	 * Returns the Template global context.
	 *
	 * @since 0.5.1
	 *
	 * @return array An associative key/value array of the Template global context.
	 */
	public function get_global_values() {
		return $this->global;
	}

	/**
	 * Returns the Template local context.
	 *
	 * @since 0.5.1
	 *
	 * @return array An associative key/value array of the Template local context.
	 */
	public function get_local_values() {
		return $this->context;
	}

	/**
	 * Returns the Template global and local context values.
	 *
	 * Local values will override the template global context values.
	 *
	 * @since 0.5.1
	 *
	 * @return array An associative key/value array of the Template global and local context.
	 */
	public function get_values() {
		return array_merge( $this->get_global_values(), $this->get_local_values() );
	}
}