-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTagLoader.php
More file actions
72 lines (56 loc) · 1.99 KB
/
Copy pathTagLoader.php
File metadata and controls
72 lines (56 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
declare(strict_types=1);
namespace Light\App\Fixture;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Light\Blog\Entity\Tag;
use RuntimeException;
use function file_get_contents;
use function json_decode;
class TagLoader extends Fixture
{
public function load(ObjectManager $manager): void
{
$jsonFile = __DIR__ . '/articles_cleaned.json';
$contents = file_get_contents($jsonFile);
if ($contents === false) {
throw new RuntimeException("Unable to read file: {$jsonFile}");
}
$categories = json_decode($contents, true);
$repository = $manager->getRepository(Tag::class);
$seenSlugs = [];
foreach ($categories as $cat) {
foreach ($cat['articles'] as $article) {
foreach ($article['tags'] ?? [] as $tagData) {
$slug = $tagData['slug'];
$name = $tagData['name'];
if (isset($seenSlugs[$slug])) {
continue;
}
$seenSlugs[$slug] = true;
$tag = $repository->findOneBy(['slug' => $slug]);
if ($tag === null) {
$tag = new Tag();
$tag->setSlug($slug);
$tag->setName($name);
$manager->persist($tag);
echo "CREATE: {$name}\n";
} else {
$changed = false;
if ($tag->getName() !== $name) {
$tag->setName($name);
$changed = true;
}
echo $changed ? "UPDATE: {$name}\n" : "UNCHANGED: {$name}\n";
}
$this->addReference('tag_' . $slug, $tag);
}
}
}
$manager->flush();
}
public function getOrder(): int
{
return 1;
}
}