Make WordPress Core


Ignore:
Timestamp:
12/20/2023 08:00:04 PM (9 months ago)
Author:
joemcgill
Message:

Themes: Improve the performance of _get_block_templates_paths.

This avoids redundant recursive lookups for block template paths in the same base directory by implementing a static cache. It also replaces an potentially expensive file_exists call in favor of doing recursive iteration of files inside a try/catch block.

Props thekt12, spacedmonkey, flixos90, mukesh27, joemcgill.
Fixes #58196.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/tests/block-template.php

    r57019 r57215  
    389389
    390390    /**
     391     * Tests `_get_block_templates_paths()` for an invalid directory.
     392     *
     393     * @ticket 58196
     394     *
     395     * @covers ::_get_block_templates_paths
     396     */
     397    public function test_get_block_templates_paths_dir_exists() {
     398        $theme_dir = get_template_directory();
     399        // Templates in the current theme.
     400        $templates = array(
     401            'parts/small-header.html',
     402            'templates/custom-single-post-template.html',
     403            'templates/index.html',
     404            'templates/page-home.html',
     405            'templates/page.html',
     406            'templates/single.html',
     407        );
     408
     409        $expected_template_paths = array_map(
     410            static function ( $template ) use ( $theme_dir ) {
     411                return $theme_dir . '/' . $template;
     412            },
     413            $templates
     414        );
     415
     416        $template_paths = _get_block_templates_paths( $theme_dir );
     417        $this->assertSameSets( $expected_template_paths, $template_paths );
     418    }
     419
     420    /**
     421     * Test _get_block_templates_paths() for a invalid dir.
     422     *
     423     * @ticket 58196
     424     *
     425     * @covers ::_get_block_templates_paths
     426     */
     427    public function test_get_block_templates_paths_dir_doesnt_exists() {
     428        // Should return empty array for invalid path.
     429        $template_paths = _get_block_templates_paths( '/tmp/random-invalid-theme-path' );
     430        $this->assertSame( array(), $template_paths );
     431    }
     432
     433    /**
    391434     * Registers a test block to log `in_the_loop()` results.
    392435     *
Note: See TracChangeset for help on using the changeset viewer.