shalvah / ensure
Clean alternative syntax for enforcing business requirements
1.0.0
2018-08-05 01:26 UTC
Requires
- php: >=5.6
Requires (Dev)
- phpunit/phpunit: ^5.0 || ^6.0 || ^7.3
This package is auto-updated.
Last update: 2024-12-06 06:07:25 UTC
README
✌🤩🤩Clean alternative syntax for enforcing business requirements. Useful for when your if
s get too clunky.
use function Shalvah\Ensure\when; use function Shalvah\Ensure\ensure; ensure($pilot->isInUniform()) ->orElseDeny('Please put on your uniform', $pilot->uniform); when(!$pilot->isLicensed()) ->ensure($flight->isTestFlight()) ->orElseDeny('You are only allowed to fly test flights.'); when(!$flightPlanHasBeenSubmitted) ->ensure( $whitelistedAirports->includes($destinationAirport) || $flight->isTestFlight() ) ->orElseDeny("You need to submit a flight plan!");
How to use
- Specify a requirement using
ensure()
. This rule must either be an expression which evaluates to strict booleantrue
/false
, or a callable which returns strict booleantrue
/false
:
ensure($day == 'Saturday')->orElseDeny('Visiting hours are Saturdays only.'); ensure(function () use ($passenger) { $flight = Flight::getFlight($passenger->flightName); return $flight && $flight->passengers->includes($passenger->id); })->orElseDeny('You are not listed for this flight.');
- You can also use
when
before callingensure
, to specify that the rule applies only in certain conditions:
when($couponCodeWasApplied) ->ensure($product->isEligibleForDiscount()) ->orElseDeny('Sorry, this product is not eligible for promotions.');
- In
orElseDeny()
, specify amessage
and any additionaldata
. This package will throw aRequirementFailedException
with the specified message and data. You can then listen for this in your code (preferably at one central location) and send the appropriate response to the user:
try { ensure($user->isAllowedToView($product)) ->orElseDeny('This product is not available in your region.', $this->suggestSimilarProducts($product, $user)); } catch (\Shalvah\Ensure\RequirementFailedException $e) { return response()->json([ 'message' => $e->getMessage(), 'similar_products' => $e->getData() ], 400); } // or you could use set_exception_handller() // or whatever mechanism your framework uses
Installation
composer require shalvah/ensure