Clone of https://github.com/NixOS/nixpkgs.git (to stress-test knotserver)
1{ pkgs, lib }: 2{ 3 # Format for defining configuration of some PHP services, that use "include 'config.php';" approach. 4 format = 5 { 6 finalVariable ? null, 7 }: 8 let 9 toPHP = 10 value: 11 { 12 "null" = "null"; 13 "bool" = if value then "true" else "false"; 14 "int" = toString value; 15 "float" = toString value; 16 "string" = string value; 17 "set" = attrs value; 18 "list" = list value; 19 } 20 .${builtins.typeOf value} 21 or (abort "should never happen: unknown value type ${builtins.typeOf value}"); 22 23 # https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single 24 escapeSingleQuotedString = lib.escape [ 25 "'" 26 "\\" 27 ]; 28 string = value: "'${escapeSingleQuotedString value}'"; 29 30 listContent = values: lib.concatStringsSep ", " (map toPHP values); 31 list = values: "[" + (listContent values) + "]"; 32 33 attrsContent = 34 values: 35 lib.pipe values [ 36 (lib.mapAttrsToList (k: v: "${toPHP k} => ${toPHP v}")) 37 (lib.concatStringsSep ", ") 38 ]; 39 attrs = set: if set ? _phpType then specialType set else "[" + attrsContent set + "]"; 40 41 mixedArray = 42 { list, set }: if list == [ ] then attrs set else "[${listContent list}, ${attrsContent set}]"; 43 44 specialType = 45 { value, _phpType }: 46 { 47 "mixed_array" = mixedArray value; 48 "raw" = value; 49 } 50 .${_phpType}; 51 52 type = 53 with lib.types; 54 nullOr (oneOf [ 55 bool 56 int 57 float 58 str 59 (attrsOf type) 60 (listOf type) 61 ]) 62 // { 63 description = "PHP value"; 64 }; 65 in 66 { 67 68 inherit type; 69 70 lib = { 71 mkMixedArray = list: set: { 72 _phpType = "mixed_array"; 73 value = { inherit list set; }; 74 }; 75 mkRaw = raw: { 76 _phpType = "raw"; 77 value = raw; 78 }; 79 }; 80 81 generate = 82 name: value: 83 pkgs.writeTextFile { 84 inherit name; 85 text = 86 let 87 # strict_types enabled here to easily debug problems when calling functions of incorrect type using `mkRaw`. 88 phpHeader = "<?php\ndeclare(strict_types=1);\n"; 89 in 90 if finalVariable == null then 91 phpHeader + "return ${toPHP value};\n" 92 else 93 phpHeader + "\$${finalVariable} = ${toPHP value};\n"; 94 }; 95 96 }; 97}