Skip to content

Ozu production seeder #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
May 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,40 @@ class DatabaseSeeder extends OzuSeeder
}
```

### Production seeder

To ease the first deployment of your project, you can use the `OzuProductionSeeder` class to seed ozu with some production data:

```php
use Code16\OzuClient\Support\Database\OzuProductionSeeder;
// ...

class DatabaseSeeder extends OzuProductionSeeder
{
public function run(): void
{
// At this point, you'll have to create your real data, you're not forced to save
// it in your local database, since Ozu will accept a model without an ID, and seed it in Production.
$myRealProjects = Project::factory()
->count(12)
->has(Media::factory()->image('cover')->withFile(), 'cover')
->has(Media::factory()->image('visuals')->withFile()->count(3), 'visuals')
->sequence(fn ($sequence) => [
'order' => $sequence->index + 1,
'country' => fake()->country(),
])
->make();

$myRealProjects
->each(fn($project) => $this->createInOzu($project)
->withFile('cover', $project->cover->file_name)
->withFileList('visuals', $project->visuals->pluck('file_name')->toArray())
);
// ...
}
}
```

### Check the demo project for an example

You can refer to the Ozu demo project [dvlpp/ozu-demo](https://github.com/dvlpp/ozu-demo) for an example of a simple project that uses Ozu.
Expand Down
20 changes: 20 additions & 0 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,26 @@ public function updateCollectionSharpConfiguration(string $collectionKey, array
);
}

public function seed(string $collection, array $payload): mixed
{
return $this->http()->post(
sprintf('/collections/%s/seed', $collection),
$payload
)->json();
}

public function seedFile(string $collection, int $id, string $field, string $path): mixed
{
return $this->http()
->attach('file', file_get_contents($path), basename($path))
->post(
sprintf('/collections/%s/seed/%s/file', $collection, $id),
[
'field' => $field,
]
)->getBody()?->getContents();
}

public function apiKey(): ?string
{
return $this->apiKey;
Expand Down
Empty file added src/Deploy/Crawler/Observer.php
Empty file.
Empty file.
Empty file added src/Deploy/Jobs/CrawlSite.php
Empty file.
Empty file.
Empty file.
Empty file.
11 changes: 3 additions & 8 deletions src/Eloquent/Media.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Facades\Schema;
use Number;

class Media extends Model
{
Expand Down Expand Up @@ -52,15 +53,9 @@ public function humanReadableSize($precision = 2): ?string
return null;
}

if ($this->size >= 0) {
$size = (int) $this->size;
$base = log($size) / log(1024);
$suffixes = [' bytes', ' KB', ' MB', ' GB', ' TB'];
$size = (int) $this->size;

return $this->size === 0 ? '0 bytes' : (round(pow(1024, $base - floor($base)), $precision).$suffixes[floor($base)]);
} else {
return $this->size;
}
return Number::fileSize($size, 1, 3);
}

/**
Expand Down
72 changes: 72 additions & 0 deletions src/Support/Database/OzuProductionSeeder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

namespace Code16\OzuClient\Support\Database;

use Code16\OzuClient\Client;
use Code16\OzuClient\Eloquent\IsOzuModel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;

class OzuProductionSeeder extends Seeder
{
protected Client $client;

private ?int $createdId = null;

private ?string $currentCollectionKey = null;

public function __construct()
{
$this->client = app(Client::class);
}

protected function createInOzu(Model $item): static
{
if (! in_array(IsOzuModel::class, class_uses_recursive($item))) {
throw new \InvalidArgumentException($item::class." doesn't have the IsOzuModel trait");
}

$this->currentCollectionKey = $collectionKey = $item?->ozuCollectionKey();

if (! $collectionKey) {
throw new \InvalidArgumentException('Unable to retrieve collection key.');
}

$this->createdId = $this->client->seed($collectionKey, $item->toArray())['id'] ?? null;

return $this;
}

protected function withFile(string $field, string $path, ?int $forceId = null): static
{
if (! $forceId && ! $this->createdId) {
throw new \InvalidArgumentException('No item created yet. Try calling createInOzu() first.');
}

if (! File::exists($path)) {
throw new \InvalidArgumentException("File not found at path: {$path}");
}

$this->client->seedFile($this->currentCollectionKey, $forceId ?? $this->createdId, $field, $path);

return $this;
}

/**
* @param array<string> $paths
*/
protected function withFileList(string $field, array $paths, ?int $forceId = null): static
{
foreach ($paths as $path) {
$this->withFile($field, $path, $forceId);
}

return $this;
}

protected function id(): ?int
{
return $this->createdId;
}
}
2 changes: 1 addition & 1 deletion tests/ArchTest.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?php

it('will not use debugging functions')
->expect(['die', 'dd', 'dump', 'ray', 'ddRawSql', 'var_dump'])
->expect(['die', 'dd', 'dump', 'ray', 'ds', 'ddRawSql', 'var_dump'])
->each->not->toBeUsed();
2 changes: 2 additions & 0 deletions tests/Fixtures/DummyTestModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ class DummyTestModel extends Model

use IsOzuModel;

protected $guarded = [];

public static function configureOzuCollection(OzuCollectionConfig $config): OzuCollectionConfig
{
return $config;
Expand Down
61 changes: 61 additions & 0 deletions tests/Unit/Database/OzuProductionSeederTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

use Code16\OzuClient\Support\Database\OzuProductionSeeder;
use Code16\OzuClient\Tests\Fixtures\DummyTestModel;
use Illuminate\Http\UploadedFile;

it('allows users to seed models in production', function () {
Http::fake();
config()->set('ozu-client.api_host', 'http://ozu.test');
config()->set('ozu-client.api_key', 'api_key');
config()->set('ozu-client.api_version', 'v1');
config()->set('ozu-client.website_key', 'key');

$seeder = new class extends OzuProductionSeeder
{
public function run()
{
$this->createInOzu(DummyTestModel::make([
'title' => 'Project 1',
]))->id();
}
};

$seeder->run();
Http::assertSent(function (Illuminate\Http\Client\Request $request) {
return
$request->url() === (sprintf('http://ozu.test/api/v1/key/collections/%s/seed', app(DummyTestModel::class)->ozuCollectionKey()))
&& collect($request->data())->has('title')
&& $request->data()['title'] === 'Project 1';
});
});

it('allows users to seed images on models in production', function () {
Http::fake();
Storage::fake('local');

config()->set('ozu-client.api_host', 'http://ozu.test');
config()->set('ozu-client.api_key', 'api_key');
config()->set('ozu-client.api_version', 'v1');
config()->set('ozu-client.website_key', 'key');

$seeder = new class extends OzuProductionSeeder
{
public function run()
{
$path = Storage::disk('local')->path('/images/image.jpg');
UploadedFile::fake()->image('image.jpg')->storeAs('/images', 'image.jpg', ['disk' => 'local']);

$this->createInOzu(DummyTestModel::make([
'title' => 'Project 1',
]))->withFile('cover', $path, forceId: 5);
}
};

$seeder->run();
Http::assertSent(function (Illuminate\Http\Client\Request $request) {
return
$request->url() === (sprintf('http://ozu.test/api/v1/key/collections/%s/seed/5/file', app(DummyTestModel::class)->ozuCollectionKey()))
&& collect($request->data())->keyBy('name')->has(['file', 'field']);
});
});