phpro / soap-client

A general purpose SOAP client for PHP
MIT License
858 stars 175 forks source link

Type replacer #525

Closed veewee closed 4 months ago

veewee commented 4 months ago

By default, a "date" type from the XSD namespace http://www.w3.org/2001/XMLSchema will be converted to a DateTimeImmutable object. However, if you configure an encoder that does not support DateTimeImmutable, you might want to replace it with a int type that represents the amount of seconds since the unix epoch.

This can be configured in the client configuration:

use Phpro\SoapClient\CodeGenerator\Config\Config;
use Phpro\SoapClient\Soap\Metadata\Manipulators\TypeReplacer\TypeReplacers;

return Config::create()
    //...
    ->setTypeReplacements(
        TypeReplacers::defaults()
            ->add(new MyDateReplacer())
    )
    // ...

The MyDateReplacer class should implement the TypeReplacerInterface and should return the correct type for the given type.

use Phpro\SoapClient\Soap\Metadata\Manipulators\TypeReplacer\TypeReplacer;
use Soap\Engine\Metadata\Model\XsdType;
use Soap\WsdlReader\Metadata\Predicate\IsOfType;use Soap\Xml\Xmlns;

final class MyDateReplacer implements TypeReplacer
{
    public function __invoke(XsdType $xsdType) : XsdType
    {
        $check = new IsOfType(Xmlns::xsd()->value(), 'date');
        if (!$check($xsdType)) {
            return $xsdType;
        }

        return $xsdType->copy('int')->withBaseType('int');
    }
}

This way, the generated code will use the int type instead of the DateTimeImmutable type for the date type in the XSD.

The TypeReplacers contain a default set of type replacements that are being used to improve the generated code: