1
0
mirror of https://github.com/flextype/flextype.git synced 2025-08-08 06:06:45 +02:00

feat(macros): Add ability to fetch specific fields from single entry and from entries collection #558

This commit is contained in:
Awilum
2021-08-02 11:55:04 +03:00
parent 12e021869b
commit 0a0cd6046c
3 changed files with 51 additions and 42 deletions

View File

@@ -71,7 +71,8 @@
"src/flextype"
],
"files": [
"src/flextype/helpers.php"
"src/flextype/helpers.php",
"src/flextype/macros.php"
]
},
"require-dev": {

View File

@@ -1,41 +0,0 @@
<?php
declare(strict_types=1);
/**
* Flextype (https://flextype.org)
* Founded by Sergey Romanenko and maintained by Flextype Community.
*/
namespace Flextype\Support\Macros;
use Atomastic\Arrays\Arrays;
use Atomastic\Macroable\Macroable;
/**
* Create a new Arrays macro for
*
* @param mixed $items Items.
* @param array $options Options array.
*
* @return array
*/
Arrays::macro('onlyFromCollection', function(array $keys) {
$result = [];
foreach ($this->toArray() as $key => $value) {
$result[$key] = arrays($value)->only($keys)->toArray();
}
return arrays($result);
});
Arrays::macro('exceptFromCollection', function(array $keys) {
$result = [];
foreach ($this->toArray() as $key => $value) {
$result[$key] = arrays($value)->except($keys)->toArray();
}
return arrays($result);
});

49
src/flextype/macros.php Normal file
View File

@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
/**
* Flextype (https://flextype.org)
* Founded by Sergey Romanenko and maintained by Flextype Community.
*/
use Atomastic\Arrays\Arrays;
use Atomastic\Macroable\Macroable;
if (! Arrays::hasMacro('onlyFromCollection')) {
/**
* Return slice of an array with just a given keys.
*
* @param array $keys List of keys to return.
*
* @return Arrays Returns instance of The Arrays class.
*/
Arrays::macro('onlyFromCollection', function(array $keys) {
$result = [];
foreach ($this->toArray() as $key => $value) {
$result[$key] = arrays($value)->only($keys)->toArray();
}
return arrays($result);
});
}
if (! Arrays::hasMacro('onlyFromCollection')) {
/**
* Return slice of an array except given keys.
*
* @param array $keys List of keys to except.
*
* @return Arrays Returns instance of The Arrays class.
*/
Arrays::macro('exceptFromCollection', function(array $keys) {
$result = [];
foreach ($this->toArray() as $key => $value) {
$result[$key] = arrays($value)->except($keys)->toArray();
}
return arrays($result);
});
}