feat: add json file transport
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
/**
|
||||
* File package transport boundary.
|
||||
*
|
||||
* @package WPContentSync
|
||||
*/
|
||||
|
||||
namespace WPContentSync\Transport;
|
||||
|
||||
use WPContentSync\Package\ContentPackage;
|
||||
|
||||
interface FileTransportInterface {
|
||||
public function export( ContentPackage $package ): string;
|
||||
|
||||
public function import( string $contents ): ContentPackage;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
/**
|
||||
* JSON file transport implementation.
|
||||
*
|
||||
* @package WPContentSync
|
||||
*/
|
||||
|
||||
namespace WPContentSync\Transport;
|
||||
|
||||
use WPContentSync\Package\ContentPackage;
|
||||
use WPContentSync\Package\PackageValidator;
|
||||
|
||||
final class JsonFileTransport implements FileTransportInterface {
|
||||
private PackageValidator $validator;
|
||||
|
||||
public function __construct( PackageValidator $validator ) {
|
||||
$this->validator = $validator;
|
||||
}
|
||||
|
||||
public function export( ContentPackage $package ): string {
|
||||
$json = wp_json_encode( $package->toArray(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES );
|
||||
|
||||
if ( false === $json ) {
|
||||
throw new \RuntimeException( 'Unable to encode content package JSON.' );
|
||||
}
|
||||
|
||||
return $json;
|
||||
}
|
||||
|
||||
public function import( string $contents ): ContentPackage {
|
||||
$decoded = json_decode( $contents, true );
|
||||
|
||||
if ( ! is_array( $decoded ) ) {
|
||||
throw new \InvalidArgumentException( 'The selected file is not valid JSON.' );
|
||||
}
|
||||
|
||||
$result = $this->validator->validate( $decoded );
|
||||
|
||||
if ( ! $result->isValid() ) {
|
||||
throw new \InvalidArgumentException( implode( ' ', $result->errors() ) );
|
||||
}
|
||||
|
||||
return ContentPackage::fromArray( $decoded );
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user