Completed
Push — master ( 2319eb...3c4d84 )
by Vladimir
02:22
created

CollectionManager::getJailedCollections()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
/**
4
 * @copyright 2017 Vladimir Jimenez
5
 * @license   https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\stakx\Manager;
9
10
use allejo\stakx\Configuration;
11
use allejo\stakx\Document\ContentItem;
12
use allejo\stakx\Document\JailedDocument;
13
use allejo\stakx\Exception\TrackedItemNotFoundException;
14
use allejo\stakx\Filesystem\File;
15
use allejo\stakx\Filesystem\FilesystemLoader as fs;
16
use Psr\Log\LoggerInterface;
17
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
18
19
/**
20
 * The class that reads and saves information about all of the collections.
21
 */
22
class CollectionManager extends TrackingManager
23
{
24
    /** @var string[][] A copy of the collection definitions to be available for later usage. */
25
    private $collectionDefinitions;
26
    private $configuration;
27
    private $eventDispatcher;
28
    private $logger;
29
30
    /**
31
     * CollectionManager constructor.
32
     */
33 36
    public function __construct(Configuration $configuration, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger)
34
    {
35 36
        $this->configuration = $configuration;
36 36
        $this->eventDispatcher = $eventDispatcher;
37 36
        $this->logger = $logger;
38 36
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43 6
    public function compileManager()
44
    {
45 6
        if (!$this->configuration->hasCollections())
46
        {
47
            $this->logger->notice('No Collections defined... Ignoring');
48
            return;
49
        }
50
51 6
        $this->parseCollections($this->configuration->getCollectionsFolders());
52 6
    }
53
54
    /**
55
     * Get all of the ContentItems grouped by Collection name.
56
     *
57
     * ```php
58
     * [
59
     *     'collection name' => [
60
     *         new ContentItem(),
61
     *         new ContentItem(),
62
     *     ]
63
     * ]
64
     * ```
65
     *
66
     * @return ContentItem[][]
67
     */
68 15
    public function &getCollections()
69
    {
70 15
        return $this->trackedItems;
71
    }
72
73
    /**
74
     * Get a ContentItem from a Collection passed on it's path.
75
     *
76
     * @param string $filePath
77
     *
78
     * @throws TrackedItemNotFoundException
79
     *
80
     * @return ContentItem
81
     */
82 1
    public function &getContentItem($filePath)
83
    {
84 1
        if (!isset($this->trackedItemsFlattened[$filePath]))
85
        {
86
            throw new TrackedItemNotFoundException("The ContentItem at '$filePath' was not found.");
87
        }
88
89 1
        return $this->trackedItemsFlattened[$filePath];
90
    }
91
92
    /**
93
     * A jailed representation of CollectionManager::getCollections().
94
     *
95
     * @return JailedDocument[][]
0 ignored issues
show
Documentation introduced by
Should the return type not be array<JailedDocument|JailedDocument[]>?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
96
     */
97 19
    public function getJailedCollections()
98
    {
99 19
        return self::getJailedTrackedItems($this->trackedItemsFlattened);
100
    }
101
102
    /**
103
     * Parse every collection and store them in the manager.
104
     *
105
     * @param string[][] $collections An array of definitions for collections
106
     */
107 36
    public function parseCollections($collections)
108
    {
109 36
        if ($collections == null || empty($collections))
110
        {
111 1
            $this->logger->debug('No collections found, nothing to parse.');
112
113 1
            return;
114
        }
115
116 36
        $this->collectionDefinitions = $collections;
117
118
        /**
119
         * The information which each collection has taken from the configuration file.
120
         *
121
         * $collection['name']   string The name of the collection
122
         *            ['folder'] string The folder where this collection has its ContentItems
123
         *
124
         * @var array
125
         */
126 36
        foreach ($collections as $collection)
127
        {
128 36
            $this->logger->notice('Loading "{name}" collection...', [
129 36
                'name' => $collection['name'],
130
            ]);
131
132 36
            $collectionFolder = fs::absolutePath($collection['folder']);
133
134 36
            if (!fs::exists($collectionFolder))
135
            {
136
                $this->logger->warning('The folder "{folder}" could not be found for the "{name}" collection', [
137
                    'folder' => $collection['folder'],
138
                    'name'   => $collection['name'],
139
                ]);
140
141
                continue;
142
            }
143
144 36
            $this->saveFolderDefinition($collection['folder'], $collection);
145 36
            $this->scanTrackableItems($collectionFolder, [
146 36
                'namespace' => $collection['name'],
147
            ]);
148
        }
149 36
    }
150
151
    /**
152
     * {@inheritdoc}
153
     */
154 1
    public function createNewItem($filePath)
155
    {
156 1
        $collection = $this->getCollectionNameFromPath($filePath);
157
158 1
        return $this->handleTrackableItem($filePath, [
159 1
            'namespace' => $collection,
160
        ]);
161
    }
162
163
    /**
164
     * {@inheritdoc}
165
     */
166
    public function refreshItem($filePath)
167
    {
168
    }
169
170
    /**
171
     * {@inheritdoc}
172
     */
173 36
    protected function handleTrackableItem(File $filePath, array $options = [])
174
    {
175 36
        $collectionName = $options['namespace'];
176
177 36
        $contentItem = new ContentItem($filePath);
178 36
        $contentItem->setNamespace($collectionName);
179 36
        $contentItem->evaluateFrontMatter([], [
180 36
            'site' => $this->configuration->getConfiguration(),
181
        ]);
182
183 36
        $this->addObjectToTracker($contentItem, $collectionName);
184
185 36
        $this->logger->info('Loading ContentItem into "{name}" collection: {path}', [
186 36
            'name' => $collectionName,
187 36
            'path' => fs::getRelativePath($filePath),
188
        ]);
189
190 36
        return $contentItem;
191
    }
192
193
    /**
194
     * Get the name of the Collection this ContentItem belongs to based on its location.
195
     *
196
     * @param File $file
197
     *
198
     * @return string
199
     */
200 1
    private function getCollectionNameFromPath(File $file)
201
    {
202 1
        $folders = array_column($this->collectionDefinitions, 'folder');
203 1
        $index = array_search($file->getRelativeParentFolder(), $folders);
204
205 1
        if (isset($this->collectionDefinitions[$index]['name']))
206
        {
207 1
            return $this->collectionDefinitions[$index]['name'];
208
        }
209
210
        return '';
211
    }
212
}
213