Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame^] | 1 | <?php |
| 2 | |
| 3 | namespace LdapRecord\Testing; |
| 4 | |
| 5 | use LdapRecord\Auth\Guard; |
| 6 | use LdapRecord\Connection; |
| 7 | use LdapRecord\Models\Model; |
| 8 | |
| 9 | class ConnectionFake extends Connection |
| 10 | { |
| 11 | /** |
| 12 | * The underlying fake LDAP connection. |
| 13 | * |
| 14 | * @var LdapFake |
| 15 | */ |
| 16 | protected $ldap; |
| 17 | |
| 18 | /** |
| 19 | * Whether the fake is connected. |
| 20 | * |
| 21 | * @var bool |
| 22 | */ |
| 23 | protected $connected = false; |
| 24 | |
| 25 | /** |
| 26 | * Make a new fake LDAP connection instance. |
| 27 | * |
| 28 | * @param array $config |
| 29 | * @param string $ldap |
| 30 | * |
| 31 | * @return static |
| 32 | */ |
| 33 | public static function make(array $config = [], $ldap = LdapFake::class) |
| 34 | { |
| 35 | $connection = new static($config, new $ldap()); |
| 36 | |
| 37 | $connection->configure(); |
| 38 | |
| 39 | return $connection; |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Set the user to authenticate as. |
| 44 | * |
| 45 | * @param Model|string $user |
| 46 | * |
| 47 | * @return $this |
| 48 | */ |
| 49 | public function actingAs($user) |
| 50 | { |
| 51 | $this->ldap->shouldAuthenticateWith( |
| 52 | $user instanceof Model ? $user->getDn() : $user |
| 53 | ); |
| 54 | |
| 55 | return $this; |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * Set the connection to bypass bind attempts as the configured user. |
| 60 | * |
| 61 | * @return $this |
| 62 | */ |
| 63 | public function shouldBeConnected() |
| 64 | { |
| 65 | $this->connected = true; |
| 66 | |
| 67 | $this->authGuardResolver = function () { |
| 68 | return new AuthGuardFake($this->ldap, $this->configuration); |
| 69 | }; |
| 70 | |
| 71 | return $this; |
| 72 | } |
| 73 | |
| 74 | /** |
| 75 | * Set the connection to attempt binding as the configured user. |
| 76 | * |
| 77 | * @return $this |
| 78 | */ |
| 79 | public function shouldNotBeConnected() |
| 80 | { |
| 81 | $this->connected = false; |
| 82 | |
| 83 | $this->authGuardResolver = function () { |
| 84 | return new Guard($this->ldap, $this->configuration); |
| 85 | }; |
| 86 | |
| 87 | return $this; |
| 88 | } |
| 89 | |
| 90 | /** |
| 91 | * @inheritdoc |
| 92 | */ |
| 93 | public function isConnected() |
| 94 | { |
| 95 | return $this->connected ?: parent::isConnected(); |
| 96 | } |
| 97 | } |