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