Skip to content

Commit

Permalink
WIP: Add DirectoryValidator
Browse files Browse the repository at this point in the history
  • Loading branch information
sukhwinder33445 committed Dec 28, 2022
1 parent 63e4a32 commit ff5fd6c
Showing 1 changed file with 110 additions and 0 deletions.
110 changes: 110 additions & 0 deletions src/DirectoryValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<?php

namespace ipl\Validator;

use ipl\I18n\Translation;

class DirectoryValidator extends BaseValidator
{
use Translation;

/** @var bool if true, check whether directory is readable */
protected $shouldReadable;

/** @var bool if true, check whether directory is writeable */
protected $shouldWriteable;

/**
* Validates whether value is a directory
*
* Available options:
*
* - writeable: (bool) If true, check whether directory is writeable, default false
* - readable: (bool) If true, check whether directory is readable, default false
*
* @param array $options
*/
public function __construct(array $options = [])
{
$this->setShouldReadable($options['readable'] ?? false);
$this->setShouldWriteable($options['writable'] ?? false);
}

/**
* Get whether directory should be readable
*
* @return bool Whether the directory should be readable
*/
public function getShouldReadable(): bool
{
return $this->shouldReadable;
}

/**
* Set whether directory should be readable
*
* @param bool $shouldReadable
*/
public function setShouldReadable($shouldReadable = true): self
{
$this->shouldReadable = (bool) $shouldReadable;

return $this;
}

/**
* Get whether directory should be writeable
*
* @return bool Whether the directory should be writeable
*/
public function getShouldWriteable(): bool
{
return $this->shouldWriteable;
}

/**
* Set whether directory should be writeable
*
* @param bool $shouldWriteable
*/
public function setShouldWriteable($shouldWriteable = true): void
{
$this->shouldWriteable = (bool) $shouldWriteable;
}

public function isValid($value)
{
// Multiple isValid() calls must not stack validation messages
$this->clearMessages();

if (! is_dir($value)) {
$this->addMessage(sprintf(
$this->translate("'%s' is not a directory"),
$value
));

return false;
}

//TODO: Separate validator class for this??
if ($this->getShouldReadable() && ! is_readable($value)) {
$this->addMessage(sprintf(
$this->translate("'%s' directory is not readable"),
$value
));

return false;
}

if ($this->getShouldWriteable() && ! is_writable($value)) {
$this->addMessage(sprintf(
$this->translate("'%s' directory is not writeable"),
$value
));

return false;
}

return true;
}
}

0 comments on commit ff5fd6c

Please sign in to comment.