PHP code example of jeanisahakyan / motion-dots

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

    

jeanisahakyan / motion-dots example snippets



MotionDots\Process\Processor;
use MotionDots\Schema\Schema;
use API\Methods\Users;

// Create schema and add methods
$schema = Schema::create()->addMethods([new Users()]);

// Create processor
$processor = new Processor($schema, '.');

// Handle request
$response = $processor->invokeProcess('users.getUser', $params);
echo json_encode($response);

class Users extends AbstractMethod {
    public function getUser(PositiveType $id): UserResponse {
        $userId = $id->parse();
        return UserResponse::create()->setId($userId);
    }
}

class EmailType extends AbstractType {
    public function parse(): string {
        $email = filter_var($this->field, FILTER_VALIDATE_EMAIL);
        if ($email === false) {
            throw new ErrorException(ErrorException::PARAM_INCORRECT, "Invalid email");
        }
        return $email;
    }
}

class UserResponse extends AbstractResponse {
    public int $id = 0;
    public string $name = '';
    
    public function setId(int $id): self {
        $this->id = $id;
        return $this;
    }
}


// index.php
ocess\Processor;
use MotionDots\Schema\Schema;
use API\Methods\Users;

// Set headers
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json; charset=UTF-8');

try {
    // Merge request parameters
    $params = array_merge($_GET, $_POST, $_FILES);
    
    // Create schema and add methods
    $schema = Schema::create()->addMethods([
        new Users(),
        // Add other method classes here
    ]);
    
    // Create processor
    $processor = new Processor($schema, '.');
    
    // Set initial context
    $processor->getContext()->setMany([
        'requestTime' => microtime(true),
        'clientIp' => $_SERVER['REMOTE_ADDR'] ?? 'unknown'
    ]);
    
    // Extract method from URL
    if (preg_match('/\/api\/([a-zA-Z\.]+)/i', $_SERVER['REQUEST_URI'], $matches)) {
        [, $method] = $matches;
    } else {
        $method = 'system.getSchema'; // Default to schema info
    }
    
    // Invoke method and return response
    $response = $processor->invokeProcess($method, $params);
    echo json_encode($response);
    
} catch (\Exception $exception) {
    echo json_encode([
        'error' => [
            'error_code' => $exception->getCode(),
            'error_message' => $exception->getMessage(),
        ]
    ]);
}


// src/API/Methods/Users.php
namespace API\Methods;

use MotionDots\Method\AbstractMethod;
use API\Responses\UserResponse;
use API\Types\EmailType;
use MotionDots\Type\PositiveType;

class Users extends AbstractMethod {
    public function getUser(PositiveType $id): UserResponse {
        $userId = $id->parse();
        return UserResponse::create()->setId($userId);
    }
    
    public function createUser(EmailType $email, string $name): UserResponse {
        $emailValue = $email->parse();
        return UserResponse::create()
            ->setEmail($emailValue)
            ->setName($name);
    }
}

public function registerUser(EmailType $email, PasswordType $password): UserResponse {
    $emailValue = $email->parse();
    $passwordValue = $password->parse();

    // Business logic here

    return UserResponse::create()
        ->setEmail($emailValue)
        ->setStatus(UserStatus::ACTIVE);
}

public function registerUser(EmailType $email, PasswordType $password): UserResponse {
    // Set data in context
    $request_time = $this->context->get('requestTime');

    // Rest of the method...
}

public function loginUser(EmailType $email, PasswordType $password): UserResponse {
    $emailValue = $email->parse();
    $passwordValue = $password->parse();

    // Business logic here

    // Set user ID in context after successful login
    $this->context->set('userId', $userId);

    return UserResponse::create()
        ->setId($userId)
        ->setEmail($emailValue)
        ->setStatus(UserStatus::ACTIVE);
}

public function updateUserStatus(int $userId, UserStatus $status): UserResponse {
    // Access user ID from context if needed
    $currentUserId = $this->context->get('userId');

    // Business logic here

    return UserResponse::create()
        ->setId($userId)
        ->setStatus($status);
}


// src/API/Responses/UserResponse.php

namespace API\Responses;

use MotionDots\Response\AbstractResponse;
use API\Enums\UserStatus;

class UserResponse extends AbstractResponse {
    public int $id;
    public string $email;
    public UserStatus $status;

    public function setId(int $id): self {
        $this->id = $id;
        return $this;
    }

    public function setEmail(string $email): self {
        $this->email = $email;
        return $this;
    }

    public function setStatus(UserStatus $status): self {
        $this->status = $status;
        return $this;
    }
}


// src/API/Types/EmailType.php

namespace API\Types;

use MotionDots\Type\AbstractType;
use MotionDots\Exception\ErrorException;

class EmailType extends AbstractType {
    public function parse(): string {
        $email = filter_var($this->field, FILTER_VALIDATE_EMAIL);
        if ($email === false) {
            throw new ErrorException(ErrorException::PARAM_INCORRECT, "`{$this->param_name}` must be a valid email address");
        }
        return $email;
    }
}


// src/API/Enums/UserStatus.php

namespace API\Enums;

enum UserStatus: string {
    case ACTIVE = 'active';
    case INACTIVE = 'inactive';
    case BANNED = 'banned';
}

public function updateUserStatus(int $userId, UserStatus $status): UserResponse {
    // Business logic here

    return UserResponse::create()
        ->setId($userId)
        ->setStatus($status);
}

  // Instantiate the processor
    $processor = new Processor($schema, '.');
    // Invoke the method and output the response
    $response = $processor->invokeProcess($method, $params);

use MotionDots\Exception\ErrorException;

if (!$user) {
    throw new ErrorException(ErrorException::PARAM_INCORRECT, "User not found");
}



use MotionDots\Schema\Typescript\Generator;

// Generate TypeScript definitions
Generator::create()
    ->setFilesPath('./frontend/src/types/api')
    ->setIsVerbose(true)
    ->excludeSpaces('admin', 'debug')
    ->generate($processor);

use MotionDots\Exception\ErrorException;

// Throw specific errors
throw new ErrorException(
    ErrorException::PARAM_INCORRECT,
    "User with ID {$userId} not found"
);

project/
├── composer.json
├── vendor/
│   └── autoload.php
├── index.php
├── docs/                    # 📚 Comprehensive documentation
└── src/
    ├── API/
    │   ├── Methods/         # 🚀 API endpoint classes
    │   │   └── Users.php
    │   ├── Responses/       # 📋 Response format classes
    │   │   └── UserResponse.php
    │   ├── Types/          # 🛡️ Custom parameter types
    │   │   ├── EmailType.php
    │   │   └── PasswordType.php
    │   └── Enums/          # 🔧 PHP 8.1 enums
    │       └── UserStatus.php
    └── (Other application files)