adbario / php-dot-notation

Dot notation access to PHP arrays

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cannot access key

ProfM2 opened this issue · comments

I have a file that I'm reading that is like:

key1.status=value1
key1.a=value2
key1.a.b=value3

I'm having issues trying to access key1.a ... it keeps giving me an array to string error, and cannot see how to access it. Also, when I dump toJson, key1.a is not in the JSON. Not sure if that's related.

This is the equivalent of doing something like:
$a = 'Test';
$a['b'] = 'Test2';

This can not work. Examine your data structure. A string can not have named properties. Only objects and arrays can have properties/keys. You can not store another value under an existing one.

You may want to examine the data structure you are trying to create. This sort of thing is not allowed in any programming language.

@ProfM2 show us a full example of your code so we can help you out.

The configuration file that I'm reading is from a Ubiqiti device, but that part doesn't matter...

The key that consistently fails is unms.uri

...
tshaper.1.status=enabled
tshaper.status=enabled
unms.status=enabled
unms.uri.changed=-
unms.uri=wss://ip.redacted:443+q8s64..key.redacted..AAAAA+allowUntrustedCertificate
update.check.status=enabled
users.1.name=admin
...

The code I use to read the configuration file (above) into Adbar\Dot:

// this will read the entire file of the system.cfg into a string (each key is separated by \n)
$configText = $this->ssh->exec('less ' . self::CONFIG_PATH);
if (null !== $configText) {
  // sort the configuration before storing it
  $configArray = [];
  foreach (preg_split("/((\r?\n)|(\r\n?))/", $configText) as $line) {
    // split our line so we can set our configuration array
    if (strlen($line) > 0)
      $configArray[] = $line;
  }
  // NOTE: sorting isn't required, but takes little time, and makes things easier to debug if needed
  sort($configArray, SORT_NATURAL | SORT_FLAG_CASE);

  // clear the configuration ... **$this->config is Adbar\Dot**
  $this->config->clear();
  foreach ($configArray as $line) {
    // split our line so we can set our configuration array
    if (strlen($line) > 0) {
      $data = explode('=', $line);
      if (key_exists('1', $data))
        $value = $data[1];
      else
        $value = '';
      $this->config->add($data[0], $value);
    }
  }
...

Initially, the UNMS.URI key didn't exist, and this recent problem wasn't an issue.

How this problem initially displayed itself, was causing the key (unms.uri) to not be in the JSON output. Everything else in the configuration file passes through Dot.

What you're trying to do won't work with this library, as unms.uri always overrides unms.uri.changed. This is just how arrays in PHP and most other languages work.

I was hoping that it could work, but I'll have to come up with a work-around.

Thanks for your help.