CallableTranscoder¶
(PHP 7 >= 7.4.0, PHP 8)
Introduction¶
CallableTranscoder is an adapter that wraps legacy callable functions into the TranscoderInterface. It provides backward compatibility for custom transcoders defined as closures or functions.
Uses CallableAdapterTrait for common adapter functionality.
Priority: User-defined
Requires: None
Class Synopsis¶
final class CallableTranscoder implements TranscoderInterface {
use CallableAdapterTrait;
/* Methods */
public __construct(callable $callable, int $priority)
public transcode(string $data, string $to, string $from, array $options): ?string
public getPriority(): int // From CallableAdapterTrait
public isAvailable(): bool // From CallableAdapterTrait
}
Features¶
- Wraps callable functions as transcoders
- Validates callable signature at construction
- Validates return type at runtime
- Supports closures, functions, and invokable objects
- Custom priority support
Methods¶
__construct¶
public __construct(callable $callable, int $priority)
Create a new CallableTranscoder.
Parameters:
- $callable - Function with signature: fn(string, string, string, array): ?string
- $priority - Execution priority
Throws: InvalidArgumentException if callable signature is invalid
transcode¶
public transcode(string $data, string $to, string $from, array $options): ?string
Execute the wrapped callable.
Throws: InvalidArgumentException if return type is invalid
getPriority¶
public getPriority(): int
Returns: User-defined priority
isAvailable¶
public isAvailable(): bool
Returns: Always true
Example¶
<?php
use Ducks\Component\EncodingRepair\Transcoder\CallableTranscoder;
use Ducks\Component\EncodingRepair\CharsetHelper;
// Create from closure
$transcoder = new CallableTranscoder(
function (string $data, string $to, string $from, array $options): ?string {
if ('CUSTOM' !== $from) {
return null;
}
return customConvert($data, $to);
},
75 // Priority
);
// Register
CharsetHelper::registerTranscoder($transcoder);
// Or use shorthand
CharsetHelper::registerTranscoder(
fn($data, $to, $from, $opts) => customConvert($data, $to),
75
);
Validation¶
CallableTranscoder validates:
- Signature: Must accept at least 3 parameters
- Return type: Must return
string|null
// Valid
$valid = new CallableTranscoder(
fn(string $d, string $t, string $f, array $o): ?string => null,
50
);
// Invalid - throws InvalidArgumentException
$invalid = new CallableTranscoder(
fn(string $d): string => $d, // Only 1 parameter
50
);