Completed
Push — master ( 808f8c...952fde )
by Vladimir
11s
created

CollectionManager::getCollectionNameFromPath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
ccs 5
cts 6
cp 0.8333
cc 2
eloc 6
nc 2
nop 1
crap 2.0185
1
<?php
2
3
/**
4
 * @copyright 2018 Vladimir Jimenez
5
 * @license   https://github.com/stakx-io/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\Event\CollectionDefinitionAdded;
14
use allejo\stakx\Event\CollectionItemAdded;
15
use allejo\stakx\Exception\TrackedItemNotFoundException;
16
use allejo\stakx\Filesystem\File;
17
use allejo\stakx\Filesystem\FilesystemLoader as fs;
18
use allejo\stakx\MarkupEngine\MarkupEngineManager;
19
use Psr\Log\LoggerInterface;
20
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
21
22
/**
23
 * The class that reads and saves information about all of the collections.
24
 */
25
class CollectionManager extends TrackingManager
26
{
27
    /** @var string[][] A copy of the collection definitions to be available for later usage. */
28
    private $collectionDefinitions;
29
    private $markupEngineManager;
30
    private $configuration;
31
    private $eventDispatcher;
32
    private $logger;
33
34
    /**
35
     * CollectionManager constructor.
36
     */
37 36
    public function __construct(MarkupEngineManager $markupEngineManager, Configuration $configuration, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger)
38
    {
39 36
        $this->markupEngineManager = $markupEngineManager;
40 36
        $this->configuration = $configuration;
41 36
        $this->eventDispatcher = $eventDispatcher;
42 36
        $this->logger = $logger;
43 36
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48 6
    public function compileManager()
49
    {
50 6
        if (!$this->configuration->hasCollections())
51
        {
52
            $this->logger->notice('No Collections defined... Ignoring');
53
54
            return;
55
        }
56
57 6
        $this->parseCollections($this->configuration->getCollectionsFolders());
58 6
    }
59
60
    /**
61
     * Get all of the ContentItems grouped by Collection name.
62
     *
63
     * ```php
64
     * [
65
     *     'collection name' => [
66
     *         new ContentItem(),
67
     *         new ContentItem(),
68
     *     ]
69
     * ]
70
     * ```
71
     *
72
     * @return ContentItem[][]
73
     */
74 15
    public function &getCollections()
75
    {
76 15
        return $this->trackedItems;
77
    }
78
79
    /**
80
     * Get a ContentItem from a Collection passed on it's path.
81
     *
82
     * @param string $filePath
83
     *
84
     * @throws TrackedItemNotFoundException
85
     *
86
     * @return ContentItem
87
     */
88 1
    public function &getContentItem($filePath)
89
    {
90 1
        if (!isset($this->trackedItemsFlattened[$filePath]))
91
        {
92
            throw new TrackedItemNotFoundException("The ContentItem at '$filePath' was not found.");
93
        }
94
95 1
        return $this->trackedItemsFlattened[$filePath];
96
    }
97
98
    /**
99
     * A jailed representation of CollectionManager::getCollections().
100
     *
101
     * @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...
102
     */
103 19
    public function getJailedCollections()
104
    {
105 19
        return self::getJailedTrackedItems($this->trackedItemsFlattened);
106
    }
107
108
    /**
109
     * Parse every collection and store them in the manager.
110
     *
111
     * @param string[][] $collections An array of definitions for collections
112
     */
113 36
    public function parseCollections($collections)
114
    {
115 36
        if ($collections == null || empty($collections))
116
        {
117 1
            $this->logger->debug('No collections found, nothing to parse.');
118
119 1
            return;
120
        }
121
122 36
        $this->collectionDefinitions = $collections;
123
124
        /**
125
         * The information which each collection has taken from the configuration file.
126
         *
127
         * $collection['name']   string The name of the collection
128
         *            ['folder'] string The folder where this collection has its ContentItems
129
         *
130
         * @var array
131
         */
132 36
        foreach ($collections as $collection)
133
        {
134 36
            $this->logger->notice('Loading "{name}" collection...', [
135 36
                'name' => $collection['name'],
136
            ]);
137
138 36
            $collectionFolder = fs::absolutePath($collection['folder']);
0 ignored issues
show
Documentation introduced by
$collection['folder'] is of type string, but the function expects a object<string>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
139
140 36
            if (!fs::exists($collectionFolder))
141
            {
142
                $this->logger->warning('The folder "{folder}" could not be found for the "{name}" collection', [
143
                    'folder' => $collection['folder'],
144
                    'name' => $collection['name'],
145
                ]);
146
147
                continue;
148
            }
149
150 36
            $event = new CollectionDefinitionAdded($collection['name'], $collection['folder']);
151 36
            $this->eventDispatcher->dispatch(CollectionDefinitionAdded::NAME, $event);
152
153 36
            $this->saveFolderDefinition($collection['folder'], $collection);
154 36
            $this->scanTrackableItems($collectionFolder, [
155 36
                'namespace' => $collection['name'],
156
            ]);
157
        }
158 36
    }
159
160
    /**
161
     * {@inheritdoc}
162
     */
163 1
    public function createNewItem($filePath)
164
    {
165 1
        $collection = $this->getCollectionNameFromPath($filePath);
166
167 1
        return $this->handleTrackableItem($filePath, [
168 1
            'namespace' => $collection,
169
        ]);
170
    }
171
172
    /**
173
     * {@inheritdoc}
174
     */
175
    public function refreshItem($filePath)
176
    {
177
    }
178
179
    /**
180
     * {@inheritdoc}
181
     */
182 36
    protected function handleTrackableItem(File $filePath, array $options = [])
183
    {
184 36
        $collectionName = $options['namespace'];
185
186 36
        $contentItem = new ContentItem($filePath);
187 36
        $contentItem->setMarkupEngine($this->markupEngineManager);
188 36
        $contentItem->setNamespace($collectionName);
189 36
        $contentItem->evaluateFrontMatter([], [
190 36
            'site' => $this->configuration->getConfiguration(),
191
        ]);
192
193 36
        $this->addObjectToTracker($contentItem, $collectionName);
194
195 36
        $this->logger->info('Loading ContentItem into "{name}" collection: {path}', [
196 36
            'name' => $collectionName,
197 36
            'path' => $filePath->getRelativeFilePath(),
198
        ]);
199
200 36
        $event = new CollectionItemAdded($contentItem);
201 36
        $this->eventDispatcher->dispatch(CollectionItemAdded::NAME, $event);
202
203 36
        return $contentItem;
204
    }
205
206
    /**
207
     * Get the name of the Collection this ContentItem belongs to based on its location.
208
     *
209
     * @param File $file
210
     *
211
     * @return string
212
     */
213 1
    private function getCollectionNameFromPath(File $file)
214
    {
215 1
        $folders = array_column($this->collectionDefinitions, 'folder');
216 1
        $index = array_search($file->getRelativeParentFolder(), $folders);
217
218 1
        if (isset($this->collectionDefinitions[$index]['name']))
219
        {
220 1
            return $this->collectionDefinitions[$index]['name'];
221
        }
222
223
        return '';
224
    }
225
}
226