PHP code example of devuri / wp-adapter

1. Go to this page and download the library: Download devuri/wp-adapter 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/ */

    

devuri / wp-adapter example snippets


use AdapterKit\Core\Contracts\OptionStorageInterface;

final class SettingsService
{
    private OptionStorageInterface $options;

    public function __construct(OptionStorageInterface $options)
    {
        $this->options = $options;
    }

    public function enable(): void
    {
        $this->options->update(
            'myplugin_settings',
            ['enabled' => true]
        );
    }
}

use AdapterKit\Core\Storage\WordPressOptionStorage;

$settings = new SettingsService(new WordPressOptionStorage());

use AdapterKit\Core\Testing\InMemoryOptionStorage;
use PHPUnit\Framework\TestCase;

final class SettingsServiceTest extends TestCase
{
    public function test_enable_stores_the_setting(): void
    {
        $options = new InMemoryOptionStorage();
        $settings = new SettingsService($options);

        $settings->enable();

        $this->assertSame(
            ['enabled' => true],
            $options->get('myplugin_settings')
        );
    }
}



// Wrong: the service now ugin_settings', []);

// Right: the service depends on a contract.
$value = $this->options->get('myplugin_settings', []);

use AdapterKit\Core\Http\WordPressHttpClient;
use AdapterKit\Core\Hooks\WordPressHooks;
use AdapterKit\Core\Logging\NullLogger;
use AdapterKit\Core\PluginContext;
use AdapterKit\Core\Storage\WordPressOptionStorage;
use AdapterKit\Core\Storage\WordPressTransientStorage;

$context = PluginContext::fromPluginFile(
    __FILE__,
    'my-plugin',
    '1.0.0',
    'my-plugin',
    'myplugin_'
);

$plugin = new MyPlugin\Plugin(
    $context,
    new WordPressHooks(),
    new WordPressOptionStorage(),
    new WordPressTransientStorage(),
    new WordPressHttpClient(),
    new NullLogger()
);

$plugin->register();

use AdapterKit\Core\Contracts\HttpClientInterface;
use AdapterKit\Core\Contracts\OptionStorageInterface;
use AdapterKit\Core\Result;
use Psr\Log\LoggerInterface;

final class LicenseService
{
    private OptionStorageInterface $options;
    private HttpClientInterface $http;
    private LoggerInterface $logger;
    private string $optionKey;

    public function __construct(
        OptionStorageInterface $options,
        HttpClientInterface $http,
        LoggerInterface $logger,
        string $optionKey
    ) {
        $this->options = $options;
        $this->http = $http;
        $this->logger = $logger;
        $this->optionKey = $optionKey;
    }

    public function activate(string $key): Result
    {
        $response = $this->http->post(
            'https://api.example.com/activate',
            ['body' => ['key' => $key]]
        );

        if ($response['is_error']) {
            $message = $response['error_message'] ?? 'Activation request failed.';
            $this->logger->warning('activation_failed', ['reason' => $message]);

            return Result::failure('activation_failed', $message);
        }

        if ($response['code'] < 200 || $response['code'] >= 300) {
            return Result::failure(
                'activation_rejected',
                'The activation server rejected the request.'
            );
        }

        $payload = json_decode($response['body'], true);

        if (!is_array($payload) || empty($payload['ok'])) {
            return Result::failure(
                'invalid_response',
                'The activation server returned an invalid response.'
            );
        }

        $this->options->update($this->optionKey, [
            'active' => true,
            'key' => $key,
        ]);

        return Result::success(['active' => true]);
    }
}

$value = $options->get('myplugin_settings', []);
$options->update('myplugin_settings', ['enabled' => true]);
$options->delete('myplugin_settings');

$transients->set('myplugin_token', 'abc123', 60);
$value = $transients->get('myplugin_token');
$transients->delete('myplugin_token');

[
    'is_error' => false,
    'error_message' => null,
    'code' => 200,
    'body' => '{"ok":true}',
]

$hooks->addAction('admin_menu', [$controller, 'registerMenu']);
$hooks->addFilter('the_content', [$formatter, 'format'], 20, 1);

$hooks->registerRestRoute('my-plugin/v1', '/settings', [
    'methods' => 'GET',
    'callback' => [$controller, 'getSettings'],
    'permission_callback' => [$controller, 'canReadSettings'],
]);

use AdapterKit\Core\Testing\InMemoryOptionStorage;

$options = new InMemoryOptionStorage([
    'myplugin_settings' => ['enabled' => true],
]);

$options->update('myplugin_settings', ['enabled' => false]);
$options->has('myplugin_settings'); // true
$options->all();                    // complete in-memory store
$options->clear();                  // removes every stored key

use AdapterKit\Core\Testing\InMemoryTransientStorage;
use AdapterKit\Core\Time\FrozenClock;

$clock = new FrozenClock(1700000000);
$transients = new InMemoryTransientStorage($clock);

$transients->set('token', 'abc123', 60);
$transients->get('token'); // 'abc123'

$clock->advance(60);
$transients->get('token'); // false because expiration is inclusive

use AdapterKit\Core\Testing\MockHttpClient;

$http = new MockHttpClient();
$http->addJsonResponse('/activate', ['ok' => true], 200);
$http->addErrorResponse('/timeout', 'Request timed out.');

$response = $http->post(
    'https://api.example.com/activate',
    ['body' => ['key' => 'VALID-KEY-123']]
);

$payload = json_decode($response['body'], true);
$http->wasRequestMadeTo('/activate');
$http->getLastRequest();
$http->getRequestHistory();
$http->getRequestCount();

use AdapterKit\Core\Testing\RecordingHooks;

$hooks = new RecordingHooks();
$plugin->register($hooks);

$hooks->hasAction('admin_menu');
$hooks->hasFilter('the_content');
$hooks->hasRestRoute('/settings');
$hooks->getActions();
$hooks->getFilters();
$hooks->getRestRoutes();

use AdapterKit\Core\Testing\RecordingLogger;

$logger = new RecordingLogger();
$service->run($logger);

$logger->hasWarning('rate_limit_exceeded');
$logger->hasError('activation_failed');
$logger->getErrors();
$logger->count('info');
$logger->all();
$logger->clear();

use AdapterKit\Core\Testing\MockEnvironment;

$environment = new MockEnvironment(
    'https://example.com',
    'https://example.com/wp-admin/',
    1700000000
);

$environment->homeUrl('pricing');
$environment->adminUrl('admin.php?page=my-plugin');
$environment->currentTime('timestamp');
$environment->currentTime('mysql');
$environment->setCurrentScreenId('settings_page_my-plugin');
$environment->getCurrentScreenId();



// WordPress is not loaded.

use AdapterKit\Core\PluginContext;

$context = PluginContext::fromPluginFile(
    __FILE__,
    'my-plugin',
    '1.0.0',
    'my-plugin',
    'myplugin_'
);

$context->getSlug();
$context->getVersion();
$context->getFile();
$context->getBasename();
$context->getDirPath();
$context->getDirUrl();
$context->getTextDomain();
$context->getOptionPrefix();

use AdapterKit\Core\Result;

$success = Result::success(['saved' => true]);
$failure = Result::failure(
    'invalid_key',
    'The license key is not valid.',
    ['field' => 'license_key']
);

$success->isSuccess();
$success->getCode();    // "success"
$success->getMessage(); // empty string
$success->getData();    // ['saved' => true]

use AdapterKit\Core\Support\KeyBuilder;

$keys = new KeyBuilder('myplugin');

$keys->option('settings');   // myplugin_settings
$keys->transient('token');   // myplugin_token
$keys->cache('license');     // myplugin_license
$keys->hook('activated');    // myplugin/activated



// Wrong: bypasses WP Adapter's build conflict check.
if (!class_exists(AdapterKit\Core\Result::class)) {
    t.php';

use AdapterKit\Core\Contracts\OptionStorageInterface;

final class NetworkOptionStorage implements OptionStorageInterface
{
    // Implement the contract with network option functions.
}