1<?php
2
3/*
4 * This file is part of the Prophecy.
5 * (c) Konstantin Kudryashov <ever.zet@gmail.com>
6 *     Marcello Duarte <marcello.duarte@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 Prophecy\Argument\Token;
13
14use Prophecy\Exception\InvalidArgumentException;
15
16/**
17 * Value type token.
18 *
19 * @author Konstantin Kudryashov <ever.zet@gmail.com>
20 */
21class TypeToken implements TokenInterface
22{
23    private $type;
24
25    /**
26     * @param string $type
27     */
28    public function __construct($type)
29    {
30        $checker = "is_{$type}";
31        if (!function_exists($checker) && !interface_exists($type) && !class_exists($type)) {
32            throw new InvalidArgumentException(sprintf(
33                'Type or class name expected as an argument to TypeToken, but got %s.', $type
34            ));
35        }
36
37        $this->type = $type;
38    }
39
40    /**
41     * Scores 5 if argument has the same type this token was constructed with.
42     *
43     * @param $argument
44     *
45     * @return bool|int
46     */
47    public function scoreArgument($argument)
48    {
49        $checker = "is_{$this->type}";
50        if (function_exists($checker)) {
51            return call_user_func($checker, $argument) ? 5 : false;
52        }
53
54        return $argument instanceof $this->type ? 5 : false;
55    }
56
57    /**
58     * Returns false.
59     *
60     * @return bool
61     */
62    public function isLast()
63    {
64        return false;
65    }
66
67    /**
68     * Returns string representation for token.
69     *
70     * @return string
71     */
72    public function __toString()
73    {
74        return sprintf('type(%s)', $this->type);
75    }
76}
77