<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonSetArticles\Classes;

/**
 * Class FileMover
 * @package Shopware\Plugins\ViisonSetArticles\Classes
 */
class FileMover
{

    private $sourceDir = null;
    private $targetDir = null;

    public function __construct($src, $trgt)
    {
        $this->sourceDir = $src;
        $this->targetDir = $trgt;
    }

    /**
     * Initiliazes copy function
     * @return bool
     */
    public function copy()
    {
        return $this->recurseCopy($this->sourceDir, $this->targetDir);
    }

    /**
     * Copies all files and folders recursively from one source folder to another destination folder.
     *
     * @param $source
     * @param $dest
     * @return bool
     */
    private function recurseCopy($source, $dest)
    {
        if (!file_exists($dest) || !is_dir($dest)) {
            mkdir($dest, 0755);
        }

        $iterator = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS),
            \RecursiveIteratorIterator::SELF_FIRST
        );
        foreach ($iterator as $item) {
            $path = $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName();
            if ($item->isDir()) {
                if (!file_exists($path) || !is_dir($path)) {
                    mkdir($path, 0777, true);
                }
            } else {
                // Copy: If the destination file already exists, it will be overwritten.
                copy($item, $path);
            }
        }

        return true;
    }
}
