Skip to content

Instantly share code, notes, and snippets.

@nicolasegp
Last active May 7, 2018 01:39
Show Gist options
  • Save nicolasegp/d64044d09087f89485090c44e592b402 to your computer and use it in GitHub Desktop.
Save nicolasegp/d64044d09087f89485090c44e592b402 to your computer and use it in GitHub Desktop.
PHP Array dot access data
<?php
class App {
const SP = '.';
const SP_REGEXP = '/[^\w.]/'; // if use " / " change to '/[^\w\/]/'
protected static $Data = [];
public static function set($Path, $Value = null) {
$Path = self::clean_path($Path);
$Ref = &self::$Data;
foreach($Path as $V) {
if(!isset($Ref[$V]))
$Ref[$V] = [];
$Ref = &$Ref[$V];
}
$Ref = $Value;
unset($Ref);
}
public static function append($Path, $Value = null) {
$Path = self::clean_path($Path);
$Ref = &self::$Data;
foreach($Path as $V) {
if(!isset($Ref[$V]))
$Ref[$V] = [];
if(!is_array($Ref[$V]))
$Ref[$V] = [ $Ref[$V] ];
$Ref = &$Ref[$V];
}
$Ref[] = $Value;
unset($Ref);
}
public static function get($Path, $Default = null) {
$Path = self::clean_path($Path);
$Ref = self::$Data;
foreach($Path as $V) {
if(!is_array($Ref) || !isset($Ref[$V]))
return $Default;
$Ref = $Ref[$V];
}
return $Ref === null ? $Default : $Ref;
}
public static function remove($Path, $First = false) {
$Path = self::clean_path($Path);
$Ref = &self::$Data;
foreach($Path as $V) {
if(!isset($Ref[$V]))
return false;
$Ref = &$Ref[$V];
}
if(is_array($Ref)) {
if($First)
array_shift($Ref);
else
array_pop($Ref);
}
unset($Ref);
}
public static function delete($Path) {
$Path = self::clean_path($Path);
$End = array_pop($Path);
$Ref = &self::$Data;
foreach($Path as $V) {
if(!isset($Ref[$V]))
return false;
$Ref = &$Ref[$V];
}
unset($Ref[$End]);
unset($Ref);
}
public static function fullData() {
return self::$Data;
}
private static function clean_path($Path) {
return explode(
self::SP,
preg_replace(
self::SP_REGEXP,
'',
strtolower($Path)
)
);
}
}
<?php
// In Config
App::set('web.title', 'Awesome Page');
App::set('web.color', '#ffffff');
App::set('author.name', 'Nicolás');
App::set('author.twitter', '@Shadowgn');
App::append('web.css', 'a.css');
App::append('web.css', 'b.css');
App::append('web.css', 'bad_link.css');
// In Controller
App::remove('web.css'); // remove bad_link.css
// App::remove('web.css', true); => remove a.css
// App::delete('web.css'); => delete all css node
echo print_r(App::fullData(), true);
Array
(
[web] => Array
(
[title] => Awesome Page
[color] => #ffffff
[css] => Array
(
[0] => a.css
[1] => b.css
)
)
[author] => Array
(
[name] => Nicolás
[twitter] => @Shadowgn
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment