<commit_before><?php

namespace Bundle\CommonBundle\Entity\User;

use Bundle\CommonBundle\Constants\UserConstant;
use Bundle\CommonBundle\Entity\Core\BaseRepository;
use Bundle\CommonBundle\Entity\User\User;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\NoResultException;
use Bundle\CommonBundle\Constants\SearchConstant;
use Bundle\CommonBundle\Entity\Group\GroupRepository;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;

use Bundle\CommonBundle\Entity\Core\BaseEntity;
use Doctrine\ORM\Query;

/**
 * UserRepository
 */
class UserRepository extends BaseRepository implements UserProviderInterface
{

    /** Событие после вставки сущности */
    protected function postPersist(BaseEntity $user)
    {
        $this->getRepository('event')->createUserCreateEvent($user);
    }
    
    public function loadUserByUsername($username)
    {
        $q = $this
            ->createQueryBuilder('u')
            ->where('u.username = :username')
            ->setParameter('username', $username)
            ->getQuery();

        try {
            $user = $q->getSingleResult();
        } catch (NoResultException $e) {
            $message = sprintf(
                'Unable to find User object identified by "%s".',
                $username
            );
            throw new UsernameNotFoundException($message, 0, $e);
        }

        return $user;
    }

    public function refreshUser(UserInterface $user)
    {
        $class = get_class($user);
        if (!$this->supportsClass($class)) {
            throw new UnsupportedUserException(
                sprintf(
                    'Instances of "%s" are not supported.',
                    $class
                )
            );
        }

        return $this->find($user->getId());
    }

    public function supportsClass($class)
    {
        return $this->getEntityName() === $class
            || is_subclass_of($class, $this->getEntityName());
    }

    /**
     * Поиск пользователей
     * @param string $text
     */
    public function search($text, $limit = null, $offset = null)
    {
        $query = $this->_prepareSearchQuery($text);

        $limit != null ? $query->setMaxResults($limit) : false;
        $offset != null ? $query->setFirstResult($offset) : false;

        return $query->getQuery()->getResult();
    }

    /**
     * Поиск количества пользователей
     * @param string $text
     * @return int
     */
    public function searchCount($text)
    {
        return $this->_prepareSearchQuery($text)
            ->select('COUNT(u.id)')
            ->getQuery()
            ->getSingleScalarResult();
    }

    /**
     * @param $text
     * @return \Doctrine\ORM\QueryBuilder
     */
    protected function _prepareSearchQuery($text)
    {
        $query = $this->createQueryBuilder('u');
        if (!empty($text)) {
            $query
                ->where('u.name LIKE :text')
                ->orWhere('u.surname LIKE :text')
                ->orWhere('u.email LIKE :text')
                ->setParameter('text', sprintf('%%%s%%', $text));
        }

        return $query;
    }

    /**
     * Получить всех пользователей
     * @return array The entities.
     */
    public function getAll()
    {
        $query = $this->createQueryBuilder('u');
        return $query->getQuery()->getResult();
    }

    /**
     * Получить массив пользователей из строки формата u1,u2,g1,g2
     * @param $usersGroupsList
     * @return array
     * @throws \Exception
     */
    public function getUsersFromGroupList($usersGroupsList)
    {
        $usersAndGroups = explode(",", $usersGroupsList);
        if (!is_array($usersAndGroups)) {
            throw new \Exception('sendBadge.noData');
        }

        $users = array();
        /** @var GroupRepository $groupRepository */
        $groupRepository = $this->getRepository('group');

        foreach ($usersAndGroups as $ug) {
            preg_match('/^([a-z]{1})(\d+)/', $ug, $matches);
            $prefix = $matches[1] ? $matches[1] : "";
            $id = $matches[2] ? $matches[2] : "";

            if (!$id || !$prefix) continue;

            switch ($prefix) {
                case SearchConstant::USER_ID_PREFIX:
                    $users[] = $this->find($id);
                    break;
                case SearchConstant::GROUP_ID_PREFIX:
                    $users = array_merge($users, $groupRepository->getAllUsersFromGroup($id));
                    break;
                default:
                    break;
            }
        }
        return $users;
    }

    /**
     * Устанавливает аватар пользователя по url изображения
     * @param type $url
     */
    public function setAvatarByUrl(User $user, $url)
    {
        try {
            /** @var $file \Symfony\Component\HttpFoundation\File\UploadedFile */
            if ($file = $this->imageProvider->getImage($url)) {
                $user->setAvatar($file);
            }
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    public function getUsersByBirthday($start, $end, $owner = null)
    {
        if ($start) {
            $startObj = new \DateTime();
            $startObj->setTimestamp($start);

            $start = $startObj;
        }
        if ($end) {
            $endObj = new \DateTime();
            $endObj->setTimestamp($end);

            $end = $endObj;
        }

        $query = $this->createQueryBuilder('u');

        $query->where(
                $query->expr()->between('u.birthdayShort', ':start', ':end')
        )
            ->setParameters(array(
                'start' => $start->format(UserConstant::BIRTHDAY_SHORT_FORMAT),
                'end' => $end->format(UserConstant::BIRTHDAY_SHORT_FORMAT)
            ));

        $result = $query->getQuery()->getResult();

        return $result;
    }

    public function getUsersEmailByWall(\Bundle\CommonBundle\Entity\Wall\Wall $wall)
    {
        $emails = array();

        if ($wall->getParentType() == 'Group') {
            if ($group = $this->getRepository('group')->find($wall->getParentId())) {
                foreach ($group->getUsers() as $user) {
                    if ($user->getEmail()) {
                        $emails[] = $user->getEmail();
                    }
                }
            };
        } else {
            $query = $this->createQueryBuilder('u');
            $query
                ->select('u.email')
                ->where('u.email IS NOT NULL')
                ;
            $users = $query->getQuery(Query::HYDRATE_ARRAY)->getResult();
            foreach ($users as $user) {
                $emails[] = $user['email'];
            }
        }

        return $emails;
    }

    public function getUsersEmailByIds($userIds)
    {
        $emails = array();

        $query = $this->createQueryBuilder('u');
        $query
            ->select('u.email')
            ->where(
                $query->expr()->in('u.id', ':ids')
            )
            ->andWhere('u.email IS NOT NULL')
            ->setParameter('ids', $userIds)
            ;
        $users = $query->getQuery(Query::HYDRATE_ARRAY)->getResult();

        foreach ($users as $user) {
            $emails[] = $user['email'];
        }

        return $emails;
    }
}
<commit_msg>#20784 -- Отсортировать пользователей по алфавиту<commit_after><?php

namespace Bundle\CommonBundle\Entity\User;

use Bundle\CommonBundle\Constants\UserConstant;
use Bundle\CommonBundle\Entity\Core\BaseRepository;
use Bundle\CommonBundle\Entity\User\User;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\NoResultException;
use Bundle\CommonBundle\Constants\SearchConstant;
use Bundle\CommonBundle\Entity\Group\GroupRepository;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;

use Bundle\CommonBundle\Entity\Core\BaseEntity;
use Doctrine\ORM\Query;

/**
 * UserRepository
 */
class UserRepository extends BaseRepository implements UserProviderInterface
{

    /** Событие после вставки сущности */
    protected function postPersist(BaseEntity $user)
    {
        $this->getRepository('event')->createUserCreateEvent($user);
    }
    
    public function loadUserByUsername($username)
    {
        $q = $this
            ->createQueryBuilder('u')
            ->where('u.username = :username')
            ->setParameter('username', $username)
            ->getQuery();

        try {
            $user = $q->getSingleResult();
        } catch (NoResultException $e) {
            $message = sprintf(
                'Unable to find User object identified by "%s".',
                $username
            );
            throw new UsernameNotFoundException($message, 0, $e);
        }

        return $user;
    }

    public function refreshUser(UserInterface $user)
    {
        $class = get_class($user);
        if (!$this->supportsClass($class)) {
            throw new UnsupportedUserException(
                sprintf(
                    'Instances of "%s" are not supported.',
                    $class
                )
            );
        }

        return $this->find($user->getId());
    }

    public function supportsClass($class)
    {
        return $this->getEntityName() === $class
            || is_subclass_of($class, $this->getEntityName());
    }

    /**
     * Поиск пользователей
     * @param string $text
     */
    public function search($text, $limit = null, $offset = null)
    {
        $query = $this->_prepareSearchQuery($text);

        $limit != null ? $query->setMaxResults($limit) : false;
        $offset != null ? $query->setFirstResult($offset) : false;

        return $query->getQuery()->getResult();
    }

    /**
     * Поиск количества пользователей
     * @param string $text
     * @return int
     */
    public function searchCount($text)
    {
        return $this->_prepareSearchQuery($text)
            ->select('COUNT(u.id)')
            ->getQuery()
            ->getSingleScalarResult();
    }

    /**
     * @param $text
     * @return \Doctrine\ORM\QueryBuilder
     */
    protected function _prepareSearchQuery($text)
    {
        $query = $this->createQueryBuilder('u');
        if (!empty($text)) {
            $query
                ->where('u.name LIKE :text')
                ->orWhere('u.surname LIKE :text')
                ->orWhere('u.email LIKE :text')
                ->setParameter('text', sprintf('%%%s%%', $text));
        }

        $query->addOrderBy('u.name');
        $query->addOrderBy('u.surname');
        return $query;
    }

    /**
     * Получить всех пользователей
     * @return array The entities.
     */
    public function getAll()
    {
        $query = $this->createQueryBuilder('u');
        $query->addOrderBy('u.name');
        $query->addOrderBy('u.surname');
        return $query->getQuery()->getResult();
    }

    /**
     * Получить массив пользователей из строки формата u1,u2,g1,g2
     * @param $usersGroupsList
     * @return array
     * @throws \Exception
     */
    public function getUsersFromGroupList($usersGroupsList)
    {
        $usersAndGroups = explode(",", $usersGroupsList);
        if (!is_array($usersAndGroups)) {
            throw new \Exception('sendBadge.noData');
        }

        $users = array();
        /** @var GroupRepository $groupRepository */
        $groupRepository = $this->getRepository('group');

        foreach ($usersAndGroups as $ug) {
            preg_match('/^([a-z]{1})(\d+)/', $ug, $matches);
            $prefix = $matches[1] ? $matches[1] : "";
            $id = $matches[2] ? $matches[2] : "";

            if (!$id || !$prefix) continue;

            switch ($prefix) {
                case SearchConstant::USER_ID_PREFIX:
                    $users[] = $this->find($id);
                    break;
                case SearchConstant::GROUP_ID_PREFIX:
                    $users = array_merge($users, $groupRepository->getAllUsersFromGroup($id));
                    break;
                default:
                    break;
            }
        }
        return $users;
    }

    /**
     * Устанавливает аватар пользователя по url изображения
     * @param type $url
     */
    public function setAvatarByUrl(User $user, $url)
    {
        try {
            /** @var $file \Symfony\Component\HttpFoundation\File\UploadedFile */
            if ($file = $this->imageProvider->getImage($url)) {
                $user->setAvatar($file);
            }
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    public function getUsersByBirthday($start, $end, $owner = null)
    {
        if ($start) {
            $startObj = new \DateTime();
            $startObj->setTimestamp($start);

            $start = $startObj;
        }
        if ($end) {
            $endObj = new \DateTime();
            $endObj->setTimestamp($end);

            $end = $endObj;
        }

        $query = $this->createQueryBuilder('u');

        $query->where(
                $query->expr()->between('u.birthdayShort', ':start', ':end')
        )
            ->setParameters(array(
                'start' => $start->format(UserConstant::BIRTHDAY_SHORT_FORMAT),
                'end' => $end->format(UserConstant::BIRTHDAY_SHORT_FORMAT)
            ));

        $result = $query->getQuery()->getResult();

        return $result;
    }

    public function getUsersEmailByWall(\Bundle\CommonBundle\Entity\Wall\Wall $wall)
    {
        $emails = array();

        if ($wall->getParentType() == 'Group') {
            if ($group = $this->getRepository('group')->find($wall->getParentId())) {
                foreach ($group->getUsers() as $user) {
                    if ($user->getEmail()) {
                        $emails[] = $user->getEmail();
                    }
                }
            };
        } else {
            $query = $this->createQueryBuilder('u');
            $query
                ->select('u.email')
                ->where('u.email IS NOT NULL')
                ;
            $users = $query->getQuery(Query::HYDRATE_ARRAY)->getResult();
            foreach ($users as $user) {
                $emails[] = $user['email'];
            }
        }

        return $emails;
    }

    public function getUsersEmailByIds($userIds)
    {
        $emails = array();

        $query = $this->createQueryBuilder('u');
        $query
            ->select('u.email')
            ->where(
                $query->expr()->in('u.id', ':ids')
            )
            ->andWhere('u.email IS NOT NULL')
            ->setParameter('ids', $userIds)
            ;
        $users = $query->getQuery(Query::HYDRATE_ARRAY)->getResult();

        foreach ($users as $user) {
            $emails[] = $user['email'];
        }

        return $emails;
    }
}

{'fraction_non_alphanumeric': 0.14486536430834213, 'fraction_numerical': 0.0016499472016895458, 'mean_word_length': 1.852597891566265, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 149, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5896611', 'n_tokens_mistral': 4337, 'n_tokens_neox': 4238, 'n_words': 780}