1<?php
2
3declare(strict_types=1);
4
5namespace Metadata;
6
7/**
8 * Base class for class metadata.
9 *
10 * This class is intended to be extended to add your own application specific
11 * properties, and flags.
12 *
13 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
14 */
15class ClassMetadata implements \Serializable
16{
17    /**
18     * @var string
19     */
20    public $name;
21
22    /**
23     * @var MethodMetadata[]
24     */
25    public $methodMetadata = [];
26
27    /**
28     * @var PropertyMetadata[]
29     */
30    public $propertyMetadata = [];
31
32    /**
33     * @var string[]
34     */
35    public $fileResources = [];
36
37    /**
38     * @var int
39     */
40    public $createdAt;
41
42    public function __construct(string $name)
43    {
44        $this->name = $name;
45        $this->createdAt = time();
46    }
47
48    public function addMethodMetadata(MethodMetadata $metadata): void
49    {
50        $this->methodMetadata[$metadata->name] = $metadata;
51    }
52
53    public function addPropertyMetadata(PropertyMetadata $metadata): void
54    {
55        $this->propertyMetadata[$metadata->name] = $metadata;
56    }
57
58    public function isFresh(?int $timestamp = null): bool
59    {
60        if (null === $timestamp) {
61            $timestamp = $this->createdAt;
62        }
63
64        foreach ($this->fileResources as $filepath) {
65            if (!file_exists($filepath)) {
66                return false;
67            }
68
69            if ($timestamp < filemtime($filepath)) {
70                return false;
71            }
72        }
73
74        return true;
75    }
76
77    /**
78     * @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint
79     * @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingReturnTypeHint
80     * @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.UselessReturnAnnotation
81     *
82     * @return string
83     */
84    public function serialize()
85    {
86        return serialize([
87            $this->name,
88            $this->methodMetadata,
89            $this->propertyMetadata,
90            $this->fileResources,
91            $this->createdAt,
92        ]);
93    }
94
95    /**
96     * @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint
97     * @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingReturnTypeHint
98     * @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.UselessReturnAnnotation
99     *
100     * @param string $str
101     * @return void
102     */
103    public function unserialize($str)
104    {
105        list(
106            $this->name,
107            $this->methodMetadata,
108            $this->propertyMetadata,
109            $this->fileResources,
110            $this->createdAt
111            ) = unserialize($str);
112    }
113}
114