2022-06-17 17:51:59 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Kirby\Http\Request;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* The Data Trait is being used in
|
|
|
|
* Query, Files and Body classes to
|
|
|
|
* provide unified get and data methods.
|
|
|
|
* Especially the get method is a bit more
|
|
|
|
* complex with the option to fetch single keys
|
|
|
|
* or entire arrays.
|
|
|
|
*
|
|
|
|
* @package Kirby Http
|
|
|
|
* @author Bastian Allgeier <bastian@getkirby.com>
|
|
|
|
* @link https://getkirby.com
|
|
|
|
* @copyright Bastian Allgeier
|
|
|
|
* @license https://opensource.org/licenses/MIT
|
|
|
|
*/
|
|
|
|
trait Data
|
|
|
|
{
|
2022-08-31 15:02:43 +02:00
|
|
|
/**
|
|
|
|
* Improved `var_dump` output
|
|
|
|
*
|
|
|
|
* @return array
|
|
|
|
*/
|
|
|
|
public function __debugInfo(): array
|
|
|
|
{
|
|
|
|
return $this->toArray();
|
|
|
|
}
|
2022-06-17 17:51:59 +02:00
|
|
|
|
2022-08-31 15:02:43 +02:00
|
|
|
/**
|
|
|
|
* The data provider method has to be
|
|
|
|
* implemented by each class using this Trait
|
|
|
|
* and has to return an associative array
|
|
|
|
* for the get method
|
|
|
|
*
|
|
|
|
* @return array
|
|
|
|
*/
|
|
|
|
abstract public function data(): array;
|
2022-06-17 17:51:59 +02:00
|
|
|
|
2022-08-31 15:02:43 +02:00
|
|
|
/**
|
|
|
|
* The get method is the heart and soul of this
|
|
|
|
* Trait. You can use it to fetch a single value
|
|
|
|
* of the data array by key or multiple values by
|
|
|
|
* passing an array of keys.
|
|
|
|
*
|
|
|
|
* @param string|array $key
|
|
|
|
* @param mixed|null $default
|
|
|
|
* @return mixed
|
|
|
|
*/
|
|
|
|
public function get($key, $default = null)
|
|
|
|
{
|
|
|
|
if (is_array($key) === true) {
|
|
|
|
$result = [];
|
|
|
|
foreach ($key as $k) {
|
|
|
|
$result[$k] = $this->get($k);
|
|
|
|
}
|
|
|
|
return $result;
|
|
|
|
}
|
2022-06-17 17:51:59 +02:00
|
|
|
|
2022-08-31 15:02:43 +02:00
|
|
|
return $this->data()[$key] ?? $default;
|
|
|
|
}
|
2022-06-17 17:51:59 +02:00
|
|
|
|
2022-08-31 15:02:43 +02:00
|
|
|
/**
|
|
|
|
* Returns the data array.
|
|
|
|
* This is basically an alias for Data::data()
|
|
|
|
*
|
|
|
|
* @return array
|
|
|
|
*/
|
|
|
|
public function toArray(): array
|
|
|
|
{
|
|
|
|
return $this->data();
|
|
|
|
}
|
2022-06-17 17:51:59 +02:00
|
|
|
|
2022-08-31 15:02:43 +02:00
|
|
|
/**
|
|
|
|
* Converts the data array to json
|
|
|
|
*
|
|
|
|
* @return string
|
|
|
|
*/
|
|
|
|
public function toJson(): string
|
|
|
|
{
|
|
|
|
return json_encode($this->data());
|
|
|
|
}
|
2022-06-17 17:51:59 +02:00
|
|
|
}
|