1<?php
2/**
3 * Zend Framework (http://framework.zend.com/)
4 *
5 * @link      http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license   http://framework.zend.com/license/new-bsd New BSD License
8 */
9
10namespace Zend\View\Helper;
11
12use Zend\Authentication\AuthenticationServiceInterface;
13use Zend\View\Exception;
14
15/**
16 * View helper plugin to fetch the authenticated identity.
17 */
18class Identity extends AbstractHelper
19{
20    /**
21     * AuthenticationService instance
22     *
23     * @var AuthenticationServiceInterface
24     */
25    protected $authenticationService;
26
27    /**
28     * Retrieve the current identity, if any.
29     *
30     * If none available, returns null.
31     *
32     * @throws Exception\RuntimeException
33     * @return mixed|null
34     */
35    public function __invoke()
36    {
37        if (!$this->authenticationService instanceof AuthenticationServiceInterface) {
38            throw new Exception\RuntimeException('No AuthenticationServiceInterface instance provided');
39        }
40
41        if (!$this->authenticationService->hasIdentity()) {
42            return;
43        }
44
45        return $this->authenticationService->getIdentity();
46    }
47
48    /**
49     * Set AuthenticationService instance
50     *
51     * @param AuthenticationServiceInterface $authenticationService
52     * @return Identity
53     */
54    public function setAuthenticationService(AuthenticationServiceInterface $authenticationService)
55    {
56        $this->authenticationService = $authenticationService;
57        return $this;
58    }
59
60    /**
61     * Get AuthenticationService instance
62     *
63     * @return AuthenticationServiceInterface
64     */
65    public function getAuthenticationService()
66    {
67        return $this->authenticationService;
68    }
69}
70