|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Sniff verifying that theme pattern slugs match their filenames. |
| 4 | + */ |
| 5 | + |
| 6 | +namespace HM\Sniffs\Files; |
| 7 | + |
| 8 | +use PHP_CodeSniffer\Files\File; |
| 9 | +use PHP_CodeSniffer\Sniffs\Sniff; |
| 10 | + |
| 11 | +/** |
| 12 | + * Flags theme pattern files whose Slug: header does not end with the file's basename. |
| 13 | + * |
| 14 | + * A pattern with `Slug: my-theme/hero-banner` must live in `hero-banner.php`. |
| 15 | + */ |
| 16 | +class PatternSlugMatchesFilenameSniff implements Sniff { |
| 17 | + |
| 18 | + /** |
| 19 | + * Register for the open tag so the check runs once per file. |
| 20 | + * |
| 21 | + * @return array<int|string> |
| 22 | + */ |
| 23 | + public function register() : array { |
| 24 | + return [ T_OPEN_TAG ]; |
| 25 | + } |
| 26 | + |
| 27 | + /** |
| 28 | + * Compare the trailing segment of the pattern's Slug header to the filename. |
| 29 | + * |
| 30 | + * @param File $phpcs_file The file being scanned. |
| 31 | + * @param int $stack_ptr Position of the open tag. |
| 32 | + * @return int Pointer past the end of the file, so the sniff runs only once. |
| 33 | + */ |
| 34 | + public function process( File $phpcs_file, $stack_ptr ) { |
| 35 | + if ( ! preg_match( '#/themes/[^/]+/patterns/([^/]+)\.php$#', $phpcs_file->getFilename(), $matches ) ) { |
| 36 | + return $phpcs_file->numTokens; |
| 37 | + } |
| 38 | + $filename = $matches[1]; |
| 39 | + |
| 40 | + foreach ( $phpcs_file->getTokens() as $ptr => $token ) { |
| 41 | + if ( T_DOC_COMMENT_STRING !== $token['code'] ) { |
| 42 | + continue; |
| 43 | + } |
| 44 | + if ( ! preg_match( '#^Slug:\s*(\S+)#', trim( $token['content'] ), $slug_match ) ) { |
| 45 | + continue; |
| 46 | + } |
| 47 | + |
| 48 | + $slug = $slug_match[1]; |
| 49 | + if ( basename( $slug ) !== $filename ) { |
| 50 | + $phpcs_file->addError( |
| 51 | + 'Pattern slug "%s" does not match the filename; expected the file to be named "%s.php".', |
| 52 | + $ptr, |
| 53 | + 'SlugMismatch', |
| 54 | + [ $slug, basename( $slug ) ] |
| 55 | + ); |
| 56 | + } |
| 57 | + break; |
| 58 | + } |
| 59 | + |
| 60 | + return $phpcs_file->numTokens; |
| 61 | + } |
| 62 | +} |
0 commit comments