### Docker Compose Setup for Ensō Source: https://context7.com/siddthartha/enso/llms.txt This bash script provides the complete Docker environment configuration for the Ensō project, suitable for both development and production. It allows starting, stopping, and checking the status of various services including Nginx, Swoole, RoadRunner, Swagger UI, MySQL, and Redis. ```bash # Start all services docker-compose up -d --build # Services available: # - Nginx + FPM: http://enso.localhost/ # - Swoole: http://enso.localhost:81/ # - RoadRunner: http://enso.localhost:82/ # - Swagger UI: http://enso.localhost:8080/ # - MySQL: localhost:3306 # - Redis: localhost:6379 # Check service status docker-compose ps # Expected output: # enso_db_1 Up 0.0.0.0:3306->3306/tcp # nginx Up 0.0.0.0:80->80/tcp, 0.0.0.0:81->81/tcp, 0.0.0.0:82->82/tcp # open-api Up 0.0.0.0:8080->8080/tcp # php Up 9000/tcp # php-sw Up 9999/tcp # redis Up 6379/tcp ``` -------------------------------- ### Codeception API Testing Example Source: https://context7.com/siddthartha/enso/llms.txt Demonstrates API testing using Codeception with the REST module in PHP. It includes tests for default routes, OpenAPI specifications, and handling of bad routes or static files. The tests verify response codes, JSON structure, and content. ```php sendGet('/'); $I->seeResponseCodeIs(200); $I->seeResponseIsJson(); $I->seeResponseMatchesJsonType([ 'before' => 'float:>0', 'after' => 'float:>0', 'preloadDuration' => 'string', 'taskDuration' => 'string', ]); } public function tryDefaultIndex(ApiTester $I) { $I->sendGet('/default/index'); $I->seeResponseCodeIs(200); $I->seeResponseIsJson(); $I->seeResponseMatchesJsonType([ 'context' => [ 'sapi' => 'string', ], ]); } public function tryDefaultOpenApi(ApiTester $I) { $I->sendGet('/default/open-api'); $I->seeResponseCodeIs(200); $I->seeResponseIsJson(); $I->seeResponseContainsJson([ 'openapi' => '3.0.0', 'info' => ['title' => 'Enso'], ]); } public function tryBadRoute(ApiTester $I) { $I->sendGet('/some/bad/link'); $I->seeResponseCodeIsServerError(); $I->seeResponseCodeIs(500); $I->seeResponseMatchesJsonType([ 'class' => 'string', 'file' => 'string', 'line' => 'integer:>0', 'message' => 'string', ]); } public function tryStaticFile(ApiTester $I) { $faviconMd5 = md5(file_get_contents("public/favicon.ico")); $I->sendGet('/favicon.ico'); $I->seeResponseCodeIs(200); $I->seeBinaryResponseEquals($faviconMd5, 'md5'); } } // Run tests: // docker-compose exec php vendor/bin/codecept run // docker-compose exec php vendor/bin/codecept run --coverage-html ``` -------------------------------- ### PHP Database Operations with Yiisoft ActiveRecord Source: https://context7.com/siddthartha/enso/llms.txt Performs database operations using Yiisoft's ActiveRecord pattern, supporting MySQL and PostgreSQL. Includes examples for table creation, record manipulation (create, save), querying, and retrieving database connection information. ```php _context->getContainer()->get(ConnectionInterface::class); // Create table (typically done via migrations) $db->createCommand() ->createTable('user', [ 'id' => 'int(11) NOT NULL AUTO_INCREMENT', 'username' => 'varchar(50)', 'email' => 'varchar(50)', 'PRIMARY KEY(id)', ]) ->execute(); // Create and save records $user = $this->_context->getContainer()->get(User::class); $user->username = 'john_doe'; $user->email = 'john@example.com'; $user->save(); // Query records $users = (new ActiveQuery(User::class)) ->where(['username' => 'john_doe']) ->asArray() ->all(); // Get all users as array $allUsers = (new ActiveQuery($user)) ->asArray() ->all(); // Database info $driverName = $db->getDriverName(); // 'mysql' $serverInfo = $db->getServerInfo(); // '8.0.28' $isActive = $db->isActive(); // true // Response format: // { // "context": { // "database": {"driver": "mysql", "version": "8.0.28", "active": true} // }, // "users": [ // {"id": 1, "username": "john_doe", "email": "john@example.com"} // ] // } ``` -------------------------------- ### API Endpoint Creation - ActionHandler (PHP) Source: https://context7.com/siddthartha/enso/llms.txt This PHP snippet illustrates how to create API endpoints using the ActionHandler abstract class in Ensō. It defines an action handler for a default index route, demonstrating how to access external services like Redis and return structured JSON responses. The code includes OpenAPI annotations for documentation generation and uses the #[Route] attribute for defining the endpoint. Dependencies include Enso's ActionHandler, Predis for Redis, and Yiisoft DB connection interface (though not directly used in this example). ```php 'tcp', 'host' => 'redis', 'port' => 6379, ]); $redisStatus = $redis->ping('hello'); // Return JSON response data return [ 'context' => [ 'php' => PHP_VERSION, 'sapi' => PHP_SAPI, 'redis' => $redisStatus, ], ]; } } // Response example: // { // "context": { // "php": "8.1.0", // "sapi": "fpm-fcgi", // "redis": "hello" // }, // "before": 1699999999.123456, // "after": 1699999999.234567, // "preloadDuration": "12.34 ms", // "taskDuration": "5.67 ms" // } ``` -------------------------------- ### Detect Runtime Environment with PHP Source: https://context7.com/siddthartha/enso/llms.txt This utility class helps detect the current runtime environment, including PHP SAPI types (CLI, FPM), async server runtimes (Swoole, RoadRunner), and I/O modes (TTY, piped). It also provides constants for exit codes and includes examples for conditional logic based on the detected environment. ```php getConfig(); $routingConfig = $config->get('routing'); // Access DI container $container = $app->getContainer(); $logger = $app->getLogger(); $cache = $app->getCache(); // Add middleware layers $app->addLayer( middleware: static function (Request $request, callable $next): ResponseInterface { // Pre-processing $response = $next->handle($request); // Post-processing: add default Content-Type header if (!$response->hasHeader('Content-type')) { return $response->withHeader('Content-type', 'application/json'); } return $response; } ); // Add router middleware with routing tree $routingTree = $app->getRoutingTree(); $app->addLayer(middleware: new Router($routingTree)); // Run the application with a request $request = $app->get(\Enso\Relay\RequestInterface::class); $response = $app->run($request); // Emit response $app->getEmitter()->emit(response: $response); ``` -------------------------------- ### Run Codeception Tests Source: https://context7.com/siddthartha/enso/llms.txt Executes tests using the Codeception testing framework. This includes building the test environment, running standard tests, and specifically running tests optimized for Swoole. These commands are executed within a Docker container. ```bash docker-compose exec php vendor/bin/codecept build docker-compose exec php vendor/bin/codecept run docker-compose exec php-sw vendor/bin/codecept run # Swoole tests ``` -------------------------------- ### Unified Request Handling for Web and CLI (PHP) Source: https://context7.com/siddthartha/enso/llms.txt Provides abstract `Request` classes (`WebRequest`, `CliRequest`) for unified handling of HTTP and command-line requests. Supports extracting routes, URIs, methods, query parameters, and arguments. Includes conversion to PSR-7 `ServerRequest` and runtime environment checks. ```php getRoute(); // ['default', 'index'] $uri = $webRequest->getUri(); $method = $webRequest->getMethod(); $queryParams = $webRequest->queryParams; $parsedBody = $webRequest->parsedBody; $cookies = $webRequest->cookies; // Web request from Swoole use Swoole\Http\Request as SwooleRequest; $swooleRequest = /* from Swoole server */; $webRequest = WebRequest::fromSwooleRequest($swooleRequest); // Convert to PSR-7 ServerRequest $psrRequest = $webRequest->asPsrServerRequest(); // CLI request from command line arguments // Example: ./enso default/index --param=value $cliRequest = CliRequest::fromGlobals(); $route = $cliRequest->getRoute(); // ['default', 'index'] $arguments = $cliRequest->getArguments(); // ['./enso', 'default/index', '--param=value'] $hasArgs = $cliRequest->hasArguments(); // true $argsLine = $cliRequest->getArgumentsLine(); // '--param=value' // Check runtime environment if (Runtime::isCLI()) { $request = CliRequest::fromGlobals(); } elseif (Runtime::isFPM() || Runtime::haveSwoole()) { $request = WebRequest::fromGlobals(); } ``` -------------------------------- ### Configure Application Routes with Target Objects (PHP) Source: https://context7.com/siddthartha/enso/llms.txt Defines application routes by mapping URL paths to action handlers. Supports HTTP method restrictions, nested routes, route aliases, and static data responses. Uses `EnsoSystemTarget` objects for configuration. ```php new Target('Application\LLMStreamAction', [], $context), // Nested routes under 'default' prefix 'default' => [ // Standard action with context injection 'index' => new Target('Application\IndexAction', [], $context), // User management endpoint 'user' => new Target('Application\UserAction', [], $context), // Telegram webhook handler 'telegram' => new Target('Application\TelegramAction'), // OpenAPI spec generator (GET and POST allowed) 'open-api' => new Target('Application\OpenApiAction', ['POST']), // Route alias - redirects to another route 'open-api-alias' => 'default/open-api', // Documentation endpoint 'docs' => new Target('Application\DocsAction', ['POST']), // Static data response (for testing) 'test' => ['value' => 123], ], ]; // Access via HTTP: // GET http://enso.localhost/default/index // GET http://enso.localhost/default/open-api // GET http://enso.localhost/ai?hello%20world // Access via CLI: // ./enso default/index // ./enso default/open-api // ./enso ai "hello world" ``` -------------------------------- ### PHP OpenRouter LLM Chat Completions Source: https://context7.com/siddthartha/enso/llms.txt Integrates with the OpenRouter API for performing chat completions using various LLM models. Supports both non-streaming and streaming responses. Requires an API key, which can be loaded from environment variables or passed directly. ```php chatCompletions( model: 'openai/gpt-4o', messages: [ ['role' => 'system', 'content' => 'You are a helpful assistant.'], ['role' => 'user', 'content' => 'What is PHP?'], ], options: [] ); // $response = ['choices' => [['message' => ['content' => '...']]]] // Streaming chat completion (returns FP functional stream) $streamResponse = $openRouter->streamChatCompletions( model: 'openai/gpt-4o', messages: [ ['role' => 'user', 'content' => 'Explain microservices'], ] ); // Process streaming response foreach ($streamResponse as $chunk) { $content = $chunk['choices'][0]['delta']['content'] ?? ''; $reasoning = $chunk['choices'][0]['delta']['reasoning'] ?? ''; echo $content; } // CLI streaming action usage: // ./enso ai "What is the meaning of life?" // Or via HTTP: // curl "http://enso.localhost/ai?What%20is%20the%20meaning%20of%20life" ``` -------------------------------- ### Generate Code Coverage Report Source: https://context7.com/siddthartha/enso/llms.txt Generates an HTML-based code coverage report for the tests executed by Codeception. This command is run within the PHP Docker container. ```bash docker-compose exec php vendor/bin/codecept run --coverage-html ``` -------------------------------- ### Generate PHPDoc Documentation Source: https://context7.com/siddthartha/enso/llms.txt Generates PHPDoc documentation for the project using a shell script. This is a common practice for documenting PHP codebases. ```bash ./generate-docs.sh ``` -------------------------------- ### PSR-7 Compatible Response Handling with Streaming (PHP) Source: https://context7.com/siddthartha/enso/llms.txt Manages application responses using the `Response` class, which wraps data and provides PSR-7 compatibility, including streaming support. Handles array serialization to JSON, streaming responses via `BufferStream`, status checks, header manipulation, and conversion to Swoole responses. ```php 'ok', 'data' => [1, 2, 3]], 200); $collapsed = $response->collapse(); // Serialize to JSON body // Streaming response $stream = new BufferStream(); $stream->write('{"streaming": true}'); $streamResponse = new Response($stream, 200); $isStream = $streamResponse->isStream(); // true // Check response status $isError = $response->isError(); // false (status < 400) $statusCode = $response->getStatusCode(); // 200 // Add headers $response = $response ->withHeader('Content-Type', 'application/json') ->withHeader('X-Custom-Header', 'value'); // Custom PSR-7 response (e.g., HTML) $body = new BufferStream(); $body->write('Hello'); $htmlResponse = (new PSRResponse()) ->withHeader('Content-type', 'text/html; charset=utf-8') ->withBody($body); // Convert to Swoole response use Swoole\Http\Response as SwooleResponse; $swooleResponse = /* from Swoole server */; Response::toSwooleResponse($response, $swooleResponse); ``` -------------------------------- ### PHP Middleware Relay System Implementation Source: https://context7.com/siddthartha/enso/llms.txt Implements a PSR-15 compliant middleware relay system in PHP. It allows for adding and processing requests through a queue of middleware functions or classes. Dependencies include PSR-7 interfaces and potentially a DI container for context. ```php before = microtime(true); $response = $next->handle($request); if ($response instanceof Response && !$response->isError()) { $response->before = $request->before; $response->after = microtime(true); $response->taskDuration = round(($response->after - $response->before) * 1000, 2) . ' ms'; } return $response; }, ], resolver: null, context: $container, // DI container ); // Add more middleware $relay->add(static function (Request $request, callable $next): ResponseInterface { // Authentication check $authHeader = $request->getHeaderLine('Authorization'); if (empty($authHeader)) { return new Response(['error' => 'Unauthorized'], 401); } return $next->handle($request); }); // Custom middleware class class LoggingMiddleware implements MiddlewareInterface { public function handle(RequestInterface $request, ?callable $next = null): ResponseInterface { error_log("Request: " . $request->getMethod() . " " . $request->getUri()); $response = $next->handle($request); error_log("Response: " . $response->getStatusCode()); return $response; } } $relay->add(new LoggingMiddleware()); // Handle request through relay $response = $relay->handle($request); ``` -------------------------------- ### Run Enso CLI Commands Source: https://context7.com/siddthartha/enso/llms.txt Executes various Enso CLI commands within a Docker container. These commands can perform default actions, generate OpenAPI specifications, or interact with AI functionalities. The output of the OpenAPI generation can be redirected to a file. ```bash docker-compose exec php ./enso default/index docker-compose exec php ./enso default/open-api > openapi.json docker-compose exec php ./enso ai "Hello world" ``` -------------------------------- ### Generate OpenAPI 3.0 Specs with PHP Source: https://context7.com/siddthartha/enso/llms.txt This utility automatically generates OpenAPI 3.0 specifications from annotated PHP code using the zircote/swagger-php library. It scans specified source directories and outputs the specification as JSON. The generated specs can be accessed via CLI or a Swagger UI interface. ```php toJson(); // Create HTTP response $body = new BufferStream(); $body->write($jsonSpec); $response = (new Response())->withBody($body); // Example OpenAPI annotations in action classes: /** * @OA\OpenApi( * @OA\Server(url="http://enso.localhost/", description="API server"), * @OA\Info( * version="1.0.0", * title="Ensō API", * description="RESTful API documentation", * @OA\Contact(name="Developer"), * @OA\License(name="BSD-3-Clause") * ) * ) */ /** * @OA\Get( * tags={"users"}, * path="/default/user", * summary="Get all users", * @OA\Response(response="200", description="User list"), * @OA\Response(response="400", description="Bad request", * @OA\JsonContent(ref="#/components/schemas/ExceptionResponse")) * ) */ // Access via CLI to export spec: // docker-compose exec php ./enso default/open-api > openapi.json // Access Swagger UI at: // http://enso.localhost:8080/ ``` -------------------------------- ### Send Telegram Messages with PHP Source: https://context7.com/siddthartha/enso/llms.txt This service allows sending messages via the Telegram Bot API using MarkdownV2 formatting. It requires specific environment variables for bot ID and API key. The service takes a recipient ID and a message string as input and returns a PSR-7 ResponseInterface object. ```php sendMessage( message: 'Hello from Ensō!', recipientId: $recipientId ); // Response is PSR-7 ResponseInterface $body = json_decode($response->getBody()->getContents(), true); // $body = ['ok' => true, 'result' => [...]] // Example webhook handler for GitLab events class TelegramWebhookAction extends ActionHandler { #[Route("/default/telegram", methods: ["POST"])] public function __invoke(): array { $request = $this->getRequest(); $headers = $request->getHeaders(); $token = $headers['X-Gitlab-Token'] ?? null; $event = $headers['X-Gitlab-Event'] ?? null; $telegram = new Telegram(); $response = $telegram->sendMessage( "`New GitLab event: {$event}`", $this->recipientId ); return [ 'apiResponse' => json_decode($response->getBody()->getContents(), true) ]; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.