PHP code example of dual-native / http-system

1. Go to this page and download the library: Download dual-native/http-system library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dual-native / http-system example snippets



DualNative\HTTP\DualNativeSystem;
use DualNative\HTTP\Events\NullEventDispatcher;
use DualNative\HTTP\Storage\InMemoryStorage;

// Initialize with null implementations (no external dependencies)
$system = new DualNativeSystem(
    ['version' => '1.0.0'],
    new NullEventDispatcher(),
    new InMemoryStorage()
);

// Compute Content Identity (CID)
$content = ['title' => 'Hello World', 'body' => 'Content here'];
$cid = $system->computeCID($content);
echo "CID: $cid\n"; // sha256-<hex>

// Validate CID
$isValid = $system->validateCID($content, $cid);
echo "Valid: " . ($isValid ? 'Yes' : 'No') . "\n";

// Generate bidirectional links
$links = $system->generateLinks('resource-123', 'https://example.com/page', 'https://api.example.com/resource/123');
print_r($links);


use DualNative\HTTP\DualNativeSystem;
use DualNative\HTTP\Events\WordPressEventDispatcher;
use DualNative\HTTP\Storage\WordPressStorage;

// Initialize with WordPress adapters
$system = new DualNativeSystem(
    [
        'version' => '1.0.0',
        'profile' => 'full',
        'cache_ttl' => 3600
    ],
    new WordPressEventDispatcher(),  // Bridges to do_action/apply_filters
    new WordPressStorage()            // Bridges to get_option/update_option
);

// Now WordPress hooks work through the library
add_action('dual_native_system_initialized', function($system) {
    // System is ready
});


use DualNative\HTTP\DualNativeSystem;
use DualNative\HTTP\Events\EventDispatcherInterface;
use DualNative\HTTP\Storage\StorageInterface;

// Create Laravel adapters
class LaravelEventDispatcher implements EventDispatcherInterface {
    public function dispatch(string $eventName, ...$args): void {
        event($eventName, $args);
    }

    public function filter(string $filterName, $value, ...$args) {
        return $value; // Or implement Laravel's equivalent
    }

    public function hasListeners(string $eventName): bool {
        return Event::hasListeners($eventName);
    }
}

class LaravelStorage implements StorageInterface {
    public function get(string $key, $default = null) {
        return cache()->get($key, $default);
    }

    public function set(string $key, $value): bool {
        return cache()->put($key, $value, 3600);
    }

    public function delete(string $key): bool {
        return cache()->forget($key);
    }

    public function has(string $key): bool {
        return cache()->has($key);
    }
}

// Initialize system
$system = new DualNativeSystem(
    config('dualnative'),
    new LaravelEventDispatcher(),
    new LaravelStorage()
);

$content = ['title' => 'My Post', 'body' => 'Content...'];

// Compute CID
$cid = $system->computeCID($content);
// Result: sha256-abc123...

// Validate CID (for safe writes)
if ($system->validateCID($content, $expectedCid)) {
    // Content hasn't changed, safe to update
}

// Get current resource
$resource = $system->getResource('post-123');
$currentCid = $resource['cid'];

// Update with CID validation
$result = $system->updateResource(
    'post-123',
    $newData,
    $currentCid  // Must match current state
);

if ($result['success']) {
    $newCid = $result['new_cid'];
} else {
    // 412 Precondition Failed - resource was modified by another process
    $actualCid = $result['actual_cid'];
}

// Create a resource
$result = $system->createResource(
    'post-123',                          // Resource ID
    ['url' => 'https://example.com/post'], // Human Representation
    ['api_url' => 'https://api.example.com/post/123', 'title' => '...'], // Machine Representation
    ['author' => 'John Doe']             // Metadata
);

// Get catalog
$catalog = $system->getCatalog(
    $since = '2024-01-01T00:00:00Z',  // Only resources updated since
    $filters = ['status' => 'publish'],
    $limit = 100,
    $offset = 0
);

$links = $system->generateLinks(
    'post-123',
    'https://example.com/post-123',    // Human Representation URL
    'https://api.example.com/posts/123' // Machine Representation URL
);

// Result:
// [
//   'hr' => ['url' => '...', 'rel' => 'self', 'type' => 'text/html'],
//   'mr' => ['url' => '...', 'rel' => 'alternate', 'type' => 'application/json']
// ]

new DualNativeSystem(
    array $config = [],
    ?EventDispatcherInterface $eventDispatcher = null,
    ?StorageInterface $storage = null
)

// Compute CID for content
$system->computeCID($content, ?array $excludeKeys = null): string
// Returns: 'sha256-<hex>'

// Validate CID matches content
$system->validateCID($content, string $expectedCID, ?array $excludeKeys = null): bool
// Returns: true if CID matches, false otherwise

// Create a dual-native resource
$system->createResource(string $rid, $hr, $mr, array $metadata = []): array
// Returns:
// [
//   'rid' => 'resource-123',
//   'cid' => 'sha256-...',
//   'hr' => [...],
//   'mr' => [...],
//   'links' => ['hr' => [...], 'mr' => [...]],
//   'catalog_updated' => true
// ]

// Get resource by RID
$system->getResource(string $rid): ?array
// Returns: resource array or null if not found
// [
//   'rid' => 'resource-123',
//   'hr' => ['url' => '...'],
//   'mr' => ['api_url' => '...', 'content_id' => '...'],
//   'cid' => 'sha256-...',
//   'updatedAt' => '2024-01-01T00:00:00Z'
// ]

// Update resource with CID validation (safe write)
$system->updateResource(string $rid, $newData, string $expectedCid): array
// Returns on success:
// [
//   'success' => true,
//   'rid' => 'resource-123',
//   'new_cid' => 'sha256-...',
//   'resource' => [...]
// ]
// Returns on failure (CID mismatch):
// [
//   'success' => false,
//   'error' => 'CID mismatch - resource has been modified by another process',
//   'rid' => 'resource-123',
//   'expected_cid' => 'sha256-abc...',
//   'actual_cid' => 'sha256-xyz...'
// ]

// Get catalog of resources
$system->getCatalog(?string $since, array $filters, int $limit, int $offset): array
// Returns:
// [
//   'count' => 42,
//   'items' => [
//     ['rid' => '...', 'cid' => '...', 'updatedAt' => '...', ...],
//     ...
//   ]
// ]

// Generate bidirectional links
$system->generateLinks(string $rid, string $hrUrl, string $mrUrl): array
// Returns:
// [
//   'hr' => ['url' => '...', 'rel' => 'self', 'type' => 'text/html'],
//   'mr' => ['url' => '...', 'rel' => 'alternate', 'type' => 'application/json']
// ]

// Validate semantic equivalence between HR and MR
$system->validateSemanticEquivalence($hrContent, $mrContent, ?array $scope): array
// Returns:
// [
//   'equivalent' => true,
//   'differences' => [],
//   'scope' => ['title', 'body', 'author']
// ]
// Or on mismatch:
// [
//   'equivalent' => false,
//   'differences' => ['title' => ['hr' => 'Title A', 'mr' => 'Title B']],
//   'scope' => ['title', 'body', 'author']
// ]

// Validate system conformance to dual-native standards
$system->validateConformance(array $systemInfo): array
// Returns:
// [
//   'conformant' => true,
//   'level' => 2,  // Conformance level (1-4)
//   'checks' => [
//     'has_rid' => true,
//     'has_cid' => true,
//     'has_bidirectional_links' => true,
//     'has_catalog' => true
//   ],
//   'issues' => []
// ]

// Perform system health check
$system->healthCheck(): array
// Returns:
// [
//   'status' => 'healthy',  // 'healthy' or 'degraded'
//   'timestamp' => '2024-01-01T00:00:00+00:00',
//   'version' => '1.0.0',
//   'components' => [
//     'cid_manager' => true,
//     'link_manager' => true,
//     'catalog_manager' => true,
//     'validation_engine' => true,
//     'http_handler' => true
//   ],
//   'profile' => 'full'
// ]

[
    'version' => '1.0.0',
    'profile' => 'full',
    'exclude_fields' => ['cid', 'etag', '_links', 'modified', 'modified_gmt'],
    'cache_ttl' => 3600
]