Seeding Data - How can I add Images to an insert

garethshaw - 2 weeks ago

Hi all So a Makes (plus Models) table has Logo, Title, etc. I know when creating the table that say Canon and Nikon need to be in the DB, I have the images.

I can seed the data to the table but I'm unsure where to put the image files or how to add the image to the Files module and utilise it, whilst also checking if it already exists.

Operations I want: Check if Logos folder exists If not create Grab Folder ID Check if Logo exists If not add to Logos folder Grab Image ID

This is what I have so far, however it relies on the image already existing, which is great whilst testing, not so great when it goes to production. Right now a few things are hard-coded, like the filename "Canon Logo.jpg" and the folder name, and since I'm not uploading the image, if the folder doesn't exist, it's impossible for the image to exist, so the checking can be pulled out of the else and the uploading of the image put before the check.

Thanks Gareth

    if (!$logo = $this->folders->findBySlug('logos')) {
        $disk = $this->disks->findBySlug('local');

        $this->folders->create(
            [
                'en' => [
                    'name' => 'Logos',
                    'description' => 'A folder for Logos.',
                ],
                'slug' => 'logos',
                'disk' => $disk,
                'allowed_types' => [
                    'png',
                    'jpeg',
                    'jpg',
                ],
            ]
        );
    } else {
        $name = "Canon Logo.jpg";
        $folder = "Logos";

        /* @var FolderInterface|null $folder */
        $folder = $this->folders->findBySlug($folder);

        $image = $this->files->findByNameAndFolder($name, $folder);
    }

garethshaw - 2 weeks ago

I've created this outline...

$name = "AscTec Falcon 8.jpg"; $folder = "Logos";

    // slugify it
    $folder_name = str_replace("+", " plus", $folder);
    $folder_name_slugified = trim($this->str->slug($folder_name, "-"));

    if (!$logo = $this->folders->findBySlug($folder_name_slugified)) {
        $disk = $this->disks->findBySlug('local');

        $this->folders->create(
            [
                'en' => [
                    'name' => $folder,
                    'description' => 'A folder for Logos.',
                ],
                'slug' => $folder_name_slugified,
                'disk' => $disk,
                'allowed_types' => [
                    'png',
                    'jpeg',
                    'jpg',
                ],
            ]
        );
    }

    /* @var FolderInterface|null $folder */
    $folder_obj = $this->folders->findBySlug($folder_name_slugified);

    if ($image = $this->files->findByNameAndFolder($name, $folder_obj)) {
        //upload
    }

piterden - 2 weeks ago

<?php namespace Defr\DefaultTheme\Page;

use Anomaly\FilesModule\File\Contract\FileRepositoryInterface;
use Anomaly\FilesModule\File\FileUploader;
use Anomaly\FilesModule\Folder\Contract\FolderRepositoryInterface;
use Anomaly\PagesModule\Page\Contract\PageRepositoryInterface;
use Anomaly\PagesModule\Type\Contract\TypeRepositoryInterface;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Http\UploadedFile;

class PageSeeder extends \Anomaly\PagesModule\Page\PageSeeder
{

    /**
     * The files repository.
     *
     * @var FileRepositoryInterface
     */
    protected $files;

    /**
     * Uploader
     *
     * @var FileUploader
     */
    protected $uploader;

    /**
     * The folders repository.
     *
     * @var FolderRepositoryInterface
     */
    protected $folders;

    /**
     * Create a new ProductSeeder instance.
     *
     * @param Filesystem                $filesystem The filesystem
     * @param FileUploader              $uploader   The uploader
     * @param PageRepositoryInterface   $pages      The pages
     * @param TypeRepositoryInterface   $types      The types
     * @param FileRepositoryInterface   $files      The files
     * @param FolderRepositoryInterface $folders    The folders
     */
    public function __construct(
        Filesystem $filesystem,
        FileUploader $uploader,
        PageRepositoryInterface $pages,
        TypeRepositoryInterface $types,
        FileRepositoryInterface $files,
        FolderRepositoryInterface $folders
    )
    {
        parent::__construct($pages, $types);

        $this->files      = $files;
        $this->folders    = $folders;
        $this->uploader   = $uploader;
        $this->filesystem = $filesystem;
    }

    /**
     * Run the seeder
     */
    public function run()
    {
        echo "\n3[37;5;228mStarting pages seeder!\n";

        $this->pages->truncate();
        $this->files->truncate();
        $this->folders->truncate();

        echo "3[35;5;228mPages truncated!\n";

        $data = include_once __DIR__ . '/../../resources/seeder/modx_site_content.php';

        $home = true;

        foreach ($data as $item)
        {
            $title   = array_get($item, 'pagetitle', '');
            $slug    = array_get($item, 'alias', '');
            $content = array_get($item, 'content', '');
            $parent  = array_get($item, 'parent', '');
            $summary = array_get($item, 'introtext', '');

            $type = ($parent == '2')
                ? $this->types->findBySlug('event')
                : $this->types->findBySlug('default');

            $entry = $type->getEntryModel()->create([
                'en' => [
                    'content' => $content,
                ],
                'ru' => [
                    'content' => $content,
                ],
            ]);

            $this->pages->create([
                'ru'           => [
                    'title'            => $title,
                    'meta_title'       => $title,
                    'meta_description' => $summary,
                ],
                'en'           => [
                    'title'            => $title,
                    'meta_title'       => $title,
                    'meta_description' => $summary,
                ],
                'slug'         => $slug,
                'entry'        => $entry,
                'type'         => $type,
                'enabled'      => true,
                'home'         => $home,
                'parent'       => $parent,
                'theme_layout' => 'theme::layouts/default.twig',
            ])->allowedRoles()->sync([]);

            $home = false;

            echo "3[36;5;228mCreated page 3[31;5;228m{$title}. Slug: {$slug}\n";

            if ($parent == '2')
            {
                if ($folder = $this->folders->findBySlug(md5($slug)))
                {
                    $images = $this->filesystem->glob(__DIR__ . '/../../resources/seeder/gallery/' . $slug . '/*.jpg');

                    $count = count($images);

                    echo "3[31;5;228mFound {$count} images. 3[36;5;228mStarting images upload!\n";

                    $i   = 1;
                    $ids = [];

                    foreach ($images as $image)
                    {
                        $uploaded = new UploadedFile(
                            $image,
                            $slug . '_' . $i . '.jpg',
                            'image/jpeg',
                            filesize($image),
                            null,
                            true
                        );

                        $file = $this->uploader->upload($uploaded, $folder);

                        $ids[] = $file->getId();

                        ++$i;

                        echo "3[31;5;228mUploaded {$image}.\n";
                    }

                    echo "3[36;5;228mAll images was uploaded!\n";

                    $entry->gallery()->sync($ids);
                    $entry->save();
                }
            }
        }

        echo "3[32;5;228mPages was seeded successfully!\n";
    }
}

piterden - 2 weeks ago

I forget about the command which fires by Eloquent event

<?php namespace Defr\DefaultTheme\Page\Command;

use Anomaly\FilesModule\Disk\Contract\DiskRepositoryInterface;
use Anomaly\FilesModule\Folder\Contract\FolderRepositoryInterface;
use Anomaly\PagesModule\Page\Contract\PageInterface;
use Anomaly\Streams\Platform\Model\Pages\PagesEventPagesEntryModel;

class CreateFolder
{

    /**
     * Page model
     *
     * @var mixed
     */
    protected $page;

    /**
     * Create an instance of CreateFolder class
     *
     * @param PageInterface $page The page
     */
    public function __construct(PageInterface $page)
    {
        $this->page = $page;
    }

    /**
     * Handle the command
     *
     * @param FolderRepositoryInterface $folders The folders
     * @param DiskRepositoryInterface   $disks   The disks
     */
    public function handle(
        FolderRepositoryInterface $folders,
        DiskRepositoryInterface $disks
    )
    {
        if ($this->page->getEntry() instanceof PagesEventPagesEntryModel) {
            $disk  = $disks->findBySlug('local');
            $slug  = $this->page->getSlug();
            $title = $this->page->getTitle();
            $hash  = md5($slug);

            $folders->create([
                'en'            => [
                    'name'        => $title,
                    'description' => "A folder for {$title}.",
                ],
                'slug'          => $hash,
                'disk'          => $disk,
                'allowed_types' => [
                    'png',
                    'jpeg',
                    'jpg',
                    'gif',
                    'svg',
                ],
            ]);
        }
    }

}