NotificationFake.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. return $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. PHPUnit::assertEmpty($this->notifications, 'Notifications were sent unexpectedly.');
  145. }
  146. /**
  147. * Assert that no notifications were sent to the given notifiable.
  148. *
  149. * @param mixed $notifiable
  150. * @return void
  151. *
  152. * @throws \Exception
  153. */
  154. public function assertNothingSentTo($notifiable)
  155. {
  156. if (is_array($notifiable) || $notifiable instanceof Collection) {
  157. if (count($notifiable) === 0) {
  158. throw new Exception('No notifiable given.');
  159. }
  160. foreach ($notifiable as $singleNotifiable) {
  161. $this->assertNothingSentTo($singleNotifiable);
  162. }
  163. return;
  164. }
  165. PHPUnit::assertEmpty(
  166. $this->notifications[get_class($notifiable)][$notifiable->getKey()] ?? [],
  167. 'Notifications were sent unexpectedly.',
  168. );
  169. }
  170. /**
  171. * Assert the total amount of times a notification was sent.
  172. *
  173. * @param string $notification
  174. * @param int $expectedCount
  175. * @return void
  176. */
  177. public function assertSentTimes($notification, $expectedCount)
  178. {
  179. $actualCount = collect($this->notifications)
  180. ->flatten(1)
  181. ->reduce(fn ($count, $sent) => $count + count($sent[$notification] ?? []), 0);
  182. PHPUnit::assertSame(
  183. $expectedCount, $actualCount,
  184. "Expected [{$notification}] to be sent {$expectedCount} times, but was sent {$actualCount} times."
  185. );
  186. }
  187. /**
  188. * Assert the total count of notification that were sent.
  189. *
  190. * @param int $expectedCount
  191. * @return void
  192. */
  193. public function assertCount($expectedCount)
  194. {
  195. $actualCount = collect($this->notifications)->flatten(3)->count();
  196. PHPUnit::assertSame(
  197. $expectedCount, $actualCount,
  198. "Expected {$expectedCount} notifications to be sent, but {$actualCount} were sent."
  199. );
  200. }
  201. /**
  202. * Get all of the notifications matching a truth-test callback.
  203. *
  204. * @param mixed $notifiable
  205. * @param string $notification
  206. * @param callable|null $callback
  207. * @return \Illuminate\Support\Collection
  208. */
  209. public function sent($notifiable, $notification, $callback = null)
  210. {
  211. if (! $this->hasSent($notifiable, $notification)) {
  212. return collect();
  213. }
  214. $callback = $callback ?: fn () => true;
  215. $notifications = collect($this->notificationsFor($notifiable, $notification));
  216. return $notifications->filter(
  217. fn ($arguments) => $callback(...array_values($arguments))
  218. )->pluck('notification');
  219. }
  220. /**
  221. * Determine if there are more notifications left to inspect.
  222. *
  223. * @param mixed $notifiable
  224. * @param string $notification
  225. * @return bool
  226. */
  227. public function hasSent($notifiable, $notification)
  228. {
  229. return ! empty($this->notificationsFor($notifiable, $notification));
  230. }
  231. /**
  232. * Get all of the notifications for a notifiable entity by type.
  233. *
  234. * @param mixed $notifiable
  235. * @param string $notification
  236. * @return array
  237. */
  238. protected function notificationsFor($notifiable, $notification)
  239. {
  240. return $this->notifications[get_class($notifiable)][$notifiable->getKey()][$notification] ?? [];
  241. }
  242. /**
  243. * Send the given notification to the given notifiable entities.
  244. *
  245. * @param \Illuminate\Support\Collection|array|mixed $notifiables
  246. * @param mixed $notification
  247. * @return void
  248. */
  249. public function send($notifiables, $notification)
  250. {
  251. $this->sendNow($notifiables, $notification);
  252. }
  253. /**
  254. * Send the given notification immediately.
  255. *
  256. * @param \Illuminate\Support\Collection|array|mixed $notifiables
  257. * @param mixed $notification
  258. * @param array|null $channels
  259. * @return void
  260. */
  261. public function sendNow($notifiables, $notification, ?array $channels = null)
  262. {
  263. if (! $notifiables instanceof Collection && ! is_array($notifiables)) {
  264. $notifiables = [$notifiables];
  265. }
  266. foreach ($notifiables as $notifiable) {
  267. if (! $notification->id) {
  268. $notification->id = Str::uuid()->toString();
  269. }
  270. $notifiableChannels = $channels ?: $notification->via($notifiable);
  271. if (method_exists($notification, 'shouldSend')) {
  272. $notifiableChannels = array_filter(
  273. $notifiableChannels,
  274. fn ($channel) => $notification->shouldSend($notifiable, $channel) !== false
  275. );
  276. }
  277. if (empty($notifiableChannels)) {
  278. continue;
  279. }
  280. $this->notifications[get_class($notifiable)][$notifiable->getKey()][get_class($notification)][] = [
  281. 'notification' => $this->serializeAndRestore && $notification instanceof ShouldQueue
  282. ? $this->serializeAndRestoreNotification($notification)
  283. : $notification,
  284. 'channels' => $notifiableChannels,
  285. 'notifiable' => $notifiable,
  286. 'locale' => $notification->locale ?? $this->locale ?? value(function () use ($notifiable) {
  287. if ($notifiable instanceof HasLocalePreference) {
  288. return $notifiable->preferredLocale();
  289. }
  290. }),
  291. ];
  292. }
  293. }
  294. /**
  295. * Get a channel instance by name.
  296. *
  297. * @param string|null $name
  298. * @return mixed
  299. */
  300. public function channel($name = null)
  301. {
  302. //
  303. }
  304. /**
  305. * Set the locale of notifications.
  306. *
  307. * @param string $locale
  308. * @return $this
  309. */
  310. public function locale($locale)
  311. {
  312. $this->locale = $locale;
  313. return $this;
  314. }
  315. /**
  316. * Specify if notification should be serialized and restored when being "pushed" to the queue.
  317. *
  318. * @param bool $serializeAndRestore
  319. * @return $this
  320. */
  321. public function serializeAndRestore(bool $serializeAndRestore = true)
  322. {
  323. $this->serializeAndRestore = $serializeAndRestore;
  324. return $this;
  325. }
  326. /**
  327. * Serialize and unserialize the notification to simulate the queueing process.
  328. *
  329. * @param mixed $notification
  330. * @return mixed
  331. */
  332. protected function serializeAndRestoreNotification($notification)
  333. {
  334. return unserialize(serialize($notification));
  335. }
  336. /**
  337. * Get the notifications that have been sent.
  338. *
  339. * @return array
  340. */
  341. public function sentNotifications()
  342. {
  343. return $this->notifications;
  344. }
  345. }