') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); GitHub - gruz/remote-model: An eloquent-like model, for the Laravel framework. · GitHub
Skip to content

Repository files navigation

Laravel Remote Model

This model provides an eloquent-like base class that can be used to build custom models for remote APIs.

Installation

Install using composer:

$ composer require gruz/remote-model

Clients

Custom request method

To implement a custom API request method in the model, simple extend the Gruz\RemoteModel\Model class and use that extended model in the app models.

Example

<?phpnamespaceApp;
useAPIClient;
useGruz\RemoteModel\Model;
class BaseModel extends Model
{
/** * Make request through API. * * @return mixed */protectedfunctionrequest($endpoint = null, $method, $params)
{
$endpoint = $endpoint ? $endpoint : $this->endpoint;
$results = APIClient::$method($endpoint, $params);
return$results ? $this->newInstance($results) : null;
}
}

Client Wrapper Method

$client = new Client();
$client->{ENDPOINT}()->{METHOD}();

ENDPOINT The "snake case", plural name of the model class will be used as the endpoint name unless another name is explicitly specified. Using protected $endpoint = 'users'; at the top of the model, this is similar to the $table variable in Laravel models.

METHOD This is the action to take on the endpoint. It can be anything that the wrapper class provides.

Example Client Wrapper

<?phpnamespacePackageName\Api;
usePackageName\Api\Exception\BadMethodCallException;
usePackageName\Api\Exception\InvalidArgumentException;
class Client
{
/** * The HTTP client instance used to communicate with API. * * @var HttpClient */private$httpClient;
/** * Instantiate a new client. */publicfunction__construct()
{
$this->httpClient = newHttpClient;
}
/** * @param string $name * * @throws InvalidArgumentException * * @return ApiInterface */publicfunctionapi($name)
{
switch ($name)
{
case'users':
$api = newEndpoints\Users($this);
break;
case'reviews':
$api = newEndpoints\Reviews($this);
break;
default:
thrownewInvalidArgumentException(sprintf('Undefined api instance called: "%s"', $name));
}
return$api;
}
/** * @param string $name * * @throws InvalidArgumentException * * @return ApiInterface */publicfunction__call($name, $args)
{
try {
return$this->api($name);
}
catch (InvalidArgumentException$e) {
thrownewBadMethodCallException(sprintf('Undefined method called: "%s"', $name));
}
}
}

Example Endpoint for Client Wrapper

This is just to give an example.

<?phpnamespacePackageName\Api\Endpoints;
usePackageName\Api\Client;
class Users
{
/** * The client. * * @var \PackageName\Api\Client */protected$client;
/** * @param \PackageName\Api\Client $client */publicfunction__construct(Client$client)
{
$this->client = $client;
}
/** * Register a user. * * @param array $params * * @return array */publicfunctionadd(array$params)
{
return$this->client->post('users', $params);
}
/* * Update user data * * @param array $params * * @return object */publicfunctionupdate(array$params)
{
return$this->client->patch('users/self', $params);
}
/** * Get extended information about a user by its id. * * @param string $user_id * * @return array */publicfunctionfind($user_id)
{
return$this->client->get('users/'.rawurlencode($user_id));
}
}

Client Service Provider

An API client must be set before any data can be retrieved . To set the client use the static Model::setClient method.

Below is an example of the service provider way of setting the client.

<?phpnamespaceApp\Providers;
useGruz\RemoteModel\Model;
usePackageName\API\Client;
useIlluminate\Support\ServiceProvider;
class ApiServiceProvider extends ServiceProvider
{
/** * Bootstrap the application events. * * @return void */publicfunctionboot()
{
Model::setClient($this->app['apiclient']);
}
/** * Register the service provider. * * @return void */publicfunctionregister()
{
$this->app->singleton('apiclient', function () {
returnnewClient(); // API Client
});
}
/** * Get the services provided by the provider. * * @return string[] */publicfunctionprovides()
{
return [
'apiclient'
];
}
}

Example model

<?phpnamespaceApp;
useDateTime;
useGruz\RemoteModel\ModelasBaseModel;
class User extends BaseModel
{
protected$hidden = [
'password'
];
protected$casts = [
'age' => 'integer'
];
publicfunctionsave()
{
returnAPI::post('/items', $this->attributes);
}
publicfunctionsetBirthdayAttribute($value)
{
$this->attributes['birthday'] = strtotime($value);
}
publicfunctiongetBirthdayAttribute($value)
{
returnnewDateTime("@$value");
}
publicfunctiongetAgeAttribute($value)
{
return$this->birthday->diff(newDateTime('now'))->y;
}
}

Using model

$item = newUser([
'name' => 'john'
]);
$item->password = 'bar';
echo$item; // {"name":"john"}

About

An eloquent-like model, for the Laravel framework.

Resources

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages