PHP code example of macsidigital / laravel-api-client

1. Go to this page and download the library: Download macsidigital/laravel-api-client 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/ */

    

macsidigital / laravel-api-client example snippets


	// Where the models are
	protected $modelNamespace = '';

    // default query string names for page and per_page fields
    protected $perPageField = 'page_size';
    protected $pageField = 'page';

    // Should return raw responses and not models/resultsets
    protected $raw = false;

    // Should return raw responses and not models/resultsets
    protected $raw = false;

    // Should we throw exceptions in cases where a server error occurs
    protected $throwExceptionsIfRaw = false;

    // Should results be paginated by default.
    protected $pagination = true;

    // Amount of pagination results per page by default, leave blank if should not paginate
    // Without pagination rate limits could be hit
    protected $defaultPaginationRecords = '20';

    // Max and Min pagination records per page, will vary by API server
    protected $maxPaginationRecords = '100';
    protected $minPaginationRecords = '1';

    // If not paginated, how many queries should we allow per search, leave '' or 0 
    // for unlimited queries. This of course will eat up any rate limits
    protected $maxQueries = '5';

    // Most APIs should 

namespace MacsiDigital\Package\Support;

use MacsiDigital\Package\Facades\Client; // This should extend the MacsiDigital\API\Support\Factory
use MacsiDigital\API\Support\Entry as ApiEntry;

class Entry extends ApiEntry
{
    protected $modelNamespace = '\MacsiDigital\Package\\';

    // Change any attributes to match API
 
	public function newRequest()
    {
        return Client::baseUrl(config('api.base_url'))->withOptions(config('api.options'));
    }

	public function newRequest()
    {
        $config = config('xero');
    	$class = $config['tokenModel'];
    	$token = new $class('xero');
    	if($token->hasExpired()){
    		$token = $token->renewToken();
    	}
        return Client::baseUrl($config['baseUrl'])->withToken($token->accessToken())->withHeaders(['xero-tenant-id' => $token->tenantId()]);
    }

	public function getBuilderClass() 
    {
        return Builder::class; // By default links to MacsiDigital/API/Support/Builder
    }

	protected $createMethod = 'post';

    protected $updateMethod = 'patch';

	public function getUpdateMethod()
    {
        return $this->updateMethod;
    }

    public function getCreateMethod()
    {
        return $this->createMethod;
    }

	//Normal
	public function getPostEndPoint() 
    {
        return $this->endPoint;
    }

    public function getPutEndPoint() 
    {
        return $this->endPoint.'/'.$this->getKey();
    }

    //Xero
	public function getPostEndPoint() 
    {
        return $this->endPoint.'/'.$this->getKey();
    }

    public function getPutEndPoint() 
    {
        return $this->endPoint;
    }

	$user = API::user()->find('ID');

	$user = API::user()->where('Name', 'Bob')->first(); // First occurrence

    $user = API::user()->where('Name', 'Bob')->last(); // Last occurrence

	$users = API::account()->all();

	$users = API::account()->where('Type', 'Admin')->get();

	protected function hydrate($response)
    {
        return $this->resource->newFromBuilder($response->json()[$this->getApiDataField()][0]);
    }

    $meetings = $user->meetings;
    // Do some logic and discover need more results
    $meetings = $meetings->nextPage();

    // $meetings->previousPage() will go back a page.

    // We can also iterate directly over the returned results
    foreach($meetings->nextPage() as $meeting)

    //Finally for those using json api in SPA app, you can utilise the toArray or toJson functions
    $meetings->toArray();

    // returns 
    array:5 [
      "current_page" => 1
      "data" => array:2 [
        0 => array:10 [
          // $attributes
        ]
        1 => array:10 [
          // $attributes
        ]
      ]
      "last_page" => 5
      "per_page" => 30
      "total" => 137
    ]

    // will add more records to the current record set. The amount of records retrieved is based on the maxQueries and per page methods.
    $meetings->getNextRecords();

	$users = API::account()->raw()->all();

	$users = API::account()->where('Type', 'Admin')->raw()->get();

	$json = $response->json();
	if($json['Type'] == 'ValidationException'){
		$message = $json['Message'];
		foreach($json['Elements'][0]['ValidationErrors'] as $error){
			$message .= ' : '.$error['Message'];
		}
    	return $message;
	} else {
    	return $json['Message'];
	}

	// These will map to RESTful requests
	// index -> get and all
	// create -> post
	// show -> first
	// update -> patch or put
	// delete -> delete
    protected $allowedMethods = ['index', 'create', 'show', 'update', 'delete'];

    protected $endPoint = 'user';

    protected $updateMethod = 'patch';

    protected $storeResource;
    protected $updateResource;

    protected $primaryKey = 'id';

    // Most APIs return data in a data attribute.  However we need to override on a model basis as some like Xero return it as 'Users' or 'Invoices'
    protected $apiDataField = 'data'; 

    // Also, some APIs return 'users' for multiple and user for single, set teh multiple field below to wheat is 

    protected $apiDataField = '';

	public function getApiMultipleDataField()
    {
    	// Xero uses pluralised end points like 'Users' so we can use this to pick the data from responses
        return $this->endPoint;
    }

	public function getKeyName()
    {
        return $this->endPoint.'ID';
    }

    protected $endPoint = 'users/{user:id}/settings';

    protected $customEndPoints = [
        'get' => 'users/{user:id}/meetings',
        'post' => 'users/{user:id}/meetings'
    ];

	protected $loadRaw = false;

	protected $dontAutoloadRelation = ['Address'];

	public function address() 
    {
    	return $this->hasOne(Address::class);
    }

	public function user() 
    {
    	return $this->belongsTo(User::class);
    }

	protected $IdSuffix = 'ID';

	// Will now look for userID instead of user_id

	$user = API::user()->find('id');

	$address = $user->address;

	// or you can also call the method for further filtering
	
	$address = $user->address()->where('type', 'billing')->first();

    // save

    $user = API::user()->find('id');

    $address = Api::address()->find('id');
    
    $user->address()->save($address);

    // create

    $user = API::user()->find('id');
    
    $user->address()->create([
        'address1' => '17 Test Street',
        ...
    ]);

    $user = API::user()->find('id');
    
    $user->address()->make([
        'address1' => '21 Test Street',
        ....
    ]);

    $user = API::user()->find('id');

    $address = Address::make([...]);

    // Do some logic checks
    
    $user->address()->attach($address);

public function addresses()
{
    $this->hasCustom(Address::class, addressHasMany::class);

}

    protected $customEndPoints = [
        'get' => 'users/{user:id}/meetings',
        'post' => 'users/{user:id}/meetings'
    ];

	$user = API::user()->where('Name', 'John Doe')->first();

	$users = API::user()->where('Name', '!=', 'John Doe')->get();

	$posts = API::post()->where('Title', 'like', 'Mechanical')->get();

	$posts = API::post()->where('created_at', '>', '2019-01-01')->where('created_at', '<', '2019-12-31')->get();

	public function getBuilderClass() 
    {
        return \Namespace\To\Your\Builder::class; 
    }

	protected function addWhereEquals($column, $operand, $value)
    {
        $this->wheres[] = ['column' => $column, 'operand' => $operand, 'value' => $value];
    }

    public function processWhereEquals($detail) // Passed in the array attached in above method
    {
        $this->processedWheres[$detail['column']] = $detail['value'];
    }

	case '=':
	    return 'Equals';
	case '!=':
	    return 'NotEquals';
	case '>':
	    return 'GreaterThan';
	case '>=':
	    return 'GreaterThanOrEquals';
	case '<':
	    return 'LessThan';
	case '<=':
	    return 'LessThanOrEquals';
	case '<>':
	    return 'GreaterThanOrLessThan';
	case 'like':
	    return 'Contains';
	default:
	    return 'Process'.Str::studly($operand);

	public function processEquals($detail) 
	{
		if(!isset($this->processedWheres['where'])){
			$this->processedWheres['where'] = '';
		}
		$this->processedWheres['where'] .= $detail['column'].'=="'.$detail['value'].'"';
		
	}

	public function processNotEquals($detail) 
	{
		if(!isset($this->processedWheres['where'])){
			$this->processedWheres['where'] = '';
		}
		$this->processedWheres['where'] .= $detail['column'].'!="'.$detail['value'].'"';
	}

	public function processGreaterThan($detail) 
	{
		if(!isset($this->processedWheres['where'])){
			$this->processedWheres['where'] = '';
		}
		$this->processedWheres['where'] .= $detail['column'].'>"'.$detail['value'].'"';
	}

	public function processGreaterThanOrEquals($detail) 
	{
		if(!isset($this->processedWheres['where'])){
			$this->processedWheres['where'] = '';
		}
		$this->processedWheres['where'] .= $detail['column'].'>="'.$detail['value'].'"';
	}

	public function processLessThan($detail) 
	{
		if(!isset($this->processedWheres['where'])){
			$this->processedWheres['where'] = '';
		}
		$this->processedWheres['where'] .= $detail['column'].'<"'.$detail['value'].'"';
	}

	public function processLessThanOrEquals($detail) 
	{
		if(!isset($this->processedWheres['where'])){
			$this->processedWheres['where'] = '';
		}
		$this->processedWheres['where'] .= $detail['column'].'<="'.$detail['value'].'"';
	}

	public function processGreaterThanOrLessThan($detail) 
	{
		if(!isset($this->processedWheres['where'])){
			$this->processedWheres['where'] = '';
		}
		$this->processedWheres['where'] .= $detail['column'].'<>"'.$detail['value'].'"';
	}

	public function processContains($detail) 
	{
		if(!isset($this->processedWheres['where'])){
			$this->processedWheres['where'] = '';
		}
		$this->processedWheres['where'] .= $detail['column'].'.Contains("'.$detail['value'].'")';
	}

	public function processStartsWith($detail) 
	{
		if(!isset($this->processedWheres['where'])){
			$this->processedWheres['where'] = '';
		}
		$this->processedWheres['where'] .= $detail['column'].'.StartsWith("'.$detail['value'].'")';
	}

	public function processEndsWith($detail) 
	{
		if(!isset($this->processedWheres['where'])){
			$this->processedWheres['where'] = '';
		}
		$this->processedWheres['where'] .= $detail['column'].'.EndsWith("'.$detail['value'].'")';
	}

	// you would need to spoof the column name, as its not used but is still $date)->get();

	public function addWhereModifiedAfter($column, $operand, $value) 
	{
		$this->wheres[] = ['operand' => $operand, 'value' => $value];
	}

	public function processWhereModifiedAfter($detail) 
	{
		$this->request->withHeader([
			'If-Modified-Since' => $detail['value']
		]);
	}

	protected $allowedOperands = ['=', '!=', '<', '>', '<=', '>=', '<>', 'like', 'ModifiedAfter'];

	protected $insertResource = 'MacsiDigital\API\Dev\Resources\StoreAddress';
    protected $updateResource = 'MacsiDigital\API\Dev\Resources\UpdateAddress';

	protected $persistAttributes = [
    	'name' => '    	'password' => '

	protected $persistAttributes = [
    	'name' => '    	'password' => 'igital\API\Dev\Resources\UpdateAddress'
    ];

	protected $persistAttributes = [
    	'street' => ''town' => ' '

    protected $relatedResource = [
    	'address' => [
            'street' => '|max:255',
    		'county' => 'nullable|string|max:255',
    		'postcode' => '

	protected $persistAttributes = [
    	'name' => '    	'password' => 'n' => '

    //Normal create
   [
        'name' => 'John Doe',
        'email' => '[email protected]'
   ] 

   // Some APIs may ' => '[email protected]'
        ]
   ]

    protected $persistAttributes = [
        'action' => '      'user_info.email' => ' end up as
    protected $mutateAttributes = [
        'name' => 'user_info.name',
        'email' => 'user_info.email'
        'type' => 'status' //can also use to mutate current attributes into attributes for the api
    ] 


	$user->save();

	$user->delete();

    public function updateProfilePicture($image)
    {
        $filesize = number_format(filesize($image) / 1048576,2);
        if($filesize > 2){
            throw new FileTooLargeException($image, $filesize, '2MB');
        } else {
            return $this->newQuery()->attachFile('pic_file', file_get_contents($image), $image)->sendRequest('post', ['users/'.$this->id.'/picture'])->successful();
        }
    }