julienmonnerie/kirby/src/Cms/Languages.php

95 lines
1.9 KiB
PHP
Raw Normal View History

2022-06-17 17:51:59 +02:00
<?php
namespace Kirby\Cms;
use Kirby\Exception\DuplicateException;
use Kirby\Filesystem\F;
/**
* A collection of all defined site languages
*
* @package Kirby Cms
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://getkirby.com/license
*/
class Languages extends Collection
{
2023-06-01 16:54:20 +02:00
/**
* All registered languages methods
*/
2025-04-21 18:57:21 +02:00
public static array $methods = [];
2023-06-01 16:54:20 +02:00
2022-08-31 15:02:43 +02:00
/**
* Creates a new collection with the given language objects
*
* @param null $parent
* @throws \Kirby\Exception\DuplicateException
*/
2025-04-21 18:57:21 +02:00
public function __construct(
array $objects = [],
$parent = null
) {
2022-08-31 15:02:43 +02:00
$defaults = array_filter(
$objects,
fn ($language) => $language->isDefault() === true
);
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
if (count($defaults) > 1) {
throw new DuplicateException('You cannot have multiple default languages. Please check your language config files.');
}
2022-06-17 17:51:59 +02:00
2025-04-21 18:57:21 +02:00
parent::__construct($objects, null);
2022-08-31 15:02:43 +02:00
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Returns all language codes as array
*/
public function codes(): array
{
2025-04-21 18:57:21 +02:00
return App::instance()->multilang() ? $this->keys() : ['default'];
2022-08-31 15:02:43 +02:00
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Creates a new language with the given props
* @internal
*/
2025-04-21 18:57:21 +02:00
public function create(array $props): Language
2022-08-31 15:02:43 +02:00
{
return Language::create($props);
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Returns the default language
*/
2025-04-21 18:57:21 +02:00
public function default(): Language|null
2022-08-31 15:02:43 +02:00
{
2022-12-19 14:56:05 +01:00
return $this->findBy('isDefault', true) ?? $this->first();
2022-08-31 15:02:43 +02:00
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Convert all defined languages to a collection
* @internal
*/
2025-04-21 18:57:21 +02:00
public static function load(): static
2022-08-31 15:02:43 +02:00
{
$languages = [];
$files = glob(App::instance()->root('languages') . '/*.php');
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
foreach ($files as $file) {
2022-12-19 14:56:05 +01:00
$props = F::load($file, allowOutput: false);
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
if (is_array($props) === true) {
// inject the language code from the filename
// if it does not exist
$props['code'] ??= F::name($file);
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
$languages[] = new Language($props);
}
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
return new static($languages);
}
2022-06-17 17:51:59 +02:00
}