|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace StellarWP\Schema\Tests\Traits; |
| 4 | + |
| 5 | +use tad\Codeception\SnapshotAssertions\SnapshotAssertions; |
| 6 | + |
| 7 | +/** |
| 8 | + * Trait for capturing and asserting query snapshots. |
| 9 | + * |
| 10 | + * @since 3.2.0 |
| 11 | + */ |
| 12 | +trait Query_Snapshot_Assertions { |
| 13 | + use SnapshotAssertions; |
| 14 | + |
| 15 | + /** |
| 16 | + * The captured query from the paginate filter. |
| 17 | + * |
| 18 | + * @var string |
| 19 | + */ |
| 20 | + protected $captured_query = ''; |
| 21 | + |
| 22 | + /** |
| 23 | + * Sets up the query capture filter. |
| 24 | + * |
| 25 | + * @before |
| 26 | + * |
| 27 | + * @return void |
| 28 | + */ |
| 29 | + protected function set_up_query_capture(): void { |
| 30 | + $this->captured_query = ''; |
| 31 | + |
| 32 | + add_filter( 'stellarwp_schema_custom_table_paginate_query', function( $query ) { |
| 33 | + $this->captured_query = $query; |
| 34 | + return $query; |
| 35 | + }, 10, 1 ); |
| 36 | + |
| 37 | + add_filter( 'stellarwp_schema_custom_table_total_items_query', function( $query ) { |
| 38 | + $this->captured_query = $query; |
| 39 | + return $query; |
| 40 | + }, 10, 1 ); |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Tears down the query capture filter. |
| 45 | + * |
| 46 | + * @after |
| 47 | + * |
| 48 | + * @return void |
| 49 | + */ |
| 50 | + protected function tear_down_query_capture(): void { |
| 51 | + $this->captured_query = ''; |
| 52 | + |
| 53 | + remove_all_filters( 'stellarwp_schema_custom_table_paginate_query' ); |
| 54 | + remove_all_filters( 'stellarwp_schema_custom_table_total_items_query' ); |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Gets the captured query. |
| 59 | + * |
| 60 | + * @return string |
| 61 | + */ |
| 62 | + protected function get_captured_query(): string { |
| 63 | + return $this->captured_query; |
| 64 | + } |
| 65 | + |
| 66 | + /** |
| 67 | + * Asserts that the captured query matches a stored snapshot. |
| 68 | + * |
| 69 | + * @return void |
| 70 | + */ |
| 71 | + protected function assertCapturedQueryMatchesSnapshot(): void { |
| 72 | + $this->assertNotEmpty( $this->captured_query ); |
| 73 | + $this->assertMatchesCodeSnapshot( $this->captured_query ); |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * Asserts that the captured query contains the expected pattern. |
| 78 | + * |
| 79 | + * @param string $expected_pattern The expected pattern. |
| 80 | + * @param string $message Optional message. |
| 81 | + * |
| 82 | + * @return void |
| 83 | + */ |
| 84 | + protected function assertQueryContains( string $expected_pattern, string $message = '' ): void { |
| 85 | + $this->assertStringContainsString( |
| 86 | + $expected_pattern, |
| 87 | + $this->captured_query, |
| 88 | + $message ?: 'Query does not contain expected pattern' |
| 89 | + ); |
| 90 | + } |
| 91 | +} |
0 commit comments