feat: add url string transformer
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace WPContentSync\Url;
|
||||
|
||||
final class UrlTransformer {
|
||||
public function transformString( string $value, UrlMappingCollection $mappings ): string {
|
||||
$transformed = $value;
|
||||
|
||||
foreach ( $mappings->all() as $mapping ) {
|
||||
$transformed = $this->replaceMapping( $transformed, $mapping );
|
||||
}
|
||||
|
||||
return $transformed;
|
||||
}
|
||||
|
||||
private function replaceMapping( string $value, UrlMapping $mapping ): string {
|
||||
$source = $mapping->sourceUrl();
|
||||
$destination = $mapping->destinationUrl();
|
||||
|
||||
$replacements = array(
|
||||
$source => $destination,
|
||||
str_replace( '&', '&', $source ) => str_replace( '&', '&', $destination ),
|
||||
$this->toProtocolRelative( $source ) => $this->toProtocolRelative( $destination ),
|
||||
);
|
||||
|
||||
return strtr( $value, $replacements );
|
||||
}
|
||||
|
||||
private function toProtocolRelative( string $url ): string {
|
||||
return preg_replace( '#^https?:#', '', $url ) ?? $url;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user