<?php

namespace ModuleUser\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Authentication\AuthenticationService;
use ModuleUser\View\Helper\User;
use ModuleUser\Service\UserServiceInterface;

class UserViewHelperFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $realServiceLocator = $serviceLocator->getServiceLocator();
        $auth = $realServiceLocator->get(AuthenticationService::class);
        $userService = $realServiceLocator->get(UserServiceInterface::class);
        try {
            $user = $userService->findUserBy('email', $auth->getIdentity());
        } catch (\Exception $e) {
            $user = null;
        }
        return new User($user);
    }
}