### Setup Development Environment Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/executing-plans/reference.md Prepare the environment by creating a feature branch, installing dependencies, and clearing the cache. ```bash # Ensure clean state git status # Create feature branch git checkout -b feature/[feature-name] # Pull latest dependencies composer install # Clear cache bin/console cache:clear # Ensure tests pass ./vendor/bin/pest # or phpunit ``` -------------------------------- ### Install Composer Dependencies Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/bootstrap-check/reference.md Run 'composer install' to download and install project dependencies, ensuring the vendor directory is present. ```bash composer install ``` -------------------------------- ### Install API Platform Core Source: https://github.com/makfly/superpowers-symfony/blob/main/docs/symfony/api-platform.md Use Composer to install the API Platform core package. ```bash composer require api-platform/core ``` -------------------------------- ### Session Configuration JSON Source: https://context7.com/makfly/superpowers-symfony/llms.txt Example of the JSON context output generated by the plugin upon session start. ```json { "plugin": "superpowers-symfony", "detected_apps": 1, "active_app": "./my-symfony-app", "symfony": { "version": "7.1", "is_lts": false }, "api_platform": { "installed": true, "version": "3.2" }, "docker": { "type": "symfony-docker", "running": true, "is_symfony_docker": true }, "test_framework": "pest", "commands": { "runner": "docker compose exec php", "console": "docker compose exec php bin/console", "composer": "docker compose exec php composer", "test": "docker compose exec php ./vendor/bin/pest" }, "guidance": null } ``` -------------------------------- ### Start Development Services Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/daily-workflow/reference.md Use Docker Compose to start your project's services in detached mode. The --wait flag is useful for ensuring services are ready before proceeding. Alternatively, start the Symfony local server if not using Docker. ```bash docker compose up -d docker compose up -d --wait symfony server:start -d ``` -------------------------------- ### Bundle Version Context Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/effective-context/reference.md Example of asking about bundle-specific syntax changes. ```text API Platform 3.2. I see examples using "operations" but my version uses "collectionOperations". Which syntax should I use? ``` -------------------------------- ### Install Symfony Cache Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/symfony-cache/reference.md Install the Symfony Cache component using Composer. ```bash composer require symfony/cache ``` -------------------------------- ### Add and Install Superpowers Symfony Plugin Source: https://github.com/makfly/superpowers-symfony/blob/main/README.md Use these bash commands to add the Superpowers Symfony plugin from the marketplace and then install it. ```bash # Add the marketplace /plugin marketplace add MakFly/superpowers-symfony # Install the plugin /plugin install superpowers-symfony@superpowers-symfony ``` -------------------------------- ### Existing Pattern Context Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/effective-context/reference.md Include an example of the existing pattern to follow. ```text Our codebase uses CQRS pattern. Here's an example command handler: [example code] I need to add a new feature following the same pattern. ``` -------------------------------- ### Effective Prompt Example Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/effective-context/reference.md A specific prompt example for a custom API Platform filter. ```text I have a Symfony 7 app with API Platform 4. I need to add a filter that searches across multiple fields (title, description, author name). Here's my entity: [paste entity code] Current filters work for single fields. How do I create a custom filter that does OR search across these fields? ``` -------------------------------- ### Install Foundry and Doctrine Fixtures Bundle Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/doctrine-fixtures-foundry/reference.md Install the necessary Composer packages for Foundry and Doctrine Fixtures. These are development dependencies. ```bash composer require zenstruck/foundry --dev composer require doctrine/doctrine-fixtures-bundle --dev ``` -------------------------------- ### PHP Version Context Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/effective-context/reference.md Example of asking about PHP version-specific features. ```text PHP 8.2, Symfony 7.1. I want to use readonly classes for my DTOs. ``` -------------------------------- ### Post Factory Usage Examples Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/doctrine-fixtures-foundry/reference.md Demonstrates how to create Post entities using the PostFactory, including explicit author assignment, automatic author creation, and applying states like 'published' and 'withTags'. ```php // Explicit author $user = UserFactory::createOne(); $post = PostFactory::createOne(['author' => $user]); // Auto-created author $post = PostFactory::createOne(); // Creates user automatically // With tags $post = PostFactory::new() ->published() ->withTags(['PHP', 'Symfony']) ->create(); ``` -------------------------------- ### Verify API Platform Setup Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/bootstrap-check/reference.md Check if API Platform is correctly configured and working by debugging the router for API routes, exporting the OpenAPI specification, and inspecting serialization groups. ```bash # Verify API Platform is working bin/console debug:router | grep api # Check API resources bin/console api:openapi:export # Verify serialization groups bin/console debug:serializer ``` -------------------------------- ### Install API Platform Testing Dependencies Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/api-platform-tests/reference.md Use Composer to add the necessary testing packages to the development environment. ```bash composer require --dev api-platform/core composer require --dev zenstruck/foundry ``` -------------------------------- ### Install Pest PHP and Symfony Plugin Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/tdd-with-pest/reference.md Install Pest PHP and its Symfony plugin using Composer for development. Also installs Zenstruck Foundry for data factories. ```bash composer require pestphp/pest --dev --with-all-dependencies composer require pestphp/pest-plugin-symfony --dev composer require zenstruck/foundry --dev # Initialize Pest ./vendor/bin/pest --init ``` -------------------------------- ### Update Dependencies and Clear Cache Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/daily-workflow/reference.md Run these commands at the start of your day or when pulling changes to ensure your project is up-to-date. Composer install updates dependencies, migrations apply database changes, and cache clear ensures fresh configuration. ```bash git pull origin main composer install bin/console doctrine:migrations:migrate --no-interaction bin/console cache:clear ``` -------------------------------- ### Example .env File Syntax Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/config-env-parameters/reference.md Defines default application configuration values including environment, debugging, secret keys, database credentials, mailer DSN, and API keys. These values can be overridden by more specific environment files. ```bash # .env # App configuration APP_ENV=dev APP_DEBUG=true APP_SECRET=change-this-in-production # Database DATABASE_URL="postgresql://user:pass@localhost:5432/myapp?serverVersion=15" # Mailer MAILER_DSN=smtp://localhost:1025 # Third-party APIs STRIPE_API_KEY=sk_test_xxx AWS_ACCESS_KEY_ID=xxx AWS_SECRET_ACCESS_KEY=xxx # Feature flags FEATURE_NEW_CHECKOUT=false ``` -------------------------------- ### Bad Factory Defaults Example Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/doctrine-fixtures-foundry/reference.md An example of a 'bad' factory default definition, highlighting issues like non-unique emails and excessive, unrealistic default values. ```php // Bad: Too many defaults, unrealistic data protected function defaults(): array { return [ 'email' => 'test@test.com', // Not unique! 'firstName' => 'Test', 'lastName' => 'User', 'phone' => '123456789', // ... 20 more fields ]; } ``` -------------------------------- ### Install Twig Component Packages Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/twig-components/reference.md Install the necessary Symfony UX packages for Twig Components and Live Components using Composer. ```bash composer require symfony/ux-twig-component # For reactive components composer require symfony/ux-live-component ``` -------------------------------- ### Usage of UserFactory Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/tdd-with-pest/reference.md Examples demonstrating how to use the UserFactory to create single or multiple user instances, with specific attributes, custom states like 'admin', or without immediate persistence. ```php use App\Tests\Factory\UserFactory; // Single user $user = UserFactory::createOne(); // With specific attributes $admin = UserFactory::createOne()->admin(); // Multiple $users = UserFactory::createMany(5); // Without persisting $user = UserFactory::new()->withoutPersisting()->create(); ``` -------------------------------- ### GET /products Source: https://github.com/makfly/superpowers-symfony/blob/main/docs/symfony/api-platform.md Retrieves a collection of products. ```APIDOC ## GET /products ### Description List all products. ### Method GET ### Endpoint /products ### Query Parameters - **page** (integer) - Optional - The page number for pagination. - **itemsPerPage** (integer) - Optional - Number of items per page. - **pagination** (boolean) - Optional - Enable or disable pagination. ``` -------------------------------- ### Symfony Version Context Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/effective-context/reference.md Example of asking about version-specific features. ```text Symfony 6.4 LTS project. Can I use MapRequestPayload attribute? Or is that only in 7.x? ``` -------------------------------- ### Vague Prompt Example Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/effective-context/reference.md An example of a poor, context-less prompt. ```text How do I search in API Platform? ``` -------------------------------- ### Good Factory Defaults Example Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/doctrine-fixtures-foundry/reference.md An example of a 'good' factory default definition, focusing on minimal, realistic, and unique values for fields like email and roles. ```php // Good: Factory with minimal, realistic defaults protected function defaults(): array { return [ 'email' => self::faker()->unique()->safeEmail(), 'roles' => ['ROLE_USER'], ]; } ``` -------------------------------- ### Install Symfony Panther Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/e2e-panther-playwright/reference.md Add the Panther library to your project as a development dependency. ```bash composer require --dev symfony/panther ``` -------------------------------- ### Create Message and Handler Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/symfony-scheduler/reference.md Example of a message class and its corresponding handler for scheduled tasks. ```php forDate ?? new \DateTimeImmutable('yesterday'); $this->reportService->generate($date); $this->logger->info('Daily report generated', ['date' => $date->format('Y-m-d')]); } } ``` -------------------------------- ### Install Symfony Scheduler Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/symfony-scheduler/reference.md Command to add the scheduler component to a Symfony project. ```bash composer require symfony/scheduler ``` -------------------------------- ### Install Symfony Rate Limiter Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/rate-limiting/reference.md Use Composer to add the rate-limiter component to your project. ```bash composer require symfony/rate-limiter ``` -------------------------------- ### GET /v1/products and /v2/products Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/api-platform-versioning/reference.md Retrieves product information using URI versioning to distinguish between different data representations. ```APIDOC ## GET /v1/products ### Description Retrieves a collection of products in the V1 format. ### Method GET ### Endpoint /v1/products ## GET /v1/products/{id} ### Description Retrieves a specific product by ID in the V1 format. ### Method GET ### Endpoint /v1/products/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the product. ## GET /v2/products ### Description Retrieves a collection of products in the V2 format. ### Method GET ### Endpoint /v2/products ## GET /v2/products/{id} ### Description Retrieves a specific product by ID in the V2 format. ### Method GET ### Endpoint /v2/products/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the product. ``` -------------------------------- ### Client Usage for Pagination Source: https://github.com/makfly/superpowers-symfony/blob/main/docs/symfony/api-platform.md Examples of how clients can request specific pages, items per page, or disable pagination. ```http GET /api/products?page=2 GET /api/products?itemsPerPage=50 GET /api/products?pagination=false ``` -------------------------------- ### Configure GitHub Actions for Panther E2E Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/e2e-panther-playwright/reference.md Automates E2E testing in CI by setting up a database service, installing browser dependencies, and running PHPUnit tests. ```yaml # .github/workflows/e2e.yml name: E2E Tests on: [push, pull_request] jobs: e2e: runs-on: ubuntu-latest services: database: image: postgres:15 env: POSTGRES_PASSWORD: test options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v4 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: 8.3 extensions: pdo_pgsql - name: Install Chrome uses: browser-actions/setup-chrome@latest - name: Install dependencies run: composer install - name: Setup database run: | bin/console doctrine:database:create --env=test bin/console doctrine:migrations:migrate --no-interaction --env=test bin/console doctrine:fixtures:load --no-interaction --env=test - name: Start server run: symfony server:start -d --no-tls - name: Run E2E tests run: ./vendor/bin/phpunit tests/E2E env: PANTHER_NO_SANDBOX: 1 - name: Upload screenshots if: failure() uses: actions/upload-artifact@v3 with: name: screenshots path: var/screenshots/ ``` -------------------------------- ### OpenAPI Operation Documentation Source: https://github.com/makfly/superpowers-symfony/blob/main/docs/symfony/api-platform.md Provides an example of documenting API operations (endpoints) for OpenAPI, including summaries, descriptions, and parameters. ```APIDOC ## OpenAPI Operation Documentation ### Description This section illustrates how to document API operations, such as retrieving a collection of products, for OpenAPI specifications. ### Operation Documentation Example ```php new GetCollection( openapiContext: [ 'summary' => 'Retrieve the product collection', 'description' => 'Returns a paginated list of all available products', 'parameters' => [ [ 'name' => 'category', 'in' => 'query', 'description' => 'Filter by category ID', 'required' => false, 'schema' => ['type' => 'integer'], ], ], ], ) ``` ``` -------------------------------- ### Defining and Using Foundry Test Factories Source: https://context7.com/makfly/superpowers-symfony/llms.txt Implementation of a persistent factory for User entities and examples of various instantiation methods. ```php */ final class UserFactory extends PersistentProxyObjectFactory { public static function class(): string { return User::class; } protected function defaults(): array { return [ 'email' => self::faker()->unique()->safeEmail(), 'password' => 'hashed_password', 'roles' => ['ROLE_USER'], 'createdAt' => \DateTimeImmutable::createFromMutable( self::faker()->dateTimeBetween('-1 year') ), ]; } // Named states for common variations public function admin(): self { return $this->with(['roles' => ['ROLE_ADMIN']]); } public function verified(): self { return $this->with(['verifiedAt' => new \DateTimeImmutable()]); } public function withPosts(int $count = 3): self { return $this->afterPersist(function (User $user) use ($count) { PostFactory::createMany($count, ['author' => $user]); }); } } // Usage in tests $user = UserFactory::createOne(); $admin = UserFactory::new()->admin()->verified()->create(); $users = UserFactory::createMany(5); $transient = UserFactory::new()->withoutPersisting()->create(); ``` -------------------------------- ### LAZY Fetch Mode Example Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/doctrine-fetch-modes/reference.md Relations are loaded on first access. This can lead to N+1 query problems if not managed carefully. ```php #[ORM\ManyToOne(fetch: 'LAZY')] private User $author; // Usage $post = $em->find(Post::class, 1); $name = $post->getAuthor()->getName(); // Triggers query ``` -------------------------------- ### Unit Test Example: Create Order Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/tdd-with-pest/reference.md A unit test for the OrderService's createOrder method. It uses Zenstruck Foundry to persist a User and then asserts the created Order's properties. ```php orderService = $this->getContainer()->get(OrderService::class); }); it('creates an order for a user', function () { // Arrange $user = persist(User::class, [ 'email' => 'test@example.com', ]); // Act $order = $this->orderService->createOrder($user->object(), [ ['productId' => 1, 'quantity' => 2], ]); // Assert expect($order) ->toBeInstanceOf(Order::class) ->and($order->getCustomer())->toBe($user->object()) ->and($order->getItems())->toHaveCount(1); }); it('throws exception for empty items', function () { $user = persist(User::class); $this->orderService->createOrder($user->object(), []); })->throws(InvalidArgumentException::class, 'Order must have at least one item'); ``` -------------------------------- ### Testing Schedule Logic Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/symfony-scheduler/reference.md Write unit tests for your schedule provider to verify that messages are scheduled correctly. This example checks for the presence and timing of a daily report message. ```php getSchedule(); $messages = $schedule->getRecurringMessages(); // Find the daily report message $dailyReport = array_filter( iterator_to_array($messages), fn($m) => $m->getMessage() instanceof GenerateDailyReport ); $this->assertCount(1, $dailyReport); // Check next run time $message = reset($dailyReport); $trigger = $message->getTrigger(); $nextRun = $trigger->getNextRunDate(new \DateTimeImmutable()); $this->assertEquals('02', $nextRun->format('H')); } } ``` -------------------------------- ### Define Implementation Steps Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/writing-plans/reference.md Checklist format for tracking development phases. ```markdown ## Implementation Steps ### Phase 1: Foundation 1. [ ] Create `OrderStatus` enum 2. [ ] Create `Order` entity with migrations 3. [ ] Create `OrderItem` entity with migrations 4. [ ] Add relation to `User` entity 5. [ ] Run migrations ### Phase 2: Business Logic 6. [ ] Create `OrderService` 7. [ ] Create `ProcessOrder` message 8. [ ] Create `ProcessOrderHandler` 9. [ ] Write unit tests for service ### Phase 3: API 10. [ ] Configure API Platform resource 11. [ ] Add security voters 12. [ ] Write functional tests ### Phase 4: Integration 13. [ ] Connect to payment service 14. [ ] Add email notifications 15. [ ] End-to-end testing ``` -------------------------------- ### Implement Service Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/executing-plans/reference.md Workflow for creating and testing a new service. ```bash # 1. Create test # tests/Unit/Service/OrderServiceTest.php # 2. Create service interface (if needed) # src/Service/OrderServiceInterface.php # 3. Create service # src/Service/OrderService.php # 4. Configure in services.yaml (if needed) # 5. Run tests ./vendor/bin/pest tests/Unit/Service/OrderServiceTest.php ``` -------------------------------- ### Configuration Context Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/effective-context/reference.md Include the current configuration file content. ```text config/packages/messenger.yaml: [current config] I need to add a second transport for high-priority messages. ``` -------------------------------- ### POST /products Source: https://github.com/makfly/superpowers-symfony/blob/main/docs/symfony/api-platform.md Creates a new product resource. ```APIDOC ## POST /products ### Description Create product. ### Method POST ### Endpoint /products ``` -------------------------------- ### API Platform Security Expression Examples Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/api-platform-security/reference.md Provides examples of common security expressions for user roles, current user comparison, object property checks, voter integration, combined conditions, and request data. ```php // User roles security: "is_granted('ROLE_USER')" security: "is_granted('ROLE_ADMIN')" // Current user security: "user == object.getOwner()" security: "object.getAuthor().getId() == user.getId()" // Object properties security: "object.isPublished() or object.getAuthor() == user" security: "object.getStatus() == 'draft' and object.getAuthor() == user" // Voters security: "is_granted('EDIT', object)" security: "is_granted('VIEW', object)" // Combined conditions security: "is_granted('ROLE_ADMIN') or (is_granted('ROLE_USER') and object.getAuthor() == user)" // Request data (for POST/PUT) security: "is_granted('ROLE_ADMIN') or request.get('category') != 'restricted'" ``` -------------------------------- ### Implement Entity Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/executing-plans/reference.md Workflow for creating and migrating a new Doctrine entity. ```bash # 1. Create test # tests/Unit/Entity/OrderTest.php # 2. Create entity bin/console make:entity Order # 3. Adjust entity code # 4. Create migration bin/console make:migration # 5. Run migration bin/console doctrine:migrations:migrate # 6. Verify bin/console doctrine:schema:validate ``` -------------------------------- ### Set Cache-Control Headers Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/symfony-cache/reference.md Demonstrates manual header setting and helper methods for Cache-Control configuration. ```php $response->headers->set('Cache-Control', 'public, max-age=3600, s-maxage=3600'); // Or using methods $response->setPublic(); $response->setPrivate(); $response->setMaxAge(3600); // Browser cache $response->setSharedMaxAge(3600); // CDN/proxy cache $response->setExpires(new \DateTime('+1 hour')); ``` -------------------------------- ### GET /products/{id} Source: https://github.com/makfly/superpowers-symfony/blob/main/docs/symfony/api-platform.md Retrieves a single product by its ID. ```APIDOC ## GET /products/{id} ### Description Get single product. ### Method GET ### Endpoint /products/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the product. ``` -------------------------------- ### View project directory structure Source: https://github.com/makfly/superpowers-symfony/blob/main/README.md Overview of the plugin's file organization, including agents, skills, and command definitions. ```text superpowers-symfony/ ├── .claude-plugin/ │ ├── marketplace.json # Marketplace catalog │ └── plugin.json # Plugin manifest ├── agents/ # 4 specialized subagents │ ├── symfony-reviewer.md │ ├── symfony-tdd-coach.md │ ├── doctrine-architect.md │ └── api-platform-builder.md ├── skills/ # 43 skill definitions │ ├── tdd-with-pest/ │ │ └── SKILL.md │ ├── doctrine-relations/ │ │ ├── SKILL.md │ │ └── reference.md │ └── ... ├── commands/ # 13 slash commands │ ├── brainstorm.md │ ├── write-plan.md │ └── ... ├── hooks/ │ ├── hooks.json # SessionStart hook config │ └── session-start.sh # Auto-detection script ├── docs/ # Additional documentation ├── scripts/ # Validation scripts ├── LICENSE └── README.md ``` -------------------------------- ### Environment-Specific Configuration with 'when@' Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/config-env-parameters/reference.md Demonstrates how to apply configuration settings conditionally based on the environment using `when@` blocks within YAML configuration files. This allows for environment-specific tuning of framework features. ```yaml # config/packages/framework.yaml when@dev: framework: profiler: collect: true when@prod: framework: profiler: collect: false when@test: framework: test: true ``` -------------------------------- ### Using Parameters in PHP Services Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/config-env-parameters/reference.md Demonstrates how to inject parameters defined in `services.yaml` into PHP services using constructor property promotion and autowiring. Parameters can also be bound directly in `services.yaml`. ```php createUser('test@example.com'); $this->assertNotNull($repository->findByEmail('test@example.com')); } ``` -------------------------------- ### Defining Parameters in services.yaml Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/config-env-parameters/reference.md Shows how to define application parameters in `services.yaml`, including direct values, environment variable references, and type-casted environment variables. ```yaml # config/services.yaml parameters: app.admin_email: 'admin@example.com' app.items_per_page: 20 app.supported_locales: ['en', 'fr', 'de'] # Using environment variables app.database_url: '%env(DATABASE_URL)%' app.stripe_key: '%env(STRIPE_API_KEY)%' # Type casting app.port: '%env(int:APP_PORT)%' app.debug: '%env(bool:APP_DEBUG)%' app.hosts: '%env(json:ALLOWED_HOSTS)%' ``` -------------------------------- ### GET /api/products (Filtering) Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/api-platform-filters/reference.md Endpoints for retrieving products with various filtering capabilities applied. ```APIDOC ## GET /api/products ### Description Retrieve a collection of products with optional filters applied via query parameters. ### Method GET ### Endpoint /api/products ### Parameters #### Query Parameters - **name** (string) - Optional - Search by name (partial match) - **category.name** (string) - Optional - Filter by related category name (exact match) - **createdAt** (date) - Optional - Filter by date (supports [after], [before], [strictly_after], [strictly_before]) - **price** (number) - Optional - Filter by price range (supports [gte], [lte], [gt], [lt], [between]) - **stock** (number) - Optional - Filter by stock level (supports [gt], [gte], [lt], [lte]) - **isActive** (boolean) - Optional - Filter by active status - **isFeatured** (boolean) - Optional - Filter by featured status - **order** (array) - Optional - Sort results (e.g., order[price]=desc) - **exists** (boolean) - Optional - Filter by existence of field (e.g., exists[deletedAt]=false) - **active** (boolean) - Optional - Custom filter for active products (not deleted) ### Response #### Success Response (200) - **collection** (array) - List of product objects ``` -------------------------------- ### Service Prioritization with Tags Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/strategy-pattern/reference.md Demonstrates how to assign priorities to tagged services. Higher priority values indicate earlier evaluation. ```php #[AutoconfigureTag('app.payment_processor', ['priority' => 10])] class StripeProcessor implements PaymentProcessorInterface { // Higher priority = checked first } ``` ```php #[AutoconfigureTag('app.payment_processor', ['priority' => 0])] class FallbackProcessor implements PaymentProcessorInterface { // Lower priority = fallback } ``` -------------------------------- ### Define Order Entity Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/writing-plans/reference.md Example of a Doctrine entity definition using PHP 8 attributes. ```php #[ORM\Entity] class Order { #[ORM\Id] #[ORM\Column(type: 'uuid')] private Uuid $id; #[ORM\ManyToOne(targetEntity: User::class)] private User $customer; #[ORM\Column(type: 'string', enumType: OrderStatus::class)] private OrderStatus $status; #[ORM\OneToMany(targetEntity: OrderItem::class, mappedBy: 'order')] private Collection $items; } ``` -------------------------------- ### Define Versioned DTO Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/api-platform-versioning/reference.md Example of a versioned Data Transfer Object documenting changes from v1 to v2. ```php prophesize(PaymentGateway::class); // Stub method $gateway->charge(1000, 'EUR') ->willReturn(new PaymentResult(success: true)); // Reveal to get actual mock $service = new OrderService($gateway->reveal()); $result = $service->processPayment(1000, 'EUR'); $this->assertTrue($result->isSuccessful()); } public function testCallsGatewayOnce(): void { $gateway = $this->prophesize(PaymentGateway::class); // Expect call $gateway->charge(1000, 'EUR') ->shouldBeCalledOnce() ->willReturn(new PaymentResult(success: true)); $service = new OrderService($gateway->reveal()); $service->processPayment(1000, 'EUR'); } } ``` -------------------------------- ### OpenAPI Property Documentation Source: https://github.com/makfly/superpowers-symfony/blob/main/docs/symfony/api-platform.md Shows how to document individual properties of an entity for OpenAPI specifications, including descriptions and examples. ```APIDOC ## OpenAPI Property Documentation ### Description This section details how to add specific documentation to entity properties for OpenAPI, enhancing API discoverability. ### Property Documentation Example ```php use ApiPlatform\Metadata\ApiProperty; class Product { #[ApiProperty( description: 'The unique identifier', readable: true, writable: false, example: 123, )] private ?int $id = null; #[ApiProperty( description: 'Product name', example: 'Wireless Keyboard', )] private string $name; } ``` ``` -------------------------------- ### Implement API Endpoint Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/executing-plans/reference.md Workflow for creating and testing an API Platform resource. ```bash # 1. Create functional test # tests/Functional/Api/OrderTest.php # 2. Configure API Platform resource # 3. Create/configure voter # 4. Run tests ./vendor/bin/pest tests/Functional/Api/OrderTest.php # 5. Verify in browser/Postman curl http://localhost/api/orders ``` -------------------------------- ### Configure Pagination Options Source: https://github.com/makfly/superpowers-symfony/blob/main/docs/symfony/api-platform.md Set default and maximum items per page, and enable client-side control over pagination. ```php #[ApiResource( paginationEnabled: true, // Enable pagination paginationItemsPerPage: 20, // Default items per page paginationMaximumItemsPerPage: 100, // Maximum allowed paginationClientEnabled: true, // Allow client to enable/disable paginationClientItemsPerPage: true, // Allow client to change page size )] ``` -------------------------------- ### Full Error Message Context Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/effective-context/reference.md Include the full stack trace, the entity, and the migration code. ```text When I run bin/console doctrine:migrations:migrate, I get: [Error message with full stack trace] My entity is: [entity code] My migration is: [migration code] ``` -------------------------------- ### Invoke Superpowers Symfony Slash Commands Source: https://github.com/makfly/superpowers-symfony/blob/main/README.md These are examples of how to invoke general slash commands provided by the Superpowers Symfony plugin. ```bash /brainstorm /write-plan /execute-plan /symfony-check ``` -------------------------------- ### Define a Custom Operation Source: https://github.com/makfly/superpowers-symfony/blob/main/docs/symfony/api-platform.md Add a custom operation like 'publish' to a resource. This example uses a specific controller and disables reading. ```php #[ApiResource( operations: [ // Standard operations... new Post( uriTemplate: '/products/{id}/publish', controller: PublishProductController::class, name: 'publish_product', read: false, openapiContext: [ 'summary' => 'Publish a product', 'requestBody' => [ 'content' => [ 'application/json' => [ 'schema' => [], ], ], ], ], ), ], )] ``` -------------------------------- ### Invoke Superpowers Symfony Skills Source: https://github.com/makfly/superpowers-symfony/blob/main/README.md These are examples of how to invoke specific skills provided by the Superpowers Symfony plugin using the /skill-name format. ```bash /symfony:tdd-with-pest /symfony:doctrine-relations /symfony:api-platform-dto-resources ``` -------------------------------- ### EAGER Fetch Mode Example Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/doctrine-fetch-modes/reference.md Relations are always loaded with the parent entity. Use this mode sparingly as it can increase initial load times. ```php #[ORM\ManyToOne(fetch: 'EAGER')] private User $author; // Usage - author loaded in same query $post = $em->find(Post::class, 1); $name = $post->getAuthor()->getName(); // No extra query ``` -------------------------------- ### Proxy Objects and Initialization Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/doctrine-fetch-modes/reference.md Illustrates how Doctrine uses proxy objects for lazy loading. It shows how to check if a proxy is initialized and how to force its initialization. ```php // $post->getAuthor() returns a Proxy, not User $author = $post->getAuthor(); // Proxy is a subclass of User $author instanceof User; // true // Check if proxy is initialized $em->getUnitOfWork()->isInIdentityMap($author); // true if loaded // Force initialization $em->getUnitOfWork()->initializeObject($author); ``` -------------------------------- ### Inject Cache Service for Product Retrieval Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/symfony-cache/reference.md Inject the CacheInterface to get or compute product data. Cache items expire after 1 hour. ```php cache->get("product_{$id}", function (ItemInterface $item) use ($id) { $item->expiresAfter(3600); // 1 hour return $this->repository->find($id); }); } } ``` -------------------------------- ### PSR-6 Cache Item Pool Usage Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/symfony-cache/reference.md Utilize the PSR-6 CacheItemPoolInterface for cache operations, including getting, setting, and saving cache items with expiration. ```php cache->getItem($key); if (!$item->isHit()) { $item->set($this->fetchData()); $item->expiresAfter(3600); $this->cache->save($item); } return $item->get(); } ``` -------------------------------- ### Define Implementation Plan Structure Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/writing-plans/reference.md Standard template for outlining feature scope, dependencies, and technical design. ```markdown # Implementation Plan: [Feature Name] ## Summary [1-2 sentence description of what we're building] ## Scope - IN: [What's included] - OUT: [What's explicitly excluded] ## Dependencies - [Required packages] - [Existing services/entities to modify] - [External services] ``` -------------------------------- ### Query-Level Fetch Mode Override Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/doctrine-fetch-modes/reference.md Overrides the entity mapping's fetch mode for a specific query. This example forces the 'author' relation to be eagerly loaded. ```php createQueryBuilder('p') ->where('p.id = :id') ->setParameter('id', $id) ->getQuery() ->setFetchMode(Post::class, 'author', ClassMetadata::FETCH_EAGER) ->getOneOrNullResult(); } ``` -------------------------------- ### Refactor Fat Controller to Lean Controller Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/controller-cleanup/reference.md This example shows a 'fat' controller with extensive validation and business logic. It's intended to be refactored into a leaner structure. ```php getContent(), true); // Validation logic in controller if (empty($data['items'])) { return new JsonResponse(['error' => 'Items required'], 400); } // Business logic in controller $order = new Order(); $order->setCustomer($this->getUser()); $order->setStatus('pending'); $total = 0; foreach ($data['items'] as $itemData) { $product = $this->em->find(Product::class, $itemData['productId']); if (!$product) { return new JsonResponse(['error' => 'Product not found'], 400); } if ($product->getStock() < $itemData['quantity']) { return new JsonResponse(['error' => 'Insufficient stock'], 400); } $item = new OrderItem(); $item->setProduct($product); $item->setQuantity($itemData['quantity']); $item->setPrice($product->getPrice()); $order->addItem($item); $total += $product->getPrice() * $itemData['quantity']; $product->setStock($product->getStock() - $itemData['quantity']); } $order->setTotal($total); // Coupon logic if (!empty($data['coupon'])) { $coupon = $this->em->getRepository(Coupon::class) ->findOneBy(['code' => $data['coupon']]); if ($coupon && $coupon->isValid()) { $discount = $total * ($coupon->getDiscount() / 100); $order->setDiscount($discount); $order->setTotal($total - $discount); } } $this->em->persist($order); $this->em->flush(); // Send email $email = (new Email()) ->to($this->getUser()->getEmail()) ->subject('Order Confirmation') ->text('Your order has been placed.'); $this->mailer->send($email); return new JsonResponse(['id' => $order->getId()], 201); } ``` -------------------------------- ### Local Development Overrides with .env.local Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/config-env-parameters/reference.md Example of using the `.env.local` file to override default environment variables for local development. This file should not be committed to version control. ```bash # .env.local (not committed) DATABASE_URL="postgresql://dev:dev@localhost:5432/myapp_dev" MAILER_DSN=smtp://localhost:1025 ``` -------------------------------- ### Backward Compatibility Context Source: https://github.com/makfly/superpowers-symfony/blob/main/skills/effective-context/reference.md Include the current response format to ensure changes do not break existing clients. ```text I need to add a new field to the API response without breaking existing clients. Current response format: [JSON example] ```