Skip to content

Commit

Permalink
Correct fixtures and change blog show template
Browse files Browse the repository at this point in the history
  • Loading branch information
maximehuran committed Aug 10, 2024
1 parent 402915f commit cd19041
Show file tree
Hide file tree
Showing 9 changed files with 120 additions and 54 deletions.
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ This plugin adds a blog to your Sylius project. It allows you to create blog art

## Compatibility

## Compatibility

| Sylius Version | PHP Version |
|---|---|
| 1.12 | 8.1 - 8.2 |
Expand Down
10 changes: 4 additions & 6 deletions src/Fixture/ArticleFixture.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,13 @@ protected function configureResourceNode(ArrayNodeDefinition $resourceNode): voi
->children()
->booleanNode('enabled')->defaultTrue()->end()
->scalarNode('image')->defaultNull()->end()
->scalarNode('tag')->defaultNull()->end()
->arrayNode('tags')
->scalarPrototype()->end()
->end()
->scalarNode('is_published')->defaultTrue()->end()
->scalarNode('publish_date')->cannotBeEmpty()->end()
->arrayNode('authors')
->arrayPrototype()
->children()
->scalarNode('name')->cannotBeEmpty()->end()
->end()
->end()
->scalarPrototype()->end()
->end()
->arrayNode('translations')
->arrayPrototype()
Expand Down
72 changes: 54 additions & 18 deletions src/Fixture/Factory/ArticleFixtureFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ final class ArticleFixtureFactory extends AbstractExampleFactory
private Generator $faker;

/**
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*
* @param FactoryInterface<ArticleInterface> $articleFactory
* @param FactoryInterface<ArticleTranslationInterface> $articleTranslationFactory
* @param TagRepositoryInterface<TagInterface> $tagRepository
Expand All @@ -64,6 +66,7 @@ public function __construct(
private RepositoryInterface $authorRepository,
private FileLocatorInterface $fileLocator,
private FileHelperInterface $fileHelper,
private string $defaultLocaleCode,
) {
$this->faker = Factory::create();

Expand All @@ -84,7 +87,9 @@ public function create(array $options = []): ArticleInterface
/** @var ArticleInterface $article */
$article = $this->articleFactory->createNew();
$article->setEnabled($options['enabled']);
$article->addTag($options['tag']);
foreach ($options['tags'] as $tag) {
$article->addTag($tag);
}
$article->setImage($options['image']);
$channels = $this->channelRepository->findAll();
/** @var ChannelInterface $channel */
Expand All @@ -107,6 +112,7 @@ public function create(array $options = []): ArticleInterface
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function configureOptions(OptionsResolver $resolver): void
{
Expand All @@ -117,15 +123,28 @@ protected function configureOptions(OptionsResolver $resolver): void

->setDefault('image', $this->lazyImageDefault(80))
->setAllowedTypes('image', ['string', 'null'])
->setNormalizer('image', function (Options $options, $previousValue): ?string {
return $this->getImagePath($previousValue);
})

->setDefault('tags', LazyOption::randomOnes($this->tagRepository, 2))
->setAllowedTypes('tags', ['array'])
->setNormalizer('tags', function (Options $options, $previousValue): array {
if (null === $previousValue || 0 === \count($previousValue)) {
return [];
}

->setDefault('tag', LazyOption::randomOne($this->tagRepository))
->setAllowedTypes('tag', ['string', TagInterface::class])
->setNormalizer('tag', function (Options $options, $previousValue): ?object {
if (null === $previousValue || \is_object($previousValue)) {
return $previousValue;
$result = [];
foreach ($previousValue as $tag) {
if (!\is_object($tag)) {
$tag = $this->tagRepository->findOneByName($tag, $this->defaultLocaleCode);
}
if (null !== $tag) {
$result[] = $tag;
}
}

return $this->tagRepository->findOneByName($previousValue, 'fr');
return $result;
})

->setDefault('authors', LazyOption::randomOnes($this->authorRepository, 2))
Expand All @@ -138,7 +157,7 @@ protected function configureOptions(OptionsResolver $resolver): void
$result = [];
foreach ($previousValue as $author) {
if (!\is_object($author)) {
$author = $this->authorRepository->findOneBy(['name' => $author['name']]);
$author = $this->authorRepository->findOneBy(['name' => $author]);
}
if (null !== $author) {
$result[] = $author;
Expand All @@ -155,7 +174,14 @@ protected function configureOptions(OptionsResolver $resolver): void
->setAllowedTypes('is_published', ['bool'])

->setDefault('publish_date', fn (Options $options): DateTimeInterface => $this->faker->dateTimeBetween('-1 years', 'now'))
->setAllowedTypes('publish_date', ['null', DateTime::class])
->setAllowedTypes('publish_date', ['null', 'string', DateTime::class])
->setNormalizer('publish_date', function (Options $options, $previousValue): DateTime {
if (\is_string($previousValue)) {
return new DateTime($previousValue);
}

return $previousValue;
})
;
}

Expand Down Expand Up @@ -224,19 +250,29 @@ private function lazyImageDefault(int $chanceOfRandomOne): Closure
}

$random = random_int(1, 5);
$sourcePath = $this->fileLocator->locate(sprintf('@MonsieurBizSyliusBlogPlugin/Resources/fixtures/article-%d.jpg', $random));
$existingImage = $this->findExistingImage(basename($sourcePath));
if (null !== $existingImage) {
return $existingImage;
}

$file = new UploadedFile($sourcePath, basename($sourcePath));
$filename = $this->fileHelper->upload($file, 'blog', 'gallery/images');

return 'gallery/images/blog/' . $filename;
return sprintf('@MonsieurBizSyliusBlogPlugin/Resources/fixtures/article-%d.jpg', $random);
};
}

private function getImagePath(?string $imagePath): ?string
{
if (null === $imagePath) {
return null;
}

$sourcePath = $this->fileLocator->locate($imagePath);
$existingImage = $this->findExistingImage(basename($sourcePath));
if (null !== $existingImage) {
return $existingImage;
}

$file = new UploadedFile($sourcePath, basename($sourcePath));
$filename = $this->fileHelper->upload($file, 'blog', 'gallery/images');

return 'gallery/images/blog/' . $filename;
}

private function findExistingImage(string $filename): ?string
{
try {
Expand Down
2 changes: 1 addition & 1 deletion src/Repository/ArticleRepositoryInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ interface ArticleRepositoryInterface extends RepositoryInterface
{
public function createListQueryBuilder(string $localeCode): QueryBuilder;

public function createShopListQueryBuilder(string $localeCode, ChannelInterface $channel, TagInterface $tag): QueryBuilder;
public function createShopListQueryBuilder(string $localeCode, ChannelInterface $channel, ?TagInterface $tag): QueryBuilder;

/**
* @return ArticleInterface[]
Expand Down
1 change: 1 addition & 0 deletions src/Resources/config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,4 @@ services:
MonsieurBiz\SyliusBlogPlugin\Fixture\Factory\ArticleFixtureFactory:
arguments:
$fileLocator: '@file_locator'
$defaultLocaleCode: '%locale%'
32 changes: 31 additions & 1 deletion src/Resources/config/sylius/fixtures.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,42 @@ sylius_fixtures:
fixtures:
monsieurbiz_blog_tag:
options:
random: 30
random: 3
custom:
- enabled: true
translations:
en_US:
name: 'Sylius'
slug: 'sylius'
- enabled: true
translations:
en_US:
name: 'E-commerce'
slug: 'e-commerce'

monsieubiz_blog_author:
options:
random: 3
custom:
- name: John Doe
- name: Jane Doe
- name: Foo Bar

monsieubiz_blog_article:
options:
random: 100
custom:
- enabled: true
is_published: true
publish_date: 'today'
image: '@MonsieurBizSyliusBlogPlugin/Resources/fixtures/cat.jpg'
tags: ['E-commerce', 'Sylius']
authors: ['John Doe', 'Jane Doe']
translations:
en_US:
title: 'The Fascinating World of Cats: A Guide to Our Furry Friends'
slug: 'the-fascinating-world-of-cats-a-guide-to-our-furry-friends'
description: |
Cats have captivated humans for thousands of years with their independent nature, playful behavior, and unique personalities. Whether lounging in a sunbeam or chasing a toy mouse, these furry companions bring joy and comfort to millions of households around the world.
content: |
[{"code":"monsieurbiz.text","data":{"content":"<p>Cats have long held a special place in human society, revered by ancient civilizations and cherished in modern homes. Their mysterious nature and graceful movements have inspired countless stories, art, and even superstitions. From the majestic lions of the wild to the domestic cats curled up on our laps, these animals are fascinating creatures with a rich history.</p><p>One of the most remarkable aspects of cats is their independence. <strong>Unlike dogs, cats do not require constant attention and are perfectly content to spend time alone. This trait makes them ideal pets for people with busy lifestyles. However, cats are also affectionate creatures, forming strong bonds with their owners and showing love in subtle ways, such as purring or gentle headbutts.</strong></p><p>Cats are also known for their playful behavior, which is a key part of their charm. Whether they are chasing a laser pointer, batting at a feather toy, or pouncing on an imaginary prey, their antics never fail to entertain. Play is essential for a cat's physical and mental well-being, helping them stay active and engaged.</p><p><strong>In addition to their playful side, cats are skilled hunters. Even though domesticated cats may not need to hunt for food, their instincts remain sharp. This predatory behavior can be observed in their stalking and pouncing habits, which they practice even during playtime. It's a reminder of their wild ancestry and the remarkable adaptability of the species.</strong></p><p>In conclusion, cats are more than just pets—they are companions with complex personalities and a rich history. Their combination of independence, playfulness, and hunting prowess makes them unique members of the animal kingdom. Whether you're a seasoned cat owner or just beginning to explore the world of felines, there's always something new to discover about these intriguing creatures.</p>","align":""}}]
Binary file added src/Resources/fixtures/cat.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
55 changes: 29 additions & 26 deletions src/Resources/views/Shop/Article/show.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -21,43 +21,46 @@
<div class="sixteen wide column">
<div class="ui">
<div class="ui header center aligned">
<div>
{% for tag in article.tags %}
<a href="{{ path('monsieurbiz_blog_tag_show', { 'slug': tag.slug }) }}">
{{ tag.name }}
</a>
{% endfor %}
</div>
<h1 class="ui huge">
{{ article.title }}
</h1>
{% if article.authors|length %}
<div class="ui list">
{% for author in article.authors %}
<div class="item">
<div class="content">
<div class="header">
{{ author.name }}
</div>
</div>
</div>
{% endfor %}
</div>
{% endif %}
<div class="ui">
<span>{{ article.publishedAt|format_date() }}</span>
</div>
</div>
<div class="ui hidden divider"></div>
<div class="ui fluid image">
{% include '@MonsieurBizSyliusBlogPlugin/Shop/Article/_image.html.twig' with {'filter': 'monsieurbiz_blog_image_large_thumbnail'} %}
<div style="width:100%; text-align:center;">
<div class="ui medium image rounded">
{% include '@MonsieurBizSyliusBlogPlugin/Shop/Article/_image.html.twig' with {'filter': 'monsieurbiz_blog_image_large_thumbnail'} %}
</div>
</div>
<div class="ui hidden divider"></div>
<div>
<div class="ui meta">
<span class="date">{{ article.publishedAt|format_date() }}</span>
</div>
<div class="ui description">
<div class="ui">
{{ article.content|monsieurbiz_richeditor_render_field }}
</div>
</div>
<div class="ui hidden divider"></div>
{% if article.tags|length %}
<div class="ui labels">
{% for tag in article.tags %}
<a href="{{ path('monsieurbiz_blog_tag_show', { 'slug': tag.slug }) }}" class="ui label">
{{ tag.name }}&nbsp;&nbsp;
<i class="tag icon"></i>
</a>
{% endfor %}
</div>
{% endif %}
{% if article.authors|length %}
<div class="ui labels">
{% for author in article.authors %}
<div class="ui label blue">
{{ author.name }}&nbsp;&nbsp;
<i class="user icon"></i>
</div>
{% endfor %}
</div>
{% endif %}
</div>
</div>
</div>
Expand Down

0 comments on commit cd19041

Please sign in to comment.