- First commit, some small work porting an old lib I had done into this first draft

This commit is contained in:
mcndave committed 2019-12-21 13:51:56 -05:00
commit a58efcdef4
4 files changed
+288

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
<?php
namespace Tell;
use RecursiveDirectoryIterator,
RecursiveIteratorIterator,
RecursiveRegexIterator,
RegexIterator;
class Iterate
{
/**
* Set value to array with a given path using recursion
* @param array $array - array to set passed by reference !
* @param string $path - path like 'person.name.first'
* @param string $value - value to set
*/
public static function arraySet(array &$array, string $path, string $value = '', string $delimiter = '.') {
$pathArr = explode($delimiter, $path);
// Go to next node
if ( isset($pathArr[1])) {
static::arraySet($array[ array_shift($pathArr) ], implode($delimiter, $pathArr), $value);
}
// We are at the end of the path, set value
else {
$array[ $pathArr[0] ] = $value;
}
}
public static function arrayGet(array $array, string $path, string $delimiter = '.') {
$pathArr = explode($delimiter, $path);
if (isset($array[$pathArr[0]])) {
if ( isset($pathArr[1]) ) {
return static::arrayGet($array[array_shift($pathArr)], implode($delimiter, $pathArr));
}
else {
return $array[$pathArr[0]];
}
}
else {
return null;
}
}
public static function splitKeys(array &$array, string $delimiter = ".", string $enclosed = '{}') {
if ( is_array($array) ) {
$swap = [];
foreach($array as $key => &$value) {
$process = strstr($key, $delimiter);
if ( $enclosed ) {
if ( ( strlen($key) - 2 ) !== strlen( $tkey = trim($key, $enclosed) ) ) {
$process = false;
}
else {
$oldKey = $key;
$key = $tkey;
}
}
if ( $process ) {
$tmp = [];
$keylist = explode($delimiter, $key);
$finalKey = array_shift($keylist);
# Arrayobj::iterate_set($keylist, $tmp, $value);
static::arraySet($tmp, $key, $value);
$swap[$finalKey] = static::splitKeys($tmp, $delimiter);
unset($array[isset($oldKey) ? $oldKey : $key]);
}
else if ( is_array($value) ) {
$value = static::splitKeys($value, $delimiter);
}
}
foreach($swap as $key => $item) {
if ( $enclosed ) {
if ( ( strlen($key) - 2 ) === ( $tkey = trim($key, $enclosed)) ) {
$key = $tkey;
}
}
$array[$key] = $item;
}
}
return $array;
}
public static function files(string $path, string $fileExtension = "") {
$retval = [];
if ( \file_exists($path) ) {
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD);
if ($fileExtension) {
$iterator = new RegexIterator($iterator, '/^.+\.'.$fileExtension.'$/i', RecursiveRegexIterator::GET_MATCH);
}
foreach ($iterator as $file) {
if ($fileExtension) {
$retval[] = $file[0];
}
else {
if ( $file->isFile() || $file->isDir() ) {
$retval[] = $file->getRealPath();
}
}
}
}
return $retval;
}
}