- Added a batch() function to ease array iterations in templates
This commit is contained in:
		
							parent
							
								
									f9c955a82a
								
							
						
					
					
						commit
						3dce6a41cb
					
				
							
								
								
									
										33
									
								
								src/Extension/BatchExtension.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										33
									
								
								src/Extension/BatchExtension.php
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,33 @@ | ||||
| <?php | ||||
| 
 | ||||
| namespace Picea\Extension; | ||||
| 
 | ||||
| use Picea\Compiler\Context; | ||||
| 
 | ||||
| class BatchExtension implements Extension, FunctionExtension { | ||||
| 
 | ||||
|     public string $token = "batch"; | ||||
| 
 | ||||
|     public function exportFunctions(): array | ||||
|     { | ||||
|         return [ | ||||
|             "batch" => [ $this, 'batch' ] | ||||
|         ]; | ||||
|     } | ||||
| 
 | ||||
|     public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string | ||||
|     { | ||||
|         return "<?php echo batch($arguments) ?>"; | ||||
|     } | ||||
| 
 | ||||
|     public function batch(iterable $array, int $size, mixed $default = null) : \Generator | ||||
|     { | ||||
|         $split = ceil( count($array) / $size ); | ||||
| 
 | ||||
|         for($i = 0; $i < $split; $i++) { | ||||
|             $slice = array_slice(is_array($array) ? $array : iterator_to_array($array, true), $i * $size, $size, true); | ||||
|             $pad = ( count($slice) !== $size ) && ( $default !== null ); | ||||
|             yield $pad ? array_pad($slice, $size, $default) : $slice; | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @ -67,6 +67,7 @@ class DefaultRegistrations implements LanguageRegistration | ||||
|         $compiler->registerExtension(new \Picea\Extension\PhpExtension()); | ||||
|         $compiler->registerExtension(new \Picea\Extension\PrintExtension()); | ||||
|         $compiler->registerExtension(new \Picea\Extension\JsonExtension()); | ||||
|         $compiler->registerExtension(new \Picea\Extension\BatchExtension()); | ||||
| 
 | ||||
|         foreach($this->extensions ?? [] as $extension) { | ||||
|             $compiler->registerExtension($extension); | ||||
|  | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user