Validator.php 2.12 KB
<?php

/**
 * @Author: irul
 * @Date:   2019-09-23 00:35:43
 * @Last Modified by:   irul
 * @Last Modified time: 2019-10-01 23:59:16
 */

/**
 * @Source: https://github.com/jeffochoa/validator-factory/blob/master/src/ValidatorFactory.php
 * @Reference: https://laravel.com/docs/5.4/validation#available-validation-rules
 */

namespace Integrasi\Reklame\Helper;

use \Illuminate\Filesystem\Filesystem;
use \Illuminate\Translation\FileLoader;
use \Illuminate\Translation\Translator;
use \Illuminate\Validation\Factory;

class Validator
{
	public $lang;
	public $group;
	public $factory;
	public $namespace;
	public $basePath;
	public static $translator;
	public static $instance;

	public function __construct($namespace = 'lang', $lang = 'en', $group = 'validation')
	{
		$this->lang      = $lang;
		$this->group     = $group;
		$this->namespace = $namespace;
		$this->basePath  = $this->getTranslationsRootPath();
		$this->factory   = new Factory($this->loadTranslator());

		self::$instance = $this;
	}

	public static function getInstance()
	{
		if (self::$instance === null) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	public static function factory()
	{
		return new Validator();
	}

	public function translationsRootPath($path = '')
	{
		if (!empty($path)) {
			$this->basePath = $path;
			$this->reloadValidatorFactory();
		}
		return $this;
	}

	private function reloadValidatorFactory()
	{
		$this->factory = new Factory($this->loadTranslator());
		return $this;
	}

	public function getTranslationsRootPath()
	{
		return dirname(__FILE__) . '/';
	}

	public function loadTranslator()
	{
		$loader = new FileLoader(new Filesystem(), $this->basePath . $this->namespace);
		$loader->addNamespace($this->namespace, $this->basePath . $this->namespace);
		$loader->load($this->lang, $this->group, $this->namespace);
		return static::$translator = new Translator($loader, $this->lang);
	}

	public function __call($method, $args)
	{
		return call_user_func_array(array($this->factory, $method), $args);
	}

	public static function __callStatic($method, $args)
	{
		return call_user_func_array(array(self::getInstance(), $method), $args);
	}
}