From 5235ab2a8936ceb5aa9214b73db126a4743903be Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 7 Jun 2019 12:11:52 -0400 Subject: [PATCH] Add $session->getVal() methods which work the same as get() but let you speicfy the fallback value --- wire/core/Session.php | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/wire/core/Session.php b/wire/core/Session.php index d5c30d19..ea677cac 100644 --- a/wire/core/Session.php +++ b/wire/core/Session.php @@ -461,6 +461,24 @@ class Session extends Wire implements \IteratorAggregate { return $value; } + /** + * Get a session variable or return $val argument if session value not present + * + * This is the same as get() except that it lets you specify a fallback return value in the method call. + * For a namespace version use `Session::getValFor()` instead. + * + * @param string $key Name of session variable to retrieve. + * @param mixed $val Fallback value to return if session does not have it. + * @return mixed Returns value of seession variable, or NULL if not found. + * @since 3.0.133 + * + */ + public function getVal($key, $val = null) { + $value = $this->get($key); + if($value === null) $value = $val; + return $value; + } + /** * Get all session variables in an associative array * @@ -538,6 +556,25 @@ class Session extends Wire implements \IteratorAggregate { if($key === '') return $data; return isset($data[$key]) ? $data[$key] : null; } + + /** + * Get a session variable or return $val argument if session value not present + * + * This is the same as get() except that it lets you specify a fallback return value in the method call. + * For a namespace version use `Session::getValFor()` instead. + * + * @param string|object $ns Namespace string or object + * @param string $key Specify variable name to retrieve + * @param mixed $val Fallback value if session does not have one + * @return mixed + * @since 3.0.133 + * + */ + public function getValFor($ns, $key, $val = null) { + $value = $this->getFor($ns, $key); + if($value === null) $value = $val; + return $value; + } /** * Set a session variable within a given namespace