The below code will delete pub/media/tmp directory and sub directory all files which is older than one month.By the help of core php function.
1 Answer
<?php
declare(strict_types=1);
/**
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
*
* @copyright Copyright (c) 2022 MageVikas, Inc.
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
namespace Vendor\Module_Name\Cron;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Psr\Log\LoggerInterface;
class RemoveTmpDir
{
/**
* @var LoggerInterface
*/
protected $logger;
/**
* @var Filesystem
*/
protected $fileSystem;
/**
* @param LoggerInterface $logger
* @param Filesystem $fileSystem
* @throws \Magento\Framework\Exception\FileSystemException
*/
public function __construct(
LoggerInterface $logger,
Filesystem $fileSystem
) {
$this->logger = $logger;
$this->directory = $fileSystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->filesystem = $fileSystem;
}
/**
* Remove tmp dir from pub/media
*
* @return void
*/
public function execute()
{
$this->logger->info('Start Execution of tmp delete cron');
try {
$this->deleteFiles();
} catch (\Exception $e) {
$this->logger->info('Execute tmp delete cron Exception');
$this->logger->critical($e->getMessage());
}
$this->logger->info('End Execution of tmp delete cron');
}
/**
* Delete folder and sub folder files
*
* @param string $mediaPath
* @param string $interval
* @return int
* @throws LocalizedException
*/
public function deleteFiles($mediaPath = null, $interval = null)
{
$deletedFiles = 0;
$absolutePath = $this->directory->getAbsolutePath();
$mediaTmpPath = ($mediaPath) ? $absolutePath . $mediaPath : $absolutePath . DirectoryList::TMP;
$interval = ($interval) ? strtotime($interval) : strtotime('-1 month');//files older than 1 month
try {
foreach (new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($mediaTmpPath, \RecursiveDirectoryIterator::KEY_AS_PATHNAME),
\RecursiveIteratorIterator::CHILD_FIRST
) as $info) {
if ($info->isFile() && $info->isReadable()) {
if (filemtime($info->getPathname()) <= $interval) {// phpcs:ignore
if ($this->directory->delete($info->getPathname())) {
$deletedFiles++;
}
}
}
}
} catch (\Exception $e) {
$this->logger->info('Tmp file deletion error');
}
$this->logger->info('Deleted Tmp Files : ' . $deletedFiles);
return $deletedFiles;
}
}