<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\Adapter\PreviewSite\CleanupAction;

use Drupal\languagewire_translation_provider\Adapter\PreviewSite\PreviewSiteCleanupActionInterface;
use Drupal\languagewire_translation_provider\Content\HtmlPreview\Result\HtmlPreviewResult;

/**
 * Preview site cleanup action base.
 */
abstract class PreviewSiteCleanupActionBase implements PreviewSiteCleanupActionInterface {

  /**
   * Find files.
   *
   * @param \Drupal\languagewire_translation_provider\Content\HtmlPreview\Result\HtmlPreviewResult $htmlPreviewResult
   *   Html preview result.
   * @param callable $filterFn
   *   Filter function.
   *
   * @return \SplFileInfo[]
   *   Spl file info.
   */
  protected function findFiles(HtmlPreviewResult $htmlPreviewResult, callable $filterFn): array {
    $rootPath = $htmlPreviewResult->getHtmlPreviewFolderPath();

    if (!is_dir($rootPath)) {
      return [];
    }

    $matchingFiles = [];
    $files = new \RecursiveIteratorIterator(
          new \RecursiveDirectoryIterator($rootPath),
          \RecursiveIteratorIterator::LEAVES_ONLY
      );

    foreach ($files as $file) {
      if ($file->isFile() && $filterFn($file)) {
        $matchingFiles[] = $file;
      }
    }

    return $matchingFiles;
  }

}
