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


// Business logic depends on the contract, not WordPress
final class LicenseService
{
    private OptionStorageInterface $options;
    private HttpClientInterface    $http;
    private LoggerInterface        $logger;

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

    public function activate(string $key): Result
    {
        // Pure logic. No WordPress functions. Fully unit-testable.
    }
}



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

$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\Testing\InMemoryOptionStorage;
use AdapterKit\Core\Testing\MockHttpClient;
use AdapterKit\Core\Testing\RecordingLogger;

final class LicenseServiceTest extends TestCase
{
    private InMemoryOptionStorage $options;
    private MockHttpClient        $http;
    private RecordingLogger       $logger;
    private LicenseService        $service;

    protected function setUp(): void
    {
        $this->options = new InMemoryOptionStorage(['myplugin_license' => []]);
        $this->http    = new MockHttpClient();
        $this->logger  = new RecordingLogger();
        $this->service = new LicenseService(
            $this->options, $this->http, $this->logger, 'myplugin_license'
        );
    }

    public function test_activate_stores_key_on_success(): void
    {
        $this->http->addJsonResponse('/activate', ['ok' => true], 200);

        $result = $this->service->activate('VALID-KEY-123');

        $this->assertTrue($result->isSuccess());
        $stored = $this->options->get('myplugin_license');
        $this->assertTrue($stored['active']);
        $this->assertSame('VALID-KEY-123', $stored['key']);
    }

    public function test_activate_returns_failure_and_logs_warning_on_http_error(): void
    {
        $this->http->addErrorResponse('/activate', 'Connection refused.');

        $result = $this->service->activate('ANY-KEY');

        $this->assertFalse($result->isSuccess());
        $this->assertSame('activation_failed', $result->getCode());
        $this->assertTrue($this->logger->hasWarning('activation_failed'));
    }
}


// WordPress is NOT loaded.

$options = new InMemoryOptionStorage(['myplugin_settings' => ['enabled' => true]]);
$options->update('myplugin_settings', ['enabled' => false]);
$options->has('myplugin_settings');  // true
$options->all();                      // full store contents
$options->clear();

$clock      = new FrozenClock(1700000000);
$transients = new InMemoryTransientStorage($clock);
$transients->set('token', 'abc123', 60);
$transients->get('token');   // 'abc123'
$clock->advance(61);
$transients->get('token');   // false — expired

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

$http->post('https://api.example.com/activate', []);

$http->wasRequestMadeTo('/activate');  // true
$http->getLastRequest();               // ['method' => 'POST', 'url' => ..., ...]
$http->getRequestCount();              // 1

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

$hooks->hasAction('admin_menu');                     // bool
$hooks->hasFilter('the_content');                    // bool
$hooks->hasRestRoute('/my-plugin/v1/settings');      // bool
$hooks->getActions();                                // array of all recorded actions

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

$logger->hasWarning('rate_limit_exceeded');  // bool
$logger->hasError('activation_failed');      // bool
$logger->getErrors();                        // array
$logger->count('info');                      // int
$logger->clear();

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

$env->homeUrl('pricing');
$env->adminUrl('admin.php?page=my-plugin');
$env->setCurrentScreenId('settings_page_my-plugin');
$env->sanitizeTextField(' hello world ');  // 'hello world'

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

$ctx->getSlug();          // 'my-plugin'
$ctx->getVersion();       // '1.0.0'
$ctx->getDirPath();       // absolute path with trailing slash
$ctx->getDirUrl();        // URL with trailing slash
$ctx->getOptionPrefix();  // 'myplugin_'

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

$result->isSuccess();   // bool
$result->getCode();     // string
$result->getMessage();  // string
$result->getData();     // array

$keys = new KeyBuilder('myplugin_');
$keys->option('settings');    // myplugin_settings
$keys->transient('token');    // myplugin_token
$keys->hook('activated');     // myplugin_/activated

// Wrong — silently accepts the first loaded version if multiple plugins use this package
if (! class_exists(AdapterKit\Core\Result::class)) {