Skip to content

Commit

Permalink
Added array values function for twig
Browse files Browse the repository at this point in the history
  • Loading branch information
WilcoLouwerse committed Jan 26, 2024
1 parent af782d3 commit dc8138d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions api/src/Twig/MappingExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public function getFunctions()
return [
new TwigFunction('map', [MappingRuntime::class, 'map']),
new TwigFunction('dotToObject', [MappingRuntime::class, 'dotToArray']),
new TwigFunction('arrayValues', [MappingRuntime::class, 'arrayValues']),
];
}
}
33 changes: 33 additions & 0 deletions api/src/Twig/MappingRuntime.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,20 @@ public function __construct(MappingService $mappingService, EntityManagerInterfa
$this->mappingService = $mappingService;
}

/**
* Uses CoreBundle MappingService to map data.
* If $list is set to true you could use the key 'listInput' in the $data array to pass along the list of items to map.
* This makes it possible to also pass along other key+value pairs to use in mapping besides just one array of items to map.
*
* @param string $mappingString The reference of a Mapping object.
* @param array $data The data to map. Or one list of items to map.
* @param bool $list False by default, if set to true mapping will be done for each item in the $data array.
*
* @return array The mapped result.
*
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\SyntaxError
*/
public function map(string $mappingString, array $data, bool $list = false): array
{
$mapping = $this->entityManager->getRepository('App:Mapping')->findOneBy(['reference' => $mappingString]);
Expand All @@ -27,10 +41,29 @@ public function map(string $mappingString, array $data, bool $list = false): arr
return $value;
}

/**
* Turns given array into an Adbar\Dot (dot notation).
*
* @param array $array The array to turn into a dot array.
*
* @return array The dot aray.
*/
public function dotToArray(array $array): array
{
$dotArray = new Dot($array, true);

return $dotArray->all();
}

/**
* Makes it possible to use the php function array_values in twig.
*
* @param array $array The array to use array_values on.
*
* @return array The updated array.
*/
public function arrayValues(array $array): array
{
return array_values($array);
}
}

0 comments on commit dc8138d

Please sign in to comment.