Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Apitk Manipulation Bundle Laravel Package

check24/apitk-manipulation-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require check24/apitk-manipulation-bundle
    

    Ensure check24/apitk-manipulation-bundle is added to config/bundles.php.

  2. Configure the Bundle: Add the bundle to your config/packages/check24_apitk_manipulation.yaml (auto-generated):

    check24_apitk_manipulation:
        api_base_url: 'https://your-api-endpoint.com/api'
        default_version: 'v1'
    
  3. First Use Case: Create a FormType (e.g., UserV1Type) and an Entity (e.g., User) as shown in the README. The bundle automates API request handling for CRUD operations (POST, PUT, PATCH, DELETE) tied to these forms.

    Example workflow:

    // In a Controller
    use Check24\ApitkManipulationBundle\Form\Type\ApiFormType;
    
    public function createUser(Request $request)
    {
        $form = $this->createForm(UserV1Type::class);
        $form->handleRequest($request);
    
        if ($form->isSubmitted() && $form->isValid()) {
            $apiResponse = $this->get('apitk_manipulation.handler')->handle($form);
            // $apiResponse contains the API result (e.g., created user data)
        }
    }
    

Implementation Patterns

Core Workflow

  1. Form-Driven API Calls: The bundle ties Symfony Forms to API endpoints. Each *V1Type (e.g., UserV1Type) implicitly maps to:

    • POST /api/v1/users (create)
    • PUT /api/v1/users/{id} (update)
    • PATCH /api/v1/users/{id} (partial update)
    • DELETE /api/v1/users/{id} (delete).
  2. Entity Validation: Use Symfony’s validation constraints (e.g., @Assert\Email) on your entity properties. The bundle validates data before sending to the API.

  3. Handler Integration: Inject the apitk_manipulation.handler service to process forms:

    $handler = $this->get('apitk_manipulation.handler');
    $response = $handler->handle($form);
    
  4. Custom Endpoints: Override the default route by adding options to your FormType:

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'api_route' => 'custom/users', // Overrides /api/v1/users
        ]);
    }
    

Common Patterns

  • Versioning: Append V1, V2 to your FormType class names to auto-route to /api/v1/, /api/v2/, etc. Example: UserV2Type/api/v2/users.

  • Nested Resources: For nested routes (e.g., /api/v1/users/{userId}/posts), configure the parent form’s api_route and use child forms with parent_id data:

    $form->add('user_id', HiddenType::class, ['data' => $userId]);
    
  • Response Handling: The bundle returns a ApiResponse object. Access data via:

    $data = $response->getData();
    $errors = $response->getErrors();
    
  • Authentication: Configure API auth in config/packages/check24_apitk_manipulation.yaml:

    check24_apitk_manipulation:
        auth:
            type: 'bearer'
            token: '%env(API_TOKEN)%'
    

    Supported types: bearer, basic.


Gotchas and Tips

Pitfalls

  1. Route Naming Collisions: If your api_route conflicts with Symfony’s router (e.g., api/users vs. a FOSUser route), explicitly prefix routes:

    api_route: 'api/v1/custom/users'
    
  2. Validation Timing: The bundle validates before sending to the API. If the API returns a 422 Unprocessable Entity, check:

    • Symfony validation constraints on the entity.
    • The API’s expected request format (e.g., snake_case vs. camelCase).
  3. Hidden Fields: Avoid using HiddenType for IDs unless necessary. The bundle auto-detects IDs from the entity’s id property.

  4. CORS Issues: If the API returns CORS errors, configure the bundle’s allowed_origins in the config or adjust your API’s CORS settings separately.

  5. Deprecated Methods: The package is last updated in 2021. Test thoroughly with your API’s current response formats (e.g., pagination, nested objects).


Debugging Tips

  1. Enable API Logs: Add this to config/packages/check24_apitk_manipulation.yaml:

    debug: true
    

    Logs will appear in var/log/dev.log.

  2. Inspect Raw Requests: Use a middleware to log requests/responses:

    // src/EventListener/ApiRequestListener.php
    public function onKernelRequest(GetResponseEvent $event)
    {
        if ($event->isMasterRequest()) {
            $request = $event->getRequest();
            if ($request->attributes->get('_route') === 'apitk_manipulation') {
                \Log::debug('API Request:', [
                    'data' => $request->request->all(),
                    'headers' => $request->headers->all(),
                ]);
            }
        }
    }
    
  3. Mock the API: For testing, override the handler service:

    # config/services_test.yaml
    services:
        Check24\ApitkManipulationBundle\Handler\ApiHandler:
            class: App\Tests\Mock\MockApiHandler
    

Extension Points

  1. Custom Response Transformers: Extend the ApiResponse class or override the handler to transform API responses:

    // src/Service/CustomApiHandler.php
    class CustomApiHandler extends AbstractApiHandler
    {
        protected function transformResponse($responseData)
        {
            // Custom logic (e.g., flatten nested arrays)
            return parent::transformResponse($responseData);
        }
    }
    

    Register it as a service alias.

  2. Dynamic API Config: Fetch the api_base_url or default_version dynamically (e.g., from a database) by implementing a ConfigProvider interface:

    use Check24\ApitkManipulationBundle\Config\ConfigProviderInterface;
    
    class DatabaseConfigProvider implements ConfigProviderInterface
    {
        public function getConfig(): array
        {
            return [
                'api_base_url' => DB::table('api_config')->value('url'),
            ];
        }
    }
    
  3. Event Listeners: Listen to apitk_manipulation.pre_request and apitk_manipulation.post_response events to modify requests/responses:

    // src/EventListener/ApiEventListener.php
    public static function getSubscribedEvents()
    {
        return [
            'apitk_manipulation.pre_request' => 'onPreRequest',
            'apitk_manipulation.post_response' => 'onPostResponse',
        ];
    }
    
  4. Testing: Use the ApiHandlerTestCase base class (if available) or mock the GuzzleHttp\Client service for unit tests:

    $this->container->set('apitk_manipulation.client', $mockClient);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui