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

Kiota Serialization Form Laravel Package

microsoft/kiota-serialization-form

PHP application/x-www-form-urlencoded serialization library for Microsoft Kiota generated SDKs. Adds support for form-encoded request/response payloads from compatible API endpoints; install via Composer and use alongside Kiota PHP projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require microsoft/kiota-serialization-form
    

    Ensure your composer.json includes:

    "require": {
        "microsoft/kiota-serialization-form": "^2.0.2"
    }
    
  2. Kiota Integration:

    • Use this package only with Kiota PHP. It provides application/x-www-form-urlencoded serialization for Kiota-generated clients.
    • Example: If you have a Kiota client class (e.g., MyApiClient), configure it to use the form serializer:
      use Microsoft\Kiota\Serialization\Form\FormSerializer;
      
      $serializer = new FormSerializer();
      $client = new MyApiClient($serializer);
      
  3. First Use Case:

    • Serialize a request payload:
      $requestInfo = new RequestInformation();
      $requestInfo->setMethod("POST");
      $requestInfo->setUrl("https://api.example.com/data");
      
      $content = new FormContent();
      $content->add("name", "John Doe");
      $content->add("active", "true");
      
      $serializer = new FormSerializer();
      $serializedContent = $serializer->serialize($content);
      // Outputs: "name=John+Doe&active=true"
      

Implementation Patterns

Core Workflows

  1. Request Serialization:

    • Use FormSerializer to convert Kiota FormContent objects to application/x-www-form-urlencoded strings:
      $serializer = new FormSerializer();
      $serialized = $serializer->serialize($formContent);
      
    • Attach to HTTP requests via Kiota’s RequestInformation:
      $requestInfo->setBodyContent($serialized);
      
  2. Response Deserialization:

    • Parse form-encoded responses into Kiota models:
      $response = $client->request($requestInfo);
      $deserializer = new FormDeserializer();
      $parsedContent = $deserializer->deserialize($response->getBody(), new FormContent());
      
  3. Complex Types:

    • Handle nested objects by implementing FormContent for custom models:
      class UserFormContent extends FormContent {
          public function addUserData(User $user) {
              $this->add("user[name]", $user->getName());
              $this->add("user[email]", $user->getEmail());
          }
      }
      

Integration Tips

  • Laravel HTTP Clients: Integrate with Laravel’s Http facade by extending ClientRequest:

    use Microsoft\Kiota\Serialization\Form\FormSerializer;
    use Illuminate\Http\Client\Request;
    
    class KiotaRequest extends Request {
        public function __construct(FormSerializer $serializer) {
            $this->serializer = $serializer;
        }
    
        public function serialize(): string {
            return $this->serializer->serialize($this->content);
        }
    }
    
  • Middleware: Use middleware to auto-attach form serialization:

    public function handle($request, Closure $next) {
        if ($request->hasHeader('Content-Type', 'application/x-www-form-urlencoded')) {
            $request->merge([
                'serializer' => new FormSerializer()
            ]);
        }
        return $next($request);
    }
    
  • Testing: Mock FormSerializer in unit tests:

    $mockSerializer = $this->createMock(FormSerializer::class);
    $mockSerializer->method('serialize')->willReturn("name=Test&active=true");
    
    $client = new MyApiClient($mockSerializer);
    

Gotchas and Tips

Pitfalls

  1. Boolean Handling:

    • The library correctly parses "false" strings to false (fixed in v2.0.1), but ensure your API expects lowercase "true"/"false" for consistency.
    • Example:
      $content->add("is_active", "false"); // Deserializes to `false`
      
  2. PHP Version:

    • Minimum PHP 8.2 (v2.0.0+). Avoid using with older versions (e.g., PHP 8.1 or lower).
  3. URL Encoding:

    • Spaces are auto-replaced with + (per application/x-www-form-urlencoded spec). Avoid manual urlencode() calls unless overriding FormSerializer.
  4. Nested Objects:

    • Kiota’s form serialization does not natively support nested objects (e.g., user[address][city]). Implement custom FormContent classes for complex structures.
  5. Empty Values:

    • Empty strings ("") or null values are omitted from the serialized output. Explicitly handle missing fields in your API logic.

Debugging

  • Validation Errors: If deserialization fails, check for:

    • Malformed form data (e.g., unescaped & or =).
    • Use FormDeserializer::getParseNode() to inspect raw parsed values:
      $parseNode = $deserializer->getParseNode($responseBody);
      dump($parseNode->getValue()); // Debug raw parsed data
      
  • Performance:

    • For large payloads, leverage FormContent::addMultiple() to reduce allocations (optimized in v2.0.1+).

Extension Points

  1. Custom Serialization: Override FormSerializer to modify behavior:

    class CustomFormSerializer extends FormSerializer {
        public function serialize(FormContent $content): string {
            $data = [];
            foreach ($content->getProperties() as $key => $value) {
                $data[$key] = strtoupper($value); // Example: Force uppercase
            }
            return http_build_query($data);
        }
    }
    
  2. Type Casting: Extend FormDeserializer to handle custom types:

    $deserializer = new FormDeserializer();
    $deserializer->setTypeMapper([
        'date' => function ($value) {
            return \Carbon\Carbon::parse($value);
        }
    ]);
    
  3. Kiota Model Integration: Use traits to auto-generate FormContent for Eloquent models:

    trait FormContentable {
        public function toFormContent(): FormContent {
            $content = new FormContent();
            foreach ($this->getFillable() as $field) {
                $content->add($field, $this->{$field});
            }
            return $content;
        }
    }
    
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