julienmonnerie/kirby/src/Cms/FilePicker.php

75 lines
1.7 KiB
PHP
Raw Normal View History

2022-06-17 17:51:59 +02:00
<?php
namespace Kirby\Cms;
use Kirby\Exception\InvalidArgumentException;
/**
* The FilePicker class helps to
* fetch the right files for the API calls
* for the file picker component in the panel.
*
* @package Kirby Cms
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://getkirby.com/license
*/
class FilePicker extends Picker
{
2022-08-31 15:02:43 +02:00
/**
* Extends the basic defaults
*/
public function defaults(): array
{
$defaults = parent::defaults();
$defaults['text'] = '{{ file.filename }}';
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
return $defaults;
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Search all files for the picker
*
* @throws \Kirby\Exception\InvalidArgumentException
*/
2025-04-21 18:57:21 +02:00
public function items(): Files|null
2022-08-31 15:02:43 +02:00
{
$model = $this->options['model'];
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
// find the right default query
2022-12-19 14:56:05 +01:00
$query = match (true) {
empty($this->options['query']) === false
=> $this->options['query'],
$model instanceof File
=> 'file.siblings',
default
=> $model::CLASS_ALIAS . '.files'
};
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
// fetch all files for the picker
$files = $model->query($query);
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
// help mitigate some typical query usage issues
// by converting site and page objects to proper
// pages by returning their children
2022-12-19 14:56:05 +01:00
$files = match (true) {
$files instanceof Site,
$files instanceof Page,
$files instanceof User => $files->files(),
$files instanceof Files => $files,
default => throw new InvalidArgumentException('Your query must return a set of files')
};
2022-06-17 17:51:59 +02:00
2025-04-21 18:57:21 +02:00
// filter protected and hidden pages
$files = $files->filter('isListable', true);
2022-08-31 15:02:43 +02:00
// search
$files = $this->search($files);
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
// paginate
return $this->paginate($files);
}
2022-06-17 17:51:59 +02:00
}