<?php
	// namespace
	namespace sven\sys\sven;

	/**
	 * utilities
	 *
	 * Collecting util functions
	 *
	 * @package sven\sys\sven
	 * @copyright 2018 Ruben Meyer
	 * @author Ruben Meyer <contact@rxbn.de>
	 * @version 0.1.0
	 * @TODO Documentation
	 */
	class utilities {

		/**
		 * getAllFiles
		 *
		 * gets all files in a directory with specific ending
		 *
		 * self::getAllFiles(dirname(__FILE__), '.php')
		 *
		 * @static
		 * @param string $dir path
		 * @param string $ending file ending (.php/.html/.css)
		 * @return array|boolean returns boolean, if directory not found
		 */
		public static function getAllFiles($dir, $ending) {
			$files = [];
			if(file_exists($dir)) {
				if(is_dir($dir)) {
					foreach (glob($dir.'\\*') as $path) {
						$temp = self::getAllFiles($path, $ending);
						if($temp !== false) array_push($files, $temp);
					}
				} elseif(self::endsWith($dir, $ending)) {
					array_push($files, $dir);
				}
				return self::arrayFlatten($files);
			} else return false;
		}

		/**
		 * startsWith
		 *
		 * check if haystack starts with needle
		 *
		 * self::startsWith('ASDFASDFASDFADSF', 'ASDF') -> boolean
		 *
		 * @static
		 * @param string $haystack
		 * @param string $needle starting string
		 * @return boolean
		 */
		public static function startsWith($haystack, $needle) {
			$length = strlen($needle);
     		return (substr($haystack, 0, $length) === $needle);
		}

		/**
		 * endsWith
		 *
		 * check if haystack ends with needle
		 *
		 * self::endsWith('ASDFASDFASDFADSF', 'ASDF') -> boolean
		 *
		 * @static
		 * @param string $haystack
		 * @param string $needle ending string
		 * @return boolean
		 */
		public static function endsWith($haystack, $needle) {
			$length = strlen($needle);
			return $length === 0 || (substr($haystack, -$length) === $needle);
		}

		/**
		 * getBetween
		 *
		 * get string between two tags
		 *
		 * self::getBetween('<START>YEES</END>', '<START>', '</END>') -> 'YEES'
		 *
		 * @static
		 * @param string $string haystack
		 * @param string $start start tag
		 * @param string $end end tag
		 * @return string
		 */
		public static function getBetween($string, $start, $end) {
			$posStart = strpos($string, $start);
			if($posStart === false) return '';
			$posStart += strlen($start);

			$length = strpos($string, $end, $posStart);
			if($length === false) return '';

			return substr($string, $posStart, $length-$posStart);
		}

		// self::arrayFlatten([[[1,2]3],[4],5,[[[6],7]]]) -> [1,2,3,4,5,6,7]
		public static function arrayFlatten($array) {
    		$result = array();
			foreach ($array as $key => $value) {
				if (is_array($value)) {
					$result = array_merge($result, self::arrayFlatten($value));
				} else {
					$result = array_merge($result, array($key => $value));
				}
			}
			return $result;
		}
	};

?>
