shalvah/ensure

强制业务要求的清洁替代语法

1.0.0 2018-08-05 01:26 UTC

This package is auto-updated.

Last update: 2024-09-06 05:39:59 UTC


README

Latest Stable Version Total Downloads Build Status

✌🤩🤩强制业务要求的清洁替代语法。当您的 if 语句过于繁琐时非常有用。

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!");

如何使用

  • 使用 ensure() 指定一个 要求。此规则必须是评估结果为 严格布尔 true/false 的表达式,或者是一个返回 严格布尔 true/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.');
  • 您还可以在调用 ensure 之前使用 when,以指定规则仅在特定条件下适用。
when($couponCodeWasApplied)
  ->ensure($product->isEligibleForDiscount())
  ->orElseDeny('Sorry, this product is not eligible for promotions.');
  • orElseDeny() 中指定一个 message 和任何额外的 data。此包将抛出一个带有指定信息和数据的 RequirementFailedException。然后您可以在代码中监听此事件(最好在中央位置),并向用户发送相应的响应。
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

安装

composer require shalvah/ensure