1<?php
2
3declare(strict_types=1);
4
5namespace Nyholm\Dsn\Configuration;
6
7use Nyholm\Dsn\Exception\InvalidArgumentException;
8
9/**
10 * A "path like" DSN string.
11 *
12 * Example:
13 * - redis:///var/run/redis/redis.sock
14 * - memcached://user:password@/var/local/run/memcached.socket?weight=25
15 *
16 * @author Tobias Nyholm <tobias.nyholm@gmail.com>
17 */
18class Path extends Dsn
19{
20    use UserPasswordTrait;
21    /**
22     * @var string
23     */
24    private $path;
25
26    /**
27     * @param array{ user?: string|null, password?: string|null, } $authentication
28     */
29    public function __construct(string $scheme, string $path, array $parameters = [], array $authentication = [])
30    {
31        $this->path = $path;
32        $this->setAuthentication($authentication);
33        parent::__construct($scheme, $parameters);
34    }
35
36    public function getScheme(): string
37    {
38        return parent::getScheme();
39    }
40
41    /**
42     * @return static
43     */
44    public function withScheme(?string $scheme)
45    {
46        if (null === $scheme || '' === $scheme) {
47            throw new InvalidArgumentException('A Path must have a schema');
48        }
49
50        return parent::withScheme($scheme);
51    }
52
53    public function getPath(): string
54    {
55        return $this->path;
56    }
57
58    /**
59     * @return static
60     */
61    public function withPath(string $path)
62    {
63        $new = clone $this;
64        $new->path = $path;
65
66        return $new;
67    }
68
69    /**
70     * @return string
71     */
72    public function __toString()
73    {
74        $parameters = $this->getParameters();
75
76        return
77            $this->getScheme().'://'.
78            $this->getUserInfoString().
79            $this->getPath().
80            (empty($parameters) ? '' : '?'.http_build_query($parameters));
81    }
82}
83