### Starting Development Servers (Bash) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md Commands to start the necessary development servers. This includes the Symfony development server and Webpack Encore's watch mode for automatic asset recompilation during development. Asset Mapper watch mode is an alternative. ```bash # Start Symfony development server symfony server:start # Start Webpack Encore in watch mode (if using Encore) npm run watch # Or start Asset Mapper watch mode php/console asset-map:compile --watch ``` -------------------------------- ### CORS Configuration Example (YAML) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md Configuration for Nelmio CORS bundle to handle Cross-Origin Resource Sharing. This example sets default origins and methods, and specifically allows all origins, headers, and methods for the '/api/' path. ```yaml # config/packages/nelmio_cors.yaml nelmio_cors: defaults: origin_regex: true allow_origin: ['^http://localhost:[0-9]+$'] allow_methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'] allow_headers: ['Content-Type', 'Authorization', 'X-Requested-With'] expose_headers: ['Content-Range', 'X-Content-Range'] max_age: 3600 paths: '^/api/': allow_origin: ['*'] allow_headers: ['*'] allow_methods: ['*'] max_age: 3600 ``` -------------------------------- ### Admin Controller Example (PHP) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md A basic Symfony controller that renders the admin interface template. This controller is routed to '/admin' and serves as the entry point for the React Admin application. ```php render('admin/index.html.twig'); } } ``` -------------------------------- ### Start Development Server Commands Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/usage_example.md These bash commands are used to start the development environment. They include starting the Symfony development server and initiating asset compilation using npm watch, which is common when using tools like Webpack Encore for managing frontend assets. ```bash # Start Symfony development server symfony server:start # Start asset compilation (if using Webpack Encore) npm run watch ``` -------------------------------- ### Testing API Endpoints (Bash) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md Example curl commands to test the API endpoints for listing users and retrieving a single user. These commands help verify that your API is functioning correctly. ```bash # Test list endpoint curl http://localhost:8080/api/users # Test single resource curl http://localhost:8080/api/users/1 ``` -------------------------------- ### Install Frontend Assets for React Admin Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/usage_example.md Installs the `react-admin` library and the bundle's data provider using npm. This step is crucial for setting up the frontend administration interface that will interact with the backend API. ```bash # Install React Admin and the bundle's data provider npm install react-admin @freema/react-admin-api-bundle ``` -------------------------------- ### React Admin Template Setup (Twig) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md This Twig template provides the basic HTML structure for the React Admin interface. It includes necessary tags for asset bundling (using Symfony Encore or Asset Mapper) and a div element where the React application will be mounted. ```twig {# templates/admin/index.html.twig #} Admin Panel {{ encore_entry_link_tags('admin') }}
{{ encore_entry_script_tags('admin') }} ``` -------------------------------- ### Building Production Assets (Bash) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md Commands to build optimized assets for production. Use 'npm run build' for Webpack Encore or 'php bin/console asset-map:compile' for Asset Mapper. ```bash # For Webpack Encore npm run build # For Asset Mapper php/console asset-map:compile ``` -------------------------------- ### Install React Admin API Bundle via Composer Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md Installs the React Admin API Bundle into your Symfony project using Composer. This command fetches the bundle and its dependencies. ```bash composer require freema/react-admin-api-bundle ``` -------------------------------- ### Complete React Admin App Setup Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/frontend-integration.md This example provides a foundational setup for a complete React Admin application. It imports necessary components from `react-admin` and the `createDataProvider` function from the API bundle. It configures the `Admin` component with the data provider and defines resources like 'users' and 'posts' using `ListGuesser` for automatic list view generation. ```javascript import React from 'react'; import { Admin, Resource, ListGuesser } from 'react-admin'; import { createDataProvider } from '@freema/react-admin-api-bundle'; const dataProvider = createDataProvider('http://localhost:8080/api'); const App = () => ( ); export default App; ``` -------------------------------- ### Install React Admin API Bundle via npm/yarn Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md Installs the React Admin API Bundle's frontend package using npm or yarn. This command adds the necessary package to your project's `node_modules` directory for use with Webpack Encore. ```bash npm install @freema/react-admin-api-bundle # or yarn add @freema/react-admin-api-bundle ``` -------------------------------- ### Simple REST Compatibility - GET Request Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/data-providers.md Example GET request format compatible with ra-data-simple-rest, using different parameter names for sorting and pagination. ```APIDOC ## GET /api/users (Simple REST Format) ### Description Retrieves a list of users using the `ra-data-simple-rest` compatible format, with sorting and range-based pagination. ### Method GET ### Endpoint /api/users ### Query Parameters - **sort** (array) - Optional - An array containing the sort field and order (e.g., `["name","ASC"]`). - **range** (array) - Optional - An array defining the start and end index for pagination (e.g., `[0,9]`). - **filter** (object) - Optional - A JSON object for filtering data. ### Response #### Success Response (200) - **data** (array) - An array of user objects. - **total** (integer) - The total number of users available. #### Response Example ```json { "data": [ {"id": 1, "name": "John Doe", "email": "john@example.com"}, {"id": 2, "name": "Jane Smith", "email": "jane@example.com"} ], "total": 25 } ``` ``` -------------------------------- ### Initializing React Admin with API Bundle (JavaScript) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md This JavaScript code sets up a new React Admin application. It imports necessary components, creates a data provider instance pointing to your API, and defines resources. Ensure the API URL is correct. ```javascript // assets/admin.js import React from 'react'; import { createRoot } from 'react-dom/client'; import { Admin, Resource, ListGuesser } from 'react-admin'; import { createDataProvider } from '@freema/react-admin-api-bundle'; const dataProvider = createDataProvider('http://localhost:8080/api'); const App = () => ( ); const container = document.getElementById('admin-app'); const root = createRoot(container); root.render(); ``` -------------------------------- ### Install Frontend Assets with Symfony Asset Mapper Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md Installs frontend assets for the React Admin API Bundle when using Symfony's Asset Mapper. This command copies necessary files to the public directory. It's typically followed by configuration in `asset_mapper.yaml`. ```bash php bin/console assets:install ``` -------------------------------- ### Custom Data Provider - GET Request Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/data-providers.md Example GET request format for the custom data provider, including sorting, pagination, and filtering. ```APIDOC ## GET /api/users ### Description Retrieves a list of users with advanced filtering, sorting, and pagination capabilities. ### Method GET ### Endpoint /api/users ### Query Parameters - **sort_field** (string) - Optional - The field to sort by. - **sort_order** (string) - Optional - The order of sorting (ASC or DESC). - **page** (integer) - Optional - The page number for pagination. - **per_page** (integer) - Optional - The number of items per page. - **filter** (object) - Optional - A JSON object for filtering data. ### Response #### Success Response (200) - **data** (array) - An array of user objects. - **total** (integer) - The total number of users available. #### Response Example ```json { "data": [ {"id": 1, "name": "John Doe", "email": "john@example.com"}, {"id": 2, "name": "Jane Smith", "email": "jane@example.com"} ], "total": 25 } ``` ``` -------------------------------- ### Debug Commands (Bash) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md A collection of helpful Symfony console commands for debugging the application. These commands can inspect configuration, routes, services, and clear the cache. ```bash # Check bundle configuration php/console debug:config react_admin_api # List all routes php/console debug:router # Check services php/console debug:container react_admin_api # Clear cache php/console cache:clear ``` -------------------------------- ### Test API Endpoints with cURL Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/usage_example.md This section provides cURL commands to test various API endpoints for managing users. It covers testing the list endpoint, retrieving a single user, creating a new user via POST, updating a user via PUT, and deleting a user. These examples demonstrate how to interact with the API and include necessary headers and JSON payloads. ```bash # Test list endpoint curl http://localhost:8080/api/users # Test single resource curl http://localhost:8080/api/users/1 # Test create (POST) curl -X POST http://localhost:8080/api/users \ -H "Content-Type: application/json" \ -d '{"name": "John Doe", "email": "john@example.com", "roles": ["ROLE_USER"]}' # Test update (PUT) curl -X PUT http://localhost:8080/api/users/1 \ -H "Content-Type: application/json" \ -d '{"name": "John Smith", "email": "john.smith@example.com"}' # Test delete curl -X DELETE http://localhost:8080/api/users/1 ``` -------------------------------- ### Copying Assets Manually (Bash) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md This command copies the compiled assets from the bundle's distribution directory to the public JavaScript directory. Ensure the destination path is correctly configured in your project. ```bash cp -r vendor/freema/react-admin-api-bundle/assets/dist/* public/js/ ``` -------------------------------- ### Service Registration Example (YAML) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/clean-architecture-integration.md Demonstrates how to register services in Symfony's `services.yaml` file, mapping a Domain interface to its Infrastructure layer implementation. This configuration ensures the correct repository is used throughout the application. ```yaml services: # Domain interface -> Infrastructure implementation Discussion\Domain\Repository\PostRepository: class: Discussion\Infrastructure\Persistence\Doctrine\Repository\PostRepository # React Admin interfaces are automatically available ``` -------------------------------- ### User API Endpoints Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/usage_example.md This section details the API endpoints for managing users, including listing, retrieving, creating, updating, and deleting users. ```APIDOC ## GET /api/users ### Description Retrieves a list of users. Supports pagination and sorting. ### Method GET ### Endpoint /api/users ### Query Parameters - **sort_field** (string) - Optional - The field to sort by. - **sort_order** (string) - Optional - The order of sorting (ASC or DESC). - **page** (integer) - Optional - The page number for pagination. - **per_page** (integer) - Optional - The number of items per page. - **sort** (string) - Optional - Sorting parameter for simple REST provider format (e.g., `["name","ASC"]`). - **range** (string) - Optional - Range parameter for simple REST provider format (e.g., `[0,9]`). ### Response #### Success Response (200) - **users** (array) - An array of user objects. #### Response Example ```json { "users": [ { "id": 1, "name": "John Doe", "email": "john@example.com", "active": true, "roles": ["ROLE_USER"], "createdAt": "2023-10-27T10:00:00Z" } ] } ``` ``` ```APIDOC ## GET /api/users/{id} ### Description Retrieves a single user by their ID. ### Method GET ### Endpoint /api/users/{id} ### Path Parameters - **id** (integer) - Required - The ID of the user to retrieve. ### Response #### Success Response (200) - **user** (object) - The user object. #### Response Example ```json { "id": 1, "name": "John Doe", "email": "john@example.com", "active": true, "roles": ["ROLE_USER"], "createdAt": "2023-10-27T10:00:00Z" } ``` ``` ```APIDOC ## POST /api/users ### Description Creates a new user. ### Method POST ### Endpoint /api/users ### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. - **roles** (array) - Optional - An array of roles for the user (e.g., `["ROLE_USER"]`). ### Request Example ```json { "name": "John Doe", "email": "john@example.com", "roles": ["ROLE_USER"] } ``` ### Response #### Success Response (200) - **user** (object) - The newly created user object. #### Response Example ```json { "id": 2, "name": "John Doe", "email": "john@example.com", "active": true, "roles": ["ROLE_USER"], "createdAt": "2023-10-27T10:05:00Z" } ``` ``` ```APIDOC ## PUT /api/users/{id} ### Description Updates an existing user by their ID. ### Method PUT ### Endpoint /api/users/{id} ### Path Parameters - **id** (integer) - Required - The ID of the user to update. ### Request Body - **name** (string) - Required - The updated name of the user. - **email** (string) - Required - The updated email address of the user. - **roles** (array) - Optional - An array of updated roles for the user. ### Request Example ```json { "name": "John Smith", "email": "john.smith@example.com", "roles": ["ROLE_USER", "ROLE_ADMIN"] } ``` ### Response #### Success Response (200) - **user** (object) - The updated user object. #### Response Example ```json { "id": 1, "name": "John Smith", "email": "john.smith@example.com", "active": true, "roles": ["ROLE_USER", "ROLE_ADMIN"], "createdAt": "2023-10-27T10:00:00Z" } ``` ``` ```APIDOC ## DELETE /api/users/{id} ### Description Deletes a user by their ID. ### Method DELETE ### Endpoint /api/users/{id} ### Path Parameters - **id** (integer) - Required - The ID of the user to delete. ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the user was deleted. #### Response Example ```json { "message": "User with ID 1 deleted successfully." } ``` ``` -------------------------------- ### Build and Watch Assets (Bash) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/data-providers.md Commands for managing frontend assets during development of the React Admin API Bundle. Includes installing dependencies, building assets, and watching for changes to automatically rebuild. ```bash # Install dependencies task assets:install # Build assets task assets:build # Watch for changes task assets:watch # Start development with assets watching task dev:with-assets ``` -------------------------------- ### Error Handling Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/usage_example.md Details the structure of error responses provided by the API. ```APIDOC ## Error Response ### Description The API returns structured error responses to indicate issues. ### Response Example ```json { "error": "DTO_CLASS_NOT_FOUND", "message": "DTO class 'App\\Dto\\NonExistentDto' does not exist. Please check the class name and make sure it's properly loaded.", "code": 500 } ``` ### Error Codes - **DTO_CLASS_NOT_FOUND**: Indicates that a specified DTO class could not be found. ``` -------------------------------- ### Test User DTO Creation and Conversion (PHP) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/usage_example.md Unit tests for the UserDto class to verify its functionality. It includes tests for creating a UserDto from a User entity and for converting a UserDto to an array. Dependencies include PHPUnit, the User entity, and the UserDto. ```php setName('John Doe'); $user->setEmail('john@example.com'); $user->setActive(true); $user->setRoles(['ROLE_USER']); $dto = UserDto::createFromEntity($user); $this->assertEquals('John Doe', $dto->name); $this->assertEquals('john@example.com', $dto->email); $this->assertTrue($dto->active); $this->assertEquals(['ROLE_USER'], $dto->roles); } public function testToArray(): void { $dto = new UserDto(); $dto->id = 1; $dto->name = 'John Doe'; $dto->email = 'john@example.com'; $dto->active = true; $dto->roles = ['ROLE_USER']; $array = $dto->toArray(); $this->assertEquals([ 'id' => 1, 'name' => 'John Doe', 'email' => 'john@example.com', 'active' => true, 'roles' => ['ROLE_USER'], 'createdAt' => null, ], $array); } } ``` -------------------------------- ### Development Exception Listener Configuration (YAML) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md This configuration enables debug mode for the React Admin API bundle's exception listener during development. This provides more detailed error information in the browser. ```yaml # config/packages/dev/react_admin_api.yaml react_admin_api: exception_listener: debug_mode: true ``` -------------------------------- ### Create Custom UserRepository for User Entity Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/usage_example.md Defines a custom Doctrine repository for the User entity, extending `ServiceEntityRepository`. This allows for the addition of custom query methods, such as `findActiveUsers`, to perform specific data retrieval operations. ```php createQueryBuilder('u') ->andWhere('u.active = :active') ->setParameter('active', true) ->orderBy('u.name', 'ASC') ->getQuery() ->getResult(); } } ``` -------------------------------- ### Configure API Routes for React Admin API Bundle Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md Sets up the necessary routing for the React Admin API Bundle in your Symfony application. This involves defining a resource in `config/routes.yaml` and specifying a base API prefix. ```yaml react_admin_api: resource: "@ReactAdminApiBundle/Resources/config/routing.yaml" prefix: /api ``` -------------------------------- ### Configure React Admin API Bundle Exception Listener Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md Optional configuration for the React Admin API Bundle's exception listener. This allows enabling or disabling exception handling and setting a debug mode for development environments. ```yaml react_admin_api: exception_listener: enabled: true debug_mode: false # Set to true in dev environment ``` -------------------------------- ### Enable React Admin API Bundle in Symfony Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md Configures Symfony to recognize and load the React Admin API Bundle. This is typically done by adding the bundle class to your `config/bundles.php` file. Symfony Flex may handle this automatically. ```php ['all' => true], ]; ``` -------------------------------- ### Create DTOs Implementing DtoInterface Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md Defines Data Transfer Objects (DTOs) for your entities, implementing the `DtoInterface`. This includes methods for converting to an array and creating DTOs from entity objects. It specifies the mapped entity class. ```php $this->id, 'name' => $this->name, 'email' => $this->email, 'active' => $this->active, 'createdAt' => $this->createdAt, ]; } public static function getMappedEntityClass(): string { return 'App\\Entity\\User'; } public static function createFromEntity($entity): self { $dto = new self(); $dto->id = $entity->getId(); $dto->name = $entity->getName(); $dto->email = $entity->getEmail(); $dto->active = $entity->isActive(); $dto->createdAt = $entity->getCreatedAt(); return $dto; } } ``` -------------------------------- ### Implement Data Repository Interfaces for Entities Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md Ensures your Doctrine repository classes implement the necessary interfaces provided by the React Admin API Bundle to handle data operations like listing, finding, creating, updating, and deleting entities. It also utilizes provided traits. ```php ( ); export default App; ``` -------------------------------- ### Install Frontend Assets with Asset Mapper (Bash) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/frontend-integration.md Installs frontend assets for the React Admin API Bundle using Symfony's Asset Mapper. This includes commands to install assets directly or manage them via importmap. ```bash php bin/console assets:install # Or use the importmap php bin/console importmap:require @freema/react-admin-api-bundle ``` -------------------------------- ### Install Frontend Assets with Webpack Encore (Bash) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/frontend-integration.md Installs frontend assets for the React Admin API Bundle using npm or yarn, typically in conjunction with Webpack Encore for asset management in a JavaScript project. ```bash # Install via npm/yarn npm install @freema/react-admin-api-bundle # or yarn add @freema/react-admin-api-bundle ``` -------------------------------- ### Configure Routing for React Admin API Bundle Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/usage_example.md Configures the routing for the ReactAdminApiBundle in Symfony. This step defines the API endpoint prefix and points to the bundle's routing resource file, enabling API access. ```yaml react_admin_api: resource: "@ReactAdminApiBundle/Resources/config/routing.yaml" prefix: /api ``` -------------------------------- ### Infrastructure Repository Implementation with React Admin (PHP) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/clean-architecture-integration.md Provides an example of an Infrastructure Repository implementation that adheres to both the Domain's repository interface and React Admin's interfaces. It includes the use of traits for React Admin functionality. ```php // src/Infrastructure/Persistence/Doctrine/Repository/PostRepository.php class PostRepository extends ServiceEntityRepository implements \Discussion\Domain\Repository\PostRepository, // Domain interface DataRepositoryListInterface, // React Admin interface DataRepositoryFindInterface // React Admin interface { use ListTrait; // React Admin functionality // Domain methods implementation public function findByAuthor(Author $author): array { } public function save(Post $post): void { } // React Admin methods implementation public function getFullSearchFields(): array { } public static function mapToDto(AdminEntityInterface $entity): AdminApiDto { } } ``` -------------------------------- ### Simple REST Compatibility Frontend Integration (JavaScript) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/data-providers.md Allows existing React Admin applications to continue using `ra-data-simple-rest` for compatibility. The backend automatically detects and handles requests in this format, ensuring seamless integration with older setups. ```javascript import simpleRestProvider from 'ra-data-simple-rest'; const dataProvider = simpleRestProvider('http://localhost:8080/api'); ``` -------------------------------- ### Create Resource (Bash) Source: https://context7.com/freema/react-admin-api-bundle/llms.txt Creates a new resource by sending JSON data to the API. The bundle automatically handles validation, returning success or detailed validation errors. ```bash curl -X POST "http://localhost:8080/api/users" \ -H "Content-Type: application/json" \ -d '{ "name": "New User", "email": "newuser@example.com", "roles": ["ROLE_USER"] }' # Success response (201) { "id": 26, "name": "New User", "email": "newuser@example.com", "roles": ["ROLE_USER"], "createdAt": "2024-01-20T09:15:00+00:00" } # Validation error response (400) { "error": "Validation failed", "violations": [ { "propertyPath": "email", "message": "This value is not a valid email address." }, { "propertyPath": "name", "message": "This value should not be blank." } ] } ``` -------------------------------- ### Including Data Provider Script in HTML (HTML) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md This HTML snippet demonstrates how to include the data provider JavaScript file in your application's HTML. This script is necessary for the frontend to communicate with the backend API. ```html ``` -------------------------------- ### Configure Asset Mapper for React Admin API Bundle Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md Configures Symfony's Asset Mapper to include the bundle's frontend assets. This involves specifying paths to the bundle's assets directory in your `config/packages/asset_mapper.yaml` file. ```yaml framework: asset_mapper: paths: - assets/ - vendor/freema/react-admin-api-bundle/assets/dist/ ``` -------------------------------- ### Building Assets Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/data-providers.md Commands for building and watching assets when developing the bundle. ```APIDOC ## Building Assets ### Description Commands to manage frontend assets during development of the bundle. ### Request Example ```bash # Install dependencies task assets:install # Build assets task assets:build # Watch for changes task assets:watch # Start development with assets watching task dev:with-assets ``` ``` -------------------------------- ### Unit Tests Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/data-providers.md Commands for running unit tests for the bundle using PHPUnit. ```APIDOC ## Unit Tests ### Description Instructions for running the comprehensive unit tests included with the bundle. ### Request Example ```bash # Run all tests docker exec react-admin-api-bundle-app ./vendor/bin/phpunit # Run specific test docker exec react-admin-api-bundle-app ./vendor/bin/phpunit tests/Service/DtoFactoryTest.php ``` ``` -------------------------------- ### Import Data Provider in Frontend JavaScript (Asset Mapper) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md Imports the `createDataProvider` function from the React Admin API Bundle into your frontend JavaScript code when using the Symfony Asset Mapper. This function is used to initialize the data provider for your React Admin application. ```javascript import { createDataProvider } from '@freema/react-admin-api-bundle'; ``` -------------------------------- ### Run Unit Tests (Bash) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/data-providers.md Commands for executing unit tests within the React Admin API Bundle using PHPUnit. Allows running all tests or targeting specific test files for focused testing. ```bash # Run all tests docker exec react-admin-api-bundle-app ./vendor/bin/phpunit # Run specific test docker exec react-admin-api-bundle-app ./vendor/bin/phpunit tests/Service/DtoFactoryTest.php ``` -------------------------------- ### Create React Admin App with API Data Provider Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/usage_example.md This snippet demonstrates how to initialize a React Admin application using the createDataProvider function from the '@freema/react-admin-api-bundle'. It configures the data provider with a base API URL and sets up a 'users' resource with associated list, edit, create, and show components. The application is then rendered into a DOM element with the ID 'admin-app'. ```javascript // assets/admin.js import React from 'react'; import { createRoot } from 'react-dom/client'; import { Admin, Resource } from 'react-admin'; import { createDataProvider } from '@freema/react-admin-api-bundle'; import { UserList, UserEdit, UserCreate, UserShow } from './users'; const dataProvider = createDataProvider('http://localhost:8080/api'); const App = () => ( ); const container = document.getElementById('admin-app'); const root = createRoot(container); root.render(); ``` -------------------------------- ### Configure Webpack Encore for React Admin API Bundle Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/installation.md Configures Webpack Encore to build your frontend assets, including those from the React Admin API Bundle. This involves setting output paths, public paths, entry points, and enabling necessary presets like React and TypeScript. ```javascript const Encore = require('@symfony/webpack-encore'); Encore .setOutputPath('public/build/') .setPublicPath('/build') .addEntry('admin', './assets/admin.js') .enableReactPreset() .enableTypeScriptLoader() // ... other configuration ``` -------------------------------- ### React Admin Data Provider Compatibility Formats Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/usage_example.md This section outlines the two data provider formats supported by the bundle: the custom provider format, which is recommended and includes parameters for sorting, pagination, and items per page, and the simple REST provider format, which uses different parameter structures for sorting and range. ```http **Custom Provider** (recommended): GET /api/users?sort_field=name&sort_order=ASC&page=1&per_page=10 **Simple REST Provider** (compatibility): GET /api/users?sort=["name","ASC"]&range=[0,9] ``` -------------------------------- ### Frontend Filter Examples (JavaScript) Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/repositories.md Provides examples of how to construct filter objects in JavaScript for use with the backend filtering configuration. These examples demonstrate standard field filters, association filters, custom filters, and combining multiple filter types, including full-text search. ```javascript // Standard field filter (entity has 'status' field) const filters = { status: 'active' }; // Association filter (entity has 'company' association) const filters = { companyId: 123 }; // Custom filter (no 'isActive' field on entity) const filters = { isActive: 'true' }; // Multiple filters const filters = { status: 'active', companyId: [1, 2, 3], hasParent: 'false', q: 'search term' }; ``` -------------------------------- ### React Admin App with Authentication Provider Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/frontend-integration.md This example demonstrates setting up a React Admin application with a custom authentication provider. It shows how to define the `login`, `logout`, `checkAuth`, `checkError`, and `getPermissions` methods required by React Admin's `authProvider`. The `dataProvider` is configured separately, and the `Admin` component integrates both. ```javascript import React from 'react'; import { Admin, Resource } from 'react-admin'; import { createDataProvider } from '@freema/react-admin-api-bundle'; const dataProvider = createDataProvider('http://localhost:8080/api'); // For authentication, use React Admin's authProvider instead: const authProvider = { login: ({ username, password }) => { // Handle login localStorage.setItem('token', 'your-token'); return Promise.resolve(); }, logout: () => { localStorage.removeItem('token'); return Promise.resolve(); }, checkAuth: () => { return localStorage.getItem('token') ? Promise.resolve() : Promise.reject(); }, checkError: (error) => { return error.status === 401 || error.status === 403 ? Promise.reject() : Promise.resolve(); }, getPermissions: () => Promise.resolve(''), }; const App = () => ( ); export default App; ``` -------------------------------- ### Create Resource Source: https://context7.com/freema/react-admin-api-bundle/llms.txt Create a new resource by sending JSON data in the request body. Validation errors are automatically handled and returned. ```APIDOC ## POST /api/users ### Description Create a new resource by sending JSON data. ### Method POST ### Endpoint /api/users ### Request Body - **name** (string) - Required - The name of the new resource. - **email** (string) - Required - The email address of the new resource. - **roles** (array) - Optional - An array of roles for the new resource. ### Request Example ```json { "name": "New User", "email": "newuser@example.com", "roles": ["ROLE_USER"] } ``` ### Response #### Success Response (201) - **id** (integer) - The unique identifier of the newly created resource. - **name** (string) - The name of the new resource. - **email** (string) - The email address of the new resource. - **roles** (array) - An array of roles for the new resource. - **createdAt** (string) - The creation timestamp. #### Response Example ```json { "id": 26, "name": "New User", "email": "newuser@example.com", "roles": ["ROLE_USER"], "createdAt": "2024-01-20T09:15:00+00:00" } ``` #### Error Response (400) - **error** (string) - "Validation failed" - **violations** (array) - An array of validation errors. - **propertyPath** (string) - The property path of the violation. - **message** (string) - The error message. #### Error Response Example ```json { "error": "Validation failed", "violations": [ { "propertyPath": "email", "message": "This value is not a valid email address." } ] } ``` ``` -------------------------------- ### Example API Error Response Structure Source: https://github.com/freema/react-admin-api-bundle/blob/main/doc/usage_example.md This JSON object illustrates the structured error response format provided by the bundle. It includes an error code (e.g., 'DTO_CLASS_NOT_FOUND'), a descriptive message explaining the error, and an HTTP status code. ```json { "error": "DTO_CLASS_NOT_FOUND", "message": "DTO class 'App\Dto\NonExistentDto' does not exist. Please check the class name and make sure it's properly loaded.", "code": 500 } ```