Many times you need to verify the current path is a regular directory or not in Magento 2 and if directory exists you need to create a new file or do some custom logic.
But How you can verify this path is a directory or not using
Magento 2, You can verify the given path is the regular directory or not.
Example, Path is, var/log/mylog
You need to verify that mylog folder exists or not by Magento 2,
<?php namespace Jesadiya\Directory\Model; use Magento\Framework\Filesystem; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Filesystem\Directory\WriteInterface; class VerifyDirectory { /** * @var Filesystem */ protected $filesystem; /** * @var WriteInterface */ protected $logDirectory; public function __construct( Filesystem $filesystem ) { $this->logDirectory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR); } /** * Check Directory exists * return boolean */ public function verifyDirectory() { $logPath = "log/customlog"; $directory = $this->logDirectory->isDirectory($logPath); return $directory; } }
$this->logDirectory hold the path up to Var directory.
$logPath variable holds the value of the path under the var directory.
Check at location, Magento2/var/log/mylog
verifyDirectory() method return boolean as the Output.
If Directory exists, Return true and false for directory not exists.
Using the above code snippet, You can identify Directory is available or not at a specific location.