Skip to content

Instantly share code, notes, and snippets.

@deuterium7
Last active August 4, 2017 07:57
Show Gist options
  • Save deuterium7/8db0f9339344bd87ba10bde4beceb602 to your computer and use it in GitHub Desktop.
Save deuterium7/8db0f9339344bd87ba10bde4beceb602 to your computer and use it in GitHub Desktop.
Zabornyi Alex

ValidatorPosts.php

<?php
	class ValidatorPosts
	{
		public $errors;
		public $postArray;
		public $validatorArray;

		public function __construct($postArray, $validatorArray) {
			$this->postArray = $postArray;
			$this->validatorArray = $validatorArray;
		}

		public function checkFields() {

			foreach ($this->validatorArray as $fieldName => $optionsArray) {

				foreach ($optionsArray as $key => $value) {
					
					if ( $value ) {
						$method = $key;
						$this->$method($fieldName); // вызов функций валидации	
					}
				}
			}
		}

		public function notEmpty($option) {

			if ( !empty($this->postArray[$option]) ) {
				return true;
			} else {
				$this->errors[$option][] = "Empty error";
			}
		}

		public function checkLen($option) {
			
			if ( strlen(utf8_decode($this->postArray[$option])) < 2 ) {
				$this->errors[$option][] = "Check length error";
			} else {
				return true;
			}
		}

		public function isInt($option) {
			$integer = false | $this->postArray[$option];

			if ( $integer ) {
				return true;
			} else {
				$this->errors[$option][] = "Is int error";	
			}
		}

		public function getErrors() {

			if ( !empty($this->errors) ) {
				var_dump($this->errors);
				echo "<br>";
			} else {
				echo "Posts ok<br>";
			}
		}
	}
?>

ValidatorFiles.php

<?php
	class ValidatorFiles
	{
		public $errors;
		public $fileArray;
		public $validatorArray;

		public function __construct($fileArray, $validatorArray) {
			$this->fileArray = $fileArray;
			$this->validatorArray = $validatorArray;
		}

		public function checkFiles() {
			$uploads = array(
		        "1" => "Размер принятого файла превысил максимально допустимый размер.",
		        "2" => "Размер загружаемого файла превысил значение.",
		        "3" => "Загружаемый файл был получен только частично.",
		        "4" => "Не выбран файл для загрузки.",
		        "6" => "Отсутствует временная папка.",
		        "7" => "Не удалось записать файл на диск.",
		        "8" => "Программа остановилы загрузку файла."
	   		);
			
			if ($this->fileArray['upload']['error'] == 0) {

				for ($i = 0; $i < count($this->fileArray['file']['name']); $i++) {

					foreach ($this->validatorArray as $key => $value) {

						if ( $value ) {
							$method = $key;
							$this->$method($i);	
						}
					}
				}
			} else {
				$this->errors[] = $uploads[$this->fileArray['upload']['error']];
			}
		}

		public function size($inList) {

			if ( $this->fileArray['file']['size'][$inList] < 2097152 ) {
				return true;
			} else {
				$this->errors[] = 'Size error';
			}	
		}

		public function inArray($inList) {
			$path_info = pathinfo($this->fileArray['file']['name'][$inList]);
			$allows = array('txt','rtf','pdf','doc','docx');

			if ( in_array($path_info['extension'], $allows) ) {
				return true;
			} else {
				$this->errors[] = 'In array error';
			}
		}

		public function move($inList) {
			
			if ( empty($this->errors) ) {
				$path_info = pathinfo($this->fileArray['file']['name'][$inList]);
				$hashname = md5(time().rand());
				
				move_uploaded_file(
					$this->fileArray['file']['tmp_name'][$inList],
					$_SERVER['DOCUMENT_ROOT']."/".$hashname.".".$path_info['extension']
				);
			}
		}

		public function getErrors() {

			if ( !empty($this->errors) ) {
				echo "<br>";
				var_dump($this->errors);
			} else {
				echo "<br>Files ok";
			}
		}
	}
?>

index.php

<!DOCTYPE html>
<html>
<head>
	<title>123</title>
</head>
<body>
	<form method="post" name="form" enctype="multipart/form-data">
		<p>Фамилия <input type="text" name="text"></p>
		<p><input type="checkbox" name="checkbox">Чек</p>
		<p><input type="radio" name="radio">Да</p>
		<p><input type="radio" name="radio" checked>Нет</p>
		<p><input type="file" name="file[]" multiple></p>
		<p><input type="submit"></p>
	</form>
</body>
</html>

<?php
	ini_set(display_errors, 1);

	include ('ValidatorPosts.php');
	include ('ValidatorFiles.php');

	$settingPost = [
		'text' => ['notEmpty' => true, 'checkLen' => true, 'isInt' => true],
		'checkbox' => ['notEmpty' => false, 'checkLen' => false, 'isInt' =>false],
		'radio' => ['notEmpty' => true, 'checkLen' => false, 'isInt' =>false],
	];

	$postValidator = new ValidatorPosts($_POST, $settingPost);
	$postValidator->checkFields();
	$postValidator->getErrors();


	$settingFile = ['size' => true, 'inArray' => true, 'move' => true];

	$fileValidator = new ValidatorFiles($_FILES, $settingFile);
	$fileValidator->checkFiles();
	$fileValidator->getErrors();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment