PHP code example of apptank / horusync

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

    

apptank / horusync example snippets


namespace App\Models\Sync;

use AppTank\Horus\Core\Entity\SyncParameter;
use AppTank\Horus\Illuminate\Database\WritableEntitySynchronizable;

class MyModel extends WritableEntitySynchronizable
{
    public static function parameters(): array
    {
        return [
            // Define the parameters of the entity
            SyncParameter::createString("name", 1),
            SyncParameter::createInt("age", 1),
            SyncParameter::createPrimaryKeyString("email", 1),
            SyncParameter::createTimestamp("datetime", 1),
            SyncParameter::createBoolean("active", 1),
            SyncParameter::createFloat("price", 1),
            SyncParameter::createRelationOneToMany("children", [ChildModel::class], 1)
        ];
    }

    public static function getEntityName(): string
    {
        return "my_model";
    }

    public static function getVersionNumber(): int
    {
        return 1;
    }
}

class AppServiceProvider extends ServiceProvider
{

    public function boot(): void
    {
       // Define the hierarchical map of entities
       $entityMap = [
            MyModel::class => [
                ChildModel::class
            ]
       ];
        
       // Define the configuration
       $config = new Config(
            validateAccess: true,
            connectionName: "sync_database",
            usesUUIDs: true,
            prefixTables: 'hs',
            entityRestrictions: [
                new MaxCountEntityRestriction("user_id","entity_name", maxCount: 10)
            ],
        );
       
         // Initialize Horus
        Horus::initialize($entityMap)->setConfig($config);
    }

}

Horus::setFileHandler($this->app->make(IFileHandler::class));

class UserImageModel extends WritableEntitySynchronizable
{
    public static function parameters(): array
    {
        return [
            // User Id
            SyncParameter::createUUIDForeignKey("user_id", 1,"users"),
            // Reference to the image file
            SyncParameter::createReferenceFile("image", 1),
        ];
    }
}


class LocalFileHandler implements IFileHandler
{
    /**
     * @throws \Exception
     */
    function upload(int|string $userOwnerId, string $fileId, string $path, UploadedFile $file): FileUploaded
    {
        $filename = basename($path);
        $basePath = dirname($path);

        $pathResult = $file->storeAs($basePath, $filename);

        if (!$pathResult) {
            throw new \Exception("Error uploading file");
        }

        $mimeType = $file->getMimeType();
        $publicUrl = $this->generateUrl($pathResult);

        return new FileUploaded(
            $fileId,
            $mimeType,
            $pathResult,
            $publicUrl,
            $userOwnerId
        );
    }

    function delete(string $pathFile): bool
    {
        return Storage::delete($pathFile);
    }

    function getMimeTypesAllowed(): array
    {
        return MimeType::IMAGES;
    }

    function copy(string $pathFrom, string $pathTo): bool
    {
        return Storage::copy($pathFrom, $pathTo);
    }

    function generateUrl(string $path): string
    {
        return Storage::url($path);
    }
}


Horus::setMiddleware([MyMiddleware::class,'throttle:60,1']);


Horus::getInstance()->setUserAuthenticated(
 new UserAuth(
   "07a35af0-7317-41e4-99a3-e3583099aff2", // User Id Authenticated
   [ // Array of Entities Granted
   new EntityGranted(
   "971785f7-0f01-46cd-a3ce-af9ce6273d3d", // User Owner Id
   "entity_name", // Entity Name
    "9135e859-b053-4cfb-b701-d5f240b0aab1", // Entity Id
    // Set the permissions for the entity
   , new AccessLevel(Permission::READ, Permission::CREATE)),
    // User Acting As
   new UserAuth("b253a0e8-027b-463c-b87a-b18f09c99ddd")
   ]
 )
);

$config = new Config(true);
$config->setupOnValidateEntityWasGranted(function () {
    return [
        new EntityGranted($userOwnerId,
        new EntityReference($entityName, $entityId), AccessLevel::all())
    ];
});
Horus::getInstance()->setConfig($config);
 
Horus::getInstance()->setEntityRestrictions([
    new MaxCountEntityRestriction("user_id","entity_name", maxCount: 10),
    new FilterEntityRestriction("entity_name", [
       new ParameterFilter("country", "CO")
    ]),
    new ExternalEntityFilterRestriction("entity_name", filterFunction: function (EntityData $entityData) {
        // Filter entities based on custom logic
        return $entityData->getData()["active"] === false; // true to filter out, false to keep
    }),
    new ExternalEntityFilterRestriction("entity_name", filterFunction: function (EntityData $entityData) {
        return false; // Don't filter any entity
    }, parameterValueTransformers: [
        new ParameterValueTransformer("name", function (EntityData $entityData, string $parameterName, mixed $value) {
            return strtoupper($value); // Transform the name to uppercase
        })
    ])
]);

Horus::getInstance()->setSharedEntities([
    new EntityReference("entity_name", "entity_id")
]);

Horus::getInstance()->setupOnSharedEntities(function(){
    return [new EntityReference("entity_name", "entity_id")];
});

Event::listen("horus.sync.insert", function (string $entityName, array $data) {
    // Your code here
});

Event::listen("horus.sync.update", function (string $entityName, array $data) {
    // Your code here
});

Event::listen("horus.sync.delete", function (string $entityName, array $data) {
    // Your code here
});
bash
php artisan horus:entity MyModelSync
bash
php artisan horus:entity MyModelSync --readable
bash
php artisan migrate
bash
php artisan horus:prune --expirationDays=7