1<?php
2
3/**
4 * This file is part of the FreeDSx SASL package.
5 *
6 * (c) Chad Sikorra <Chad.Sikorra@gmail.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace FreeDSx\Sasl\Challenge;
13
14use FreeDSx\Sasl\Encoder\AnonymousEncoder;
15use FreeDSx\Sasl\Message;
16use FreeDSx\Sasl\SaslContext;
17
18/**
19 * The ANONYMOUS challenge / response class.
20 *
21 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
22 */
23class AnonymousChallenge implements ChallengeInterface
24{
25    /**
26     * @var SaslContext
27     */
28    protected $context;
29
30    /**
31     * @var AnonymousEncoder
32     */
33    protected $encoder;
34
35    public function __construct(bool $isServerMode = false)
36    {
37        $this->encoder = new AnonymousEncoder();
38        $this->context = new SaslContext();
39        $this->context->setIsServerMode($isServerMode);
40    }
41
42    /**
43     * {@inheritDoc}
44     */
45    public function challenge(?string $received = null, array $options = []): SaslContext
46    {
47        if ($this->context->isServerMode()) {
48            $this->processServer($received);
49        } else {
50            $this->processClient($options);
51        }
52
53        return $this->context;
54    }
55
56    protected function processServer(?string $received): void
57    {
58        if ($received === null) {
59            return;
60        }
61        $received = $this->encoder->decode($received, $this->context);
62
63        $this->context->setIsComplete(true);
64        $this->context->setIsAuthenticated(true);
65
66        if ($received->has('trace')) {
67            $this->context->set('trace', $received->get('trace'));
68        }
69    }
70
71    protected function processClient(array $options): void
72    {
73        $data = [];
74
75        if (isset($options['username']) || isset($options['trace'])) {
76            $data['trace'] = $options['trace'] ?? $options['username'];
77        }
78
79        $this->context->setResponse($this->encoder->encode(new Message($data), $this->context));
80        $this->context->setIsComplete(true);
81        $this->context->setIsAuthenticated(true);
82    }
83}
84