|
| 1 | +<?php |
| 2 | +/************************************************************************ |
| 3 | + * |
| 4 | + * Copyright 2024 Adobe |
| 5 | + * All Rights Reserved. |
| 6 | + * |
| 7 | + * NOTICE: All information contained herein is, and remains |
| 8 | + * the property of Adobe and its suppliers, if any. The intellectual |
| 9 | + * and technical concepts contained herein are proprietary to Adobe |
| 10 | + * and its suppliers and are protected by all applicable intellectual |
| 11 | + * property laws, including trade secret and copyright laws. |
| 12 | + * Dissemination of this information or reproduction of this material |
| 13 | + * is strictly forbidden unless prior written permission is obtained |
| 14 | + * from Adobe. |
| 15 | + * ********************************************************************** |
| 16 | + */ |
| 17 | +declare(strict_types = 1); |
| 18 | + |
| 19 | +namespace Magento2\Sniffs\Templates; |
| 20 | + |
| 21 | +use PHP_CodeSniffer\Files\File; |
| 22 | +use PHP_CodeSniffer\Sniffs\Sniff; |
| 23 | + |
| 24 | +/** |
| 25 | + * Templates must not instantiate new objects within their code. |
| 26 | + * All objects must be passed from the Block object. |
| 27 | + * |
| 28 | + * @see https://developer.adobe.com/commerce/php/coding-standards/technical-guidelines/#62-presentation-layer 6.2.6 |
| 29 | + * @link https://developer.adobe.com/commerce/frontend-core/guide/layouts/xml-instructions/#obtain-arguments-examples-in-template |
| 30 | + * @link https://developer.adobe.com/commerce/frontend-core/guide/templates/override/#getting-argument-values-from-layout |
| 31 | + */ |
| 32 | +class ObjectManagerSniff implements Sniff |
| 33 | +{ |
| 34 | + private const WARNING_CODE_OBJECT_MANAGER_USAGE = 'ObjectManagerUsageFound'; |
| 35 | + |
| 36 | + /** |
| 37 | + * @inheritdoc |
| 38 | + */ |
| 39 | + public function register() |
| 40 | + { |
| 41 | + return [T_DOUBLE_COLON]; |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * @inheritdoc |
| 46 | + */ |
| 47 | + public function process(File $phpcsFile, $stackPtr) |
| 48 | + { |
| 49 | + $tokens = $phpcsFile->getTokens(); |
| 50 | + |
| 51 | + if ($tokens[$stackPtr - 1]['content'] !== 'ObjectManager' |
| 52 | + && $tokens[$stackPtr + 1]['content'] !== 'getInstance' |
| 53 | + ) { |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + $phpcsFile->addWarning( |
| 58 | + 'ObjectManager should not be used in .phtml template. ' . |
| 59 | + 'Templates must not instantiate new objects within their code. ' . |
| 60 | + 'All objects must be passed from the Block object.', |
| 61 | + $stackPtr, |
| 62 | + self::WARNING_CODE_OBJECT_MANAGER_USAGE |
| 63 | + ); |
| 64 | + } |
| 65 | +} |
0 commit comments