diff --git a/includes/create-theme/theme-patterns.php b/includes/create-theme/theme-patterns.php index 5d4b7c95..87f62a94 100644 --- a/includes/create-theme/theme-patterns.php +++ b/includes/create-theme/theme-patterns.php @@ -131,9 +131,27 @@ public static function create_pattern_link( $attributes ) { return ''; } - public static function replace_local_pattern_references( $pattern, $options = null ) { - // Find any references to pattern in templates - $templates_to_update = array(); + /** + * Replace references to a pattern stored in the database with references + * to the equivalent local pattern file. + * + * Templates and template parts that reference the pattern are written to + * the theme filesystem. Clearing their user customizations is left to + * clear_saved_pattern_template_customizations() so that it can happen once + * every pattern has been processed. + * + * @param object $pattern The pattern being moved to the theme. + * @param array|null $options Export options. + * @param array $templates_already_written Slugs already written during + * this save, keyed by post type. + * @return array Slugs newly written to disk, keyed by post type. + */ + public static function replace_local_pattern_references( $pattern, $options = null, $templates_already_written = array() ) { + // Find any references to pattern in templates. + $templates_to_update = array( + 'wp_template' => array(), + 'wp_template_part' => array(), + ); $args = array( 'post_type' => array( 'wp_template', 'wp_template_part' ), 'posts_per_page' => -1, @@ -142,30 +160,97 @@ public static function replace_local_pattern_references( $pattern, $options = nu $find_pattern_refs = new WP_Query( $args ); if ( $find_pattern_refs->have_posts() ) { foreach ( $find_pattern_refs->posts as $post ) { - $slug = $post->post_name; - array_push( $templates_to_update, $slug ); + $post_type = 'wp_template_part' === $post->post_type ? 'wp_template_part' : 'wp_template'; + $templates_to_update[ $post_type ][] = $post->post_name; } } - $templates_to_update = array_unique( $templates_to_update ); - // Only update templates that reference the pattern - CBT_Theme_Templates::add_templates_to_local( 'all', null, null, $options, $templates_to_update ); + $already_written = array_merge( + array( + 'wp_template' => array(), + 'wp_template_part' => array(), + ), + $templates_already_written + ); + + $base_dir = get_stylesheet_directory(); + $template_folders = get_block_theme_folders(); + $folder_by_type = array( + 'wp_template' => $template_folders['wp_template'], + 'wp_template_part' => $template_folders['wp_template_part'], + ); - // List all template and pattern files in the theme - $base_dir = get_stylesheet_directory(); + // A template that references several patterns is written on the first + // iteration. Do not write it again from the database on later + // iterations: that would restore the numeric references that were + // already replaced with local pattern references. + foreach ( $templates_to_update as $post_type => $slugs ) { + $slugs = array_values( array_unique( $slugs ) ); + $slugs = array_values( array_diff( $slugs, $already_written[ $post_type ] ) ); + + // Only update templates that reference the pattern. + // Passing an empty list to add_templates_to_local() would make it + // fall back to exporting every template, so skip it when there is + // nothing to update. + if ( ! empty( $slugs ) ) { + CBT_Theme_Templates::add_templates_to_local( 'all', null, null, $options, $slugs, $post_type ); + } + + // Record only the files that exist. A failed write must not lead to + // the database customization being cleared. + $written_slugs = array(); + foreach ( $slugs as $slug ) { + if ( file_exists( $base_dir . DIRECTORY_SEPARATOR . $folder_by_type[ $post_type ] . DIRECTORY_SEPARATOR . $slug . '.html' ) ) { + $written_slugs[] = $slug; + } + } + $templates_to_update[ $post_type ] = $written_slugs; + } + + // List all template and pattern files in the theme. $patterns = glob( $base_dir . DIRECTORY_SEPARATOR . 'patterns' . DIRECTORY_SEPARATOR . '*.php' ); - $templates = glob( $base_dir . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . '*.html' ); - $template_parts = glob( $base_dir . DIRECTORY_SEPARATOR . 'template-parts' . DIRECTORY_SEPARATOR . '*.html' ); + $templates = glob( $base_dir . DIRECTORY_SEPARATOR . $template_folders['wp_template'] . DIRECTORY_SEPARATOR . '*.html' ); + $template_parts = glob( $base_dir . DIRECTORY_SEPARATOR . $template_folders['wp_template_part'] . DIRECTORY_SEPARATOR . '*.html' ); - // Replace references to the local patterns in the theme - foreach ( array_merge( $patterns, $templates, $template_parts ) as $file ) { + // Replace references to the local patterns in the theme. + // This runs on every iteration, even when no new file was written, so + // files written for an earlier pattern also lose this pattern's numeric + // reference. + $files = array_merge( + $patterns ? $patterns : array(), + $templates ? $templates : array(), + $template_parts ? $template_parts : array() + ); + foreach ( $files as $file ) { $file_content = file_get_contents( $file ); $file_content = str_replace( 'wp:block {"ref":' . $pattern->id . '}', 'wp:pattern {"slug":"' . $pattern->slug . '"}', $file_content ); file_put_contents( $file, $file_content ); } - CBT_Theme_Templates::clear_user_templates_customizations(); - CBT_Theme_Templates::clear_user_template_parts_customizations(); + return $templates_to_update; + } + + /** + * Clear the user customizations for the templates and template parts that + * were written to disk while saving patterns. + * + * Only items that were written to disk are cleared. Other user + * customizations are left untouched so they are not lost when saving + * patterns without saving templates. + * + * @param array $templates_written Slugs written to disk, keyed by post type. + */ + private static function clear_saved_pattern_template_customizations( $templates_written ) { + $template_slugs = isset( $templates_written['wp_template'] ) ? array_unique( $templates_written['wp_template'] ) : array(); + $template_part_slugs = isset( $templates_written['wp_template_part'] ) ? array_unique( $templates_written['wp_template_part'] ) : array(); + + if ( ! empty( $template_slugs ) ) { + CBT_Theme_Templates::clear_user_templates_customizations( $template_slugs ); + } + + if ( ! empty( $template_part_slugs ) ) { + CBT_Theme_Templates::clear_user_template_parts_customizations( $template_part_slugs ); + } } public static function prepare_pattern_for_export( $pattern, $options = null ) { @@ -194,6 +279,9 @@ public static function prepare_pattern_for_export( $pattern, $options = null ) { /** * Copy the local patterns as well as any media to the theme filesystem. + * + * @param array|null $options Export options. + * @return WP_Error|void WP_Error when a pattern file with the same name already exists. */ public static function add_patterns_to_theme( $options = null ) { $base_dir = get_stylesheet_directory(); @@ -206,6 +294,11 @@ public static function add_patterns_to_theme( $options = null ) { ) ); + $templates_written = array( + 'wp_template' => array(), + 'wp_template_part' => array(), + ); + if ( $pattern_query->have_posts() ) { // If there is no patterns folder, create it. if ( ! is_dir( $patterns_dir ) ) { @@ -219,13 +312,18 @@ public static function add_patterns_to_theme( $options = null ) { // Check pattern name doesn't already exist before creating the file. $existing_patterns = glob( $patterns_dir . DIRECTORY_SEPARATOR . '*.php' ); - foreach ( $existing_patterns as $existing_pattern ) { - if ( strpos( $existing_pattern, $pattern->name . '.php' ) !== false ) { + foreach ( $existing_patterns ? $existing_patterns : array() as $existing_pattern ) { + if ( basename( $existing_pattern ) === $pattern->name . '.php' ) { $pattern_exists = true; } } if ( $pattern_exists ) { + // Templates written for earlier patterns still have database + // customizations that reference patterns already removed + // from the database. Clear only those before bailing out. + self::clear_saved_pattern_template_customizations( $templates_written ); + return new WP_Error( 'pattern_already_exists', sprintf( @@ -245,11 +343,16 @@ public static function add_patterns_to_theme( $options = null ) { $pattern->content ); - self::replace_local_pattern_references( $pattern, $options ); + $written_now = self::replace_local_pattern_references( $pattern, $options, $templates_written ); + + $templates_written['wp_template'] = array_merge( $templates_written['wp_template'], $written_now['wp_template'] ); + $templates_written['wp_template_part'] = array_merge( $templates_written['wp_template_part'], $written_now['wp_template_part'] ); // Remove it from the database to ensure that these patterns are loaded from the theme. wp_delete_post( $pattern->id, true ); } } + + self::clear_saved_pattern_template_customizations( $templates_written ); } } diff --git a/includes/create-theme/theme-templates.php b/includes/create-theme/theme-templates.php index 88f30572..b8a09501 100644 --- a/includes/create-theme/theme-templates.php +++ b/includes/create-theme/theme-templates.php @@ -9,17 +9,27 @@ class CBT_Theme_Templates { * Build a collection of templates and template-parts that should be exported (and modified) * based on the given export_type. * - * @param string $export_type The type of export to perform. 'all', 'current', or 'user'. - * @param array $templates_to_export List of specific templates to export. + * @param string $export_type The type of export to perform. 'all', 'current', or 'user'. + * @param array|null $templates_to_export List of specific templates to export. + * @param string|null $post_type Optional. Limit the collection to 'wp_template' or + * 'wp_template_part'. Default null returns both. * @return object An object containing the templates and parts that should be exported. */ - public static function get_theme_templates( $export_type, $templates_to_export = null ) { + public static function get_theme_templates( $export_type, $templates_to_export = null, $post_type = null ) { - $templates = get_block_templates( array( 'slug__in' => $templates_to_export ) ); - $template_parts = get_block_templates( array( 'slug__in' => $templates_to_export ), 'wp_template_part' ); + $templates = array(); + $template_parts = array(); $exported_templates = array(); $exported_parts = array(); + if ( null === $post_type || 'wp_template' === $post_type ) { + $templates = get_block_templates( array( 'slug__in' => $templates_to_export ) ); + } + + if ( null === $post_type || 'wp_template_part' === $post_type ) { + $template_parts = get_block_templates( array( 'slug__in' => $templates_to_export ), 'wp_template_part' ); + } + // build collection of templates/parts in currently activated theme $templates_paths = get_block_theme_folders(); $templates_path = get_stylesheet_directory() . '/' . $templates_paths['wp_template'] . '/'; @@ -102,29 +112,47 @@ public static function replace_template_namespace( $template, $new_slug ) { } /** - * Clear all user templates customizations. - * This will remove all user templates from the database. + * Clear user template customizations. + * + * @param array|null $slugs Optional list of template slugs to clear. If null, + * all custom template customizations are removed. + * An empty array clears nothing. */ - public static function clear_user_templates_customizations() { + public static function clear_user_templates_customizations( $slugs = null ) { $templates = get_block_templates(); foreach ( $templates as $template ) { if ( 'custom' !== $template->source ) { continue; } + if ( empty( $template->wp_id ) ) { + continue; + } + if ( null !== $slugs && ! in_array( $template->slug, $slugs, true ) ) { + continue; + } wp_delete_post( $template->wp_id, true ); } } /** - * Clear all user template-parts customizations. - * This will remove all user template-parts from the database. + * Clear user template-part customizations. + * + * @param array|null $slugs Optional list of template-part slugs to clear. If + * null, all custom template-part customizations are removed. + * An empty array clears nothing. */ - public static function clear_user_template_parts_customizations() { + public static function clear_user_template_parts_customizations( $slugs = null ) { $template_parts = get_block_templates( array(), 'wp_template_part' ); foreach ( $template_parts as $template ) { if ( 'custom' !== $template->source ) { continue; } + if ( empty( $template->wp_id ) ) { + continue; + } + if ( null !== $slugs && ! in_array( $template->slug, $slugs, true ) ) { + continue; + } wp_delete_post( $template->wp_id, true ); } } @@ -215,15 +243,24 @@ private static function add_validated_media_to_options( $options, $validated_med * as well as any media to the theme filesystem. * If patterns need to be created for media or localizations they will also be added. * - * @param string $export_type The type of export to perform. 'all', 'current', or 'user'. - * @param string $path The path to the theme folder. If null it is assumed to be the current theme. - * @param string $slug The slug of the theme. If null it is assumed to be the current theme. - * @param array $options An array of options to use when exporting the templates. - * @param array $templates_to_export List of specific templates to export. If null it will be fetched. + * @param string $export_type The type of export to perform. 'all', 'current', or 'user'. + * @param string|null $path The path to the theme folder. If null it is assumed to be the current theme. + * @param string|null $slug The slug of the theme. If null it is assumed to be the current theme. + * @param array|null $options An array of options to use when exporting the templates. + * @param array|null $templates_to_export List of specific templates to export. If null it will be fetched. + * @param string|null $post_type Optional. Limit the export to 'wp_template' or + * 'wp_template_part'. Default null exports both. */ - public static function add_templates_to_local( $export_type, $path = null, $slug = null, $options = null, $templates_to_export = null ) { + public static function add_templates_to_local( $export_type, $path = null, $slug = null, $options = null, $templates_to_export = null, $post_type = null ) { + + // An empty list means "no templates" here, not "all templates". + // WordPress treats an empty slug__in filter as no filter, which would + // export every template. + if ( is_array( $templates_to_export ) && empty( $templates_to_export ) ) { + return; + } - $theme_templates = self::get_theme_templates( $export_type, $templates_to_export ); + $theme_templates = self::get_theme_templates( $export_type, $templates_to_export, $post_type ); $template_folders = get_block_theme_folders(); $base_dir = $path ? $path : get_stylesheet_directory(); diff --git a/tests/test-theme-patterns.php b/tests/test-theme-patterns.php index dac9771a..db3360b5 100644 --- a/tests/test-theme-patterns.php +++ b/tests/test-theme-patterns.php @@ -415,6 +415,344 @@ public function test_add_patterns_to_theme_localizes_backslash_quote_text() { $this->uninstall_theme( $test_theme_slug ); } + /** + * Create a custom template or template-part post for the active theme. + * + * @param string $slug Template slug. + * @param string $content Template content. + * @param string $post_type Either 'wp_template' or 'wp_template_part'. + * @return int The post ID. + */ + private function create_template_customization( $slug, $content, $post_type = 'wp_template' ) { + $post_id = $this->factory->post->create( + array( + 'post_type' => $post_type, + 'post_status' => 'publish', + 'post_name' => $slug, + 'post_title' => $slug, + 'post_content' => $content, + ) + ); + + wp_set_object_terms( $post_id, get_stylesheet(), 'wp_theme' ); + + return $post_id; + } + + public function test_add_patterns_to_theme_keeps_customizations_that_do_not_reference_patterns() { + $admin = $this->factory->user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $admin ); + + $test_theme_slug = $this->create_blank_theme(); + + $pattern = $this->make_wp_block_post( + '

Pattern used by a template

', + 'CBT Referenced Pattern' + ); + + $referencing_template_id = $this->create_template_customization( + 'page', + '' + ); + $unrelated_template_id = $this->create_template_customization( + 'single', + '

Unsaved customization

' + ); + + CBT_Theme_Patterns::add_patterns_to_theme( + array( + 'localizeText' => false, + 'localizeImages' => false, + 'removeNavRefs' => false, + ) + ); + + // The template that referenced the pattern was written to disk, so its + // database customization can be cleared. + $this->assertNull( get_post( $referencing_template_id ) ); + $this->assertFileExists( get_stylesheet_directory() . '/templates/page.html' ); + + // The unrelated customization was never written to disk and must not be + // deleted. + $this->assertNotNull( get_post( $unrelated_template_id ) ); + $this->assertFileDoesNotExist( get_stylesheet_directory() . '/templates/single.html' ); + + $this->uninstall_theme( $test_theme_slug ); + } + + public function test_add_patterns_to_theme_writes_every_referencing_template_before_clearing_customizations() { + $admin = $this->factory->user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $admin ); + + $test_theme_slug = $this->create_blank_theme(); + + $first_pattern = $this->make_wp_block_post( + '

First pattern

', + 'CBT First Pattern' + ); + $second_pattern = $this->make_wp_block_post( + '

Second pattern

', + 'CBT Second Pattern' + ); + + $template_id = $this->create_template_customization( + 'page', + '' + ); + $part_id = $this->create_template_customization( + 'header', + '', + 'wp_template_part' + ); + + CBT_Theme_Patterns::add_patterns_to_theme( + array( + 'localizeText' => false, + 'localizeImages' => false, + 'removeNavRefs' => false, + ) + ); + + // Both templates reference a saved pattern, so both must be written to + // disk before any customization is cleared. + $this->assertFileExists( get_stylesheet_directory() . '/templates/page.html' ); + $this->assertFileExists( get_stylesheet_directory() . '/parts/header.html' ); + + $template_content = file_get_contents( get_stylesheet_directory() . '/templates/page.html' ); + $part_content = file_get_contents( get_stylesheet_directory() . '/parts/header.html' ); + $this->assertStringContainsString( 'wp:pattern {"slug":"', $template_content ); + $this->assertStringContainsString( 'wp:pattern {"slug":"', $part_content ); + + $this->assertNull( get_post( $template_id ) ); + $this->assertNull( get_post( $part_id ) ); + + $this->uninstall_theme( $test_theme_slug ); + } + + public function test_add_patterns_to_theme_replaces_all_pattern_references_in_one_template() { + $admin = $this->factory->user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $admin ); + + $test_theme_slug = $this->create_blank_theme(); + + $first_pattern = $this->make_wp_block_post( + '

First pattern

', + 'CBT First Shared Pattern' + ); + $second_pattern = $this->make_wp_block_post( + '

Second pattern

', + 'CBT Second Shared Pattern' + ); + + $template_id = $this->create_template_customization( + 'page', + '' . "\n" . + '' + ); + + CBT_Theme_Patterns::add_patterns_to_theme( + array( + 'localizeText' => false, + 'localizeImages' => false, + 'removeNavRefs' => false, + ) + ); + + // The template is written once on the first pattern iteration. Later + // iterations must not rewrite it from the database and restore the + // numeric references that were already replaced. + $template_content = file_get_contents( get_stylesheet_directory() . '/templates/page.html' ); + $this->assertStringNotContainsString( 'wp:block {"ref":', $template_content ); + $this->assertSame( 2, substr_count( $template_content, 'wp:pattern {"slug":"' ) ); + + $this->assertNull( get_post( $template_id ) ); + + $this->uninstall_theme( $test_theme_slug ); + } + + public function test_add_patterns_to_theme_keeps_unrelated_template_part_customizations() { + $admin = $this->factory->user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $admin ); + + $test_theme_slug = $this->create_blank_theme(); + + $pattern = $this->make_wp_block_post( + '

Pattern used by a template

', + 'CBT Part Pattern' + ); + + $referencing_template_id = $this->create_template_customization( + 'page', + '' + ); + $unrelated_part_id = $this->create_template_customization( + 'cbt-unrelated-part', + '

Unsaved part customization

', + 'wp_template_part' + ); + + CBT_Theme_Patterns::add_patterns_to_theme( + array( + 'localizeText' => false, + 'localizeImages' => false, + 'removeNavRefs' => false, + ) + ); + + $this->assertNull( get_post( $referencing_template_id ) ); + $this->assertNotNull( get_post( $unrelated_part_id ) ); + $this->assertFileDoesNotExist( get_stylesheet_directory() . '/parts/cbt-unrelated-part.html' ); + + $this->uninstall_theme( $test_theme_slug ); + } + + public function test_add_patterns_to_theme_clears_written_templates_before_duplicate_pattern_error() { + $admin = $this->factory->user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $admin ); + + $test_theme_slug = $this->create_blank_theme(); + + $older_pattern = $this->make_wp_block_post( + '

Older pattern

', + 'CBT Duplicate Older' + ); + $newer_pattern = $this->make_wp_block_post( + '

Newer pattern

', + 'CBT Duplicate Newer' + ); + + wp_update_post( + array( + 'ID' => $older_pattern->ID, + 'post_date' => '2020-01-01 00:00:00', + 'post_date_gmt' => '2020-01-01 00:00:00', + ) + ); + wp_update_post( + array( + 'ID' => $newer_pattern->ID, + 'post_date' => '2020-01-02 00:00:00', + 'post_date_gmt' => '2020-01-02 00:00:00', + ) + ); + + $older_pattern = get_post( $older_pattern->ID ); + $newer_pattern = get_post( $newer_pattern->ID ); + + $template_id = $this->create_template_customization( + 'page', + '' + ); + + // Simulate a pattern file that already exists for the older pattern. + $patterns_dir = get_stylesheet_directory() . '/patterns'; + wp_mkdir_p( $patterns_dir ); + $older_name = CBT_Theme_Patterns::pattern_from_wp_block( $older_pattern )->name; + file_put_contents( $patterns_dir . '/' . $older_name . '.php', ' false, + 'localizeImages' => false, + 'removeNavRefs' => false, + ) + ); + + $this->assertWPError( $result ); + $this->assertSame( 'pattern_already_exists', $result->get_error_code() ); + + // The template written for the newer pattern is on disk, so its + // database customization must be cleared before the error returns. + $this->assertFileExists( get_stylesheet_directory() . '/templates/page.html' ); + $this->assertNull( get_post( $template_id ) ); + + $this->uninstall_theme( $test_theme_slug ); + } + + public function test_add_patterns_to_theme_keeps_unrelated_part_with_same_slug_as_template() { + $admin = $this->factory->user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $admin ); + + $test_theme_slug = $this->create_blank_theme(); + + $pattern = $this->make_wp_block_post( + '

Pattern used by a template

', + 'CBT Collision Pattern' + ); + + $template_id = $this->create_template_customization( + 'page', + '' + ); + $part_id = $this->create_template_customization( + 'page', + '

Unrelated part with the same slug

', + 'wp_template_part' + ); + + CBT_Theme_Patterns::add_patterns_to_theme( + array( + 'localizeText' => false, + 'localizeImages' => false, + 'removeNavRefs' => false, + ) + ); + + $this->assertNull( get_post( $template_id ) ); + $this->assertNotNull( get_post( $part_id ) ); + $this->assertFileExists( get_stylesheet_directory() . '/templates/page.html' ); + $this->assertFileDoesNotExist( get_stylesheet_directory() . '/parts/page.html' ); + + $this->uninstall_theme( $test_theme_slug ); + } + + public function test_add_patterns_to_theme_replaces_references_for_same_slug_in_template_and_part() { + $admin = $this->factory->user->create( array( 'role' => 'administrator' ) ); + wp_set_current_user( $admin ); + + $test_theme_slug = $this->create_blank_theme(); + + $template_pattern = $this->make_wp_block_post( + '

Template pattern

', + 'CBT Collision Template Pattern' + ); + $part_pattern = $this->make_wp_block_post( + '

Part pattern

', + 'CBT Collision Part Pattern' + ); + + $template_id = $this->create_template_customization( + 'page', + '' + ); + $part_id = $this->create_template_customization( + 'page', + '', + 'wp_template_part' + ); + + CBT_Theme_Patterns::add_patterns_to_theme( + array( + 'localizeText' => false, + 'localizeImages' => false, + 'removeNavRefs' => false, + ) + ); + + $template_content = file_get_contents( get_stylesheet_directory() . '/templates/page.html' ); + $part_content = file_get_contents( get_stylesheet_directory() . '/parts/page.html' ); + + $this->assertStringNotContainsString( 'wp:block {"ref":', $template_content ); + $this->assertStringNotContainsString( 'wp:block {"ref":', $part_content ); + $this->assertSame( 1, substr_count( $template_content, 'wp:pattern {"slug":"' ) ); + $this->assertSame( 1, substr_count( $part_content, 'wp:pattern {"slug":"' ) ); + + $this->assertNull( get_post( $template_id ) ); + $this->assertNull( get_post( $part_id ) ); + + $this->uninstall_theme( $test_theme_slug ); + } + /** * Create a fresh test theme via the plugin's REST endpoint and activate it. *