PHP code example of salesrender / plugin-core-macros

1. Go to this page and download the library: Download salesrender/plugin-core-macros 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/ */

    

salesrender / plugin-core-macros example snippets


namespace SalesRender\Plugin\Core\Macros\Factories;

class WebAppFactory extends \SalesRender\Plugin\Core\Factories\WebAppFactory
{
    public function build(): App
    {
        $this
            ->addCors()
            ->addBatchActions();

        return parent::build();
    }
}

namespace SalesRender\Plugin\Core\Macros\Factories;

class ConsoleAppFactory extends \SalesRender\Plugin\Core\Factories\ConsoleAppFactory
{
    public function build(): Application
    {
        $this->addBatchCommands();
        return parent::build();
    }
}



use SalesRender\Plugin\Components\Batch\BatchContainer;
use SalesRender\Plugin\Components\Db\Components\Connector;
use SalesRender\Plugin\Components\Info\Developer;
use SalesRender\Plugin\Components\Info\Info;
use SalesRender\Plugin\Components\Info\PluginType;
use SalesRender\Plugin\Components\Purpose\MacrosPluginClass;
use SalesRender\Plugin\Components\Purpose\PluginEntity;
use SalesRender\Plugin\Components\Purpose\PluginPurpose;
use SalesRender\Plugin\Components\Settings\Settings;
use SalesRender\Plugin\Components\Translations\Translator;
use SalesRender\Plugin\Core\Actions\Upload\LocalUploadAction;
use SalesRender\Plugin\Core\Actions\Upload\UploadersContainer;
use Medoo\Medoo;
use MyVendor\Plugin\Instance\Macros\Components\MyHandler;
use MyVendor\Plugin\Instance\Macros\Forms\BatchOptionsForm;
use MyVendor\Plugin\Instance\Macros\Forms\SettingsForm;
use XAKEPEHOK\Path\Path;

rm
Settings::setForm(fn($context) => new SettingsForm($context));

# 6. Configure batch forms and handler
BatchContainer::config(
    function (int $number) {
        switch ($number) {
            case 1: return new BatchOptionsForm();
            default: return null;
        }
    },
    new MyHandler()
);



namespace MyVendor\Plugin\Instance\Macros\Components;

use SalesRender\Plugin\Components\Batch\Batch;
use SalesRender\Plugin\Components\Batch\BatchHandlerInterface;
use SalesRender\Plugin\Components\Batch\Process\Error;
use SalesRender\Plugin\Components\Batch\Process\Process;
use SalesRender\Plugin\Components\Settings\Settings;

class MyHandler implements BatchHandlerInterface
{
    public function __invoke(Process $process, Batch $batch)
    {
        // Guard: ensure settings are valid
        Settings::guardIntegrity();

        // Read settings
        $settings = Settings::find()->getData();

        // Read batch options from step 1
        $options = $batch->getOptions(1);

        // Get API client and FSP (Filters, Sort, Pagination) from the batch
        $apiClient = $batch->getApiClient();
        $fsp = $batch->getFsp();

        // Create an iterator to fetch orders from the API
        $iterator = new OrdersFetcherIterator(
            ['id', 'createdAt', 'status.id'],
            $apiClient,
            $fsp
        );

        // Initialize the process with the total count
        $process->initialize(count($iterator));

        // Process each order
        foreach ($iterator as $order) {
            try {
                // Your processing logic here
                $this->processOrder($order, $settings, $options);
                $process->handle();
            } catch (\Throwable $e) {
                $process->addError(new Error($e->getMessage(), $order['id']));
            }
            $process->save();
        }

        // Optional: post-processing phase
        $process->setState(Process::STATE_POST_PROCESSING);
        $process->save();

        // Finish with result (true = success, false = error, string = download URL)
        $process->finish(true);
        $process->save();
    }

    private function processOrder(array $order, $settings, $options): void
    {
        // Implement your order processing logic
    }
}

interface BatchHandlerInterface
{
    public function __invoke(Process $process, Batch $batch);
}



use SalesRender\Plugin\Core\Macros\Factories\WebAppFactory;

$application->run();

#!/usr/bin/env php


use SalesRender\Plugin\Core\Macros\Factories\ConsoleAppFactory;

;



namespace MyVendor\Plugin\Instance\Macros\Forms;

use SalesRender\Plugin\Components\Form\FieldDefinitions\BooleanDefinition;
use SalesRender\Plugin\Components\Form\FieldDefinitions\ListOfEnum\Limit;
use SalesRender\Plugin\Components\Form\FieldDefinitions\ListOfEnum\Values\StaticValues;
use SalesRender\Plugin\Components\Form\FieldDefinitions\ListOfEnumDefinition;
use SalesRender\Plugin\Components\Form\FieldDefinitions\StringDefinition;
use SalesRender\Plugin\Components\Form\FieldGroup;
use SalesRender\Plugin\Components\Form\Form;
use SalesRender\Plugin\Components\Translations\Translator;

class SettingsForm extends Form
{
    public function __construct(array $context)
    {
        $this->setContext($context);
        parent::__construct(
            Translator::get('settings', 'Settings'),
            Translator::get('settings', 'Configure your macros plugin'),
            [
                'group_1' => new FieldGroup(
                    Translator::get('settings', 'General'),
                    null,
                    [
                        'fields' => new ListOfEnumDefinition(
                            Translator::get('settings', 'Columns'),
                            Translator::get('settings', 'Select data columns'),
                            function ($values) {
                                $errors = [];
                                if (!is_array($values) || count($values) < 1) {
                                    $errors[] = Translator::get('errors', 'Select at least one field');
                                }
                                return $errors;
                            },
                            new StaticValues([
                                'id' => ['title' => 'ID', 'group' => 'Order'],
                                'createdAt' => ['title' => 'Created At', 'group' => 'Order'],
                            ]),
                            new Limit(1, null),
                            ['id', 'createdAt']
                        ),
                    ]
                ),
            ],
            Translator::get('settings', 'Save')
        );
    }
}



namespace MyVendor\Plugin\Instance\Macros\Forms;

use SalesRender\Plugin\Components\Form\FieldDefinitions\IntegerDefinition;
use SalesRender\Plugin\Components\Form\FieldDefinitions\BooleanDefinition;
use SalesRender\Plugin\Components\Form\FieldGroup;
use SalesRender\Plugin\Components\Form\Form;
use SalesRender\Plugin\Components\Translations\Translator;

class BatchOptionsForm extends Form
{
    public function __construct()
    {
        parent::__construct(
            Translator::get('batch_options', 'Processing Options'),
            Translator::get('batch_options', 'Configure processing parameters'),
            [
                'options' => new FieldGroup(
                    Translator::get('batch_options', 'Options'),
                    null,
                    [
                        'skipErrors' => new BooleanDefinition(
                            Translator::get('batch_options', 'Skip errors'),
                            Translator::get('batch_options', 'Continue processing on error'),
                            function ($value) {
                                $errors = [];
                                if (!is_bool($value)) {
                                    $errors[] = 'Value must be boolean';
                                }
                                return $errors;
                            },
                            false
                        ),
                    ]
                ),
            ],
            Translator::get('batch_options', 'Start')
        );
    }
}

namespace SalesRender\Plugin\Components\Batch;

interface BatchHandlerInterface
{
    public function __invoke(Process $process, Batch $batch);
}

namespace SalesRender\Plugin\Components\Batch\Process;

class Process extends Model implements JsonSerializable
{
    const STATE_SCHEDULED = 'scheduled';
    const STATE_PROCESSING = 'processing';
    const STATE_POST_PROCESSING = 'post_processing';
    const STATE_ENDED = 'ended';

    public function initialize(?int $init): void;
    public function handle(): void;
    public function skip(): void;
    public function addError(Error $error): void;
    public function setState(string $state): void;
    public function finish($value): void;       // bool|int|string
    public function terminate(Error $error): void;
    public function save(): void;

    public function getHandledCount(): int;
    public function getSkippedCount(): int;
    public function getFailedCount(): int;
    public function getState(): string;
    public function getResult();
}

namespace SalesRender\Plugin\Components\Batch;

class Batch extends Model
{
    public function getApiClient(): ApiClient;
    public function getFsp(): FSP;
    public function getOptions(int $number): Dot;  // Returns batch step options as Dot notation object
}

namespace SalesRender\Plugin\Components\Batch;

final class BatchContainer
{
    public static function config(callable $forms, BatchHandlerInterface $handler): void;
    public static function getForm(int $number, array $context = []): ?Form;
    public static function getHandler(): BatchHandlerInterface;
}

namespace SalesRender\Plugin\Components\Purpose;

class PluginPurpose implements JsonSerializable
{
    public function __construct(PluginClass $class, PluginEntity $entity);
}

namespace SalesRender\Plugin\Core\Actions;

interface ActionInterface
{
    public function __invoke(ServerRequest $request, Response $response, array $args): Response;
}

class ExampleHandler implements BatchHandlerInterface
{
    public function __invoke(Process $process, Batch $batch)
    {
        Settings::guardIntegrity();

        // Read batch step options
        $delay = $batch->getOptions(1)->get('response_options.delay');

        // Create order iterator
        $iterator = new OrdersFetcherIterator(
            Columns::getQueryColumns($fields),
            $batch->getApiClient(),
            $batch->getFsp()
        );

        // Initialize with total count
        $process->initialize(count($iterator));

        // Process each order
        foreach ($iterator as $field) {
            $process->handle();  // or skip() or addError()
            $process->save();
            sleep($delay);
        }

        // Post-processing phase
        $process->setState(Process::STATE_POST_PROCESSING);
        $process->save();

        // Finish (true = success, string = URL, false = error)
        $process->finish(true);
        $process->save();
    }
}

plugin-macros-example/
    bootstrap.php              # Full configuration with batch, autocomplete, previews
    console.php                # CLI entry point
    example.env                # Environment variable template
    composer.json
    db/
    public/
        index.php              # Web entry point
        icon.png               # Plugin icon
        iframe/                # Static files for IFrame fields
    runtime/
    translations/              # Translation files (en_US.json, ru_RU.json)
    src/
        Autocomplete/
            Example.php             # AutocompleteInterface implementation
            ExampleWithDeps.php     # Autocomplete with dependencies
        Components/
            Columns.php             # Column definitions for order data
            ExampleHandler.php      # BatchHandlerInterface implementation
            FieldParser.php         # Field parsing utility
            OrdersFetcherIterator.php  # Order fetching via API
        Forms/
            SettingsForm.php              # Plugin settings form
            ResponseOptionsForm.php       # Batch step 1 form
            SecondResponseOptionsForm.php # Batch step 2 form
            PreviewOptionsForm.php        # Batch step 3 (preview) form
        MarkdownPreviewAction/
            MarkdownPreviewExample.php    # Markdown preview implementation
        TablePreviewAction/
            TablePreviewExample.php       # Table preview implementation
            TablePreviewExcel.php         # Excel table preview
    tests/                     # HTTP test files