├── .gitignore ├── LICENSE-ENTERPRISE ├── .github ├── ISSUE_TEMPLATE │ └── bug_report.md └── FUNDING.yml ├── src ├── LaravelLogger.php ├── LaravelConfigurationVariableService.php ├── EloquentRepository.php ├── Config │ ├── PDO │ │ ├── MySqlDriver.php │ │ ├── SQLiteDriver.php │ │ ├── PostgresDriver.php │ │ ├── SqlServerDriver.php │ │ ├── Concerns │ │ │ └── ConnectsToDatabase.php │ │ ├── SqlServerConnection.php │ │ └── Connection.php │ ├── LaravelTenantDatabaseSwitcher.php │ ├── LaravelConnectionReference.php │ ├── LaravelConnectionResolver.php │ └── LaravelConnectionModule.php ├── EloquentRepositoryBuilder.php ├── EcotoneCacheClear.php ├── Queue │ ├── LaravelQueueAcknowledgementCallback.php │ ├── LaravelQueueMessageChannelBuilder.php │ └── LaravelQueueMessageChannel.php └── EcotoneProvider.php ├── behat.yml ├── LICENSE ├── README.md ├── composer.json └── config ├── logging.php └── ecotone.php /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | vendor/ 3 | bin/ 4 | tests/coverage 5 | !tests/coverage/.gitkeep 6 | .phpunit.result.cache 7 | composer.lock 8 | phpunit.xml 9 | tests/Application/storage/logs/laravel.log -------------------------------------------------------------------------------- /LICENSE-ENTERPRISE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2025 Dariusz Gafka 2 | 3 | Licence is available at [ecotone.tech/documents/ecotone_enterprise_licence.pdf](https://ecotone.tech/documents/ecotone_enterprise_licence.pdf) -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: This is Read-Only repository 3 | about: Report at ecotoneframework/ecotone-dev 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | Report issue at [ecotone-dev](ecotoneframework/ecotone-dev) -------------------------------------------------------------------------------- /src/LaravelLogger.php: -------------------------------------------------------------------------------- 1 | save(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Config/PDO/MySqlDriver.php: -------------------------------------------------------------------------------- 1 | eloquentRepository = new EloquentRepository(); 20 | } 21 | 22 | public function canHandle(string $aggregateClassName): bool 23 | { 24 | return $this->eloquentRepository->canHandle($aggregateClassName); 25 | } 26 | 27 | public function compile(MessagingContainerBuilder $builder): Definition|Reference 28 | { 29 | return new Definition(EloquentRepository::class); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Config/PDO/SqlServerDriver.php: -------------------------------------------------------------------------------- 1 | getLaravelConnectionName()); 30 | } 31 | } 32 | 33 | public function switchOff(): void 34 | { 35 | Config::set('database.default', $this->defaultConnectionName); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2025 Dariusz Gafka 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 10 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 11 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 12 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 13 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 14 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 15 | THE SOFTWARE. 16 | 17 | **Scope of the License** 18 | 19 | Apache-2.0 Licence applies to non Enterprise Functionalities of the Ecotone Framework. 20 | Functionalities of the Ecotone Framework referred to as Enterprise functionalities, are not covered under the Apache-2.0 license. These functionalities are provided under a separate Enterprise License. 21 | For details on the Enterprise License, please refer to the [LICENSE-ENTERPRISE](./LICENSE-ENTERPRISE) file. -------------------------------------------------------------------------------- /src/EcotoneCacheClear.php: -------------------------------------------------------------------------------- 1 | laravelConnectionName); 22 | } 23 | 24 | public static function create(string $connectionName, ?string $referenceName = null): self 25 | { 26 | return new self($connectionName, $referenceName ?? 'ecotone.laravel.connection.' . $connectionName); 27 | } 28 | 29 | public static function defaultConnection(string $connectionName): self 30 | { 31 | return new self($connectionName, DbalConnectionFactory::class); 32 | } 33 | 34 | public function getLaravelConnectionName(): string 35 | { 36 | return $this->laravelConnectionName; 37 | } 38 | 39 | public function getDefinition(): Definition 40 | { 41 | return new Definition( 42 | LaravelConnectionReference::class, 43 | [ 44 | $this->laravelConnectionName, 45 | $this->getReferenceName(), 46 | ], 47 | [ 48 | self::class, 49 | 'create', 50 | ] 51 | ); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Config/LaravelConnectionResolver.php: -------------------------------------------------------------------------------- 1 | getLaravelConnectionName()); 26 | if (method_exists($connection, 'getDoctrineConnection')) { 27 | $doctrineConnection = $connection->getDoctrineConnection(); 28 | } else { 29 | $driver = self::createDriver($connection->getDriverName()); 30 | 31 | $doctrineConnection = new Connection(array_filter([ 32 | 'pdo' => $connection->getPdo(), 33 | 'dbname' => $connection->getDatabaseName(), 34 | 'driver' => $driver->getName(), 35 | 'serverVersion' => $connection->getConfig('server_version'), 36 | ]), $driver); 37 | } 38 | 39 | return DbalConnection::create($doctrineConnection); 40 | } 41 | 42 | private static function createDriver($driverName): Driver 43 | { 44 | $className = match ($driverName) { 45 | 'pgsql' => 'PostgresDriver', 46 | 'mysql' => 'MySqlDriver', 47 | 'sqlite' => 'SqliteDriver', 48 | 'sqlsrv' => 'SqlServerDriver', 49 | }; 50 | $className = '\Ecotone\Laravel\Config\PDO\\' . $className; 51 | 52 | return new $className(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/Queue/LaravelQueueAcknowledgementCallback.php: -------------------------------------------------------------------------------- 1 | failureStrategy; 45 | } 46 | 47 | /** 48 | * @inheritDoc 49 | */ 50 | public function isAutoAcked(): bool 51 | { 52 | return $this->isAutoAcked; 53 | } 54 | 55 | /** 56 | * @inheritDoc 57 | */ 58 | public function accept(): void 59 | { 60 | $this->job->delete(); 61 | } 62 | 63 | /** 64 | * @inheritDoc 65 | */ 66 | public function reject(): void 67 | { 68 | $this->job->delete(); 69 | } 70 | 71 | /** 72 | * @inheritDoc 73 | */ 74 | public function resend(): void 75 | { 76 | $this->job->release(); 77 | } 78 | 79 | /** 80 | * @inheritDoc 81 | */ 82 | public function release(): void 83 | { 84 | $this->job->release(); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # This is Read Only Repository 2 | To contribute make use of [Ecotone-Dev repository](https://github.com/ecotoneframework/ecotone-dev). 3 | 4 |

5 | 6 |

7 | 8 | ![Github Actions](https://github.com/ecotoneFramework/ecotone-dev/actions/workflows/split-testing.yml/badge.svg) 9 | [![Latest Stable Version](https://poser.pugx.org/ecotone/ecotone/v/stable)](https://packagist.org/packages/ecotone/ecotone) 10 | [![License](https://poser.pugx.org/ecotone/ecotone/license)](https://packagist.org/packages/ecotone/ecotone) 11 | [![Total Downloads](https://img.shields.io/packagist/dt/ecotone/ecotone)](https://packagist.org/packages/ecotone/ecotone) 12 | [![PHP Version Require](https://img.shields.io/packagist/dependency-v/ecotone/ecotone/php.svg)](https://packagist.org/packages/ecotone/ecotone) 13 | 14 | The roots of Object Oriented Programming (OOP) were mainly about communication using Messages and logic encapsulation. 15 | `Ecotone` aims to return to the origins of OOP, by providing tools which allows us to fully move the focus from Objects to Flows, from Data storage to Application Design, from Technicalities to Business logic. 16 | Ecotone does that by making Messages first class-citizen in our Applications. 17 | 18 | Thanks to being Message-Driven at the foundation level, Ecotone provides architecture which is resilient and scalable by default, making it possible for Developers to focus on business problems instead of technical concerns. 19 | Together with declarative configuration and higher level building blocks, it makes the system design explicit, easy to follow and change no matter of Developers experience. 20 | 21 | Visit main page [ecotone.tech](https://ecotone.tech) to learn more. 22 | 23 | > Ecotone can be used with [Symfony](https://docs.ecotone.tech/modules/symfony-ddd-cqrs-event-sourcing) and [Laravel](https://docs.ecotone.tech/modules/laravel-ddd-cqrs-event-sourcing) frameworks, or any other framework using [Ecotone Lite](https://docs.ecotone.tech/install-php-service-bus#install-ecotone-lite-no-framework). 24 | 25 | ## Getting started 26 | 27 | The quickstart [page](https://docs.ecotone.tech/quick-start) of the 28 | [reference guide](https://docs.ecotone.tech) provides a starting point for using Ecotone. 29 | Read more on the [Ecotone's Blog](https://blog.ecotone.tech). 30 | 31 | ## Feature requests and issue reporting 32 | 33 | Use [issue tracking system](https://github.com/ecotoneframework/ecotone-dev/issues) for new feature request and bugs. 34 | Please verify that it's not already reported by someone else. 35 | 36 | ## Contact 37 | 38 | If you want to talk or ask questions about Ecotone 39 | 40 | - [**Twitter**](https://twitter.com/EcotonePHP) 41 | - **support@simplycodedsoftware.com** 42 | - [**Community Channel**](https://discord.gg/GwM2BSuXeg) 43 | 44 | ## Support Ecotone 45 | 46 | If you want to help building and improving Ecotone consider becoming a sponsor: 47 | 48 | - [Sponsor Ecotone](https://github.com/sponsors/dgafka) 49 | - [Contribute to Ecotone](https://github.com/ecotoneframework/ecotone-dev). 50 | 51 | ## Tags 52 | 53 | PHP, DDD, CQRS, Event Sourcing, Symfony, Laravel, Service Bus, Event Driven Architecture, SOA, Events, Commands 54 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ecotone/laravel", 3 | "minimum-stability": "dev", 4 | "homepage": "https://docs.ecotone.tech/", 5 | "forum": "https://discord.gg/GwM2BSuXeg", 6 | "prefer-stable": true, 7 | "license": [ 8 | "Apache-2.0", 9 | "proprietary" 10 | ], 11 | "type": "library", 12 | "authors": [ 13 | { 14 | "name": "Dariusz Gafka", 15 | "email": "support@simplycodedsoftware.com" 16 | } 17 | ], 18 | "keywords": [ 19 | "ddd", 20 | "cqrs", 21 | "messaging", 22 | "eip", 23 | "distributed architecture", 24 | "ecotone", 25 | "ddd and cqrs on top of eip" 26 | ], 27 | "description": "Laravel integration for Ecotone", 28 | "autoload": { 29 | "psr-4": { 30 | "Ecotone\\Laravel\\": "src" 31 | } 32 | }, 33 | "autoload-dev": { 34 | "psr-4": { 35 | "Test\\Ecotone\\Laravel\\": "tests", 36 | "App\\MultiTenant\\": "tests/MultiTenant/app", 37 | "App\\Licence\\Laravel\\": "tests/Licence/app" 38 | } 39 | }, 40 | "require": { 41 | "ecotone/ecotone": "~1.283.0", 42 | "laravel/framework": "^9.5.2|^10.0|^11.0|^12.0|^13.0" 43 | }, 44 | "require-dev": { 45 | "phpunit/phpunit": "^10.5|^11.0", 46 | "behat/behat": "^3.10", 47 | "guzzlehttp/psr7": "^2.0", 48 | "phpstan/phpstan": "^1.8", 49 | "orchestra/testbench": "^8.0|^9.0|^10.0|^11.0", 50 | "wikimedia/composer-merge-plugin": "^2.1", 51 | "symfony/expression-language": "^6.4|^7.0|^8.0", 52 | "nesbot/carbon": "^2.71|^3.0", 53 | "moneyphp/money": "^4.1.0", 54 | "ecotone/dbal": "~1.283.0", 55 | "timacdonald/log-fake": "^2.0" 56 | }, 57 | "extra": { 58 | "laravel": { 59 | "providers": [ 60 | "Ecotone\\Laravel\\EcotoneProvider" 61 | ] 62 | }, 63 | "branch-alias": { 64 | "dev-main": "1.283.0-dev" 65 | }, 66 | "ecotone": { 67 | "repository": "laravel" 68 | }, 69 | "merge-plugin": { 70 | "include": [ 71 | "../local_packages.json" 72 | ] 73 | }, 74 | "license-info": { 75 | "Apache-2.0": { 76 | "name": "Apache License 2.0", 77 | "url": "https://github.com/ecotoneframework/ecotone-dev/blob/main/LICENSE", 78 | "description": "Allows to use non Enterprise features of Ecotone. For more information please write to support@simplycodedsoftware.com" 79 | }, 80 | "proprietary": { 81 | "name": "Enterprise License", 82 | "description": "Allows to use Enterprise features of Ecotone. For more information please write to support@simplycodedsoftware.com" 83 | } 84 | }, 85 | "release-time": "2025-12-20 16:06:24" 86 | }, 87 | "scripts": { 88 | "tests:phpstan": "vendor/bin/phpstan", 89 | "tests:phpunit": [ 90 | "vendor/bin/phpunit --no-coverage" 91 | ], 92 | "tests:ci": [ 93 | "@tests:phpstan", 94 | "@tests:phpunit" 95 | ] 96 | }, 97 | "config": { 98 | "allow-plugins": { 99 | "wikimedia/composer-merge-plugin": true 100 | } 101 | } 102 | } -------------------------------------------------------------------------------- /src/Queue/LaravelQueueMessageChannelBuilder.php: -------------------------------------------------------------------------------- 1 | withHeaderMapping('*'); 35 | } 36 | 37 | public static function create( 38 | string $queueName, 39 | ?string $connectionName = null, 40 | ): self { 41 | return new self( 42 | $connectionName ?? Config::get('queue.default'), 43 | $queueName 44 | ); 45 | } 46 | 47 | public function getMessageChannelName(): string 48 | { 49 | return $this->queueName; 50 | } 51 | 52 | public function isPollable(): bool 53 | { 54 | return true; 55 | } 56 | 57 | /** 58 | * @param string $headerMapper 59 | * @return static 60 | */ 61 | public function withHeaderMapping(string $headerMapper): self 62 | { 63 | $headerMapper = explode(',', $headerMapper); 64 | $this->headerMapper = DefaultHeaderMapper::createWith($headerMapper, $headerMapper); 65 | 66 | return $this; 67 | } 68 | 69 | public function withDefaultOutboundConversionMediaType(MediaType $mediaType): self 70 | { 71 | $this->defaultOutboundConversionMediaType = $mediaType; 72 | 73 | return $this; 74 | } 75 | 76 | public function withFinalFailureStrategy(FinalFailureStrategy $finalFailureStrategy): self 77 | { 78 | Assert::isTrue($finalFailureStrategy !== FinalFailureStrategy::RELEASE, 'Laravel Queue does not support message release', true); 79 | 80 | $this->finalFailureStrategy = $finalFailureStrategy; 81 | 82 | return $this; 83 | } 84 | 85 | public function getConversionMediaType(): ?MediaType 86 | { 87 | return $this->defaultOutboundConversionMediaType; 88 | } 89 | 90 | public function getHeaderMapper(): HeaderMapper 91 | { 92 | return $this->headerMapper; 93 | } 94 | 95 | public function isStreamingChannel(): bool 96 | { 97 | return false; 98 | } 99 | 100 | public function compile(MessagingContainerBuilder $builder): Definition 101 | { 102 | return new Definition( 103 | LaravelQueueMessageChannel::class, 104 | [ 105 | new Reference('queue'), 106 | $this->connectionName, 107 | $this->queueName, 108 | $this->acknowledgeMode, 109 | new Definition(OutboundMessageConverter::class, [ 110 | $this->headerMapper->getDefinition(), 111 | $this->defaultOutboundConversionMediaType?->getDefinition(), 112 | ]), 113 | new Reference(ConversionService::REFERENCE_NAME), 114 | $this->finalFailureStrategy, 115 | ] 116 | ); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /config/logging.php: -------------------------------------------------------------------------------- 1 | env('LOG_CHANNEL', 'stack'), 21 | 22 | /* 23 | |-------------------------------------------------------------------------- 24 | | Deprecations Log Channel 25 | |-------------------------------------------------------------------------- 26 | | 27 | | This option controls the log channel that should be used to log warnings 28 | | regarding deprecated PHP and library features. This allows you to get 29 | | your application ready for upcoming major versions of dependencies. 30 | | 31 | */ 32 | 33 | 'deprecations' => env('LOG_DEPRECATIONS_CHANNEL', 'null'), 34 | 35 | /* 36 | |-------------------------------------------------------------------------- 37 | | Log Channels 38 | |-------------------------------------------------------------------------- 39 | | 40 | | Here you may configure the log channels for your application. Out of 41 | | the box, Laravel uses the Monolog PHP logging library. This gives 42 | | you a variety of powerful log handlers / formatters to utilize. 43 | | 44 | | Available Drivers: "single", "daily", "slack", "syslog", 45 | | "errorlog", "monolog", 46 | | "custom", "stack" 47 | | 48 | */ 49 | 50 | 'channels' => [ 51 | 'stack' => [ 52 | 'driver' => 'stack', 53 | 'channels' => ['single'], 54 | 'ignore_exceptions' => false, 55 | ], 56 | 57 | 'single' => [ 58 | 'driver' => 'single', 59 | 'path' => storage_path('logs/laravel.log'), 60 | 'level' => env('LOG_LEVEL', 'debug'), 61 | ], 62 | 63 | 'daily' => [ 64 | 'driver' => 'daily', 65 | 'path' => storage_path('logs/laravel.log'), 66 | 'level' => env('LOG_LEVEL', 'debug'), 67 | 'days' => 14, 68 | ], 69 | 70 | 'slack' => [ 71 | 'driver' => 'slack', 72 | 'url' => env('LOG_SLACK_WEBHOOK_URL'), 73 | 'username' => 'Laravel Log', 74 | 'emoji' => ':boom:', 75 | 'level' => env('LOG_LEVEL', 'critical'), 76 | ], 77 | 78 | 'papertrail' => [ 79 | 'driver' => 'monolog', 80 | 'level' => env('LOG_LEVEL', 'debug'), 81 | 'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class), 82 | 'handler_with' => [ 83 | 'host' => env('PAPERTRAIL_URL'), 84 | 'port' => env('PAPERTRAIL_PORT'), 85 | 'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'), 86 | ], 87 | ], 88 | 89 | 'stderr' => [ 90 | 'driver' => 'monolog', 91 | 'level' => env('LOG_LEVEL', 'debug'), 92 | 'handler' => StreamHandler::class, 93 | 'formatter' => env('LOG_STDERR_FORMATTER'), 94 | 'with' => [ 95 | 'stream' => 'php://stderr', 96 | ], 97 | ], 98 | 99 | 'syslog' => [ 100 | 'driver' => 'syslog', 101 | 'level' => env('LOG_LEVEL', 'debug'), 102 | ], 103 | 104 | 'errorlog' => [ 105 | 'driver' => 'errorlog', 106 | 'level' => env('LOG_LEVEL', 'debug'), 107 | ], 108 | 109 | 'null' => [ 110 | 'driver' => 'monolog', 111 | 'handler' => NullHandler::class, 112 | ], 113 | 114 | 'emergency' => [ 115 | 'path' => storage_path('logs/laravel.log'), 116 | ], 117 | ], 118 | 119 | ]; 120 | -------------------------------------------------------------------------------- /src/Config/LaravelConnectionModule.php: -------------------------------------------------------------------------------- 1 | getTenantToConnectionMapping() as $connectionReference) { 45 | if ($connectionReference instanceof LaravelConnectionReference) { 46 | $laravelConnections[] = $connectionReference; 47 | $laravelRelatedMultiTenantConfigurations[$multiTenantConfiguration->getReferenceName()] = $multiTenantConfiguration; 48 | } 49 | } 50 | } 51 | 52 | $laravelConnections = array_unique($laravelConnections); 53 | foreach ($laravelConnections as $connection) { 54 | $messagingConfiguration->registerServiceDefinition( 55 | $connection->getReferenceName(), 56 | new Definition( 57 | ConnectionFactory::class, 58 | [ 59 | $connection, 60 | ], 61 | [ 62 | LaravelConnectionResolver::class, 63 | 'resolveLaravelConnection', 64 | ] 65 | ) 66 | ); 67 | } 68 | 69 | $messagingConfiguration->registerServiceDefinition( 70 | LaravelTenantDatabaseSwitcher::class, 71 | new Definition( 72 | LaravelTenantDatabaseSwitcher::class, 73 | [], 74 | [ 75 | LaravelTenantDatabaseSwitcher::class, 76 | 'create', 77 | ] 78 | ) 79 | ); 80 | $messagingConfiguration->registerMessageHandler( 81 | ServiceActivatorBuilder::create(LaravelTenantDatabaseSwitcher::class, 'switchOn') 82 | ->withInputChannelName(HeaderBasedMultiTenantConnectionFactory::TENANT_ACTIVATED_CHANNEL_NAME) 83 | ); 84 | $messagingConfiguration->registerMessageHandler( 85 | ServiceActivatorBuilder::create(LaravelTenantDatabaseSwitcher::class, 'switchOff') 86 | ->withInputChannelName(HeaderBasedMultiTenantConnectionFactory::TENANT_DEACTIVATED_CHANNEL_NAME) 87 | ); 88 | } 89 | 90 | public function canHandle($extensionObject): bool 91 | { 92 | return $extensionObject instanceof LaravelConnectionReference || $extensionObject instanceof MultiTenantConfiguration; 93 | } 94 | 95 | public function getModulePackageName(): string 96 | { 97 | return ModulePackageList::LARAVEL_PACKAGE; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/Config/PDO/SqlServerConnection.php: -------------------------------------------------------------------------------- 1 | connection = $connection; 49 | } 50 | 51 | /** 52 | * Prepare a new SQL statement. 53 | * 54 | * @param string $sql 55 | * @return StatementInterface 56 | */ 57 | public function prepare(string $sql): StatementInterface 58 | { 59 | return new Statement( 60 | $this->connection->prepare($sql) 61 | ); 62 | } 63 | 64 | /** 65 | * Execute a new query against the connection. 66 | * 67 | * @param string $sql 68 | * @return Result 69 | */ 70 | public function query(string $sql): Result 71 | { 72 | return $this->connection->query($sql); 73 | } 74 | 75 | /** 76 | * Execute an SQL statement. 77 | * 78 | * @param string $statement 79 | * @return int 80 | */ 81 | public function exec(string $statement): int 82 | { 83 | return $this->connection->exec($statement); 84 | } 85 | 86 | /** 87 | * Get the last insert ID. 88 | * 89 | * @param string|null $name 90 | * @return mixed 91 | */ 92 | public function lastInsertId($name = null) 93 | { 94 | if ($name === null) { 95 | return $this->connection->lastInsertId($name); 96 | } 97 | 98 | return $this->prepare('SELECT CONVERT(VARCHAR(MAX), current_value) FROM sys.sequences WHERE name = ?') 99 | ->execute([$name]) 100 | ->fetchOne(); 101 | } 102 | 103 | /** 104 | * Begin a new database transaction. 105 | * 106 | * @return bool 107 | */ 108 | public function beginTransaction() 109 | { 110 | return $this->connection->beginTransaction(); 111 | } 112 | 113 | /** 114 | * Commit a database transaction. 115 | * 116 | * @return bool 117 | */ 118 | public function commit() 119 | { 120 | return $this->connection->commit(); 121 | } 122 | 123 | /** 124 | * Rollback a database transaction. 125 | * 126 | * @return bool 127 | */ 128 | public function rollBack() 129 | { 130 | return $this->connection->rollBack(); 131 | } 132 | 133 | /** 134 | * Wrap quotes around the given input. 135 | * 136 | * @param string $value 137 | * @param int $type 138 | * @return string 139 | */ 140 | public function quote($value, $type = ParameterType::STRING) 141 | { 142 | $val = $this->connection->quote($value, $type); 143 | 144 | // Fix for a driver version terminating all values with null byte... 145 | if (is_string($val) && str_contains($val, "\0")) { 146 | $val = substr($val, 0, -1); 147 | } 148 | 149 | return $val; 150 | } 151 | 152 | /** 153 | * Get the server version for the connection. 154 | * 155 | * @return string 156 | */ 157 | public function getServerVersion() 158 | { 159 | return $this->connection->getServerVersion(); 160 | } 161 | 162 | /** 163 | * Get the wrapped PDO connection. 164 | * 165 | * @return PDO 166 | */ 167 | public function getWrappedConnection(): PDO 168 | { 169 | return $this->connection->getWrappedConnection(); 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /config/ecotone.php: -------------------------------------------------------------------------------- 1 | env('ECOTONE_SERVICE_NAME'), 15 | 16 | /* 17 | |-------------------------------------------------------------------------- 18 | | Load Namespaces 19 | |-------------------------------------------------------------------------- 20 | | 21 | | Whether or not Ecotone should automatically load all namespaces. 22 | | 23 | */ 24 | 'loadAppNamespaces' => true, 25 | 26 | /* 27 | |-------------------------------------------------------------------------- 28 | | Namespaces 29 | |-------------------------------------------------------------------------- 30 | | 31 | | A list of namespaces that Ecotone should look in for configurations, 32 | | command handlers, aggregates, projections, etc. 33 | | 34 | */ 35 | 'namespaces' => [], 36 | 37 | /* 38 | |-------------------------------------------------------------------------- 39 | | Cache Configuration 40 | |-------------------------------------------------------------------------- 41 | | 42 | | Determines whether or not Ecotone should cache the configuration. 43 | | 44 | | If true, then Ecotone will cache all configurations. This will decrease 45 | | application load time, but results in slower feedback for the developer 46 | | as the cache will need to be cleared after changes are made. This is 47 | | best suited for production. 48 | | 49 | | If false, then Ecotone will not cache any configurations. This will 50 | | increase application load time, but results in quicker feedback for the 51 | | developer. This is best suited for local development. 52 | | 53 | */ 54 | 'cacheConfiguration' => env('ECOTONE_CACHE', false), 55 | 56 | /* 57 | |-------------------------------------------------------------------------- 58 | | Default Serialization Media Type 59 | |-------------------------------------------------------------------------- 60 | | 61 | | Describes the default serialization type within the application. If not 62 | | configured, the default serialization will be application/x-php-serialized, 63 | | which is a serialized PHP class. 64 | | 65 | */ 66 | 'defaultSerializationMediaType' => env('ECOTONE_DEFAULT_SERIALIZATION_TYPE'), 67 | 68 | /* 69 | |-------------------------------------------------------------------------- 70 | | Default Error Channel 71 | |-------------------------------------------------------------------------- 72 | | 73 | | Provides the default Poller configuration with an error channel for all 74 | | asynchronous consumers. 75 | | 76 | */ 77 | 'defaultErrorChannel' => env('ECOTONE_DEFAULT_ERROR_CHANNEL'), 78 | 79 | /* 80 | |-------------------------------------------------------------------------- 81 | | Default Connection Exception Retry 82 | |-------------------------------------------------------------------------- 83 | | 84 | | Provides the default connection retry strategy for asynchronous 85 | | consumers in case of connection failure. 86 | | 87 | | initialDelay - delay after first retry in milliseconds 88 | | multiplier - how much initialDelay should be multiplied with each try 89 | | maxAttempts - how many attempts should be made before closing the endpoint 90 | | 91 | */ 92 | 'defaultConnectionExceptionRetry' => null, 93 | 94 | /* 95 | |-------------------------------------------------------------------------- 96 | | Namespaces 97 | |-------------------------------------------------------------------------- 98 | | 99 | | A list of namespaces that Ecotone should look in for configurations, 100 | | command handlers, aggregates, projections, etc. 101 | | 102 | */ 103 | 'skippedModulePackageNames' => [], 104 | 105 | /* 106 | |-------------------------------------------------------------------------- 107 | | test 108 | |-------------------------------------------------------------------------- 109 | | 110 | | Whether ecotone test module should be loaded 111 | | 112 | */ 113 | 'test' => false, 114 | 115 | /* 116 | |-------------------------------------------------------------------------- 117 | | licenceKey 118 | |-------------------------------------------------------------------------- 119 | | 120 | | Licence key to use Ecotone Enterprise features 121 | | 122 | */ 123 | 'licenceKey' => null, 124 | ]; 125 | -------------------------------------------------------------------------------- /src/Queue/LaravelQueueMessageChannel.php: -------------------------------------------------------------------------------- 1 | getConnection(); 49 | 50 | $outboundMessage = $this->outboundMessageConverter->prepare($message, $this->conversionService); 51 | $jobName = $this->prepareJobName($message); 52 | $jobPayload = $this->prepareJobPayload($outboundMessage); 53 | 54 | if ($outboundMessage->getDeliveryDelay()) { 55 | $connection->laterOn( 56 | $this->queueName, 57 | ceil($outboundMessage->getDeliveryDelay() / 1000), 58 | $jobName, 59 | $jobPayload 60 | ); 61 | 62 | return; 63 | } 64 | 65 | Assert::isTrue(! $connection instanceof SyncQueue, 'Sync mode is not supported for Laravel Queue Message Channel.'); 66 | $connection->pushOn( 67 | $this->queueName, 68 | $jobName, 69 | $jobPayload 70 | ); 71 | } 72 | 73 | public function receive(): ?Message 74 | { 75 | $connection = $this->getConnection(); 76 | 77 | $job = $connection->pop($this->queueName); 78 | 79 | if (! $job) { 80 | return null; 81 | } 82 | 83 | $message = json_decode($job->getRawBody(), true, 512, JSON_THROW_ON_ERROR); 84 | $message = json_decode($message['data'], true, 512, JSON_THROW_ON_ERROR); 85 | $messageBuilder = MessageBuilder::withPayload($message[self::PAYLOAD]) 86 | ->setMultipleHeaders($message[self::HEADERS]); 87 | 88 | $messageBuilder = $messageBuilder 89 | ->setHeader( 90 | MessageHeaders::CONSUMER_ACK_HEADER_LOCATION, 91 | self::ECOTONE_LARAVEL_ACKNOWLEDGE_HEADER 92 | ) 93 | ->setHeader( 94 | self::ECOTONE_LARAVEL_ACKNOWLEDGE_HEADER, 95 | LaravelQueueAcknowledgementCallback::create($job, $this->finalFailureStrategy, $this->acknowledgeMode === LaravelQueueAcknowledgementCallback::AUTO_ACK) 96 | ); 97 | 98 | return $messageBuilder 99 | ->build(); 100 | } 101 | 102 | public function receiveWithTimeout(PollingMetadata $pollingMetadata): ?Message 103 | { 104 | return $this->receive(); 105 | } 106 | 107 | public function onConsumerStop(): void 108 | { 109 | // No cleanup needed for Laravel queue channels 110 | } 111 | 112 | private function getConnection(): Queue 113 | { 114 | return $this->queueFactory->connection($this->connectionName); 115 | } 116 | 117 | private function prepareJobPayload(OutboundMessage $outboundMessage): string|false 118 | { 119 | return json_encode([ 120 | self::PAYLOAD => $outboundMessage->getPayload(), 121 | self::HEADERS => array_merge( 122 | $outboundMessage->getHeaders(), 123 | [MessageHeaders::CONTENT_TYPE => $outboundMessage->getContentType()] 124 | ), 125 | ], JSON_THROW_ON_ERROR); 126 | } 127 | 128 | private function prepareJobName(Message $message): mixed 129 | { 130 | return $message->getHeaders()->containsKey(MessageHeaders::ROUTING_SLIP) 131 | ? $message->getHeaders()->get(MessageHeaders::ROUTING_SLIP) 132 | : 'ecotone'; 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /src/Config/PDO/Connection.php: -------------------------------------------------------------------------------- 1 | connection = $connection; 51 | } 52 | 53 | /** 54 | * Execute an SQL statement. 55 | * 56 | * @param string $statement 57 | * @return int 58 | */ 59 | public function exec(string $statement): int 60 | { 61 | try { 62 | $result = $this->connection->exec($statement); 63 | 64 | assert($result !== false); 65 | 66 | return $result; 67 | } catch (PDOException $exception) { 68 | throw Exception::new($exception); 69 | } 70 | } 71 | 72 | /** 73 | * Prepare a new SQL statement. 74 | * 75 | * @param string $sql 76 | * @return StatementInterface 77 | * 78 | * @throws Exception 79 | */ 80 | public function prepare(string $sql): StatementInterface 81 | { 82 | try { 83 | return $this->createStatement( 84 | $this->connection->prepare($sql) 85 | ); 86 | } catch (PDOException $exception) { 87 | throw Exception::new($exception); 88 | } 89 | } 90 | 91 | /** 92 | * Execute a new query against the connection. 93 | * 94 | * @param string $sql 95 | * @return ResultInterface 96 | */ 97 | public function query(string $sql): ResultInterface 98 | { 99 | try { 100 | $stmt = $this->connection->query($sql); 101 | 102 | assert($stmt instanceof PDOStatement); 103 | 104 | return new Result($stmt); 105 | } catch (PDOException $exception) { 106 | throw Exception::new($exception); 107 | } 108 | } 109 | 110 | /** 111 | * Get the last insert ID. 112 | * 113 | * @param string|null $name 114 | * @return mixed 115 | * 116 | * @throws Exception 117 | */ 118 | public function lastInsertId(): string|int 119 | { 120 | try { 121 | return $this->connection->lastInsertId(); 122 | } catch (PDOException $exception) { 123 | throw Exception::new($exception); 124 | } 125 | } 126 | 127 | /** 128 | * Create a new statement instance. 129 | * 130 | * @param PDOStatement $stmt 131 | * @return Statement 132 | */ 133 | protected function createStatement(PDOStatement $stmt): Statement 134 | { 135 | return new Statement($stmt); 136 | } 137 | 138 | /** 139 | * Begin a new database transaction. 140 | */ 141 | public function beginTransaction(): void 142 | { 143 | $this->connection->beginTransaction(); 144 | } 145 | 146 | /** 147 | * Commit a database transaction. 148 | */ 149 | public function commit(): void 150 | { 151 | $this->connection->commit(); 152 | } 153 | 154 | /** 155 | * Rollback a database transaction. 156 | */ 157 | public function rollBack(): void 158 | { 159 | $this->connection->rollBack(); 160 | } 161 | 162 | /** 163 | * Wrap quotes around the given input. 164 | * 165 | * @param string $input 166 | * @param string $type 167 | * @return string 168 | */ 169 | public function quote(string $value): string 170 | { 171 | return $this->connection->quote($value); 172 | } 173 | 174 | /** 175 | * Get the server version for the connection. 176 | * 177 | * @return string 178 | */ 179 | public function getServerVersion(): string 180 | { 181 | return $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION); 182 | } 183 | 184 | /** 185 | * Get the native connection. 186 | * 187 | * @return PDO 188 | */ 189 | public function getNativeConnection(): PDO 190 | { 191 | return $this->connection; 192 | } 193 | 194 | /** 195 | * Get the wrapped PDO connection. 196 | * 197 | * @return PDO 198 | */ 199 | public function getWrappedConnection(): PDO 200 | { 201 | return $this->connection; 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /src/EcotoneProvider.php: -------------------------------------------------------------------------------- 1 | mergeConfigFrom( 47 | __DIR__ . '/../config/ecotone.php', 48 | 'ecotone' 49 | ); 50 | 51 | $environment = App::environment(); 52 | $rootCatalog = App::basePath(); 53 | $useProductionCache = in_array($environment, ['prod', 'production']) ? true : Config::get('ecotone.cacheConfiguration'); 54 | $cacheDirectory = $this->getCacheDirectoryPath() . DIRECTORY_SEPARATOR . 'ecotone'; 55 | $enableTesting = Config::get('ecotone.test'); 56 | 57 | $errorChannel = Config::get('ecotone.defaultErrorChannel'); 58 | 59 | $skippedModules = Config::get('ecotone.skippedModulePackageNames') ?? []; 60 | /** @TODO Ecotone 2.0 use ServiceContext to configure Laravel */ 61 | $applicationConfiguration = ServiceConfiguration::createWithDefaults() 62 | ->withEnvironment($environment) 63 | ->withLoadCatalog(Config::get('ecotone.loadAppNamespaces') ? 'app' : '') 64 | ->withFailFast(false) 65 | ->withNamespaces(Config::get('ecotone.namespaces') ?? []) 66 | ->withSkippedModulePackageNames($skippedModules) 67 | ->withCacheDirectoryPath($cacheDirectory); 68 | 69 | if (Config::get('ecotone.licenceKey') !== null) { 70 | $applicationConfiguration = $applicationConfiguration->withLicenceKey(Config::get('ecotone.licenceKey')); 71 | } 72 | 73 | $serializationMediaType = Config::get('ecotone.defaultSerializationMediaType'); 74 | if ($serializationMediaType) { 75 | $applicationConfiguration = $applicationConfiguration 76 | ->withDefaultSerializationMediaType($serializationMediaType); 77 | } 78 | $serviceName = Config::get('ecotone.serviceName'); 79 | if ($serviceName) { 80 | $applicationConfiguration = $applicationConfiguration 81 | ->withServiceName($serviceName); 82 | } 83 | 84 | if ($errorChannel) { 85 | $applicationConfiguration = $applicationConfiguration 86 | ->withDefaultErrorChannel($errorChannel); 87 | } 88 | 89 | $retryTemplate = Config::get('ecotone.defaultConnectionExceptionRetry'); 90 | if ($retryTemplate) { 91 | $applicationConfiguration = $applicationConfiguration 92 | ->withConnectionRetryTemplate( 93 | RetryTemplateBuilder::exponentialBackoffWithMaxDelay( 94 | $retryTemplate['initialDelay'], 95 | $retryTemplate['maxAttempts'], 96 | $retryTemplate['multiplier'] 97 | ) 98 | ); 99 | } 100 | 101 | $applicationConfiguration = $applicationConfiguration->withExtensionObjects([new EloquentRepositoryBuilder()]); 102 | $applicationConfiguration = MessagingSystemConfiguration::addCorePackage($applicationConfiguration, $enableTesting); 103 | 104 | [$serviceCacheConfiguration, $definitionHolder] = $this->prepareFromCache($useProductionCache, $rootCatalog, $applicationConfiguration, $enableTesting, $cacheDirectory); 105 | 106 | foreach ($definitionHolder->getDefinitions() as $id => $definition) { 107 | $this->app->singleton($id, function () use ($definition) { 108 | return $this->resolveArgument($definition); 109 | }); 110 | } 111 | 112 | $this->app->singleton( 113 | ConfigurationVariableService::REFERENCE_NAME, 114 | function () { 115 | return new LaravelConfigurationVariableService(); 116 | } 117 | ); 118 | $this->app->singleton( 119 | EloquentRepository::class, 120 | function () { 121 | return new EloquentRepository(); 122 | } 123 | ); 124 | $this->app->singleton( 125 | ServiceCacheConfiguration::REFERENCE_NAME, 126 | fn () => $serviceCacheConfiguration 127 | ); 128 | 129 | if ($this->app->runningInConsole()) { 130 | foreach ($definitionHolder->getRegisteredCommands() as $oneTimeCommandConfiguration) { 131 | $commandName = $oneTimeCommandConfiguration->getName(); 132 | 133 | foreach ($oneTimeCommandConfiguration->getParameters() as $parameter) { 134 | $commandName .= $parameter->isOption() ? ' {--' : ' {'; 135 | $commandName .= $parameter->getName(); 136 | 137 | if ($parameter->isArray()) { 138 | $commandName .= '=*'; 139 | } elseif ($parameter->hasDefaultValue()) { 140 | $commandName .= '=' . $parameter->getDefaultValue(); 141 | } 142 | 143 | $commandName .= '}'; 144 | } 145 | 146 | Artisan::command( 147 | $commandName, 148 | function (ConfiguredMessagingSystem $configuredMessagingSystem) { 149 | /** @var ConsoleCommandRunner $consoleCommandRunner */ 150 | $consoleCommandRunner = $configuredMessagingSystem->getGatewayByName(ConsoleCommandRunner::class); 151 | 152 | /** @var ClosureCommand $self */ 153 | $self = $this; 154 | 155 | /** @var ConsoleCommandResultSet $result */ 156 | $result = $consoleCommandRunner->execute($self->getName(), array_merge($self->arguments(), $self->options())); 157 | 158 | if ($result) { 159 | $self->table($result->getColumnHeaders(), $result->getRows()); 160 | } 161 | 162 | return 0; 163 | } 164 | ); 165 | } 166 | } 167 | } 168 | 169 | /** 170 | * Bootstrap services. 171 | * 172 | * @return void 173 | */ 174 | public function boot() 175 | { 176 | $this->publishes( 177 | [ 178 | __DIR__ . '/../config/ecotone.php' => config_path('ecotone.php'), 179 | ], 180 | 'ecotone-config' 181 | ); 182 | 183 | if (! $this->app->has('logger')) { 184 | $this->app->singleton('logger', LaravelLogger::class); 185 | } 186 | 187 | // Hook into Laravel's optimization commands to clear Ecotone cache 188 | $this->registerOptimizationHooks(); 189 | } 190 | 191 | public static function getCacheDirectoryPath(): string 192 | { 193 | return App::storagePath() . DIRECTORY_SEPARATOR . 'framework' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'data'; 194 | } 195 | 196 | private function instantiateDefinition(Definition $definition): object 197 | { 198 | $arguments = $this->resolveArgument($definition->getArguments()); 199 | if ($definition->hasFactory()) { 200 | $factory = $definition->getFactory(); 201 | if (method_exists($factory[0], $factory[1]) && (new ReflectionMethod($factory[0], $factory[1]))->isStatic()) { 202 | // static call 203 | return $factory(...$arguments); 204 | } else { 205 | // method call from a service instance 206 | $service = $this->app->make($factory[0]); 207 | return $service->{$factory[1]}(...$arguments); 208 | } 209 | } else { 210 | $class = $definition->getClassName(); 211 | return new $class(...$arguments); 212 | } 213 | } 214 | 215 | private function resolveArgument(mixed $argument): mixed 216 | { 217 | if (is_array($argument)) { 218 | return array_map(fn ($argument) => $this->resolveArgument($argument), $argument); 219 | } elseif ($argument instanceof Definition) { 220 | $object = $this->instantiateDefinition($argument); 221 | foreach ($argument->getMethodCalls() as $methodCall) { 222 | $object->{$methodCall->getMethodName()}(...$this->resolveArgument($methodCall->getArguments())); 223 | } 224 | return $object; 225 | } elseif ($argument instanceof Reference) { 226 | if ($this->app->has($argument->getId())) { 227 | return $this->app->get($argument->getId()); 228 | } 229 | if ($argument->getInvalidBehavior() === ContainerImplementation::NULL_ON_INVALID_REFERENCE) { 230 | return null; 231 | } 232 | if (class_exists($argument->getId())) { 233 | return $this->app->make($argument->getId()); 234 | } 235 | throw new InvalidArgumentException("Reference to {$argument->getId()} is not found"); 236 | } else { 237 | return $argument; 238 | } 239 | } 240 | 241 | public function prepareFromCache(mixed $useProductionCache, string $rootCatalog, ServiceConfiguration $applicationConfiguration, mixed $enableTesting, string $cacheDirectory): array 242 | { 243 | if ($useProductionCache && $cacheDirectory) { 244 | $messagingFile = $cacheDirectory . DIRECTORY_SEPARATOR . self::MESSAGING_SYSTEM_FILE_NAME; 245 | 246 | if (file_exists($messagingFile)) { 247 | /** It may fail on deserialization, then return `false` and we can build new one */ 248 | $definitionHolder = unserialize(file_get_contents($messagingFile)); 249 | 250 | if ($definitionHolder) { 251 | return [new ServiceCacheConfiguration($cacheDirectory, true), $definitionHolder]; 252 | } 253 | } 254 | } 255 | 256 | $annotationFinder = AnnotationFinderFactory::createForAttributes( 257 | realpath($rootCatalog), 258 | $applicationConfiguration->getNamespaces(), 259 | $applicationConfiguration->getEnvironment(), 260 | $applicationConfiguration->getLoadedCatalog() ?? '', 261 | MessagingSystemConfiguration::getModuleClassesFor($applicationConfiguration), 262 | isRunningForTesting: $enableTesting, 263 | ); 264 | 265 | $cacheHash = $annotationFinder->getCacheMessagingFileNameBasedOnConfig( 266 | realpath($rootCatalog), 267 | $applicationConfiguration, 268 | Config::all(), 269 | $enableTesting 270 | ); 271 | 272 | $serviceCacheConfiguration = new ServiceCacheConfiguration( 273 | $useProductionCache ? $cacheDirectory : ($cacheDirectory . DIRECTORY_SEPARATOR . $cacheHash), 274 | true, 275 | ); 276 | 277 | $definitionHolder = null; 278 | 279 | $messagingSystemCachePath = $serviceCacheConfiguration->getPath() . DIRECTORY_SEPARATOR . self::MESSAGING_SYSTEM_FILE_NAME; 280 | 281 | if ($serviceCacheConfiguration->shouldUseCache() && file_exists($messagingSystemCachePath)) { 282 | /** It may fail on deserialization, then return `false` and we can build new one */ 283 | $definitionHolder = unserialize(file_get_contents($messagingSystemCachePath)); 284 | } 285 | 286 | if (! $definitionHolder) { 287 | $configuration = MessagingSystemConfiguration::prepareWithAnnotationFinder( 288 | $annotationFinder, 289 | new LaravelConfigurationVariableService(), 290 | $applicationConfiguration, 291 | enableTestPackage: $enableTesting 292 | ); 293 | $definitionHolder = ContainerConfig::buildDefinitionHolder($configuration); 294 | 295 | if ($serviceCacheConfiguration->shouldUseCache()) { 296 | MessagingSystemConfiguration::prepareCacheDirectory($serviceCacheConfiguration); 297 | file_put_contents($messagingSystemCachePath, serialize($definitionHolder)); 298 | } 299 | } 300 | 301 | return [$serviceCacheConfiguration, $definitionHolder]; 302 | } 303 | 304 | /** 305 | * Register hooks to clear Ecotone cache when Laravel optimization commands are run 306 | */ 307 | private function registerOptimizationHooks(): void 308 | { 309 | $this->app['events']->listen( 310 | CommandFinished::class, 311 | function ($event) { 312 | // Clear Ecotone cache when optimize commands finishes successfully 313 | if (in_array($event->command, ['optimize', 'optimize:clear', 'cache:clear']) && $event->exitCode === 0) { 314 | EcotoneCacheClear::clearEcotoneCacheDirectories($this->getCacheDirectoryPath()); 315 | } 316 | } 317 | ); 318 | } 319 | } 320 | --------------------------------------------------------------------------------