├── tests ├── functional │ ├── _data │ │ ├── .gitkeep │ │ └── files │ │ │ └── debug_logging │ │ │ └── .magento.env.yaml │ └── _output │ │ └── .gitignore └── static │ ├── phpstan.neon │ ├── phpcs-ruleset.xml │ ├── Sniffs │ ├── Whitespace │ │ └── MultipleEmptyLinesSniff.php │ └── Directives │ │ └── StrictTypesSniff.php │ └── phpmd-ruleset.xml ├── .gitignore ├── Test ├── Functional │ ├── Acceptance.suite.dist.yml │ └── Acceptance │ │ ├── Acceptance82Cest.php │ │ ├── Acceptance83Cest.php │ │ ├── Acceptance84Cest.php │ │ ├── Acceptance81Cest.php │ │ └── AcceptanceCest.php └── Unit │ ├── phpunit.xml.dist │ └── Model │ ├── UrlFinderFactoryTest.php │ ├── UrlFixerTest.php │ └── UrlFinder │ └── EntityTest.php ├── registration.php ├── etc ├── module.xml ├── crontab.xml ├── events.xml └── di.xml ├── Model ├── UrlFinderInterface.php ├── Logger │ └── Handler │ │ └── Debug.php ├── UrlFixer.php ├── Observer │ ├── CacheFlushAll.php │ └── IndexerStateSaveAfter.php ├── Indexation │ └── Logger.php ├── UrlFinderFactory.php ├── UrlFinder │ ├── Entity.php │ └── Product.php ├── Cache │ ├── InvalidateLogger.php │ └── Evictor.php └── DebugTrace.php ├── COPYING.txt ├── .github ├── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── .metadata.json ├── PULL_REQUEST_TEMPLATE.md ├── CONTRIBUTING.md └── CODE_OF_CONDUCT.md ├── Cron └── Evict.php ├── Console └── Command │ ├── CacheEvict.php │ ├── ConfigShowDefaultUrlCommand.php │ ├── ConfigShowStoreUrlCommand.php │ └── ConfigShowEntityUrlsCommand.php ├── codeception.dist.yml ├── composer.json ├── README.md └── LICENSE_OSL.txt /tests/functional/_data/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/functional/_output/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | /_workdir 3 | /composer.lock 4 | /vendor 5 | /auth.json 6 | -------------------------------------------------------------------------------- /tests/functional/_data/files/debug_logging/.magento.env.yaml: -------------------------------------------------------------------------------- 1 | stage: 2 | global: 3 | MIN_LOGGING_LEVEL: debug 4 | 5 | log: 6 | file: 7 | min_level: "debug" 8 | stream: 9 | min_level: "debug" 10 | -------------------------------------------------------------------------------- /Test/Functional/Acceptance.suite.dist.yml: -------------------------------------------------------------------------------- 1 | actor: CliTester 2 | modules: 3 | enabled: 4 | - Magento\CloudDocker\Test\Functional\Codeception\TestInfrastructure 5 | - Magento\CloudDocker\Test\Functional\Codeception\Docker 6 | - PhpBrowser 7 | - Asserts 8 | -------------------------------------------------------------------------------- /registration.php: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Model/UrlFinderInterface.php: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | 0 */12 * * * 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Test/Functional/Acceptance/Acceptance82Cest.php: -------------------------------------------------------------------------------- 1 | '2.4.6'], 22 | ]; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Test/Functional/Acceptance/Acceptance83Cest.php: -------------------------------------------------------------------------------- 1 | '2.4.7'], 22 | ]; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Test/Functional/Acceptance/Acceptance84Cest.php: -------------------------------------------------------------------------------- 1 | '2.4.8'], 22 | ]; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Test/Functional/Acceptance/Acceptance81Cest.php: -------------------------------------------------------------------------------- 1 | '2.4.4'], 22 | ['magentoVersion' => '2.4.5'], 23 | ]; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /COPYING.txt: -------------------------------------------------------------------------------- 1 | Copyright © 2013-present Magento, Inc. 2 | 3 | Each Magento source file included in this distribution is licensed under OSL 3.0 or the Magento Customer Agreement. 4 | 5 | http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) 6 | Please see LICENSE_OSL.txt for the full text of the OSL 3.0 license or contact engcom@adobe.com for a copy. 7 | 8 | Subject to Licensee's payment of fees and compliance with the terms and conditions of the Customer Agreement, the Customer Agreement supersedes the OSL 3.0 license for each source file. Please visit https://magento.com/legal/terms for the full text of the 9 | Customer Agreement. 10 | -------------------------------------------------------------------------------- /Model/Logger/Handler/Debug.php: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /Test/Unit/phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 10 | 11 | 12 | ./ 13 | 14 | 15 | 16 | 17 | ../../ 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /.github/.metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "templateVersion": "0.2", 3 | "product": { 4 | "name": "Magento Cloud Components", 5 | "description": "The Magento Cloud Components module extends Magento Commerce core functionality for sites deployed on the Cloud platform. This module contains cloud-specific functionality for use with the ece-tools package." 6 | }, 7 | "contacts": { 8 | "team": { 9 | "name": "Mystic Mountain", 10 | "DL": "Grp-Mystic-Mountain", 11 | "slackChannel": "#mystic-mountain-team" 12 | } 13 | }, 14 | "ticketTracker": { 15 | "functionalJiraQueue": { 16 | "projectKey": "MCLOUD" 17 | }, 18 | "securityJiraQueue": { 19 | "projectKey": "MAGREQ", 20 | "component": "MAGREQ/Magento Cloud Engineering" 21 | } 22 | }, 23 | "productionCodeBranches": ["1.0", "1.1"] 24 | } 25 | -------------------------------------------------------------------------------- /Model/UrlFixer.php: -------------------------------------------------------------------------------- 1 | getForceDisableRewrites() || !$store->getConfig(Store::XML_PATH_USE_REWRITES)) 27 | && strpos($url, '/magento/') !== false 28 | ) { 29 | return preg_replace('|/magento/|', '/', $url, 1); 30 | } 31 | 32 | return rtrim($url, '/'); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Model/Observer/CacheFlushAll.php: -------------------------------------------------------------------------------- 1 | logger = $logger; 31 | } 32 | 33 | /** 34 | * Log cache flush action to a file 35 | * 36 | * @param Observer $observer 37 | * @SuppressWarnings(PHPMD.UnusedFormalParameter) 38 | */ 39 | public function execute(Observer $observer) 40 | { 41 | $this->logger->execute(['tags' => ['all']]); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /tests/static/phpcs-ruleset.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | Custom coding standard. 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | _files 29 | _file 30 | vendor 31 | etc 32 | 33 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Technical issue with the Magento Cloud Components 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | --- 8 | 9 | 19 | 20 | ### Preconditions 21 | 25 | 1. 26 | 2. 27 | 28 | ### Steps to reproduce 29 | 33 | 1. 34 | 2. 35 | 3. 36 | 37 | ### Expected result 38 | 39 | 1. [Screenshots, logs or description] 40 | 41 | ### Actual result 42 | 43 | 1. [Screenshots, logs or description] 44 | -------------------------------------------------------------------------------- /Model/Indexation/Logger.php: -------------------------------------------------------------------------------- 1 | logger = $logger; 39 | $this->debugTrace = $debugTrace; 40 | } 41 | 42 | /** 43 | * Log full re-indexation to a file 44 | * 45 | * @param ActionInterface $subject 46 | */ 47 | public function afterExecuteFull(ActionInterface $subject) 48 | { 49 | $this->logger->debug( 50 | 'full_indexation: ' . get_class($subject), 51 | [ 52 | 'trace' => $this->debugTrace->getTrace() 53 | ] 54 | ); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Cron/Evict.php: -------------------------------------------------------------------------------- 1 | evictor = $evictor; 42 | $this->deploymentConfig = $deploymentConfig; 43 | $this->logger = $logger; 44 | } 45 | 46 | /** 47 | * Perform keys eviction. 48 | */ 49 | public function execute() 50 | { 51 | if (!$this->deploymentConfig->get(Evictor::CONFIG_PATH_ENABLED)) { 52 | $this->logger->info('Keys eviction is disabled'); 53 | 54 | return; 55 | } 56 | 57 | $this->evictor->evict(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Console/Command/CacheEvict.php: -------------------------------------------------------------------------------- 1 | evictor = $evictor; 32 | 33 | parent::__construct('cache:evict'); 34 | } 35 | 36 | /** 37 | * @inheritdoc 38 | */ 39 | protected function configure() 40 | { 41 | $this->setDescription('Evicts unused keys by performing scan command'); 42 | } 43 | 44 | /** 45 | * @inheritdoc 46 | */ 47 | public function execute(InputInterface $input, OutputInterface $output): int 48 | { 49 | $output->writeln('Begin scanning of cache keys'); 50 | 51 | $count = $this->evictor->evict(); 52 | 53 | $output->writeln(sprintf( 54 | 'Total scanned keys: %s', 55 | $count 56 | )); 57 | 58 | return Cli::RETURN_SUCCESS; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Model/Observer/IndexerStateSaveAfter.php: -------------------------------------------------------------------------------- 1 | logger = $logger; 33 | } 34 | 35 | /** 36 | * Log all indexers invalidations to a file 37 | * 38 | * @param Observer $observer 39 | */ 40 | public function execute(Observer $observer) 41 | { 42 | $indexerState = $observer->getData('indexer_state'); 43 | if ($indexerState->getData('status') !== $indexerState->getOrigData('status') 44 | && $indexerState->getData('status') === StateInterface::STATUS_INVALID 45 | ) { 46 | $this->logger->debug( 47 | 'indexer_invalidation: ' . $indexerState->getData('indexer_id'), 48 | [ 49 | 'trace' => debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) 50 | ] 51 | ); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /codeception.dist.yml: -------------------------------------------------------------------------------- 1 | paths: 2 | tests: /Test/Functional 3 | output: tests/functional/_output 4 | data: tests/functional/_data 5 | support: vendor/magento/magento-cloud-docker/tests/functional/_support 6 | actor_suffix: Tester 7 | settings: 8 | colors: true 9 | extensions: 10 | enabled: 11 | - Codeception\Extension\RunFailed 12 | - Codeception\Extension\FailedInfo 13 | params: 14 | - vendor/magento/magento-cloud-docker/tests/functional/configuration.dist.yml 15 | - env 16 | modules: 17 | config: 18 | Magento\CloudDocker\Test\Functional\Codeception\TestInfrastructure: 19 | template_repo: "https://github.com/magento/magento-cloud.git" 20 | mcd_repo: "https://github.com/magento/magento-cloud-docker.git" 21 | mcc_repo: "https://github.com/magento/magento-cloud-components.git" 22 | mcp_repo: "https://github.com/magento/magento-cloud-patches.git" 23 | composer_magento_username: "%REPO_USERNAME%" 24 | composer_magento_password: "%REPO_PASSWORD%" 25 | composer_github_token: "%GITHUB_TOKEN%" 26 | printOutput: false 27 | Magento\CloudDocker\Test\Functional\Codeception\Docker: 28 | system_magento_dir: "%Magento.docker.settings.system.magento_dir%" 29 | printOutput: false 30 | PhpBrowser: 31 | url: "%Magento.docker.settings.env.url.base%" 32 | Magento\CloudDocker\Test\Functional\Codeception\MagentoDb: 33 | dsn: "mysql:host=%Magento.docker.settings.db.host%;port=%Magento.docker.settings.db.port%;dbname=%Magento.docker.settings.db.path%" 34 | user: "%Magento.docker.settings.db.username%" 35 | password: "%Magento.docker.settings.db.password%" 36 | exposed_port: "%Magento.docker.settings.db.port%" 37 | reconnect: true 38 | -------------------------------------------------------------------------------- /tests/static/Sniffs/Whitespace/MultipleEmptyLinesSniff.php: -------------------------------------------------------------------------------- 1 | getTokens(); 32 | if ($phpcsFile->hasCondition($stackPtr, T_FUNCTION) 33 | || $phpcsFile->hasCondition($stackPtr, T_CLASS) 34 | || $phpcsFile->hasCondition($stackPtr, T_INTERFACE) 35 | ) { 36 | if ($tokens[($stackPtr - 1)]['line'] < $tokens[$stackPtr]['line'] 37 | && $tokens[($stackPtr - 2)]['line'] === $tokens[($stackPtr - 1)]['line'] 38 | ) { 39 | // This is an empty line and the line before this one is not 40 | // empty, so this could be the start of a multiple empty line block 41 | $next = $phpcsFile->findNext(T_WHITESPACE, $stackPtr, null, true); 42 | $lines = $tokens[$next]['line'] - $tokens[$stackPtr]['line']; 43 | if ($lines > 1) { 44 | $error = 'Code must not contain multiple empty lines in a row; found %s empty lines'; 45 | $data = [$lines]; 46 | $phpcsFile->addError($error, $stackPtr, 'MultipleEmptyLines', $data); 47 | } 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "magento/magento-cloud-components", 3 | "description": "Cloud Components Module for Magento 2.x", 4 | "type": "magento2-module", 5 | "version": "1.1.3", 6 | "require": { 7 | "php": "^8.0", 8 | "ext-json": "*", 9 | "colinmollenhour/cache-backend-redis": "^1.14.2", 10 | "colinmollenhour/credis": "^1.6.0 || ^1.13" 11 | }, 12 | "suggest": { 13 | "magento/framework": "*", 14 | "magento/module-store": "*", 15 | "magento/module-url-rewrite": "*" 16 | }, 17 | "require-dev": { 18 | "codeception/codeception": "^5.1", 19 | "codeception/module-asserts": "^3.0", 20 | "codeception/module-db": "^3.0", 21 | "codeception/module-phpbrowser": "^3.0", 22 | "codeception/module-rest": "^3.0", 23 | "consolidation/robo": "^3.0 || ^4.0 || ^5.0", 24 | "phpmd/phpmd": "@stable", 25 | "phpstan/phpstan": "~1.2.0 || ^2.0", 26 | "phpunit/phpunit": "^10.0", 27 | "squizlabs/php_codesniffer": "^3.7" 28 | }, 29 | "config": { 30 | "sort-packages": true 31 | }, 32 | "scripts": { 33 | "test": [ 34 | "@phpstan", 35 | "@phpcs", 36 | "@phpmd", 37 | "@phpunit" 38 | ], 39 | "phpstan": "phpstan analyse -c tests/static/phpstan.neon", 40 | "phpcs": "phpcs ./ --standard=tests/static/phpcs-ruleset.xml -p -n", 41 | "phpmd": "phpmd Console xml tests/static/phpmd-ruleset.xml", 42 | "phpunit": "phpunit --configuration Test/Unit", 43 | "pre-install-cmd": "@install_suggested", 44 | "pre-update-cmd": "@install_suggested", 45 | "install_suggested": "composer config repositories.magento composer https://repo.magento.com/ && composer require \"magento/framework:*\" --no-update && composer require \"magento/module-store:*\" --no-update && composer require \"magento/module-url-rewrite:*\" --no-update" 46 | }, 47 | "autoload": { 48 | "files": [ "registration.php" ], 49 | "psr-4": { 50 | "Magento\\CloudComponents\\": "", 51 | "Magento\\CloudComponents\\Test\\Functional\\": "tests/functional/" 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Model/UrlFinderFactory.php: -------------------------------------------------------------------------------- 1 | UrlFinder\Entity::class, 30 | Rewrite::ENTITY_TYPE_CATEGORY => UrlFinder\Entity::class, 31 | Rewrite::ENTITY_TYPE_PRODUCT => UrlFinder\Product::class, 32 | ]; 33 | 34 | /** 35 | * @param ObjectManagerInterface $objectManager 36 | */ 37 | public function __construct(ObjectManagerInterface $objectManager) 38 | { 39 | $this->objectManager = $objectManager; 40 | } 41 | 42 | /** 43 | * Creates UrlFinder objects depends on entity type. 44 | * 45 | * @param string $entityType 46 | * @param array $data 47 | * @return mixed 48 | */ 49 | public function create(string $entityType, array $data): UrlFinderInterface 50 | { 51 | if (!isset(self::$classMap[$entityType])) { 52 | throw new \UnexpectedValueException('Wrong entity type.'); 53 | } 54 | 55 | if ($entityType === Rewrite::ENTITY_TYPE_PRODUCT) { 56 | return $this->objectManager->create(self::$classMap[$entityType], [ 57 | 'stores' => $data['stores'], 58 | 'productSku' => $data['productSku'], 59 | 'productLimit' => $data['productLimit'] 60 | ]); 61 | } 62 | 63 | return $this->objectManager->create(self::$classMap[$entityType], [ 64 | 'entityType' => $entityType, 65 | 'stores' => $data['stores'] 66 | ]); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Console/Command/ConfigShowDefaultUrlCommand.php: -------------------------------------------------------------------------------- 1 | storeManager = $storeManager; 42 | $this->urlFixer = $urlFixer; 43 | } 44 | 45 | /** 46 | * @inheritdoc 47 | */ 48 | protected function configure() 49 | { 50 | $this->setName('config:show:default-url') 51 | ->setDescription('Shows base url for default store of default website'); 52 | 53 | parent::configure(); 54 | } 55 | 56 | /** 57 | * Returns base url for default store of default website 58 | * 59 | * @inheritdoc 60 | */ 61 | protected function execute(InputInterface $input, OutputInterface $output) 62 | { 63 | /** @var Store $store */ 64 | $store = $this->storeManager->getDefaultStoreView(); 65 | $baseUrl = $store->getBaseUrl(UrlInterface::URL_TYPE_LINK, $store->isUrlSecure()); 66 | $output->writeln($this->urlFixer->run($store, $baseUrl)); 67 | 68 | return Cli::RETURN_SUCCESS; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 8 | 9 | 10 | 11 | ### Description 12 | 16 | 17 | ### Fixed Issues (if relevant) 18 | 22 | 1. magento/magento-cloud-components#: Issue title 23 | 2. ... 24 | 25 | ### Manual testing scenarios 26 | 30 | 1. ... 31 | 2. ... 32 | 33 | ### Release notes 34 | 35 | For user-facing changes, add a meaningful release note. For examples, see [Magento Cloud Components release notes](https://devdocs.magento.com/cloud/release-notes/mcc-release-notes.html). 36 | 37 | ### Associated documentation updates 38 | 41 | Add link to Magento DevDocs PR or Issue, if needed. 42 | 43 | ### Contribution checklist 44 | - [ ] Pull request has a meaningful description of its purpose 45 | - [ ] Pull request introduces user-facing changes and includes meaningful updates for any required release notes and documentation changes 46 | - [ ] All commits are accompanied by meaningful commit messages 47 | -------------------------------------------------------------------------------- /tests/static/phpmd-ruleset.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 12 | Magento Cloud Code Check Rules 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | _files 48 | vendor 49 | etc 50 | 51 | -------------------------------------------------------------------------------- /Model/UrlFinder/Entity.php: -------------------------------------------------------------------------------- 1 | urlFactory = $urlFactory; 62 | $this->urlFinder = $urlFinder; 63 | $this->urlFixer = $urlFixer; 64 | $this->entityType = $entityType; 65 | $this->stores = $stores; 66 | } 67 | 68 | /** 69 | * Returns list of url by store ids and entity type 70 | * 71 | * @return array 72 | */ 73 | public function get(): array 74 | { 75 | $urls = []; 76 | 77 | foreach ($this->stores as $store) { 78 | $url = $this->urlFactory->create()->setScope($store->getId()); 79 | 80 | $entities = $this->urlFinder->findAllByData([ 81 | UrlRewrite::STORE_ID => $store->getId(), 82 | UrlRewrite::ENTITY_TYPE => $this->entityType 83 | ]); 84 | 85 | foreach ($entities as $urlRewrite) { 86 | $urls[] = $this->urlFixer->run($store, $url->getBaseUrl().$urlRewrite->getRequestPath()); 87 | } 88 | } 89 | 90 | return $urls; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /Test/Unit/Model/UrlFinderFactoryTest.php: -------------------------------------------------------------------------------- 1 | objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); 40 | 41 | $this->urlFinderFactory = new UrlFinderFactory($this->objectManagerMock); 42 | } 43 | 44 | public function testCreateCategoryOrCmsPageEntity(): void 45 | { 46 | $this->objectManagerMock->expects($this->once()) 47 | ->method('create') 48 | ->with(Entity::class, [ 49 | 'entityType' => 'category', 50 | 'stores' => ['store1'], 51 | ]) 52 | ->willReturn($this->getMockForAbstractClass(UrlFinderInterface::class)); 53 | 54 | $this->urlFinderFactory->create('category', [ 55 | 'stores' => ['store1'], 56 | ]); 57 | } 58 | 59 | public function testCreateProductEntity(): void 60 | { 61 | $this->objectManagerMock->expects($this->once()) 62 | ->method('create') 63 | ->with(Product::class, [ 64 | 'stores' => ['store1'], 65 | 'productSku' => ['sku1', 'sku2'], 66 | 'productLimit' => 100 67 | ]) 68 | ->willReturn($this->getMockForAbstractClass(UrlFinderInterface::class)); 69 | 70 | $this->urlFinderFactory->create('product', [ 71 | 'stores' => ['store1'], 72 | 'productSku' => ['sku1', 'sku2'], 73 | 'productLimit' => 100 74 | ]); 75 | } 76 | 77 | public function testCreateWrongType(): void 78 | { 79 | $this->expectException(UnexpectedValueException::class); 80 | $this->expectExceptionMessage('Wrong entity type.'); 81 | 82 | $this->urlFinderFactory->create('wrong_type', []); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Magento Cloud Components 2 | The Magento Cloud Components module extends Magento Commerce core functionality for sites deployed on the Cloud platform. This module contains cloud-specific functionality for use with the [ece-tools](https://github.com/magento/ece-tools) package. 3 | 4 | ## Contributing to the Magento Cloud Components Code Base 5 | You can submit issues and pull requests to extend functionality or fix potential bugs. Improvements to Magento Cloud Components can include work such as improving the developer experience or optimizing the deployment process. If you find a bug or have a suggestion, let us know by creating a Github issue. 6 | 7 | **Note:** This repository is not an official support channel. To receive project-specific help, submit a support ticket using the [Magento Support Portal](https://support.magento.com). Any support-related issues opened in this repository will be closed with a request to open a support ticket. 8 | 9 | # Magento Cloud Suite 10 | The Magento Cloud Suite includes a set of packages designed to deploy and manage Magento Commerce installations on the Cloud platform. 11 | - The [ece-tools package](https://github.com/magento/ece-tools) - A set of scripts and tools designed to manage and deploy Cloud projects 12 | - [Magento Cloud Components](https://github.com/magento/magento-cloud-components) package - Extended Magento Commerce core functionality for sites deployed on the Cloud platform 13 | - [Magento Cloud Docker](https://github.com/magento/magento-cloud-docker) package - Functionality and Docker images to deploy Magento Commerce to a local Cloud environment 14 | - [Magento Cloud Patches](https://github.com/magento/magento-cloud-patches) package - A set of patches which improve the integration of all Magento versions with Cloud environments 15 | 16 | ## Useful Resources 17 | - [Release Notes](https://github.com/magento/magento-cloud-components/releases) 18 | - [Magento Cloud Guide DevDocs](https://devdocs.magento.com/guides/v2.3/cloud/bk-cloud.html) 19 | - [Cloud Knowledge Base and Support](https://support.magento.com) 20 | - [Cloud Slack Channel](https://magentocommeng.slack.com) (join #cloud and #cloud-docker) 21 | 22 | ## License 23 | Each Magento source file included in this distribution is licensed under OSL 3.0 or the Magento Customer Agreement. 24 | 25 | [Open Software License (OSL 3.0)](https://opensource.org/licenses/osl-3.0.php). Please see [LICENSE_OSL.txt](LICENSE_OSL.txt) for the full text of the OSL 3.0 license or contact [engcom@adobe.com](mailto:engcom@adobe.com) for a copy. 26 | 27 | Subject to Licensee's payment of fees and compliance with the terms and conditions of the Customer Agreement, the Customer Agreement supersedes the OSL 3.0 license for each source file. Please visit https://magento.com/legal/terms for the full text of the 28 | Customer Agreement. 29 | -------------------------------------------------------------------------------- /Model/Cache/InvalidateLogger.php: -------------------------------------------------------------------------------- 1 | debugTrace = $debugTrace; 78 | } 79 | 80 | /** 81 | * Log cache invalidation to a file 82 | * 83 | * @param mixed $invalidateInfo 84 | */ 85 | public function execute($invalidateInfo) 86 | { 87 | $needTrace = false; 88 | if (is_array($invalidateInfo) && isset($invalidateInfo['tags'])) { 89 | foreach ($invalidateInfo['tags'] as $tag) { 90 | if (in_array(strtolower($tag), $this->tagsToLog)) { 91 | $needTrace = true; 92 | } 93 | } 94 | 95 | if ($needTrace) { 96 | $invalidateInfo['trace'] = $this->debugTrace->getTrace(); 97 | } 98 | } 99 | parent::execute($invalidateInfo); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /Model/DebugTrace.php: -------------------------------------------------------------------------------- 1 | $line) { 63 | if (!isset($line['function'], $line['class'], $line['file'])) { 64 | continue; 65 | } 66 | if (in_array($line['function'], $this->notAllowedFunctions) 67 | || in_array($line['class'], $this->notAllowedClasses) 68 | || strpos($line['file'], 'Interceptor.php') !== false 69 | ) { 70 | unset($trace[$index]); 71 | } 72 | unset($trace[$index]['type']); 73 | } 74 | 75 | if (function_exists('gzcompress')) { 76 | return bin2hex( 77 | gzcompress( 78 | print_r( 79 | $trace, 80 | true 81 | ) 82 | ) 83 | ); 84 | } 85 | return $trace; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /Console/Command/ConfigShowStoreUrlCommand.php: -------------------------------------------------------------------------------- 1 | storeManager = $storeManager; 50 | $this->urlFixer = $urlFixer; 51 | } 52 | 53 | /** 54 | * @inheritdoc 55 | */ 56 | protected function configure() 57 | { 58 | $this->setName('config:show:store-url') 59 | ->setDescription( 60 | 'Shows store base url for given id. Shows base url for all stores if id wasn\'t passed' 61 | ); 62 | 63 | $this->addArgument( 64 | self::INPUT_ARGUMENT_STORE_ID, 65 | InputArgument::OPTIONAL, 66 | 'Store ID' 67 | ); 68 | 69 | parent::configure(); 70 | } 71 | 72 | /** 73 | * Returns store url or all store urls if store id wasn't provided 74 | * 75 | * @inheritdoc 76 | */ 77 | protected function execute(InputInterface $input, OutputInterface $output) 78 | { 79 | try { 80 | /** @var Store $store */ 81 | $storeId = $input->getArgument(self::INPUT_ARGUMENT_STORE_ID); 82 | if ($storeId !== null) { 83 | $store = $this->storeManager->getStore($storeId); 84 | $baseUrl = $store->getBaseUrl(UrlInterface::URL_TYPE_LINK, $store->isUrlSecure()); 85 | 86 | $output->writeln($this->urlFixer->run($store, $baseUrl)); 87 | } else { 88 | $urls = []; 89 | foreach ($this->storeManager->getStores(true) as $store) { 90 | $urls[$store->getId()] = $this->urlFixer->run( 91 | $store, 92 | $store->getBaseUrl(UrlInterface::URL_TYPE_LINK, $store->isUrlSecure()) 93 | ); 94 | } 95 | 96 | $output->writeln(json_encode($urls, JSON_FORCE_OBJECT)); 97 | } 98 | 99 | return Cli::RETURN_SUCCESS; 100 | } catch (\Exception $e) { 101 | $output->writeln(sprintf('%s', $e->getMessage())); 102 | return Cli::RETURN_FAILURE; 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /Model/UrlFinder/Product.php: -------------------------------------------------------------------------------- 1 | urlFixer = $urlFixer; 75 | $this->productCollectionFactory = $productCollectionFactory; 76 | $this->productVisibility = $productVisibility; 77 | $this->stores = $stores; 78 | $this->productSku = $productSku; 79 | $this->productLimit = $productLimit; 80 | } 81 | 82 | /** 83 | * Returns product urls by given skus and store ids 84 | * 85 | * @return array 86 | */ 87 | public function get(): array 88 | { 89 | $urls = []; 90 | 91 | foreach ($this->stores as $store) { 92 | $products = $this->getProducts($store->getId()); 93 | foreach ($products as $product) { 94 | $urls[] = $this->urlFixer->run($store, $product->getProductUrl()); 95 | } 96 | } 97 | 98 | return $urls; 99 | } 100 | 101 | /** 102 | * Returns product collection by given product SKUs 103 | * In case when product SKUs wasn't provided returns self::PRODUCT_LIMIT products 104 | * 105 | * @param $storeId 106 | * @return Collection 107 | */ 108 | private function getProducts($storeId): Collection 109 | { 110 | /** @var Collection $collection */ 111 | $collection = $this->productCollectionFactory->create(); 112 | $collection->addStoreFilter($storeId); 113 | $collection->setVisibility($this->productVisibility->getVisibleInSiteIds()); 114 | 115 | if (count($this->productSku)) { 116 | $collection->addAttributeToFilter('sku', $this->productSku); 117 | } else { 118 | $collection->setPageSize($this->productLimit); 119 | } 120 | 121 | return $collection; 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /etc/di.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | 12 | Magento\CloudComponents\Console\Command\ConfigShowStoreUrlCommand 13 | Magento\CloudComponents\Console\Command\ConfigShowEntityUrlsCommand 14 | Magento\CloudComponents\Console\Command\ConfigShowDefaultUrlCommand 15 | Magento\CloudComponents\Console\Command\CacheEvict 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | /var/log/cache.log 24 | 25 | 26 | 27 | 28 | main 29 | 30 | Magento\CloudComponents\Model\Logger\Handler\Debug 31 | 32 | 33 | 34 | 35 | 36 | Magento\CloudComponents\Model\Logger\CacheInvalidate 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | /var/log/indexation.log 45 | 46 | 47 | 48 | 49 | main 50 | 51 | Magento\CloudComponents\Model\Logger\Handler\Debug\Indexation 52 | 53 | 54 | 55 | 56 | 57 | Magento\CloudComponents\Model\Logger\Monolog\Indexation 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | Magento\CloudComponents\Model\Logger\Monolog\Indexation 66 | 67 | 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /Test/Functional/Acceptance/AcceptanceCest.php: -------------------------------------------------------------------------------- 1 | cleanupWorkDir(); 23 | } 24 | 25 | /** 26 | * @param \CliTester $I 27 | * @param string $magentoVersion 28 | */ 29 | protected function prepareTemplate(\CliTester $I, string $magentoVersion): void 30 | { 31 | $I->cloneTemplateToWorkDir($magentoVersion); 32 | $I->createAuthJson(); 33 | $I->createArtifactsDir(); 34 | $I->createArtifactCurrentTestedCode('components', '1.0.99'); 35 | $I->addArtifactsRepoToComposer(); 36 | $I->addDependencyToComposer('magento/magento-cloud-components', '1.0.99'); 37 | 38 | $I->addEceToolsGitRepoToComposer(); 39 | $I->addEceDockerGitRepoToComposer(); 40 | $I->addCloudPatchesGitRepoToComposer(); 41 | $I->addQualityPatchesGitRepoToComposer(); 42 | 43 | $dependencies = [ 44 | 'magento/ece-tools', 45 | 'magento/magento-cloud-docker', 46 | 'magento/magento-cloud-patches', 47 | 'magento/quality-patches' 48 | ]; 49 | 50 | foreach ($dependencies as $dependency) { 51 | $I->assertTrue( 52 | $I->addDependencyToComposer($dependency, $I->getDependencyVersion($dependency)), 53 | 'Can not add dependency ' . $dependency 54 | ); 55 | } 56 | 57 | $I->composerUpdate(); 58 | } 59 | 60 | /** 61 | * @param \CliTester $I 62 | * @param \Codeception\Example $data 63 | * @throws \Robo\Exception\TaskException 64 | * @dataProvider patchesDataProvider 65 | */ 66 | public function testPatches(\CliTester $I, \Codeception\Example $data): void 67 | { 68 | $this->prepareTemplate($I, $data['magentoVersion']); 69 | $this->removeESIfExists($I, $data['magentoVersion']); 70 | $I->generateDockerCompose('--mode=production'); 71 | $I->runDockerComposeCommand('run build cloud-build'); 72 | $I->startEnvironment(); 73 | $I->runDockerComposeCommand('run deploy cloud-deploy'); 74 | $I->runDockerComposeCommand('run deploy cloud-post-deploy'); 75 | $I->amOnPage('/'); 76 | $I->see('Home page'); 77 | $I->see('CMS homepage content goes here.'); 78 | } 79 | 80 | /** 81 | * @param \CliTester $I 82 | * @param string $magentoVersion 83 | */ 84 | protected function removeESIfExists(\CliTester $I, string $magentoVersion): void 85 | { 86 | if ($magentoVersion !== 'master' && version_compare($magentoVersion, '2.4.0', '<')) { 87 | $services = $I->readServicesYaml(); 88 | 89 | if (isset($services['elasticsearch'])) { 90 | unset($services['elasticsearch']); 91 | $I->writeServicesYaml($services); 92 | 93 | $app = $I->readAppMagentoYaml(); 94 | unset($app['relationships']['elasticsearch']); 95 | $I->writeAppMagentoYaml($app); 96 | } 97 | } 98 | } 99 | 100 | /** 101 | * @return array 102 | */ 103 | abstract protected function patchesDataProvider(): array; 104 | 105 | /** 106 | * @param \CliTester $I 107 | */ 108 | public function _after(\CliTester $I): void 109 | { 110 | $I->stopEnvironment(); 111 | $I->removeWorkDir(); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /Test/Unit/Model/UrlFixerTest.php: -------------------------------------------------------------------------------- 1 | storeMock = $this->getMockBuilder(Store::class) 36 | ->disableOriginalConstructor() 37 | ->onlyMethods(['getConfig']) 38 | ->addMethods(['getForceDisableRewrites']) 39 | ->getMock(); 40 | $this->urlFixer = new UrlFixer(); 41 | } 42 | 43 | /** 44 | * @param bool $rewritesDisabled 45 | * @param bool $useConfigRewrites 46 | * @param string $url 47 | * @param string $expectedUrl 48 | * @dataProvider runDataProvider 49 | */ 50 | public function testRunWithConfigRewrites( 51 | string $url, 52 | string $expectedUrl, 53 | bool $rewritesDisabled = false, 54 | bool $useConfigRewrites = true 55 | ) { 56 | $this->storeMock->expects($this->once()) 57 | ->method('getForceDisableRewrites') 58 | ->willReturn($rewritesDisabled); 59 | 60 | if (!$rewritesDisabled) { 61 | $this->storeMock->expects($this->once()) 62 | ->method('getConfig') 63 | ->with(Store::XML_PATH_USE_REWRITES) 64 | ->willReturn($useConfigRewrites); 65 | } else { 66 | $this->storeMock->expects($this->never()) 67 | ->method('getConfig'); 68 | } 69 | 70 | $this->assertEquals($expectedUrl, $this->urlFixer->run($this->storeMock, $url)); 71 | } 72 | 73 | /** 74 | * @return array 75 | */ 76 | public static function runDataProvider(): array 77 | { 78 | return [ 79 | 'rewrites enabled, url without "magento" part' => [ 80 | 'http://example.com/', 81 | 'http://example.com', 82 | ], 83 | 'rewrites disabled, url without "magento" part' => [ 84 | 'http://example.com/', 85 | 'http://example.com', 86 | true, 87 | true, 88 | ], 89 | 'rewrites enabled, url with "magento" part' => [ 90 | 'http://example.com/magento/', 91 | 'http://example.com/magento', 92 | false, 93 | true, 94 | ], 95 | 'rewrites disabled in store, url with "magento" part' => [ 96 | 'http://example.com/magento/', 97 | 'http://example.com/', 98 | true, 99 | false, 100 | ], 101 | 'rewrites disabled in config, url with "magento" part' => [ 102 | 'http://example.com/magento/', 103 | 'http://example.com/', 104 | false, 105 | false, 106 | ], 107 | 'rewrites disabled, url with multiple "magento" part' => [ 108 | 'http://example.com/magento/magento/magento/test.html', 109 | 'http://example.com/magento/magento/test.html', 110 | true, 111 | false, 112 | ], 113 | 'rewrites disabled, url with "magento2" part' => [ 114 | 'http://example.com/magento2/', 115 | 'http://example.com/magento2', 116 | true, 117 | false, 118 | ], 119 | 'rewrites disabled, with "magento" host' => [ 120 | 'http://magento.com/magento2/', 121 | 'http://magento.com/magento2', 122 | true, 123 | false, 124 | ], 125 | ]; 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /tests/static/Sniffs/Directives/StrictTypesSniff.php: -------------------------------------------------------------------------------- 1 | getTokens(); 46 | 47 | // Tokens to look for. 48 | $findTokens = [ 49 | T_DECLARE, 50 | T_NAMESPACE, 51 | T_CLASS 52 | ]; 53 | 54 | // Find the first occurrence of the tokens to look for. 55 | $position = $phpcsFile->findNext($findTokens, $stackPtr); 56 | 57 | if ($position === false) { 58 | return; 59 | } 60 | 61 | // If the first token found is not T_DECLARE, then the file does not include a strict_types declaration. 62 | if ($tokens[$position]['code'] !== T_DECLARE) { 63 | // Fix and set the boolean flag to true. 64 | $this->fix($phpcsFile, $position); 65 | } 66 | 67 | // If the file includes a declare directive, and the file has not already been fixed, scan specifically 68 | // for strict_types and fix as needed. 69 | if (!$this->fixed) { 70 | if (!$this->scan($phpcsFile, $tokens, $position)) { 71 | $this->fix($phpcsFile, $position); 72 | } 73 | } 74 | } 75 | 76 | /** 77 | * Fixer to add the strict_types declaration. 78 | * 79 | * @param File $phpcsFile 80 | * @param int $position 81 | */ 82 | private function fix(File $phpcsFile, int $position) : void 83 | { 84 | // Get the fixer. 85 | $fixer = $phpcsFile->fixer; 86 | // Record the error. 87 | $phpcsFile->addFixableError("Missing strict_types declaration", $position, self::class); 88 | // Prepend content at the given position. 89 | $fixer->addContentBefore($position, "declare(strict_types=1);\n\n"); 90 | // Set flag. 91 | $this->fixed = true; 92 | } 93 | 94 | /** 95 | * Recursive method to scan declare statements for strict_types. 96 | * 97 | * @param File $phpcsFile 98 | * @param array $tokens 99 | * @param int $position 100 | * @return bool 101 | */ 102 | private function scan(File $phpcsFile, array $tokens, int $position) : bool 103 | { 104 | // Exit statement, if the beginning of the file has been reached. 105 | if ($tokens[$position]['code'] === T_OPEN_TAG || $position === 0) { 106 | return false; 107 | } 108 | 109 | if (!$phpcsFile->findNext([T_STRING], $position)) { 110 | // If there isn't a T_STRING token for the declare directive, continue scan. 111 | return $this->scan($phpcsFile, $tokens, $phpcsFile->findPrevious([T_DECLARE], $position - 1)); 112 | } else { 113 | // Checking specifically for strict_types. 114 | $temp = $phpcsFile->findNext([T_STRING], $position); 115 | if ($tokens[$temp]['content'] === 'strict_types') { 116 | // Return true as strict_types directive has been found. 117 | return true; 118 | } else { 119 | // Continue scan if strict_types hasn't been found. 120 | return $this->scan($phpcsFile, $tokens, $phpcsFile->findPrevious([T_DECLARE], $position - 1)); 121 | } 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Magento Cloud Components code 2 | 3 | Use the GitHub fork & pull model contribution model to submit your code contributions to the Magento Cloud Components codebase. 4 | In this contribution model, you maintain your own [fork](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/working-with-forks) of the Magento Cloud Components repository, and create a [pull request](https://help.github.com/articles/about-pull-requests/) to submit your proposed changes to the base repository. For details on the fork & pull contribution model, see the [Beginners guide](https://github.com/magento/magento2/wiki/Getting-Started). 5 | 6 | Contributions can take the form of new features, changes to existing features, tests, bug fixes, or optimizations. You can also contribute new or updated documentation. 7 | 8 | The Magento Cloud development team and community maintainers review all issues and contributions submitted by the developer community in first in, first out order (FIFO). During the review process, reviewers might notify a contributor to request clarification on the proposed changes. 9 | 10 | ## Prerequisites 11 | 12 | You must have a [GitHub account](https://help.github.com/en/github/getting-started-with-github/signing-up-for-a-new-github-account) with [two-factor authentication](https://help.github.com/en/github/authenticating-to-github/configuring-two-factor-authentication) enabled to contribute to Magento repositories. We also recommend creating a [personal access token](https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line) to use when interacting with GitHub using scripts and the command line. 13 | 14 | ## Contribution requirements 15 | 16 | 1. Contributions must adhere to the [Magento coding standards](https://devdocs.magento.com/guides/v2.3/coding-standards/bk-coding-standards.html). 17 | 2. When you submit a Pull request (PR), write a meaningful description to explain the purpose of your contribution. Comprehensive descriptions increase the chances that a pull request can be merged quickly, without requests for additional clarification. See the [Magento Cloud Components Pull Request Template](https://github.com/magento/magento-cloud-components/blob/develop/.github/PULL_REQUEST_TEMPLATE.md) for more information. 18 | 3. Commits must be accompanied by meaningful commit messages. 19 | 4. If your PR includes bug fixes, provide a step-by-step description of how to reproduce the bug in the pull request description. 20 | 3. If your PR includes new logic or new features, you must also submit the following information along with the pull request 21 | * Unit/integration test coverage 22 | * Proposed documentation updates: Submit developer documentation contributions to the [Magento DevDocs repository](https://github.com/magento/devdocs/blob/master/.github/CONTRIBUTING.md). Submit updates to Magento user documentation to the [Magento Merchant documentation repository](https://github.com/magento/merchdocs/blob/master/.github/CONTRIBUTING.md). 23 | 4. For larger features or changes, [open an issue](https://github.com/magento/magento-cloud-components/issues/new) to discuss the proposed changes prior to development. Discussing the updates in advance can prevent duplicate or unnecessary effort and allow other contributors to provide input. 24 | 25 | ## Contribution process 26 | 1. Search current [listed issues](https://github.com/magento/magento-cloud-components/issues) (open or closed) for similar proposals of intended contribution before starting work on a new contribution. 27 | 2. Review and sign the [Contributor License Agreement (CLA)](https://opensource.adobe.com/cla.html) if this is your first time contributing. You only need to sign the CLA once. 28 | 3. Create and test your work. 29 | 4. Fork the Magento Cloud Components repository according to the [Fork A Repository instructions](https://github.com/magento/magento2/wiki/Forking-and-Branching) and when you are ready to send us a pull request – follow the [Create A Pull Request instructions](https://github.com/magento/magento2/wiki/Working-Issues-and-PRs#submitting-prs). 30 | 5. After you submit the pull request, the Magento Cloud development team will review the contribution and collaborate with you as needed to incorporate your proposed changes. 31 | 32 | ## Code of Conduct 33 | 34 | This project is released with a Contributor Code of Conduct. We expect you to agree to its terms when participating in this project. 35 | The full text is available in the repository [Wiki](https://github.com/magento/magento2/wiki/Magento-Code-of-Conduct). 36 | 37 | ## Connecting with Community! 38 | 39 | Need to find a project? Check out the [Slack Channels](https://github.com/magento/magento2/wiki/Slack-Channels) (with listed project info) and the [Magento Community Portal](https://opensource.magento.com/). 40 | -------------------------------------------------------------------------------- /Model/Cache/Evictor.php: -------------------------------------------------------------------------------- 1 | deploymentConfig = $deploymentConfig; 46 | $this->logger = $logger; 47 | } 48 | 49 | /** 50 | * Evicts all keys using iterator. 51 | * 52 | * @return int 53 | */ 54 | public function evict(): int 55 | { 56 | $options = $this->deploymentConfig->getConfigData(FrontendPool::KEY_CACHE)[FrontendPool::KEY_FRONTEND_CACHE] 57 | ?? []; 58 | $evictedKeys = 0; 59 | 60 | foreach ($options as $name => $cacheConfig) { 61 | $this->logger->info(sprintf( 62 | 'Scanning keys for "%s" database', 63 | $name 64 | )); 65 | 66 | $backendOptions = $this->getConfigBackendOptions((array)$cacheConfig); 67 | if (!$this->validateBackendOptions($backendOptions)) { 68 | $this->logger->debug(sprintf( 69 | 'Cache config for database "%s" config is not valid', 70 | $name 71 | )); 72 | 73 | continue; 74 | } 75 | 76 | $dbKeys = $this->run( 77 | (string)$backendOptions[self::BACKEND_OPTION_KEY_SERVER], 78 | (int)$backendOptions[self::BACKEND_OPTION_KEY_PORT], 79 | (int)$backendOptions[self::BACKEND_OPTION_KEY_DATABASE] 80 | ); 81 | $evictedKeys += $dbKeys; 82 | 83 | $this->logger->info(sprintf('Keys scanned: %s', $dbKeys)); 84 | } 85 | 86 | return $evictedKeys; 87 | } 88 | 89 | /** 90 | * Get Cache Config Value 91 | * 92 | * @param array $cacheConfig 93 | * @return array 94 | */ 95 | private function getConfigBackendOptions(array $cacheConfig): array 96 | { 97 | $backendOptions = []; 98 | if (isset($cacheConfig['backend_options'])) { 99 | $backendOptions = $cacheConfig['backend_options']; 100 | } 101 | if (isset($cacheConfig['backend_options']['remote_backend_options'])) { 102 | $backendOptions = $cacheConfig['backend_options']['remote_backend_options']; 103 | } 104 | return (array)$backendOptions; 105 | } 106 | 107 | /** 108 | * Validate Cache Configuration 109 | * 110 | * @param array $backendOptions 111 | * @return bool 112 | */ 113 | private function validateBackendOptions(array $backendOptions): bool 114 | { 115 | if (isset($backendOptions[self::BACKEND_OPTION_KEY_SERVER]) 116 | && isset($backendOptions[self::BACKEND_OPTION_KEY_PORT]) 117 | && isset($backendOptions[self::BACKEND_OPTION_KEY_DATABASE]) 118 | ) { 119 | return true; 120 | } 121 | return false; 122 | } 123 | 124 | /** 125 | * @param string $host 126 | * @param int $port 127 | * @param int $db 128 | * @return int 129 | */ 130 | private function run(string $host, int $port, int $db): int 131 | { 132 | $client = new Client($host, $port, null, '', $db); 133 | $evictedKeys = 0; 134 | 135 | do { 136 | $keys = $client->scan( 137 | $iterator, 138 | Backend::PREFIX_KEY . '*', 139 | (int)$this->deploymentConfig->get(self::CONFIG_PATH_LIMIT, self::DEFAULT_EVICTION_LIMIT) 140 | ); 141 | 142 | if ($keys === false) { 143 | $this->logger->debug('Reached end'); 144 | } else { 145 | $keysCount = count($keys); 146 | $evictedKeys += $keysCount; 147 | } 148 | 149 | /* Give Redis some time to handle other requests */ 150 | usleep(self::DEFAULT_SLEEP_TIMEOUT); 151 | } while ($iterator > 0); 152 | 153 | return $evictedKeys; 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Magento Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our project and community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. 6 | 7 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 8 | 9 | ## Our Standards 10 | 11 | Examples of behavior that contribute to a positive environment for our project and community include: 12 | 13 | * Demonstrating empathy and kindness toward other people 14 | * Being respectful of differing opinions, viewpoints, and experiences 15 | * Giving and gracefully accepting constructive feedback 16 | * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 17 | * Focusing on what is best, not just for us as individuals but for the overall community 18 | 19 | Examples of unacceptable behavior include: 20 | 21 | * The use of sexualized language or imagery, and sexual attention or advances of any kind 22 | * Trolling, insulting or derogatory comments, and personal or political attacks 23 | * Public or private harassment 24 | * Publishing others’ private information, such as a physical or email address, without their explicit permission 25 | * Other conduct which could reasonably be considered inappropriate in a professional setting 26 | 27 | ## Our Responsibilities 28 | 29 | Project maintainers are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any instances of unacceptable behavior. 30 | 31 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for behaviors that they deem inappropriate, threatening, offensive, or harmful. 32 | 33 | ## Scope 34 | 35 | This Code of Conduct applies when an individual is representing the project or its community both within project spaces and in public spaces. Examples of representing a project or community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 36 | 37 | ## Enforcement 38 | 39 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by first contacting the project team at engcom@adobe.com. Oversight of Adobe projects is handled by the Adobe Open Source Office, which has final say in any violations and enforcement of this Code of Conduct and can be reached at Grp-opensourceoffice@adobe.com. All complaints will be reviewed and investigated promptly and fairly. 40 | 41 | The project team must respect the privacy and security of the reporter of any incident. 42 | 43 | Project maintainers who do not follow or enforce the Code of Conduct may face temporary or permanent repercussions as determined by other members of the project's leadership or the Adobe Open Source Office. 44 | 45 | ## Enforcement Guidelines 46 | 47 | Project maintainers will follow these Community Impact Guidelines in determining the consequences for any action they deem to be in violation of this Code of Conduct: 48 | 49 | **1. Correction** 50 | 51 | Community Impact: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 52 | 53 | Consequence: A private, written warning from project maintainers describing the violation and why the behavior was unacceptable. A public apology may be requested from the violator before any further involvement in the project by violator. 54 | 55 | **2. Warning** 56 | 57 | Community Impact: A relatively minor violation through a single incident or series of actions. 58 | 59 | Consequence: A written warning from project maintainers that includes stated consequences for continued unacceptable behavior. Violator must refrain from interacting with the people involved for a specified period of time as determined by the project maintainers, including, but not limited to, unsolicited interaction with those enforcing the Code of Conduct through channels such as community spaces and social media. Continued violations may lead to a temporary or permanent ban. 60 | 61 | **3. Temporary Ban** 62 | 63 | Community Impact: A more serious violation of community standards, including sustained unacceptable behavior. 64 | 65 | Consequence: A temporary ban from any interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Failure to comply with the temporary ban may lead to a permanent ban. 66 | 67 | **4. Permanent Ban** 68 | 69 | Community Impact: Demonstrating a consistent pattern of violation of community standards or an egregious violation of community standards, including, but not limited to, sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 70 | 71 | Consequence: A permanent ban from any interaction with the community. 72 | 73 | ## Attribution 74 | 75 | This Code of Conduct is adapted from the Contributor Covenant, version 2.1, available at https://www.contributor-covenant.org/version/2/1/code_of_conduct.html. 76 | -------------------------------------------------------------------------------- /Console/Command/ConfigShowEntityUrlsCommand.php: -------------------------------------------------------------------------------- 1 | storeManager = $storeManager; 74 | $this->urlFinderFactory = $urlFinderFactory; 75 | $this->state = $state; 76 | 77 | parent::__construct(); 78 | } 79 | 80 | /** 81 | * @inheritdoc 82 | */ 83 | protected function configure() 84 | { 85 | $this->setName('config:show:urls') 86 | ->setDescription( 87 | 'Returns urls for entity type and given store id or for all stores if store id isn\'t provided.' 88 | ); 89 | 90 | $this->addOption( 91 | self::INPUT_OPTION_STORE_ID, 92 | null, 93 | InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL, 94 | 'Store ID' 95 | ); 96 | $this->addOption( 97 | self::INPUT_OPTION_ENTITY_TYPE, 98 | null, 99 | InputOption::VALUE_REQUIRED, 100 | 'Entity type: ' . implode(',', $this->possibleEntities) 101 | ); 102 | $this->addOption( 103 | self::INPUT_OPTION_PRODUCT_SKU, 104 | null, 105 | InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL, 106 | 'Product SKUs' 107 | ); 108 | $this->addOption( 109 | self::INPUT_OPTION_PRODUCT_LIMIT, 110 | null, 111 | InputOption::VALUE_OPTIONAL, 112 | 'Product limit per store uses in case when product SKUs isn\'t provided', 113 | Product::PRODUCT_LIMIT 114 | ); 115 | 116 | parent::configure(); 117 | } 118 | 119 | /** 120 | * @param InputInterface $input 121 | * @param OutputInterface $output 122 | * @return int 123 | */ 124 | protected function execute(InputInterface $input, OutputInterface $output) 125 | { 126 | try { 127 | $this->setArea(); 128 | $entityType = $input->getOption(self::INPUT_OPTION_ENTITY_TYPE); 129 | if (!in_array($entityType, $this->possibleEntities)) { 130 | $output->write(sprintf( 131 | 'Wrong entity type "%s", possible values: %s', 132 | $entityType, 133 | implode(',', $this->possibleEntities) 134 | )); 135 | return Cli::RETURN_FAILURE; 136 | } 137 | 138 | $urlFinder = $this->urlFinderFactory->create($entityType, [ 139 | 'stores' => $this->getStores($input), 140 | 'productSku' => $input->getOption(self::INPUT_OPTION_PRODUCT_SKU), 141 | 'productLimit' => $input->getOption(self::INPUT_OPTION_PRODUCT_LIMIT), 142 | ]); 143 | 144 | $output->writeln(json_encode(array_values(array_unique($urlFinder->get())))); 145 | return Cli::RETURN_SUCCESS; 146 | } catch (\Exception $e) { 147 | $output->writeln($e->getMessage()); 148 | return Cli::RETURN_FAILURE; 149 | } 150 | } 151 | 152 | /** 153 | * @param InputInterface $input 154 | * @return StoreInterface[] 155 | * @throws NoSuchEntityException 156 | */ 157 | private function getStores(InputInterface $input): array 158 | { 159 | $storeIds = $input->getOption(self::INPUT_OPTION_STORE_ID); 160 | 161 | if (!empty($storeIds)) { 162 | $stores = []; 163 | foreach ($storeIds as $storeId) { 164 | $stores[] = $this->storeManager->getStore($storeId); 165 | } 166 | } else { 167 | $stores = $this->storeManager->getStores(); 168 | } 169 | 170 | return $stores; 171 | } 172 | 173 | /** 174 | * Sets area code. 175 | */ 176 | private function setArea() 177 | { 178 | try { 179 | $this->state->setAreaCode(Area::AREA_GLOBAL); 180 | } catch (LocalizedException $e) { 181 | } 182 | } 183 | } 184 | -------------------------------------------------------------------------------- /Test/Unit/Model/UrlFinder/EntityTest.php: -------------------------------------------------------------------------------- 1 | urlFactoryMock = $this->createMock(UrlFactory::class); 46 | $this->urlFinderMock = $this->createMock(UrlFinderInterface::class); 47 | $this->urlFixerMock = $this->createMock(UrlFixer::class); 48 | } 49 | 50 | public function testGetEmptyStores() 51 | { 52 | $this->urlFactoryMock->expects($this->never()) 53 | ->method('create'); 54 | 55 | $entity = $this->createEntity('category', []); 56 | 57 | $this->assertEquals([], $entity->get()); 58 | } 59 | 60 | public function testGet() 61 | { 62 | $storeMock1 = $this->createMock(Store::class); 63 | $storeMock2 = $this->createMock(Store::class); 64 | 65 | $urlMock1 = $this->createMock(UrlInterface::class); 66 | $urlMock2 = $this->createMock(UrlInterface::class); 67 | 68 | $urlRewriteMock1 = $this->createMock(UrlRewrite::class); 69 | $urlRewriteMock2 = $this->createMock(UrlRewrite::class); 70 | 71 | $this->setupUrlMocks($urlMock1, '/path1', 'http://site1.com/path1', 'store1'); 72 | $this->setupUrlMocks($urlMock2, '/path2', 'http://site2.com/path2', 'store2'); 73 | 74 | $this->setupStoreMocks($storeMock1, 'store1', 2); 75 | $this->setupStoreMocks($storeMock2, 'store2', 2); 76 | 77 | $this->setupUrlRewriteMocks($urlRewriteMock1, '/path1'); 78 | $this->setupUrlRewriteMocks($urlRewriteMock2, '/path2'); 79 | 80 | $this->setupUrlFactoryMock($urlMock1, $urlMock2); 81 | $this->urlFinderMock->expects($this->exactly(2)) 82 | ->method('findAllByData') 83 | ->willReturnCallback(function ($data) use ($urlRewriteMock1, $urlRewriteMock2) { 84 | $expected1 = ['store_id' => 'store1', 'entity_type' => 'category']; 85 | $expected2 = ['store_id' => 'store2', 'entity_type' => 'category']; 86 | 87 | if (array_intersect_assoc($expected1, $data) == $expected1) { 88 | return [$urlRewriteMock1]; 89 | } 90 | 91 | if (array_intersect_assoc($expected2, $data) == $expected2) { 92 | return [$urlRewriteMock2]; 93 | } 94 | 95 | return []; 96 | }); 97 | 98 | $this->urlFixerMock->expects($this->exactly(2)) 99 | ->method('run') 100 | ->willReturnCallback(function ($store, $url) use ($storeMock1, $storeMock2) { 101 | static $callCount = 0; 102 | $callCount++; 103 | 104 | if ($callCount === 1 && $store === $storeMock1 && $url === '/path1') { 105 | return 'http://site1.com/fixed/path1'; 106 | } 107 | 108 | if ($callCount === 2 && $store === $storeMock2 && $url === '/path2') { 109 | return 'http://site2.com/fixed/path2'; 110 | } 111 | 112 | return ''; 113 | }); 114 | 115 | $entity = $this->createEntity('category', [$storeMock1, $storeMock2]); 116 | $this->assertEquals( 117 | [ 118 | 'http://site1.com/fixed/path1', 119 | 'http://site2.com/fixed/path2', 120 | ], 121 | $entity->get() 122 | ); 123 | } 124 | 125 | private function setupStoreMocks($storeMock, $storeId, $times) 126 | { 127 | $storeMock->expects($this->exactly($times)) 128 | ->method('getId') 129 | ->willReturn($storeId); 130 | } 131 | 132 | private function setupUrlMocks($urlMock, $requestPath, $returnUrl, $storeId) 133 | { 134 | $urlMock->expects($this->any()) 135 | ->method('setScope') 136 | ->with($storeId) 137 | ->willReturnSelf(); 138 | $urlMock->expects($this->any()) 139 | ->method('getUrl') 140 | ->with($requestPath) 141 | ->willReturn($returnUrl); 142 | } 143 | 144 | private function setupUrlRewriteMocks($urlRewriteMock, $requestPath) 145 | { 146 | $urlRewriteMock->expects($this->once()) 147 | ->method('getRequestPath') 148 | ->willReturn($requestPath); 149 | } 150 | 151 | private function setupUrlFactoryMock($urlMock1, $urlMock2) 152 | { 153 | $this->urlFactoryMock->expects($this->exactly(2)) 154 | ->method('create') 155 | ->willReturnCallback(function () use ($urlMock1, $urlMock2) { 156 | static $callCount = 0; 157 | $callCount++; 158 | 159 | return $callCount === 1 ? $urlMock1 : $urlMock2; 160 | }); 161 | } 162 | 163 | /** 164 | * @param string $entityType 165 | * @param array $stores 166 | * @return Entity 167 | */ 168 | private function createEntity(string $entityType, array $stores): Entity 169 | { 170 | return new Entity( 171 | $this->urlFactoryMock, 172 | $this->urlFinderMock, 173 | $this->urlFixerMock, 174 | $entityType, 175 | $stores 176 | ); 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /LICENSE_OSL.txt: -------------------------------------------------------------------------------- 1 | Open Software License v. 3.0 (OSL-3.0) 2 | 3 | This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: 4 | 5 | Licensed under the Open Software License version 3.0 6 | 7 | 1) Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: 8 | 9 | a) to reproduce the Original Work in copies, either alone or as part of a collective work; 10 | 11 | b) to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; 12 | 13 | c) to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License; 14 | 15 | d) to perform the Original Work publicly; and 16 | 17 | e) to display the Original Work publicly. 18 | 19 | 2) Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. 20 | 21 | 3) Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. 22 | 23 | 4) Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. 24 | 25 | 5) External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). 26 | 27 | 6) Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. 28 | 29 | 7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. 30 | 31 | 8) Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. 32 | 33 | 9) Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). 34 | 35 | 10) Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. 36 | 37 | 11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. 38 | 39 | 12) Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. 40 | 41 | 13) Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. 42 | 43 | 14) Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 44 | 45 | 15) Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. 46 | 47 | 16) Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. 48 | --------------------------------------------------------------------------------