Skip to content

WIP: Handle Custom Filesystem Definition #11

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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
28 changes: 27 additions & 1 deletion config/ozu-client.php
Original file line number Diff line number Diff line change
@@ -1,15 +1,41 @@
<?php

use Code16\OzuClient\OzuCms\Storage\OzuCustomFTPStorage;
use Code16\OzuClient\OzuCms\Storage\OzuCustomS3Storage;

return [
// List here your collections, ie the Models that will be handled by the Ozu CMS.
// You must also properly configure them (see documentation).
'collections' => [
// \App\Models\Project::class,
// \App\Models\Project::class,
],

// The Ozu unique key of the website to use
'website_key' => env('OZU_WEBSITE_KEY'),

// If you want to use custom storage for your files, you can configure it here.
// If you change your configuration after having uploaded files, you will have to manually move them to the new storage
// Or reset them in ozu.
// This is an example of how to configure a custom S3 storage:

/* 'custom_storage' => OzuCustomS3Storage::make()
->setBucketName(env('OZU_S3_BUCKET'))
->setRegion(env('OZU_S3_REGION'))
->setKey(env('OZU_S3_KEY'))
->setSecret(env('OZU_S3_SECRET'))
->setEndpoint(env('OZU_S3_ENDPOINT'))
->setUsePathStyleEndpoint(env('OZU_S3_USE_PATH_STYLE_ENDPOINT'))
,*/

// This is an example of how to configure a custom FTP storage:
/*'custom_storage' => OzuCustomFTPStorage::make()
->setHost(env('OZU_FTP_HOST'))
->setPort(env('OZU_FTP_PORT'))
->setUsername(env('OZU_FTP_USERNAME'))
->setPassword(env('OZU_FTP_PASSWORD'))
->setRootPath(env('OZU_FTP_ROOT_PATH'))
,*/

// The API key to use to authenticate with the Ozu API
// (do not fill this value here, use the .env file instead)
'api_key' => env('OZU_API_KEY'),
Expand Down
12 changes: 6 additions & 6 deletions database/factories/MediaFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,17 +44,17 @@ public function file(string $key): Factory
});
}

public function withFile(?string $fileName = null, string $type="image")
public function withFile(?string $fileName = null, string $type = 'image')
{
return $this->state(function (array $attributes) use ($fileName,$type) {
$fileName = $fileName ?: fake()->slug() . ($type==='image'?'.jpg':'.pdf');
$path = ($type==="image" ? $this->getRandomFixtureImagePath() : $this->getRandomFixtureDocumentPath());
return $this->state(function (array $attributes) use ($fileName, $type) {
$fileName = $fileName ?: fake()->slug().($type === 'image' ? '.jpg' : '.pdf');
$path = ($type === 'image' ? $this->getRandomFixtureImagePath() : $this->getRandomFixtureDocumentPath());

Storage::disk('local')
->put("/data/".($type==='image'?'medias':'files')."/$fileName", file_get_contents($path));
->put('/data/'.($type === 'image' ? 'medias' : 'files')."/$fileName", file_get_contents($path));

return [
'file_name' => "data/".($type==='image'?'medias':'files')."/$fileName",
'file_name' => 'data/'.($type === 'image' ? 'medias' : 'files')."/$fileName",
];
});
}
Expand Down
11 changes: 9 additions & 2 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ public function __construct(
protected ?string $apiKey,
protected string $apiVersion,
protected string $websiteKey,
) {
}
) {}

public function updateCollectionSharpConfiguration(string $collectionKey, array $collectionData): void
{
Expand All @@ -23,6 +22,14 @@ public function updateCollectionSharpConfiguration(string $collectionKey, array
);
}

public function updateCustomStorageConfiguration(array $configuration): void
{
$this->http()->post(
'/storage/configure',
$configuration
);
}

public function apiKey(): ?string
{
return $this->apiKey;
Expand Down
61 changes: 44 additions & 17 deletions src/Console/ConfigureCmsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,26 @@
use Closure;
use Code16\OzuClient\Client;
use Code16\OzuClient\OzuCms\Form\OzuField;
use Code16\OzuClient\OzuCms\List\OzuColumn;
use Code16\OzuClient\OzuCms\OzuCollectionConfig;
use Code16\OzuClient\OzuCms\OzuCollectionFormConfig;
use Code16\OzuClient\OzuCms\OzuCollectionListConfig;
use Code16\OzuClient\OzuCms\OzuCollectionConfig;
use Code16\OzuClient\OzuCms\List\OzuColumn;
use Code16\OzuClient\OzuCms\Storage\OzuAbstractCustomStorage;
use Illuminate\Console\Command;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Schema;

class ConfigureCmsCommand extends Command
{
protected $signature = 'ozu:configure-cms';

protected $description = 'Send CMS configuration to Ozu.';

public function handle(Client $ozuClient): int
{
if (empty(config('ozu-client.collections'))) {
$this->info('No collections to configure.');

return self::SUCCESS;
}

Expand All @@ -33,9 +36,9 @@ public function handle(Client $ozuClient): int
default => $collection,
};

$collection = $model::configureOzuCollection(new OzuCollectionConfig());
$list = $model::configureOzuCollectionList(new OzuCollectionListConfig());
$form = $model::configureOzuCollectionForm(new OzuCollectionFormConfig());
$collection = $model::configureOzuCollection(new OzuCollectionConfig);
$list = $model::configureOzuCollectionList(new OzuCollectionListConfig);
$form = $model::configureOzuCollectionForm(new OzuCollectionFormConfig);

return [
'key' => $model->ozuCollectionKey(),
Expand All @@ -45,7 +48,7 @@ public function handle(Client $ozuClient): int
'autoDeployDateField' => $collection->autoDeployDateField(),
'isCreatable' => $collection->isCreatable(),
'isDeletable' => $collection->isDeletable(),
'order' => $k+1,
'order' => $k + 1,
'list' => [
'isReorderable' => $list->isReorderable(),
'isSearchable' => $list->isSearchable(),
Expand All @@ -59,49 +62,73 @@ public function handle(Client $ozuClient): int
'key' => $column->key(),
'label' => $column->label(),
'size' => $column->size(),
])
]),
],
'form' => [
'title' => $form->titleField()?->toArray(),
'cover' => $form->coverField()?->toArray(),
'content' => $form->contentField()?->toArray(),
'fields' => $form
->customFields()
->map(fn (OzuField $field) => $field->toArray())
->map(fn (OzuField $field) => $field->toArray()),
],
'customFields' => collect(Schema::getColumnListing($model->getTable()))
->filter(fn (string $column) => !in_array($column, $model::$ozuColumns))
->filter(fn (string $column) => ! in_array($column, $model::$ozuColumns))
->mapWithKeys(fn (string $column) => [
$column => match(Schema::getColumnType($model->getTable(), $column)) {
$column => match (Schema::getColumnType($model->getTable(), $column)) {
'datetime', 'timestamps' => 'dateTime',
'date' => 'date',
'int', 'bigint', 'smallint', 'mediumint', 'tinyint' => 'integer',
'float', 'double' => 'float',
'text', 'json' => 'text',
default => 'string',
}
])
},
]),
];
})
->each(function (array $collection) use ($ozuClient) {
$this->info('Update CMS configuration for [' . $collection['key'] . '].');
try{
$this->info('Update CMS configuration for ['.$collection['key'].'].');
try {
$ozuClient->updateCollectionSharpConfiguration(
$collection['key'],
$collection
);
} catch(RequestException $e) {
} catch (RequestException $e) {
if ($message = $e->response->json()) {
if(!isset($message['message'])) {
if (! isset($message['message'])) {
throw $e;
}
$this->error('[' . $collection['key'] . '] '.$message['message']);
$this->error('['.$collection['key'].'] '.$message['message']);
} else {
throw $e;
}
}
});

if (config('ozu-client.custom_storage')) {
$customStorage = config('ozu-client.custom_storage');

if ($customStorage instanceof OzuAbstractCustomStorage) {
if ($customStorage->meetRequirements()) {
$ozuClient->updateCustomStorageConfiguration(config('ozu-client.custom_storage')->toArray());
} else {
$this->error(
sprintf('Custom storage does not meet requirements. Missing : %s',
$customStorage->whatsMissing()->join(', ')
)
);

return self::FAILURE;
}
} else {
$this->error('Custom storage must be an instance of OzuAbstractCustomStorage');

return self::FAILURE;
}
} else {
$ozuClient->updateCustomStorageConfiguration([]);
}

$this->info('CMS configuration sent to Ozu.');

return self::SUCCESS;
Expand Down
4 changes: 2 additions & 2 deletions src/Deploy/Crawler/Observer.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ public function crawled(UriInterface $url, ResponseInterface $response, ?UriInte
{
try {
parent::crawled($url, $response, $foundOnUrl, $linkText);
} catch(\RuntimeException $e) {
if(preg_match('/returned status code \[4\d\d]/', $e->getMessage())) {
} catch (\RuntimeException $e) {
if (preg_match('/returned status code \[4\d\d]/', $e->getMessage())) {
Log::warning("Crawled URL {$url} found on {$foundOnUrl} returned status code 4xx", [
'url' => (string) $url,
'status_code' => $response->getStatusCode(),
Expand Down
2 changes: 1 addition & 1 deletion src/Deploy/DeployServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public function register()
public function boot()
{
$this->app['events']->listen(function (CommandStarting $event) {
if($event->command === 'export') {
if ($event->command === 'export') {
Artisan::call('cache:clear', [], $event->output);
}
});
Expand Down
4 changes: 2 additions & 2 deletions src/Deploy/Jobs/CrawlSite.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<?php

namespace Code16\OzuClient\Deploy\Jobs;

use Code16\OzuClient\Deploy\Crawler\Observer;
use Illuminate\Contracts\Routing\UrlGenerator;
use Illuminate\Foundation\Bus\Dispatchable;
use Psr\Http\Message\UriInterface;
use Spatie\Crawler\Crawler;
use Spatie\Crawler\CrawlProfiles\CrawlInternalUrls;
use Spatie\Export\Crawler\LocalClient;
Expand All @@ -18,7 +18,7 @@ public function handle(UrlGenerator $urlGenerator, Destination $destination): vo
{
$entry = config('app.url');

(new Crawler(new LocalClient()))
(new Crawler(new LocalClient))
->setCrawlObserver(new Observer($entry, $destination))
->setCrawlProfile(new CrawlInternalUrls($entry))
->startCrawling($entry);
Expand Down
2 changes: 1 addition & 1 deletion src/Deploy/Jobs/CrawlSiteHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ class CrawlSiteHandler
{
public function __invoke(): void
{
app(Dispatcher::class)->dispatchNow(new CrawlSite());
app(Dispatcher::class)->dispatchNow(new CrawlSite);
}
}
2 changes: 1 addition & 1 deletion src/Deploy/Routing/UrlGenerator.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<?php

namespace Code16\OzuClient\Deploy\Routing;
use Illuminate\Routing\UrlGenerator as BaseUrlGenerator;

use Illuminate\Routing\UrlGenerator as BaseUrlGenerator;

class UrlGenerator extends BaseUrlGenerator
{
Expand Down
4 changes: 1 addition & 3 deletions src/Deploy/RoutingServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ public function register()
$this->registerUrlGenerator();
}

public function boot()
{
}
public function boot() {}

/**
* @see parent::registerUrlGenerator();
Expand Down
11 changes: 6 additions & 5 deletions src/Eloquent/Media.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace Code16\OzuClient\Eloquent;

use Code16\OzuClient\Database\Factories\MediaFactory;
use Code16\OzuClient\Support\Thumbnails\LocalThumbnail;
use Code16\OzuClient\Support\Thumbnails\Thumbnail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
Expand All @@ -15,23 +14,25 @@ class Media extends Model
use HasFactory;

protected $guarded = [];

protected $table = 'medias';

protected $casts = [
'custom_properties' => 'array',
'size' => 'integer',
];

protected static function newFactory()
{
return new MediaFactory();
return new MediaFactory;
}

public function model(): MorphTo
{
return $this->morphTo('model');
}

public function thumbnail(int $width = null, int $height = null, bool $fit = false): ?string
public function thumbnail(?int $width = null, ?int $height = null, bool $fit = false): ?string
{
return app(Thumbnail::class)
->forMedia($this)
Expand All @@ -54,9 +55,9 @@ public function humanReadableSize($precision = 2): ?string
if ($this->size >= 0) {
$size = (int) $this->size;
$base = log($size) / log(1024);
$suffixes = array(' bytes', ' KB', ' MB', ' GB', ' TB');
$suffixes = [' bytes', ' KB', ' MB', ' GB', ' TB'];

return $this->size === 0 ? '0 bytes' : (round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)]);
return $this->size === 0 ? '0 bytes' : (round(pow(1024, $base - floor($base)), $precision).$suffixes[floor($base)]);
} else {
return $this->size;
}
Expand Down
1 change: 0 additions & 1 deletion src/OzuCms/Form/OzuBelongsToField.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,3 @@ public function toArray(): array
]);
}
}

8 changes: 6 additions & 2 deletions src/OzuCms/Form/OzuEditorField.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,19 @@
class OzuEditorField extends OzuField
{
private bool $withoutParagraphs = false;

private bool $hideToolbar = false;

private array $toolbar = [
OzuEditorToolbarEnum::Bold,
OzuEditorToolbarEnum::Italic,
OzuEditorToolbarEnum::Separator,
OzuEditorToolbarEnum::BulletList,
OzuEditorToolbarEnum::Link,
];

private int $height = 200;

private ?int $maxHeight = null;

public function setWithoutParagraphs(): self
Expand All @@ -37,7 +41,7 @@ public function hideToolbar(): self
return $this;
}

public function setHeight(int $height, int|null $maxHeight = null): self
public function setHeight(int $height, ?int $maxHeight = null): self
{
$this->height = $height;
$this->maxHeight = $maxHeight;
Expand All @@ -55,7 +59,7 @@ public function toArray(): array
return array_merge(parent::toArray(), [
'withoutParagraphs' => $this->withoutParagraphs,
'hideToolbar' => $this->hideToolbar,
'toolbar' => collect($this->toolbar)->map(fn($item) => $item->value)->toArray(),
'toolbar' => collect($this->toolbar)->map(fn ($item) => $item->value)->toArray(),
'height' => $this->height,
'maxHeight' => $this->maxHeight,
]);
Expand Down
Loading
Loading