Pink-Crab / Perique-Framework

The Perqiue Plugin Framework for WordPress
5 stars 0 forks source link

Allow absolute paths for components #84

Closed gin0115 closed 1 year ago

gin0115 commented 1 year ago

Currently all paths being passed through the PHP_Eninge are resolved with the base path being applied.

This needs to be avoided for components to allow them to be contained within composer packages.

This has been implemented locally on the Perique Form project. the changes needed are as follows.

src/Services/View/PHP_Engine.php


#####################################################
# Ammend the Component method to handle calling the buffer.
#####################################################

/**
 * Renders a component.
 *
 * @param Component $component
 * @return string|void
 */
public function component( Component $component, bool $print = true ) {

    // Throw exception of no compiler passed.
    if ( ! is_a( $this->component_compiler, Component_Compiler::class ) ) {
        throw new Exception( 'No component compiler passed to PHP_Engine' );
    }

    // Compile the component.
    $compiled = $this->component_compiler->compile( $component );
    if ( $print ) {
        print( $this->render_buffer( $compiled->template(), $compiled->data() ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    } else {
        return $this->render_buffer( $compiled->template(), $compiled->data() );
    }
}

#####################################################
# Make render() actually resolve the path
#####################################################

/**
 * Renders a template with data.
 *
 * @param string $view
 * @param iterable<string, mixed> $data
 * @param bool $print
 * @return string|void
 */
public function render( string $view, iterable $data, bool $print = true ) {
    $view = $this->resolve_file_path( $view );
    if ( $print ) {
        print( $this->render_buffer( $view, $data ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    } else {
        return $this->render_buffer( $view, $data );
    }
}

#####################################################
#Prevent the buffer from resolving the paths.
#####################################################

/**
 * Builds the view.
 *
 * @param string $view
 * @param iterable<string, mixed> $__data
 * @return string
 * @throws Exception
 */
protected function render_buffer( string $view, iterable $__data ): string {
    if ( ! file_exists( $view ) ) {
        throw new Exception( "{$view} doesn't exist" );
    }

    $output = '';
    ob_start();

    // Set all the data values a parameters.
    foreach ( $__data as $__key => $__value ) {
        if ( is_string( $__key ) ) {
            ${\wp_strip_all_tags( $__key )} = $__value;
        }
        // Unset the key and value.
        unset( $__key, $__value, $__data );
    }

    include $view;
    $output = ob_get_contents();
    ob_end_clean();
    return $output ?: '';
}