1<?php
2
3declare(strict_types=1);
4
5namespace Nyholm\Dsn\Configuration;
6
7trait UserPasswordTrait
8{
9    /**
10     * @var array{ user: string|null, password: string|null, }
11     */
12    private $authentication = ['user' => null, 'password' => null];
13
14    public function getAuthentication(): array
15    {
16        return $this->authentication;
17    }
18
19    /**
20     * @param array{ user?: string|null, password?: string|null, } $authentication
21     */
22    private function setAuthentication(array $authentication): void
23    {
24        if (!empty($authentication)) {
25            $this->authentication['user'] = $authentication['user'] ?? null;
26            $this->authentication['password'] = $authentication['password'] ?? null;
27        }
28    }
29
30    public function getUser(): ?string
31    {
32        return $this->authentication['user'] ?? null;
33    }
34
35    /**
36     * @return static
37     */
38    public function withUser(?string $user)
39    {
40        $new = clone $this;
41        $new->authentication['user'] = $user;
42
43        return $new;
44    }
45
46    public function getPassword(): ?string
47    {
48        return $this->authentication['password'] ?? null;
49    }
50
51    /**
52     * @return static
53     */
54    public function withPassword(?string $password)
55    {
56        $new = clone $this;
57        $new->authentication['password'] = $password;
58
59        return $new;
60    }
61
62    private function getUserInfoString(): string
63    {
64        $user = $this->getUser() ?? '';
65        $password = $this->getPassword() ?? '';
66
67        if ('' === $password && '' === $user) {
68            return '';
69        }
70
71        return $user.('' === $password ? '' : ':'.$password).'@';
72    }
73}
74