master

laravel/framework

Last updated at: 29/12/2023 09:23

MessageSent.php

TLDR

This file defines the MessageSent class in the Illuminate\Mail\Events namespace. The class represents an event that is triggered when a message is sent. It contains properties for the sent message and its data, as well as methods for serialization, unserialization, and dynamically accessing the original message.

Classes

MessageSent

The MessageSent class represents an event that is triggered when a message is sent. It has the following properties:

  • $sent: Represents the sent message and is of type \Illuminate\Mail\SentMessage.
  • $data: Represents the message data and is of type array.

The class has the following methods:

  • __construct(SentMessage $message, array $data = []): Initializes a new instance of the MessageSent class with the given sent message and data.
  • __serialize(): Gets the serializable representation of the object.
  • __unserialize(array $data): Marshals the object from its serialized data.
  • __get(string $key): Dynamically gets the original message.
<?php

namespace Illuminate\Mail\Events;

use Exception;
use Illuminate\Mail\SentMessage;

/**
 * @property \Symfony\Component\Mime\Email $message
 */
class MessageSent
{
    /**
     * The message that was sent.
     *
     * @var \Illuminate\Mail\SentMessage
     */
    public $sent;

    /**
     * The message data.
     *
     * @var array
     */
    public $data;

    /**
     * Create a new event instance.
     *
     * @param  \Illuminate\Mail\SentMessage  $message
     * @param  array  $data
     * @return void
     */
    public function __construct(SentMessage $message, array $data = [])
    {
        $this->sent = $message;
        $this->data = $data;
    }

    /**
     * Get the serializable representation of the object.
     *
     * @return array
     */
    public function __serialize()
    {
        $hasAttachments = collect($this->message->getAttachments())->isNotEmpty();

        return [
            'sent' => $this->sent,
            'data' => $hasAttachments ? base64_encode(serialize($this->data)) : $this->data,
            'hasAttachments' => $hasAttachments,
        ];
    }

    /**
     * Marshal the object from its serialized data.
     *
     * @param  array  $data
     * @return void
     */
    public function __unserialize(array $data)
    {
        $this->sent = $data['sent'];

        $this->data = (($data['hasAttachments'] ?? false) === true)
            ? unserialize(base64_decode($data['data']))
            : $data['data'];
    }

    /**
     * Dynamically get the original message.
     *
     * @param  string  $key
     * @return mixed
     *
     * @throws \Exception
     */
    public function __get($key)
    {
        if ($key === 'message') {
            return $this->sent->getOriginalMessage();
        }

        throw new Exception('Unable to access undefined property on '.__CLASS__.': '.$key);
    }
}