1<?php
2/**
3 * This file is part of the FreeDSx LDAP package.
4 *
5 * (c) Chad Sikorra <Chad.Sikorra@gmail.com>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10
11namespace FreeDSx\Ldap\Protocol\Queue\MessageWrapper;
12
13use FreeDSx\Ldap\Protocol\Queue\MessageWrapperInterface;
14use FreeDSx\Sasl\Exception\SaslBufferException;
15use FreeDSx\Sasl\SaslBuffer;
16use FreeDSx\Sasl\SaslContext;
17use FreeDSx\Sasl\Security\SecurityLayerInterface;
18use FreeDSx\Socket\Exception\PartialMessageException;
19use FreeDSx\Socket\Queue\Buffer;
20use function strlen;
21
22/**
23 * Used to wrap / unwrap SASL messages in the queue.
24 *
25 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
26 */
27class SaslMessageWrapper implements MessageWrapperInterface
28{
29    /**
30     * @var SaslContext
31     */
32    protected $context;
33
34    /**
35     * @var SecurityLayerInterface
36     */
37    protected $securityLayer;
38
39    public function __construct(SecurityLayerInterface $securityLayer, SaslContext $context)
40    {
41        $this->securityLayer = $securityLayer;
42        $this->context = $context;
43    }
44
45    /**
46     * {@inheritDoc}
47     */
48    public function wrap(string $message): string
49    {
50        $data = $this->securityLayer->wrap($message, $this->context);
51
52        return SaslBuffer::wrap($data);
53    }
54
55    /**
56     * {@inheritDoc}
57     */
58    public function unwrap(string $message): Buffer
59    {
60        try {
61            $data = SaslBuffer::unwrap($message);
62
63            return new Buffer(
64                $this->securityLayer->unwrap($data, $this->context),
65                strlen($data) + 4
66            );
67        } catch (SaslBufferException $exception) {
68            throw new PartialMessageException($exception->getMessage(), $exception->getCode(), $exception);
69        }
70    }
71}
72