NotificationFake.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. <?php
  2. namespace Illuminate\Support\Testing\Fakes;
  3. use Closure;
  4. use Exception;
  5. use Illuminate\Contracts\Notifications\Dispatcher as NotificationDispatcher;
  6. use Illuminate\Contracts\Notifications\Factory as NotificationFactory;
  7. use Illuminate\Contracts\Queue\ShouldQueue;
  8. use Illuminate\Contracts\Translation\HasLocalePreference;
  9. use Illuminate\Notifications\AnonymousNotifiable;
  10. use Illuminate\Support\Collection;
  11. use Illuminate\Support\Str;
  12. use Illuminate\Support\Traits\Macroable;
  13. use Illuminate\Support\Traits\ReflectsClosures;
  14. use PHPUnit\Framework\Assert as PHPUnit;
  15. class NotificationFake implements Fake, NotificationDispatcher, NotificationFactory
  16. {
  17. use Macroable, ReflectsClosures;
  18. /**
  19. * All of the notifications that have been sent.
  20. *
  21. * @var array
  22. */
  23. protected $notifications = [];
  24. /**
  25. * Locale used when sending notifications.
  26. *
  27. * @var string|null
  28. */
  29. public $locale;
  30. /**
  31. * Indicates if notifications should be serialized and restored when pushed to the queue.
  32. *
  33. * @var bool
  34. */
  35. protected $serializeAndRestore = false;
  36. /**
  37. * Assert if a notification was sent on-demand based on a truth-test callback.
  38. *
  39. * @param string|\Closure $notification
  40. * @param callable|null $callback
  41. * @return void
  42. *
  43. * @throws \Exception
  44. */
  45. public function assertSentOnDemand($notification, $callback = null)
  46. {
  47. $this->assertSentTo(new AnonymousNotifiable, $notification, $callback);
  48. }
  49. /**
  50. * Assert if a notification was sent based on a truth-test callback.
  51. *
  52. * @param mixed $notifiable
  53. * @param string|\Closure $notification
  54. * @param callable|null $callback
  55. * @return void
  56. *
  57. * @throws \Exception
  58. */
  59. public function assertSentTo($notifiable, $notification, $callback = null)
  60. {
  61. if (is_array($notifiable) || $notifiable instanceof Collection) {
  62. if (count($notifiable) === 0) {
  63. throw new Exception('No notifiable given.');
  64. }
  65. foreach ($notifiable as $singleNotifiable) {
  66. $this->assertSentTo($singleNotifiable, $notification, $callback);
  67. }
  68. return;
  69. }
  70. if ($notification instanceof Closure) {
  71. [$notification, $callback] = [$this->firstClosureParameterType($notification), $notification];
  72. }
  73. if (is_numeric($callback)) {
  74. return $this->assertSentToTimes($notifiable, $notification, $callback);
  75. }
  76. PHPUnit::assertTrue(
  77. $this->sent($notifiable, $notification, $callback)->count() > 0,
  78. "The expected [{$notification}] notification was not sent."
  79. );
  80. }
  81. /**
  82. * Assert if a notification was sent on-demand a number of times.
  83. *
  84. * @param string $notification
  85. * @param int $times
  86. * @return void
  87. */
  88. public function assertSentOnDemandTimes($notification, $times = 1)
  89. {
  90. $this->assertSentToTimes(new AnonymousNotifiable, $notification, $times);
  91. }
  92. /**
  93. * Assert if a notification was sent a number of times.
  94. *
  95. * @param mixed $notifiable
  96. * @param string $notification
  97. * @param int $times
  98. * @return void
  99. */
  100. public function assertSentToTimes($notifiable, $notification, $times = 1)
  101. {
  102. $count = $this->sent($notifiable, $notification)->count();
  103. PHPUnit::assertSame(
  104. $times, $count,
  105. "Expected [{$notification}] to be sent {$times} times, but was sent {$count} times."
  106. );
  107. }
  108. /**
  109. * Determine if a notification was sent based on a truth-test callback.
  110. *
  111. * @param mixed $notifiable
  112. * @param string|\Closure $notification
  113. * @param callable|null $callback
  114. * @return void
  115. *
  116. * @throws \Exception
  117. */
  118. public function assertNotSentTo($notifiable, $notification, $callback = null)
  119. {
  120. if (is_array($notifiable) || $notifiable instanceof Collection) {
  121. if (count($notifiable) === 0) {
  122. throw new Exception('No notifiable given.');
  123. }
  124. foreach ($notifiable as $singleNotifiable) {
  125. $this->assertNotSentTo($singleNotifiable, $notification, $callback);
  126. }
  127. return;
  128. }
  129. if ($notification instanceof Closure) {
  130. [$notification, $callback] = [$this->firstClosureParameterType($notification), $notification];
  131. }
  132. PHPUnit::assertCount(
  133. 0, $this->sent($notifiable, $notification, $callback),
  134. "The unexpected [{$notification}] notification was sent."
  135. );
  136. }
  137. /**
  138. * Assert that no notifications were sent.
  139. *
  140. * @return void
  141. */
  142. public function assertNothingSent()
  143. {
  144. $notificationNames = (new Collection($this->notifications))
  145. ->map(fn ($notifiableModels) => (new Collection($notifiableModels))
  146. ->map(fn ($notifiables) => (new Collection($notifiables))->keys())
  147. )
  148. ->flatten()->join("\n- ");
  149. PHPUnit::assertEmpty($this->notifications, "The following notifications were sent unexpectedly:\n\n- $notificationNames\n");
  150. }
  151. /**
  152. * Assert that no notifications were sent to the given notifiable.
  153. *
  154. * @param mixed $notifiable
  155. * @return void
  156. *
  157. * @throws \Exception
  158. */
  159. public function assertNothingSentTo($notifiable)
  160. {
  161. if (is_array($notifiable) || $notifiable instanceof Collection) {
  162. if (count($notifiable) === 0) {
  163. throw new Exception('No notifiable given.');
  164. }
  165. foreach ($notifiable as $singleNotifiable) {
  166. $this->assertNothingSentTo($singleNotifiable);
  167. }
  168. return;
  169. }
  170. PHPUnit::assertEmpty(
  171. $this->notifications[get_class($notifiable)][$notifiable->getKey() ?? ''] ?? [],
  172. 'Notifications were sent unexpectedly.',
  173. );
  174. }
  175. /**
  176. * Assert the total amount of times a notification was sent.
  177. *
  178. * @param string $notification
  179. * @param int $expectedCount
  180. * @return void
  181. */
  182. public function assertSentTimes($notification, $expectedCount)
  183. {
  184. $actualCount = (new Collection($this->notifications))
  185. ->flatten(1)
  186. ->reduce(fn ($count, $sent) => $count + count($sent[$notification] ?? []), 0);
  187. PHPUnit::assertSame(
  188. $expectedCount, $actualCount,
  189. sprintf(
  190. "Expected [{$notification}] to be sent {$expectedCount} %s, but was sent {$actualCount} %s.",
  191. Str::plural('time', $expectedCount),
  192. Str::plural('time', $actualCount)
  193. )
  194. );
  195. }
  196. /**
  197. * Assert the total count of notification that were sent.
  198. *
  199. * @param int $expectedCount
  200. * @return void
  201. */
  202. public function assertCount($expectedCount)
  203. {
  204. $actualCount = (new Collection($this->notifications))->flatten(3)->count();
  205. PHPUnit::assertSame(
  206. $expectedCount, $actualCount,
  207. "Expected {$expectedCount} notifications to be sent, but {$actualCount} were sent."
  208. );
  209. }
  210. /**
  211. * Get all of the notifications matching a truth-test callback.
  212. *
  213. * @param mixed $notifiable
  214. * @param string $notification
  215. * @param callable|null $callback
  216. * @return \Illuminate\Support\Collection
  217. */
  218. public function sent($notifiable, $notification, $callback = null)
  219. {
  220. if (! $this->hasSent($notifiable, $notification)) {
  221. return new Collection;
  222. }
  223. $callback = $callback ?: fn () => true;
  224. $notifications = new Collection($this->notificationsFor($notifiable, $notification));
  225. return $notifications->filter(
  226. fn ($arguments) => $callback(...array_values($arguments))
  227. )->pluck('notification');
  228. }
  229. /**
  230. * Determine if there are more notifications left to inspect.
  231. *
  232. * @param mixed $notifiable
  233. * @param string $notification
  234. * @return bool
  235. */
  236. public function hasSent($notifiable, $notification)
  237. {
  238. return ! empty($this->notificationsFor($notifiable, $notification));
  239. }
  240. /**
  241. * Get all of the notifications for a notifiable entity by type.
  242. *
  243. * @param mixed $notifiable
  244. * @param string $notification
  245. * @return array
  246. */
  247. protected function notificationsFor($notifiable, $notification)
  248. {
  249. return $this->notifications[get_class($notifiable)][(string) $notifiable->getKey()][$notification] ?? [];
  250. }
  251. /**
  252. * Send the given notification to the given notifiable entities.
  253. *
  254. * @param \Illuminate\Support\Collection|mixed $notifiables
  255. * @param mixed $notification
  256. * @return void
  257. */
  258. public function send($notifiables, $notification)
  259. {
  260. $this->sendNow($notifiables, $notification);
  261. }
  262. /**
  263. * Send the given notification immediately.
  264. *
  265. * @param \Illuminate\Support\Collection|mixed $notifiables
  266. * @param mixed $notification
  267. * @param array|null $channels
  268. * @return void
  269. */
  270. public function sendNow($notifiables, $notification, ?array $channels = null)
  271. {
  272. if (! $notifiables instanceof Collection && ! is_array($notifiables)) {
  273. $notifiables = [$notifiables];
  274. }
  275. foreach ($notifiables as $notifiable) {
  276. if (! $notification->id) {
  277. $notification->id = (string) Str::uuid();
  278. }
  279. $notifiableChannels = $channels ?: $notification->via($notifiable);
  280. if (method_exists($notification, 'shouldSend')) {
  281. $notifiableChannels = array_filter(
  282. $notifiableChannels,
  283. fn ($channel) => $notification->shouldSend($notifiable, $channel) !== false
  284. );
  285. }
  286. if (empty($notifiableChannels)) {
  287. continue;
  288. }
  289. $this->notifications[get_class($notifiable)][(string) $notifiable->getKey()][get_class($notification)][] = [
  290. 'notification' => $this->serializeAndRestore && $notification instanceof ShouldQueue
  291. ? $this->serializeAndRestoreNotification($notification)
  292. : $notification,
  293. 'channels' => $notifiableChannels,
  294. 'notifiable' => $notifiable,
  295. 'locale' => $notification->locale ?? $this->locale ?? value(function () use ($notifiable) {
  296. if ($notifiable instanceof HasLocalePreference) {
  297. return $notifiable->preferredLocale();
  298. }
  299. }),
  300. ];
  301. }
  302. }
  303. /**
  304. * Get a channel instance by name.
  305. *
  306. * @param string|null $name
  307. * @return mixed
  308. */
  309. public function channel($name = null)
  310. {
  311. //
  312. }
  313. /**
  314. * Set the locale of notifications.
  315. *
  316. * @param string $locale
  317. * @return $this
  318. */
  319. public function locale($locale)
  320. {
  321. $this->locale = $locale;
  322. return $this;
  323. }
  324. /**
  325. * Specify if notification should be serialized and restored when being "pushed" to the queue.
  326. *
  327. * @param bool $serializeAndRestore
  328. * @return $this
  329. */
  330. public function serializeAndRestore(bool $serializeAndRestore = true)
  331. {
  332. $this->serializeAndRestore = $serializeAndRestore;
  333. return $this;
  334. }
  335. /**
  336. * Serialize and unserialize the notification to simulate the queueing process.
  337. *
  338. * @param mixed $notification
  339. * @return mixed
  340. */
  341. protected function serializeAndRestoreNotification($notification)
  342. {
  343. return unserialize(serialize($notification));
  344. }
  345. /**
  346. * Get the notifications that have been sent.
  347. *
  348. * @return array
  349. */
  350. public function sentNotifications()
  351. {
  352. return $this->notifications;
  353. }
  354. }