https://github.com/mfn/php-util-simpleorderedmap
Ordered map accepting arbitrary keys
https://github.com/mfn/php-util-simpleorderedmap
Last synced: 2 months ago
JSON representation
Ordered map accepting arbitrary keys
- Host: GitHub
- URL: https://github.com/mfn/php-util-simpleorderedmap
- Owner: mfn
- License: mit
- Created: 2014-08-30T12:12:10.000Z (over 10 years ago)
- Default Branch: master
- Last Pushed: 2015-11-07T07:45:47.000Z (over 9 years ago)
- Last Synced: 2025-01-23T22:25:35.710Z (4 months ago)
- Language: PHP
- Size: 176 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# Ordered map accepting arbitrary keys for PHP[ ](https://travis-ci.org/mfn/php-util-simpleorderedmap)
Homepage: https://github.com/mfn/php-util-simpleorderedmap
## Basic usage:
```PHP
$map = new \Mfn\Util\Map\SimpleOrderedMap;
$map->add(new \stdClass, "value");
foreach ($map->keys() as $key) {
echo $map->get($key), PHP_EOL;
}
```
Outputs: `value`## Common usage
Add and set keys/values:
```PHP
use \Mfn\Util\Map\SimpleOrderedMap;
$map = SimpleOrderedMap;
$map->add($key, $val); # throws exception if key already exists
$map->set($key, $val); # replaces value if key already exists
```
Retrieve:
```PHP
$val = $map->get($key); # throws exception if key does not exist
if ($map->exists($key)) {
# ...
}
```
Remove:
```PHP
$map->del($key); # throws exception if key does not exist
```
The keys are always kept in their order when removing, this position index are available:
```PHP
$index = $map->getKeyPosition($key);
$key = $map->getKayAt($index);
$val = $map->getValueAt($index);
```
Create from existing hashes or arrays:
```PHP
use \Mfn\Util\Map\SimpleOrderedMap;
$map = SimpleOrderedMap::fromHash(['a'=>true,10=>NULL]);
$map->keys(); # ['a',10]
$map->values(): # [true,NULL]# The same with separate arrays. Note: arrays length must match
$map = SimpleOrderedMap::fromArrays(
['a',10],
[true,NULL]
);
$map->keys(); # ['a',10]
$map->values(): # [true,NULL]
```
Many more methods, please see [the source of SimpleOrderedMap](lib/SimpleOrderedMap.php)## Using with key/value validation
If you feel like you need some kind of validation, you can use
SimpleOrderedValidatingMap which provides callbacks for checking new added key
and values:```PHP
use Mfn\Util\Map\SimpleOrderedValidatingMap as Map;$map = new Map(
function($key) {
if ($key instanceof \stdClass) {
return;
}
throw new \Mfn\Util\Map\SimpleOrderedValidatingMapException(
'Only keys of type stdClass are allowed'
);
},
function($value) {
if ($value instanceof \stdClass) {
return;
}
throw new \Mfn\Util\Map\SimpleOrderedValidatingMapException(
'Only values of type stdClass are allowed'
);
}
);
# Throws an exception
$map->add(1,2);
```# Install
Using composer: `composer.phar require mfn/util-simpleorderedmap 0.0.2`
# Contribute
Fork it, hack on a feature branch, create a pull request© Markus Fischer