1
<?php
2

3
declare(strict_types=1);
4

5
namespace Kreait\Firebase\Messaging;
6

7
use Kreait\Firebase\Exception\InvalidArgumentException;
8

9
final class MessageData implements \JsonSerializable
10
{
11
    /** @var array<string, string> */
12
    private $data = [];
13

14 8
    private function __construct()
15
    {
16
    }
17

18
    /**
19
     * @param array<string, string> $data
20
     */
21 8
    public static function fromArray(array $data): self
22
    {
23 8
        $messageData = new self();
24

25 8
        foreach ($data as $key => $value) {
26 8
            if (!self::isStringable($key) || !self::isStringable($value)) {
27 6
                throw new InvalidArgumentException('Message data must be a one-dimensional array of string(able) keys and values.');
28
            }
29

30 8
            if (self::isBinary((string) $value)) {
31 6
                throw new InvalidArgumentException(
32 6
                    "The message data field '{$key}' seems to contain binary data. As this can lead to broken messages, "
33 6
                    .'please convert it to a string representation first, e.g. with bin2hex() or base64encode().'
34
                );
35
            }
36

37 8
            $messageData->data[(string) $key] = (string) $value;
38
        }
39

40 8
        return $messageData;
41
    }
42

43
    /**
44
     * @return array<string, string>
45
     */
46 8
    public function jsonSerialize(): array
47
    {
48 8
        return $this->data;
49
    }
50

51
    /**
52
     * @param mixed $value
53
     */
54 8
    private static function isStringable($value): bool
55
    {
56 8
        return \is_null($value) || \is_scalar($value) || (\is_object($value) && \method_exists($value, '__toString'));
57
    }
58

59 8
    private static function isBinary(string $value): bool
60
    {
61 8
        return \mb_detect_encoding($value) === false;
62
    }
63
}

Read our documentation on viewing source code .

Loading