Coder Social home page Coder Social logo

registry's Introduction

The Registry Package Build Status

Latest Stable Version Total Downloads Latest Unstable Version License

The Registry package provides an indexed key-value data store and an API for importing/exporting this data to several formats.

Load config by Registry

use Joomla\Registry\Registry;

$registry = new Registry();

// Load by string
$registry->loadString('{"foo" : "bar"}');

$registry->loadString('<root></root>', 'xml');

// Load by object or array
$registry->loadObject($object);
$registry->loadArray($array);

// Load by file
$registry->loadFile($root . '/config/config.json', 'json');

Accessing a Registry by getter & setter

Get value

$registry->get('foo');

// Get a non-exists value and return default
$registry->get('foo', 'default');

// OR

$registry->get('foo') ?: 'default';

Set value

// Set value
$registry->set('bar', $value);

// Sets a default value if not already assigned.
$registry->def('bar', $default);

Accessing children value by path

$json = '{
    "parent" : {
        "child" : "Foo"
    }
}';

$registry = new Registry($json);

$registry->get('parent.child'); // return 'Foo'

$registry->set('parent.child', $value);

Removing values from Registry

// Set value
$registry->set('bar', $value);

// Remove the key
$registry->remove('bar');

// Works for nested keys too
$registry->set('nested.bar', $value);
$registry->remove('nested.bar');

Accessing a Registry as an Array

The Registry class implements ArrayAccess so the properties of the registry can be accessed as an array. Consider the following examples:

// Set a value in the registry.
$registry['foo'] = 'bar';

// Get a value from the registry;
$value = $registry['foo'];

// Check if a key in the registry is set.
if (isset($registry['foo']))
{
    echo 'Say bar.';
}

Merge Registry

Using load* methods to merge two config files.

$json1 = '{
    "field" : {
        "keyA" : "valueA",
        "keyB" : "valueB"
    }
}';

$json2 = '{
    "field" : {
        "keyB" : "a new valueB"
    }
}';

$registry->loadString($json1);
$registry->loadString($json2);

Output

Array(
    field => Array(
        keyA => valueA
        keyB => a new valueB
    )
)

Merge another Registry

$object1 = '{
    "foo" : "foo value",
    "bar" : {
        "bar1" : "bar value 1",
        "bar2" : "bar value 2"
    }
}';

$object2 = '{
    "foo" : "foo value",
    "bar" : {
        "bar2" : "new bar value 2"
    }
}';

$registry1 = new Registry(json_decode($object1));
$registry2 = new Registry(json_decode($object2));

$registry1->merge($registry2);

If you just want to merge first level, do not hope recursive:

$registry1->merge($registry2, false); // Set param 2 to false that Registry will only merge first level

Dump to one dimension

$array = array(
    'flower' => array(
        'sunflower' => 'light',
        'sakura' => 'samurai'
    )
);

$registry = new Registry($array);

// Make data to one dimension

$flatted = $registry->flatten();

print_r($flatted);

The result:

Array
(
    [flower.sunflower] => light
    [flower.sakura] => samurai
)

Installation via Composer

Add "joomla/registry": "~2.0" to the 'require' block in your composer.json and then run composer install.

{
    "require": {
        "joomla/registry": "~2.0"
    }
}

Alternatively, you can simply run the following from the command line:

composer require joomla/registry "~2.0"

registry's People

Contributors

abemedia avatar andrepereiradasilva avatar asika32764 avatar brianteeman avatar demis-palma avatar denitz avatar dongilbert avatar eddieajau avatar elkuku avatar fabpot avatar fedik avatar frankmayer avatar frostmakk avatar gjedeer avatar hackwar avatar hleithner avatar ianmacl avatar joomla-jenkins avatar laoneo avatar mbabker avatar nibra avatar okonomiyaki3000 avatar philetaylor avatar photodude avatar realityking avatar sharkykz avatar wang-yu-chao avatar wilsonge avatar zero-24 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

registry's Issues

namespace for php ?

i suggest this cahnge changing

  $str = "<?php\nclass " . $params['class'] . " {\n";
  $str .= $vars;
  $str .= "}";

to:

  if (!empty($params['namespace'])) {
      $params['namespace'] = 'namespace '. $params['namespace'] . ';';
  }

  $str = "<?php " . $params['namespace'] . "\nclass " . $params['class'] . " {\n";
  $str .= $vars;
  $str .= "}";

this would enable to create a "config file" with namespace

I am talkign about: https://github.com/joomla-framework/registry/blob/master/src/Format/Php.php#L31

on another node is stringToObject missing in pourpose? eg loadFile(..., PHP) do not work because of this?

forced to do ( $config = new Registry(new \App\Config\Config()); )

this is where the namespace for the config comes in handy.

i can commit and make pull request if needed.

  $options = array();
  $options['namespace'] = 'App\Config';
  $options['class'] = 'Config';

  $config = new Registry();

  $config->set('lol.asd', 'goo');

  $config->toString('PHP', $options);

i tested like this and it seems to work.

looking forward to your feedback.

-Thanks

loadString() behaviour

Steps to reproduce the issue

$config = new Registry;
$config->set('options', $someObj);
$config->loadFile($file);

Expected result

$someObj + data from file

Actual result

Only data from file since $this->initialized still is false after calling set method.
loadString has a check for $this->initialized and overwrites existing data that was set.

Is it intended that we have to call one of the load methods first to get $this->initialized set to true to get them merged or can we get rid of that if statement?

Deprecated version 3 or 4

which is it v3 or v4?

registry/src/Registry.php

Lines 460 to 470 in 299ea76

* @deprecated The $separator parameter will be removed in version 4.
*/
public function set($path, $value, $separator = null)
{
if ($separator === null) {
$separator = $this->separator;
} else {
\trigger_deprecation(
'joomla/registry',
'__DEPLOY_VERSION__',
'The $separator parameter will be removed in version 3.',

Instances being converted into stdClass

Instances being converted into stdClass.

/** @var \JTable $message */
$registry = new Joomla\Registry\Registry(compact('message'));

Expected:

$registry->get('message') instanceof HelloTableMessage

Got

$registry->get('message') instanceof stdClass

Registry changes data type on merge

Steps to reproduce the issue

  1. Create a registry
  2. Add an associative array item
  3. Add an object item (with an object and associative array property)
  4. Merge it into another registry

Expected result

Preserve original data on merge. It would be nice to preserve object class too.

Actual result

If merged with recursive = false, all objects are converted to associative arrays, even object properties
If merged with recursive = true, all arrays are converted to stdClass, even object properties
All classes are returned as stdClass.

System information (as much as possible)

Joomla 3.9.26

Additional comments

joomla/joomla-cms#34981

Code

defined('_JEXEC') or die;
use Joomla\Registry\Registry;

class FooBar {
    public $arrayprop = ['key1' => 'value1', 'key2' => 'value2'];
    public $objprop;
}

$foo = new FooBar;
$foo->objprop = (object) ['key1' => 'value1', 'key2' => 'value2'];

$registry = new Registry();
$registry->set('associative-array-item', ['key1' => 'value1', 'key2' => 'value2']);
$registry->set('class-item', $foo);

echo '<pre>Before merge<br>';
print_r($registry);

$merge1 = new Registry(['merge' => '$recursive = false']);
$merge1->merge($registry);

$merge2 = new Registry(['merge' => '$recursive = true']);
$merge2->merge($registry, true);

echo 'Merge results:<br>';
print_r($merge1);
print_r($merge2);

echo '</pre>';

Output

Before merge
Joomla\Registry\Registry Object
(
    [data:protected] => stdClass Object
        (
            [associative-array-item] => Array
                (
                    [key1] => value1
                    [key2] => value2
                )

            [class-item] => FooBar Object
                (
                    [arrayprop] => Array
                        (
                            [key1] => value1
                            [key2] => value2
                        )

                    [objprop] => stdClass Object
                        (
                            [key1] => value1
                            [key2] => value2
                        )

                )

        )

    [initialized:protected] => 
    [separator] => .
)
Merge results:
Joomla\Registry\Registry Object
(
    [data:protected] => stdClass Object
        (
            [merge] => $recursive = false
            [associative-array-item] => Array
                (
                    [key1] => value1
                    [key2] => value2
                )

            [class-item] => Array
                (
                    [arrayprop] => Array
                        (
                            [key1] => value1
                            [key2] => value2
                        )

                    [objprop] => Array
                        (
                            [key1] => value1
                            [key2] => value2
                        )

                )

        )

    [initialized:protected] => 1
    [separator] => .
)
Joomla\Registry\Registry Object
(
    [data:protected] => stdClass Object
        (
            [merge] => $recursive = true
            [associative-array-item] => stdClass Object
                (
                    [key1] => value1
                    [key2] => value2
                )

            [class-item] => stdClass Object
                (
                    [arrayprop] => stdClass Object
                        (
                            [key1] => value1
                            [key2] => value2
                        )

                    [objprop] => stdClass Object
                        (
                            [key1] => value1
                            [key2] => value2
                        )

                )

        )

    [initialized:protected] => 1
    [separator] => .
)

3rd argument for get() function

May be pointless but would it be possible to add a 3rd argument ($cast) for the get() function, just like there is for JInput?

public function get($path, $default = null, $cast = null)
{
}

Meaning that for example when we get parameters, like so:

$params->get('number', 1)

We don't need to manually cast to an integer/bool/string (or whatever it may be) if we want to perform strict comparisons.

Now:

$number = (int) $params->get('number', 1);

if (1 === $number)
{
}

After:

$number = $params->get('number', 1, 'INT');

if (1 === $number)
{
}

[2.0] Make PHP formatter output proper types

Test Script:

<?php
require_once __DIR__ . '/vendor/autoload.php';

$registry = new Joomla\Registry\Registry(
    [
        'boolean' => true,
        'integer' => 42,
        'float' => 3.141592,
        'string' => 'Joomla! Framework',
        'array' => [
            'boolean' => true,
            'integer' => 42,
            'float' => 3.141592,
            'string' => 'Joomla! Framework',
        ],
    ]
);

file_put_contents(
    __DIR__ . '/registry.php',
    $registry->toString(
        'PHP',
        [
            'closingtag' => false,
        ]
    )
);

Current result:

<?php
class Registry {
    public $boolean = '1';
    public $integer = '42';
    public $float = '3.141592';
    public $string = 'Joomla! Framework';
    public $array = array("boolean" => "1", "integer" => "42", "float" => "3.141592", "string" => "Joomla! Framework");
}

The formatter should respect the value's type and not cast it to a string. Refactor this in 2.0 to be type aware.

Formats as a package

In addtition to this pull: #7 I propose separating registry formats to an independent package as they create stdClass instances from strings (and vice versa) but not Registry instances directly.
This will make them more flexible and there will be a chance to implement new options and formats used not only by the Registry class.

Set function doesn't return previous value

While trying to use the $key = $app->setUserState('key','') to directly clean the user state I noticed that the returned value is not the expected old value. As in the CMS interface documentation this have to return the old value or void (null). But the underlying Registry doesn't return the old value on set. This is expected by the original documentation and maybe by the current documentation.

The current function documentation is hard to understand (at least for me and deepl/google translate).

Steps to reproduce the issue

$registry = new Registry();
$registry->set('bla', 'blubb');

$x = $registry->set('bla', 'none');
echo $x;

Expected result

Should return the old value
blubb

Actual result

Returns the new set Value
none

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.