diff --git a/steering_docs/php-tech/basics.md b/steering_docs/php-tech/basics.md new file mode 100644 index 00000000000..5435df091e8 --- /dev/null +++ b/steering_docs/php-tech/basics.md @@ -0,0 +1,188 @@ +# PHP Interactive Scenario Generation + +## MANDATORY: Knowledge Base Consultation (FIRST STEP) +**🚨 CRITICAL - Must be completed BEFORE any code generation** + +```bash +# Step 1: List available knowledge bases +ListKnowledgeBases() + +# Step 2: Query coding standards (REQUIRED) +QueryKnowledgeBases("coding-standards-KB", "PHP-code-example-standards") + +# Step 3: Query implementation patterns (REQUIRED) +QueryKnowledgeBases("PHP-premium-KB", "PHP implementation patterns structure") + +# Step 4: AWS service research (REQUIRED) +search_documentation("What is [AWS Service] and what are its key API operations?") +read_documentation("https://docs.aws.amazon.com/[service]/latest/[relevant-page]") +``` + +**FAILURE TO COMPLETE KNOWLEDGE BASE CONSULTATION WILL RESULT IN INCORRECT CODE STRUCTURE** + +## Purpose +Generate interactive scenarios that demonstrate complete workflows using multiple service operations in a guided, educational manner. Implementation must be based on the service SPECIFICATION.md file. + +## Requirements +- **Specification-Driven**: MUST read the `scenarios/basics/{service}/SPECIFICATION.md` +- **Interactive**: Use `testable_readline()` for user input and clear output +- **Educational**: Break complex workflows into logical phases +- **Comprehensive**: Cover setup, demonstration, examination, and cleanup +- **Error Handling**: Graceful error handling with user-friendly messages +- **Service Classes**: MUST use service wrapper classes for all operations +- **Runner Pattern**: MUST implement interactive Runner.php pattern + +## File Structure +``` +example_code/{service}/ +├── Runner.php # Interactive menu runner +├── {Service}Service.php # Service wrapper class +├── composer.json +├── README.md +└── tests/ + ├── {Service}Test.php + └── phpunit.xml +```## MA +NDATORY Pre-Implementation Steps + +### Step 1: Read Service Specification +**CRITICAL**: Always read `scenarios/basics/{service}/SPECIFICATION.md` first to understand: +- **API Actions Used**: Exact operations to implement +- **Proposed Example Structure**: Setup, demonstration, examination, cleanup phases +- **Error Handling**: Specific error codes and handling requirements +- **Scenario Flow**: Step-by-step workflow description + +### Step 2: Extract Implementation Requirements +From the specification, identify: +- **Setup Phase**: What resources need to be created/configured +- **Demonstration Phase**: What operations to demonstrate +- **Examination Phase**: What data to display and how to filter/analyze +- **Cleanup Phase**: What resources to clean up and user options + +## Runner Pattern Structure +**MANDATORY for most services:** + +```php +list{Resources}(); + break; + case '4': + $service = new {Service}Service(); + $resourceName = testable_readline("Enter resource name: "); + $service->create{Resource}($resourceName); + break; + case '5': + $service = new {Service}Service(); + $resourceId = testable_readline("Enter resource ID: "); + $service->delete{Resource}($resourceId); + break; + case '0': + echo "Goodbye!\n"; + break; + default: + echo "Invalid choice\n"; +} +``` + +## Scenario Phase Structure (Based on Specification) + +### Setup Phase +- **Read specification Setup section** for exact requirements +- Check for existing resources as specified +- Create necessary resources using service methods +- Configure service settings per specification +- Verify setup completion as described + +### Demonstration Phase +- **Follow specification Demonstration section** exactly +- Perform core service operations using service methods +- Generate sample data if specified in the specification +- Show service capabilities as outlined +- Provide educational context from specification + +### Examination Phase +- **Implement specification Examination section** requirements +- List and examine results using service methods +- Filter and analyze data as specified +- Display detailed information per specification format +- Allow user interaction as described in specification + +### Cleanup Phase +- **Follow specification Cleanup section** guidance +- Offer cleanup options with warnings from specification +- Handle cleanup errors gracefully using service methods +- Provide alternative management options as specified +- Confirm completion per specification + +## User Interaction Patterns + +### Input Handling +```php +// Yes/No questions +$useExisting = testable_readline("Use existing resource? (y/n): "); +$isYes = strtolower($useExisting) === 'y'; + +// Text input +$resourceName = testable_readline("Enter resource name: "); + +// Numeric input with validation +do { + $count = testable_readline("How many items? "); +} while (!is_numeric($count) || $count < 1); +``` + +### Information Display +```php +// Progress indicators +echo "✓ Operation completed successfully\n"; +echo "⚠ Warning message\n"; +echo "✗ Error occurred\n"; + +// Formatted output +echo str_repeat('-', 60) . "\n"; +echo "Found " . count($items) . " items:\n"; +foreach ($items as $item) { + echo " • {$item['name']}\n"; +} +``` + +## Runner Requirements +- ✅ **ALWAYS** read and implement based on `scenarios/basics/{service}/SPECIFICATION.md` +- ✅ **ALWAYS** provide interactive menu for multiple examples +- ✅ **ALWAYS** include hello scenario as first option +- ✅ **ALWAYS** handle user input gracefully using `testable_readline()` +- ✅ **ALWAYS** include proper error handling +- ✅ **ALWAYS** provide clear output and feedback +- ✅ **ALWAYS** use service wrapper classes for all AWS operations +- ✅ **ALWAYS** implement proper cleanup in finally block +- ✅ **ALWAYS** break scenario into logical phases per specification +- ✅ **ALWAYS** include error handling per specification's Errors section +- ✅ **ALWAYS** provide educational context and explanations from specification \ No newline at end of file diff --git a/steering_docs/php-tech/hello.md b/steering_docs/php-tech/hello.md new file mode 100644 index 00000000000..95cfa26c2c6 --- /dev/null +++ b/steering_docs/php-tech/hello.md @@ -0,0 +1,96 @@ +# PHP Hello Examples Generation + +## MANDATORY: Knowledge Base Consultation (FIRST STEP) +**🚨 CRITICAL - Must be completed BEFORE any code generation** + +```bash +# Step 1: List available knowledge bases +ListKnowledgeBases() + +# Step 2: Query coding standards (REQUIRED) +QueryKnowledgeBases("coding-standards-KB", "PHP-code-example-standards") + +# Step 3: Query implementation patterns (REQUIRED) +QueryKnowledgeBases("PHP-premium-KB", "PHP implementation patterns") + +# Step 4: AWS service research (REQUIRED) +search_documentation("What is [AWS Service] and what are its key API operations?") +read_documentation("https://docs.aws.amazon.com/[service]/latest/[relevant-page]") +``` + +**FAILURE TO COMPLETE KNOWLEDGE BASE CONSULTATION WILL RESULT IN INCORRECT CODE STRUCTURE** + +## Purpose +Generate simple "Hello" examples that demonstrate basic service connectivity and the most fundamental operation using direct AWS SDK for PHP client calls. + +## Requirements +- **MANDATORY**: Every AWS service MUST include a "Hello" scenario +- **Simplicity**: Should be the most basic, minimal example possible +- **Standalone**: Must work independently of other examples +- **Direct Client**: Use AWS SDK for PHP client directly, no wrapper classes needed + +## File Structure +``` +example_code/{service}/ +├── Hello{Service}.php # Hello example file +``` + +## Hello Scenario File Pattern +**MANDATORY standalone hello file:** + +```php + 'us-east-1', + 'version' => 'latest' + ]); + + // Simple service operation + $result = $client->someBasicOperation(); + echo "Successfully connected to {AWS Service}\n"; + // Display basic result + +} catch (AwsException $e) { + echo "Error: " . $e->getMessage() . "\n"; +} +``` + +## Hello Examples by Service Type + +### List-Based Services (S3, DynamoDB, etc.) +- **Operation**: List primary resources (buckets, tables, etc.) +- **Message**: Show count and names of resources + +### Status-Based Services (GuardDuty, Config, etc.) +- **Operation**: Check service status or list detectors/configurations +- **Message**: Show service availability and basic status + +### Compute Services (EC2, Lambda, etc.) +- **Operation**: List instances/functions or describe regions +- **Message**: Show available resources or regions + +## Validation Requirements +- ✅ **Must run without errors** (with proper credentials) +- ✅ **Must handle credential issues gracefully** +- ✅ **Must display meaningful output** +- ✅ **Must use direct AWS SDK for PHP client calls** +- ✅ **Must include proper copyright header** + +## Common Patterns +- Always use `new {Service}Client()` directly +- Include comprehensive error handling with try-catch blocks +- Provide user-friendly output messages using echo +- Handle both service-specific and general exceptions +- Keep it as simple as possible - no additional classes or complexity +- Use appropriate AWS SDK for PHP v3 patterns \ No newline at end of file diff --git a/steering_docs/php-tech/metadata.md b/steering_docs/php-tech/metadata.md new file mode 100644 index 00000000000..b3a4c445030 --- /dev/null +++ b/steering_docs/php-tech/metadata.md @@ -0,0 +1,169 @@ +# PHP Metadata and Project Structure + +## MANDATORY: Knowledge Base Consultation (FIRST STEP) +**🚨 CRITICAL - Must be completed BEFORE any code generation** + +```bash +# Step 1: List available knowledge bases +ListKnowledgeBases() + +# Step 2: Query coding standards (REQUIRED) +QueryKnowledgeBases("coding-standards-KB", "PHP-code-example-standards") + +# Step 3: Query implementation patterns (REQUIRED) +QueryKnowledgeBases("PHP-premium-KB", "PHP implementation patterns metadata") + +# Step 4: AWS service research (REQUIRED) +search_documentation("What is [AWS Service] and what are its key API operations?") +read_documentation("https://docs.aws.amazon.com/[service]/latest/[relevant-page]") +``` + +**FAILURE TO COMPLETE KNOWLEDGE BASE CONSULTATION WILL RESULT IN INCORRECT CODE STRUCTURE** + +## Purpose +Generate proper project structure, Composer configuration, and metadata files for PHP AWS SDK examples. + +## File Structure +``` +example_code/{service}/ +├── Hello{Service}.php # Standalone hello scenario file +├── {Service}Actions.php # Individual action examples +├── {Service}Service.php # Service wrapper class +├── Runner.php # Interactive menu runner +├── composer.json # Composer configuration +├── README.md # Service documentation +└── tests/ + ├── {Service}Test.php # Unit and integration tests + └── phpunit.xml # PHPUnit configuration +``` + +## Composer Configuration Pattern +**MANDATORY for every service directory:** + +```json +{ + "name": "awsdocs/{service}-examples", + "description": "AWS SDK for PHP examples for {AWS Service}", + "type": "library", + "license": "Apache-2.0", + "authors": [ + { + "name": "AWS Documentation Team", + "email": "aws-doc-sdk-examples@amazon.com" + } + ], + "require": { + "php": "^8.1", + "aws/aws-sdk-php": "^3.209", + "ext-readline": "*" + }, + "require-dev": { + "phpunit/phpunit": "^9.5" + }, + "autoload": { + "psr-4": { + "{Service}\\": "./" + } + }, + "autoload-dev": { + "psr-4": { + "{Service}\\Tests\\": "tests/" + } + }, + "scripts": { + "test": "phpunit", + "test-unit": "phpunit --group unit", + "test-integ": "phpunit --group integ" + } +} +``` + +## File Naming Conventions +- Use PascalCase for class files and main example files +- Service prefix pattern: `{Service}Actions.php` (e.g., `S3Actions.php`) +- Hello scenarios: `Hello{Service}.php` (e.g., `HelloS3.php`) +- Runner files: `Runner.php` (standard entry point) +- Test files: `{Service}Test.php` +- Service wrapper: `{Service}Service.php` + +## Code Structure Standards +- **Namespace naming**: Use PascalCase with backslashes (e.g., `S3\`, `DynamoDb\`) +- **Class structure**: One public class per file matching filename +- **Method naming**: Use camelCase for method names +- **Constants**: Use UPPER_SNAKE_CASE for constants +- **Properties**: Use camelCase for properties +- **PSR-4 autoloading**: Follow PSR-4 standards for autoloading + +## Copyright Header Pattern +**MANDATORY for every PHP file:** + +```php +listResources()); +" +``` + +### Automated Execution +```bash +# Non-interactive testing +PHPUNIT_TESTING=1 php Runner.php + +# Batch execution with input +echo -e "1\n0\n" | php Runner.php +``` + +## Environment Configuration + +### AWS Configuration +- **Credentials**: Support AWS credential chain (environment, profile, IAM roles) +- **Region**: Configurable through client constructor or environment +- **Endpoint**: Support custom endpoints for testing + +### PHP Configuration +```bash +# Required PHP extensions +php -m | grep -E "(curl|json|mbstring|openssl|readline)" + +# Memory and execution limits +php -d memory_limit=256M -d max_execution_time=300 Runner.php +``` + +## Build Validation + +### Pre-commit Checks +```bash +#!/bin/bash +# Pre-commit validation script + +echo "Running PHP validation..." + +# 1. Syntax check +find . -name "*.php" -exec php -l {} \; | grep -v "No syntax errors" + +# 2. Composer validation +composer validate --strict + +# 3. Code style check +vendor/bin/phpcs --standard=../.github/linters/phpcs.xml --extensions=php --ignore=vendor ./ + +# 4. Unit tests +phpunit --group unit + +echo "✅ All checks passed" +``` + +### Continuous Integration +```yaml +# Example GitHub Actions workflow +name: PHP Tests +on: [push, pull_request] +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.1' + extensions: curl, json, mbstring, openssl, readline + - name: Install dependencies + run: composer install + - name: Run tests + run: composer test + - name: Check code style + run: composer lint +``` + +## Performance Considerations + +### Memory Management +- Use appropriate memory limits for large datasets +- Implement pagination for list operations +- Clean up resources properly in finally blocks + +### Execution Time +- Set appropriate timeout values for AWS operations +- Implement retry logic with exponential backoff +- Use async operations when available + +## Error Handling in Build Process + +### Common Build Failures +- **Composer install fails**: Check PHP version and extensions +- **Tests fail**: Verify AWS credentials and permissions +- **Linting fails**: Run phpcbf to auto-fix style issues +- **Autoloading fails**: Run composer dump-autoload + +### Debugging Commands +```bash +# Debug composer issues +composer diagnose + +# Debug autoloading +composer dump-autoload -v + +# Debug PHP configuration +php --ini +php -m + +# Debug AWS credentials +aws sts get-caller-identity +``` \ No newline at end of file diff --git a/steering_docs/php-tech/readme_writeme.md b/steering_docs/php-tech/readme_writeme.md new file mode 100644 index 00000000000..3d626e13cb3 --- /dev/null +++ b/steering_docs/php-tech/readme_writeme.md @@ -0,0 +1,324 @@ +# PHP README and Documentation Generation + +## MANDATORY: Knowledge Base Consultation (FIRST STEP) +**🚨 CRITICAL - Must be completed BEFORE any code generation** + +```bash +# Step 1: List available knowledge bases +ListKnowledgeBases() + +# Step 2: Query coding standards (REQUIRED) +QueryKnowledgeBases("coding-standards-KB", "PHP-code-example-standards") + +# Step 3: Query implementation patterns (REQUIRED) +QueryKnowledgeBases("PHP-premium-KB", "PHP implementation patterns documentation") + +# Step 4: AWS service research (REQUIRED) +search_documentation("What is [AWS Service] and what are its key API operations?") +read_documentation("https://docs.aws.amazon.com/[service]/latest/[relevant-page]") +``` + +**FAILURE TO COMPLETE KNOWLEDGE BASE CONSULTATION WILL RESULT IN INCORRECT CODE STRUCTURE** + +## Purpose +Generate comprehensive README documentation for PHP AWS SDK examples with setup instructions, usage examples, and troubleshooting guidance. + +## README Structure Template + +```markdown +# {AWS Service} examples for the SDK for PHP + +## Overview + +This section contains examples demonstrating how to use the AWS SDK for PHP with {AWS Service}. + +{AWS Service} is {brief service description and primary use cases}. + +## ⚠ Important + +* Running this code might result in charges to your AWS account. For more details, see [AWS Pricing](https://aws.amazon.com/pricing/) and [Free Tier](https://aws.amazon.com/free/). +* Running the tests might result in charges to your AWS account. +* We recommend that you grant your code least privilege. At most, grant only the minimum permissions required to perform the task. For more information, see [Grant least privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege). +* This code is not tested in every AWS Region. For more information, see [AWS Regional Services](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services). + +## Prerequisites + +For general prerequisites, see the [README](../../README.md#Prerequisites) in the `php` folder. + +### PHP Version +* PHP 8.1 or later +* Composer for dependency management + +### AWS SDK for PHP +* AWS SDK for PHP v3.209 or later + +### AWS Credentials +Configure your AWS credentials using one of the following methods: +* AWS credentials file +* Environment variables +* IAM roles (for EC2 instances) +* AWS CLI configuration + +## Setup + +1. **Install dependencies**: + ```bash + composer install + ``` + +2. **Configure AWS credentials** (if not already configured): + ```bash + aws configure + ``` + +3. **Verify setup**: + ```bash + php Hello{Service}.php + ``` + +## Code examples + +### Get started + +* [Hello {Service}](Hello{Service}.php) - Demonstrates basic connectivity to {AWS Service} + +### Scenarios + +* [Run {Service} basics scenario](Runner.php) - Interactive scenario demonstrating common {AWS Service} operations + +### Actions + +The following examples show you how to perform individual {AWS Service} actions: + +* [List {resources}]({Service}Actions.php#L{line}) - `{APIOperation}` +* [Create {resource}]({Service}Actions.php#L{line}) - `{APIOperation}` +* [Get {resource} details]({Service}Actions.php#L{line}) - `{APIOperation}` +* [Update {resource}]({Service}Actions.php#L{line}) - `{APIOperation}` +* [Delete {resource}]({Service}Actions.php#L{line}) - `{APIOperation}` + +## Running the examples + +### Hello {Service} +The simplest way to get started is with the Hello example: + +```bash +php Hello{Service}.php +``` + +This example demonstrates basic connectivity and lists available {resources}. + +### Interactive Runner +For a guided experience with multiple operations: + +```bash +php Runner.php +``` + +This provides an interactive menu with the following options: +1. Hello {Service} - Basic connectivity test +2. Run {Service} basics scenario - Complete workflow demonstration +3. List {resources} - Show available resources +4. Create {resource} - Create a new resource +5. Delete {resource} - Remove a resource + +### Individual Actions +You can also run specific actions directly: + +```bash +# List resources +php -r " +require 'vendor/autoload.php'; +use {Service}\{Service}Service; +\$service = new {Service}Service(); +\$resources = \$service->listResources(); +foreach (\$resources as \$resource) { + echo \$resource['Name'] . \"\n\"; +} +" +``` + +## Testing + +### Unit Tests +Run unit tests with mocked AWS responses: + +```bash +composer test-unit +# or +phpunit --group unit +``` + +### Integration Tests +Run integration tests against real AWS services: + +```bash +composer test-integ +# or +phpunit --group integ +``` + +**Note**: Integration tests will make actual AWS API calls and may incur charges. + +### All Tests +Run both unit and integration tests: + +```bash +composer test +# or +phpunit +``` + +## Code Quality + +### Linting +Check code style compliance: + +```bash +composer lint +# or +vendor/bin/phpcs --standard=../.github/linters/phpcs.xml --extensions=php --ignore=vendor ./ +``` + +### Auto-fix Code Style +Automatically fix code style issues: + +```bash +composer lint-fix +# or +vendor/bin/phpcbf --standard=../.github/linters/phpcs.xml --extensions=php --ignore=vendor ./ +``` + +## Troubleshooting + +### Common Issues + +#### Composer Install Fails +```bash +# Check PHP version +php --version + +# Check required extensions +php -m | grep -E "(curl|json|mbstring|openssl|readline)" + +# Update Composer +composer self-update +``` + +#### AWS Credentials Not Found +```bash +# Check AWS configuration +aws configure list + +# Test credentials +aws sts get-caller-identity + +# Set environment variables +export AWS_ACCESS_KEY_ID=your_access_key +export AWS_SECRET_ACCESS_KEY=your_secret_key +export AWS_DEFAULT_REGION=us-east-1 +``` + +#### Permission Denied Errors +Ensure your AWS credentials have the necessary permissions for {AWS Service}: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "{service}:List*", + "{service}:Get*", + "{service}:Describe*", + "{service}:Create*", + "{service}:Update*", + "{service}:Delete*" + ], + "Resource": "*" + } + ] +} +``` + +#### Service-Specific Errors +* **ResourceNotFoundException**: The specified resource doesn't exist +* **InvalidParameterException**: Check parameter values and formats +* **ThrottlingException**: Reduce request rate or implement retry logic +* **AccessDeniedException**: Verify IAM permissions + +### Debug Mode +Enable debug output for troubleshooting: + +```bash +# Set debug environment variable +export AWS_DEBUG=1 +php Hello{Service}.php + +# Or enable in code +\$client = new {Service}Client([ + 'region' => 'us-east-1', + 'version' => 'latest', + 'debug' => true +]); +``` + +## Additional resources + +* [{AWS Service} User Guide](https://docs.aws.amazon.com/{service}/latest/userguide/) +* [{AWS Service} API Reference](https://docs.aws.amazon.com/{service}/latest/APIReference/) +* [AWS SDK for PHP Documentation](https://docs.aws.amazon.com/sdk-for-php/) +* [AWS SDK for PHP API Reference](https://docs.aws.amazon.com/aws-sdk-php/v3/api/) + +--- + +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: Apache-2.0 +``` + +## Documentation Requirements + +### Essential Sections +- ✅ **Overview**: Clear service description and use cases +- ✅ **Prerequisites**: PHP version, SDK version, credentials +- ✅ **Setup**: Step-by-step installation and configuration +- ✅ **Code Examples**: Links to all example files with descriptions +- ✅ **Running Examples**: Clear execution instructions +- ✅ **Testing**: Unit and integration test instructions +- ✅ **Troubleshooting**: Common issues and solutions +- ✅ **Additional Resources**: Links to AWS documentation + +### Code Example Documentation +- **Hello Examples**: Basic connectivity demonstration +- **Scenarios**: Complete workflow examples +- **Actions**: Individual API operation examples +- **Service Classes**: Wrapper class usage examples + +### Setup Instructions +- **Dependencies**: Composer install process +- **Credentials**: Multiple configuration methods +- **Verification**: Test setup with Hello example +- **Environment**: PHP and extension requirements + +### Troubleshooting Guide +- **Common Errors**: Installation, credentials, permissions +- **Debug Methods**: Environment variables, client configuration +- **Service Errors**: Specific error codes and solutions +- **Performance**: Memory and timeout considerations + +### Testing Documentation +- **Unit Tests**: Mock-based testing approach +- **Integration Tests**: Real AWS service testing +- **Code Quality**: Linting and formatting tools +- **CI/CD**: Automated testing workflows + +## README Generation Checklist +- ✅ **Service-specific content** customized for the AWS service +- ✅ **Working code examples** with actual file references +- ✅ **Complete setup instructions** from prerequisites to execution +- ✅ **Comprehensive troubleshooting** covering common issues +- ✅ **Testing instructions** for both unit and integration tests +- ✅ **Code quality guidelines** with linting commands +- ✅ **Resource links** to official AWS documentation +- ✅ **Copyright and license** information included \ No newline at end of file diff --git a/steering_docs/php-tech/tests.md b/steering_docs/php-tech/tests.md new file mode 100644 index 00000000000..67c38afe9bd --- /dev/null +++ b/steering_docs/php-tech/tests.md @@ -0,0 +1,247 @@ +# PHP Test Generation + +## MANDATORY: Knowledge Base Consultation (FIRST STEP) +**🚨 CRITICAL - Must be completed BEFORE any code generation** + +```bash +# Step 1: List available knowledge bases +ListKnowledgeBases() + +# Step 2: Query coding standards (REQUIRED) +QueryKnowledgeBases("coding-standards-KB", "PHP-code-example-standards") + +# Step 3: Query implementation patterns (REQUIRED) +QueryKnowledgeBases("PHP-premium-KB", "PHP implementation patterns testing") + +# Step 4: AWS service research (REQUIRED) +search_documentation("What is [AWS Service] and what are its key API operations?") +read_documentation("https://docs.aws.amazon.com/[service]/latest/[relevant-page]") +``` + +**FAILURE TO COMPLETE KNOWLEDGE BASE CONSULTATION WILL RESULT IN INCORRECT CODE STRUCTURE** + +## Purpose +Generate comprehensive test suites including unit tests and integration tests using PHPUnit framework with proper mocking and AWS data structures. + +## Requirements +- **Complete Data**: Use complete AWS data structures in tests +- **Proper Attributes**: Use PHPUnit annotations for test categorization +- **Error Coverage**: Test all error conditions from specification +- **Mock Framework**: Use AWS MockHandler for unit tests + +## File Structure +``` +example_code/{service}/tests/ +├── {Service}Test.php # Unit and integration tests +└── phpunit.xml # PHPUnit configuration +``` + +## PHPUnit Configuration +**MANDATORY phpunit.xml structure:** + +```xml + + + + + . + + + + + unit + integ + + + +``` + +## Test Class Pattern +```php +mockHandler = new MockHandler(); + $this->service = new ServiceClass([ + 'handler' => $this->mockHandler, + 'region' => 'us-east-1' + ]); + } + + /** + * @group unit + */ + public function testHelloService(): void + { + $this->mockHandler->append(new Result(['Buckets' => []])); + + $result = $this->service->helloService(); + + $this->assertIsArray($result); + } + + /** + * @group integ + */ + public function testIntegrationExample(): void + { + // Integration test with real AWS service + $result = $this->service->realServiceCall(); + $this->assertNotNull($result); + } +} +``` + +## Unit Test Pattern +```php +/** + * @group unit + * @dataProvider errorCodeProvider + */ +public function testActionWithVariousConditions(?string $errorCode): void +{ + // Arrange + $paramValue = 'test-value'; + $expectedResponse = new Result([ + 'ResponseKey' => 'response-value' + ]); + + if ($errorCode === null) { + $this->mockHandler->append($expectedResponse); + } else { + $this->mockHandler->append(function (CommandInterface $cmd, RequestInterface $req) use ($errorCode) { + return new \Aws\Exception\AwsException($errorCode, $cmd); + }); + } + + // Act & Assert + if ($errorCode === null) { + $result = $this->service->performAction($paramValue); + $this->assertEquals('response-value', $result['ResponseKey']); + } else { + $this->expectException(\Aws\Exception\AwsException::class); + $this->service->performAction($paramValue); + } +} + +public function errorCodeProvider(): array +{ + return [ + 'success' => [null], + 'bad_request' => ['BadRequestException'], + 'internal_error' => ['InternalServerErrorException'], + ]; +} +``` + +## Integration Test Pattern +```php +/** + * @group integ + */ +public function testServiceIntegration(): void +{ + // Arrange + $service = new ServiceClass(); + + // Act - This should not raise an exception + $result = $service->listResources(); + + // Assert - Verify result structure + $this->assertIsArray($result); +} + +/** + * @group integ + */ +public function testResourceLifecycleIntegration(): void +{ + // Arrange + $service = new ServiceClass(); + $resourceId = null; + + try { + // Act - Create resource + $resourceId = $service->createResource('test-resource'); + $this->assertNotNull($resourceId); + + // Use resource + $result = $service->getResource($resourceId); + $this->assertNotNull($result); + } finally { + // Clean up + if ($resourceId !== null) { + try { + $service->deleteResource($resourceId); + } catch (Exception $e) { + // Ignore cleanup errors + } + } + } +} +``` + +## Test Execution Commands + +### Unit Tests +```bash +phpunit --group unit +``` + +### Integration Tests +```bash +phpunit --group integ +``` + +### All Tests +```bash +phpunit +``` + +## Test Requirements Checklist +- ✅ **PHPUnit configuration file created** with proper bootstrap +- ✅ **Mock framework setup** (AWS MockHandler for mocking clients) +- ✅ **Complete AWS data structures** in all tests +- ✅ **Proper PHPUnit annotations** (`@group unit`, `@group integ`) +- ✅ **Error condition coverage** per specification +- ✅ **Integration tests** for real AWS service calls +- ✅ **Data providers** for testing multiple scenarios +- ✅ **Proper cleanup** in integration tests + +## Testing Standards +- **Test framework**: Use PHPUnit with appropriate annotations +- **Integration tests**: Mark with `@group integ` annotation +- **Unit tests**: Mark with `@group unit` annotation +- **Test naming**: Use descriptive method names with `test` prefix +- **Test types**: Prefer Integration test coverage +- **Resource management**: Proper cleanup in `tearDown()` methods +- **Testable Readline**: Use the `testable_readline` function instead of `readline` so tests can be passed values rather than read from stdin + +## Common Test Failures to Avoid +- ❌ **Not using MockHandler** for unit tests +- ❌ **Using incomplete AWS data structures** in unit tests +- ❌ **Missing PHPUnit annotations** for test groups +- ❌ **Not testing all error conditions** from specification +- ❌ **Forgetting to set AWS region** in test clients +- ❌ **Not cleaning up resources** in integration tests +- ❌ **Missing data providers** for multiple test scenarios \ No newline at end of file diff --git a/steering_docs/php-tech/wrapper.md b/steering_docs/php-tech/wrapper.md new file mode 100644 index 00000000000..9963a803870 --- /dev/null +++ b/steering_docs/php-tech/wrapper.md @@ -0,0 +1,340 @@ +# PHP Service Wrapper Classes + +## MANDATORY: Knowledge Base Consultation (FIRST STEP) +**🚨 CRITICAL - Must be completed BEFORE any code generation** + +```bash +# Step 1: List available knowledge bases +ListKnowledgeBases() + +# Step 2: Query coding standards (REQUIRED) +QueryKnowledgeBases("coding-standards-KB", "PHP-code-example-standards") + +# Step 3: Query implementation patterns (REQUIRED) +QueryKnowledgeBases("PHP-premium-KB", "PHP implementation patterns wrapper") + +# Step 4: AWS service research (REQUIRED) +search_documentation("What is [AWS Service] and what are its key API operations?") +read_documentation("https://docs.aws.amazon.com/[service]/latest/[relevant-page]") +``` + +**FAILURE TO COMPLETE KNOWLEDGE BASE CONSULTATION WILL RESULT IN INCORRECT CODE STRUCTURE** + +## Purpose +Generate service wrapper classes that encapsulate AWS SDK operations with proper error handling, logging, and user-friendly interfaces. + +## Requirements +- **Encapsulation**: Wrap AWS SDK client operations +- **Error Handling**: Comprehensive exception handling with user-friendly messages +- **Logging**: Optional logging for debugging and monitoring +- **Testability**: Support dependency injection for testing +- **Documentation**: Complete PHPDoc documentation + +## File Structure +``` +example_code/{service}/ +├── {Service}Service.php # Service wrapper class +├── {Service}Actions.php # Individual action examples (optional) +``` + +## Service Class Pattern +**MANDATORY for organized services:** + +```php + 'us-east-1', + 'version' => 'latest' + ]; + + $this->client = new {Service}Client(array_merge($defaultConfig, $config)); + } + + /** + * List all resources in the service. + * + * @return array Array of resource information + * @throws {Service}Exception When the operation fails + */ + public function listResources(): array + { + try { + $result = $this->client->listResources(); + return $result['Resources'] ?? []; + } catch ({Service}Exception $e) { + $this->handleServiceException($e, 'listing resources'); + throw $e; + } catch (AwsException $e) { + $this->handleAwsException($e, 'listing resources'); + throw $e; + } + } + + /** + * Create a new resource. + * + * @param string $resourceName Name for the new resource + * @param array $options Additional options for resource creation + * @return string The ID of the created resource + * @throws {Service}Exception When the operation fails + */ + public function createResource(string $resourceName, array $options = []): string + { + try { + $params = array_merge([ + 'ResourceName' => $resourceName + ], $options); + + $result = $this->client->createResource($params); + + echo "✓ Created resource: {$resourceName}\n"; + return $result['ResourceId']; + } catch ({Service}Exception $e) { + $this->handleServiceException($e, "creating resource '{$resourceName}'"); + throw $e; + } catch (AwsException $e) { + $this->handleAwsException($e, "creating resource '{$resourceName}'"); + throw $e; + } + } + + /** + * Get detailed information about a resource. + * + * @param string $resourceId The ID of the resource + * @return array Resource details + * @throws {Service}Exception When the operation fails + */ + public function getResource(string $resourceId): array + { + try { + $result = $this->client->getResource([ + 'ResourceId' => $resourceId + ]); + + return $result['Resource']; + } catch ({Service}Exception $e) { + $this->handleServiceException($e, "getting resource '{$resourceId}'"); + throw $e; + } catch (AwsException $e) { + $this->handleAwsException($e, "getting resource '{$resourceId}'"); + throw $e; + } + } + + /** + * Delete a resource. + * + * @param string $resourceId The ID of the resource to delete + * @return bool True if deletion was successful + * @throws {Service}Exception When the operation fails + */ + public function deleteResource(string $resourceId): bool + { + try { + $this->client->deleteResource([ + 'ResourceId' => $resourceId + ]); + + echo "✓ Deleted resource: {$resourceId}\n"; + return true; + } catch ({Service}Exception $e) { + $this->handleServiceException($e, "deleting resource '{$resourceId}'"); + throw $e; + } catch (AwsException $e) { + $this->handleAwsException($e, "deleting resource '{$resourceId}'"); + throw $e; + } + } + + /** + * Handle service-specific exceptions with user-friendly messages. + * + * @param {Service}Exception $e The exception to handle + * @param string $operation Description of the operation that failed + */ + private function handleServiceException({Service}Exception $e, string $operation): void + { + $errorCode = $e->getAwsErrorCode(); + $message = match ($errorCode) { + 'ResourceNotFoundException' => "The resource was not found while {$operation}.", + 'InvalidParameterException' => "Invalid parameters provided while {$operation}.", + 'AccessDeniedException' => "Access denied while {$operation}. Check your permissions.", + 'ThrottlingException' => "Request was throttled while {$operation}. Please retry.", + default => "Service error while {$operation}: " . $e->getAwsErrorMessage() + }; + + echo "✗ Error: {$message}\n"; + } + + /** + * Handle general AWS exceptions with user-friendly messages. + * + * @param AwsException $e The exception to handle + * @param string $operation Description of the operation that failed + */ + private function handleAwsException(AwsException $e, string $operation): void + { + echo "✗ AWS Error while {$operation}: " . $e->getMessage() . "\n"; + } +} +``` + +## Actions Class Pattern (Optional) +For services with many individual operations, create separate action classes: + +```php +client = $client ?? new {Service}Client([ + 'region' => 'us-east-1', + 'version' => 'latest' + ]); + } + + /** + * Example action method. + * + * @param string $parameter Example parameter + * @return array Result of the operation + */ + public function exampleAction(string $parameter): array + { + try { + $result = $this->client->someOperation([ + 'Parameter' => $parameter + ]); + + echo "✓ Operation completed successfully\n"; + return $result->toArray(); + } catch (AwsException $e) { + echo "✗ Error: " . $e->getMessage() . "\n"; + throw $e; + } + } +} +``` + +## Error Handling Patterns + +### Service-Specific Error Handling +```php +private function handleServiceException({Service}Exception $e, string $operation): void +{ + $errorCode = $e->getAwsErrorCode(); + + switch ($errorCode) { + case 'BadRequestException': + echo "✗ Invalid request while {$operation}. Please check your parameters.\n"; + break; + case 'InternalServerErrorException': + echo "✗ Service temporarily unavailable while {$operation}. Please retry.\n"; + break; + case 'UnauthorizedOperation': + echo "✗ You don't have permission for {$operation}.\n"; + break; + default: + echo "✗ Service error while {$operation}: " . $e->getAwsErrorMessage() . "\n"; + } +} +``` + +### Retry Logic Pattern +```php +/** + * Perform operation with retry logic. + * + * @param callable $operation The operation to perform + * @param int $maxRetries Maximum number of retries + * @return mixed Result of the operation + */ +private function performWithRetry(callable $operation, int $maxRetries = 3) +{ + $attempt = 0; + + while ($attempt < $maxRetries) { + try { + return $operation(); + } catch ({Service}Exception $e) { + $attempt++; + + if ($e->getAwsErrorCode() === 'ThrottlingException' && $attempt < $maxRetries) { + $delay = pow(2, $attempt); // Exponential backoff + echo "⚠ Throttled. Retrying in {$delay} seconds...\n"; + sleep($delay); + continue; + } + + throw $e; + } + } +} +``` + +## Wrapper Class Requirements +- ✅ **ALWAYS** include comprehensive PHPDoc documentation +- ✅ **ALWAYS** use proper namespace matching service name +- ✅ **ALWAYS** implement constructor with configurable client +- ✅ **ALWAYS** include user-friendly error handling +- ✅ **ALWAYS** provide meaningful success/failure messages +- ✅ **ALWAYS** support dependency injection for testing +- ✅ **ALWAYS** follow PSR-4 autoloading standards +- ✅ **ALWAYS** include proper exception handling for all methods + +## Method Naming Conventions +- Use camelCase for method names +- Use descriptive names that indicate the operation +- Prefix with action verb (create, get, list, delete, update) +- Include resource type in method name when appropriate + +## Documentation Standards +- **Class documentation**: Describe the purpose and main functionality +- **Method documentation**: Include @param, @return, and @throws tags +- **Parameter documentation**: Describe each parameter's purpose and type +- **Exception documentation**: List all possible exceptions that can be thrown +- **Usage examples**: Include code examples in documentation when helpful \ No newline at end of file