Working with InputData - phpgt/Input GitHub Wiki
InputData is the value object used throughout the library to represent a set of request parameters.
We get InputData from:
Input::getAll()- trigger callbacks
- selected subsets created through
select()andselectAllExcept()
What InputData can do
InputData implements:
ArrayAccessIteratorCountable
So we can use it in familiar PHP ways:
foreach($input->getAll() as $key => $value) {
echo $key, ": ", $value, PHP_EOL;
}
$data = $input->getAll();
if(isset($data["email"])) {
echo $data["email"];
}
echo count($data);
Type-safe getters also work here
Because InputData uses the same getter trait as Input, we can call the same typed methods on a selected subset:
$input->when(["do" => "checkout"])
->select("email", "postcode")
->call(function($data) {
$email = $data->getString("email");
$postcode = $data->getString("postcode");
});
Checking presence and values
InputData provides:
contains($key)to check whether the key existshasValue($key)to check whether the key contains a non-empty value
if($data->contains("referrer") && $data->hasValue("referrer")) {
// Referrer exists and is not empty.
}
Converting to a plain PHP array
Use asArray() when another part of the application expects a plain array:
$payload = $input->getAll()->asArray();
Single values become strings, while multiple values become arrays of strings.
Mutating InputData
There's support for adding and removing keys:
$data = $input->getAll();
$data->remove("csrf");
That is mainly useful when we are preparing a sanitised or narrowed set of input for another layer of code. In most request-handling code, we should prefer selecting the right keys up front.
Next: Handling file uploads