1:  2:  3:  4:  5:  6:  7:  8:  9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 
<?php

declare(strict_types=1);

namespace Wtf\Auth\Repository;

use Psr\Container\ContainerInterface;
use Wtf\Root;

class LDAP extends Root implements RepositoryInterface
{
    public function __construct(ContainerInterface $container)
    {
        parent::__construct($container);
        //@codeCoverageIgnoreStart
        if (!\class_exists('\Symfony\Component\Ldap\Ldap')) {
            throw new \Exception('symfony/ldap package required for ldap auth');
        }
        //@codeCoverageIgnoreEnd
    }

    /**
     * {@inheritdoc}
     */
    public function getLoginFields(): array
    {
        return $this->config('auth.ldap.fields.login', ['uid', 'mail']);
    }

    /**
     * {@inheritdoc}
     */
    public function login(string $login, string $password): ?Root
    {
        $user = $this->getByLogin($login);
        if (null === $user) {
            return null;
        }

        try {
            $this->ldap_client->bind($user->get($this->config('auth.ldap.fields.loginInDb', 'email')), $password);

            return $user;
        } catch (\Throwable $t) {
            return null;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getByLogin(string $login): ?Root
    {
        $query = '(|';
        foreach ($this->getLoginFields() as $field) {
            $query .= '('.$field.'='.$login.')';
        }
        $query .= ')';
        $collection = $this->ldap_client
                           ->query($this->config('auth.ldap.baseDN'), $query)
                           ->execute();

        foreach ($collection->toArray() as $entry) {
            $user = $this->entity($this->config('auth.entity'))->load($entry->getDn(), $this->config('auth.ldap.fields.loginInDb', 'email'));
            foreach ($entry->getAttributes() as $attribute => $value) {
                $field = $this->config('auth.ldap.fields.map.'.$attribute);
                if ($field) {
                    $user->set($field, $value[0] ?? null);
                }
                $user->set($this->config('auth.ldap.fields.loginInDb', 'email'), $entry->getDn());
            }
            $user->save();

            return $user;
        }

        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function forgot(string $login): string
    {
        return '';
    }

    /**
     * {@inheritdoc}
     */
    public function reset(string $code, string $new_password): bool
    {
        return false;
    }
}