PHP code example of edulazaro / larasources

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

    

edulazaro / larasources example snippets


// config/larasources.php, if you want this convention
'origins' => [
    'my_provider' => [
        'api_key' => env('MY_PROVIDER_API_KEY'),
        'sandbox' => env('MY_PROVIDER_SANDBOX', false),
        'timeout' => 15,
        'retry' => ['attempts' => 3, 'delay' => 1000],
    ],
],

class MyProviderOrigin extends Origin
{
    protected function config(?string $key = null, mixed $default = null): mixed
    {
        $credentials = $this->integration->credentials ?? [];

        return $key ? ($credentials[$key] ?? $default) : $credentials;
    }
}

'sources' => [
    'weather' => ['units' => 'metric'],
],

$this->config('units');     // inside the source
$source->config('units');   // from outside

use Illuminate\Database\Eloquent\Model;
use EduLazaro\Larasources\Concerns\HasSources;
use App\Sources\WeatherSource;

class City extends Model
{
    use HasSources;

    protected array $sources = [
        'weather' => WeatherSource::class,
    ];
}

$city = City::find(1);

// Access external data (autoloaded from cache or fetched on miss)
$weather = $city->source('weather');
echo $weather->temperature;
echo $weather->humidity;

// Push data to the external API and persist locally. Failures throw.
$city->source('weather')->save();

// Same, reporting the outcome instead of throwing
$result = $city->source('weather')->trySave();

if ($result->failed()) {
    return back()->withErrors($result->message);
}

// Read live from the API and refresh the cached record
$fresh = $city->source('weather')->fetch();

// Delete remote and clear cache
$city->source('weather')->delete();

namespace App\Sources;

use EduLazaro\Larasources\Source;
use EduLazaro\Larasources\Attributes\UsesOrigin;
use App\Origins\MyProviderOrigin;

#[UsesOrigin(MyProviderOrigin::class)]
class WeatherSource extends Source
{
    protected $fillable = [
        'temperature',
        'humidity',
        'description',
    ];

    protected $casts = [
        'temperature' => 'float',
        'humidity'    => 'integer',
    ];

    protected function arguments(): array
    {
        return [
            'city_id' => 'external_id', // maps to $city->external_id
        ];
    }

    public function getFeelsLikeAttribute(): float
    {
        return $this->temperature - ($this->humidity / 10);
    }
}

namespace App\Origins;

use EduLazaro\Larasources\Origins\Origin;
use Illuminate\Support\Facades\Http;

class MyProviderOrigin extends Origin
{
    public static function getAlias(): string
    {
        return 'my_provider';
    }

    public function fetch(array $arguments = []): array
    {
        $response = Http::withToken($this->config('api_key'))
            ->get('https://api.example.com/weather/' . $arguments['city_id']);

        return $response->json();
    }

    public function save(array $data): array
    {
        $response = Http::withToken($this->config('api_key'))
            ->post('https://api.example.com/weather', $data);

        return $response->json();
    }

    public function delete(): bool
    {
        return true;
    }
}

$scraped = $article->source('scraped')->fetch();

$article->source('translation')
    ->useArgument('scraped', $scraped)   // a model, a source, or its record
    ->fetch();                           // the origin receives the scraped payload

$city->source('weather')->setVariant('forecast')->fetch();

// Pass runtime arguments
$city->source('weather', ['city_id' => 'custom_id'])->fetch();

// Has it ever been fetched/saved? One query, looked up once per instance
if ($source->record()) {
    // It is stored locally
}

// What the origin says right now, cached on the way out
$source->fetch();

// Compare what is stored with what the origin has
$stored = $source->record()->toArray();   // name, variant, origin, attributes, dates
$live   = $source->fetch()->toArray();    // the fields, straight from the service

// Clear the cache for this source
$source->clear();

use EduLazaro\Larasources\Enums\OriginStatus;
use EduLazaro\Larasources\OriginResult;

public function save(array $data): array|OriginResult
{
    $response = $this->http()->post($this->endpoint, $data)->throw()->json();

    return new OriginResult(
        status: $response['published'] ? OriginStatus::Saved : OriginStatus::Processing,
        data: $response,
        message: $response['reason'] ?? null,
    );
}

SourceRecord::processing()->where('updated_at', '<', now()->subHour())->get();

// Where the latency is yours to spend: a scheduled command, not a page render
foreach (SourceRecord::processing()->get() as $record) {
    try {
        $record->toSource(ListingSource::class)->reconcile();
    } catch (OriginException $e) {
        // One service being down does not stop the rest
    }
}

// Or on the source you already have
$listing = $property->source('listing')->reconcile();

$info = $property->source('listing')->origin()->fetchQuota();

class AdvertDescriptionSource extends Source
{
    public function regenerateFromBriefing(string $briefing): static
    {
        $this->fill($this->origin()->generateFromBriefing($briefing));

        return $this->persist();
    }
}

return new OriginResult(
    status: OriginStatus::Saved,
    data: $response,
    externalId: $response['propertyId'],
);

public function save(array $data): array|OriginResult
{
    $id = $this->source->externalId();

    $response = $id
        ? $this->http()->put("{$this->baseUrl}/listings/{$id}", $data)->throw()->json()
        : $this->http()->post("{$this->baseUrl}/listings", $data)->throw()->json();

    return new OriginResult(OriginStatus::Saved, data: $response, externalId: $response['id']);
}

$record = SourceRecord::where('name', 'listing')->where('external_id', $id)->first();

$property = $record?->sourceable;

// No model exists yet: the external id is the identity
$scraped = ListingSource::make()->setExternalId($link)->fetch();

// Whatever it turns out to be
$property = Property::create(['reference' => $scraped->reference]);

// And the row becomes that model's source
$scraped->attachTo($property);

// What is still waiting
SourceRecord::unattached()->where('name', 'ListingSource')->get();

use EduLazaro\Larasources\Exceptions\OriginException;

try {
    $weather = $city->source('weather')->fetch();
} catch (OriginException $e) {
    Log::error('Provider error: ' . $e->getMessage());
}

$result = $city->source('weather')->trySave();

match ($result->status) {
    OriginStatus::Saved      => $this->notify('Published'),
    OriginStatus::Processing => $this->notify('Publishing'),
    OriginStatus::Failed     => $this->notify($result->message),
};

$mock = new WeatherSource(['temperature' => 22.5, 'humidity' => 60]);
$city->mockSource(WeatherSource::class, $mock);

$weather = $city->source('weather');
// $weather is the mocked instance
bash
php artisan migrate