Skip to content

Instantly share code, notes, and snippets.

@fffaraz
Created January 12, 2018 21:38
Show Gist options
  • Save fffaraz/1fb2936ebb557737817258e04c6c75ea to your computer and use it in GitHub Desktop.
Save fffaraz/1fb2936ebb557737817258e04c6c75ea to your computer and use it in GitHub Desktop.
FileAlterationMonitor
<?php
class FileAlterationMonitor
{
private $scanFolder, $initialFoundFiles;
public function __construct($scanFolder)
{
$this->scanFolder = $scanFolder;
$this->updateMonitor();
}
private function _arrayValuesRecursive($array)
{
$arrayValues = array();
foreach ($array as $value)
{
if (is_scalar($value) OR is_resource($value))
{
$arrayValues[] = $value;
}
elseif (is_array($value))
{
$arrayValues = array_merge($arrayValues, $this->_arrayValuesRecursive($value));
}
}
return $arrayValues;
}
private function _scanDirRecursive($directory)
{
$folderContents = array();
$directory = realpath($directory).DIRECTORY_SEPARATOR;
foreach (scandir($directory) as $folderItem)
{
if ($folderItem != "." AND $folderItem != "..")
{
if (is_dir($directory.$folderItem.DIRECTORY_SEPARATOR))
{
$folderContents[$folderItem] = $this->_scanDirRecursive($directory.$folderItem."\\");
}
else
{
$folderContents[] = $folderItem;
}
}
}
return $folderContents;
}
public function getNewFiles()
{
$finalFoundFiles = $this->_arrayValuesRecursive($this->_scanDirRecursive($this->scanFolder));
if ($this->initialFoundFiles != $finalFoundFiles)
{
$newFiles = array_diff($finalFoundFiles, $this->initialFoundFiles);
return empty($newFiles) ? FALSE : $newFiles;
}
}
public function getRemovedFiles()
{
$finalFoundFiles = $this->_arrayValuesRecursive($this->_scanDirRecursive($this->scanFolder));
if ($this->initialFoundFiles != $finalFoundFiles)
{
$removedFiles = array_diff( $this->initialFoundFiles, $finalFoundFiles);
return empty($removedFiles) ? FALSE : $removedFiles;
}
}
public function updateMonitor()
{
$this->initialFoundFiles = $this->_arrayValuesRecursive($this->_scanDirRecursive( $this->scanFolder));
}
}
$f = new FileAlterationMonitor($MY_FOLDER_TO_MONITOR)
while (TRUE)
{
sleep(1);
if ($newFiles = $f->getNewFiles())
{
// Code to handle new files
// $newFiles is an array that contains added files
}
if ($removedFiles = $f->getRemovedFiles())
{
// Code to handle removed files
// $newFiles is an array that contains removed files
}
$f->updateMonitor();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment