|
6 | 6 |
|
7 | 7 | use Exception;
|
8 | 8 | use Stringable;
|
| 9 | +use Syndesi\CypherDataStructures\Contract\NodeInterface; |
| 10 | +use Syndesi\CypherDataStructures\Contract\RelationInterface; |
9 | 11 | use Syndesi\CypherDataStructures\Exception\InvalidArgumentException;
|
10 | 12 |
|
11 | 13 | class ToStringHelper
|
@@ -159,4 +161,64 @@ public static function labelsToString(array $labels, bool $escapeAllLabels = fal
|
159 | 161 |
|
160 | 162 | return implode($parts);
|
161 | 163 | }
|
| 164 | + |
| 165 | + /** |
| 166 | + * Turns a node to its Cypher string variant. |
| 167 | + * |
| 168 | + * @note relations are not included. |
| 169 | + */ |
| 170 | + public static function nodeToString(NodeInterface $node, bool $identifying = false): string |
| 171 | + { |
| 172 | + $parts = []; |
| 173 | + $parts[] = self::labelsToString($node->getLabels()); |
| 174 | + $properties = $node->getProperties(); |
| 175 | + if ($identifying) { |
| 176 | + $properties = $node->getIdentifiers(); |
| 177 | + } |
| 178 | + $propertyString = self::propertyArrayToString($properties); |
| 179 | + if (strlen($propertyString) > 0) { |
| 180 | + $parts[] = sprintf("{%s}", $propertyString); |
| 181 | + } |
| 182 | + |
| 183 | + return sprintf( |
| 184 | + "(%s)", |
| 185 | + implode(' ', $parts) |
| 186 | + ); |
| 187 | + } |
| 188 | + |
| 189 | + public static function relationToString(RelationInterface $relation, bool $identifying = false, bool $withNodes = true): string |
| 190 | + { |
| 191 | + $parts = []; |
| 192 | + if ($withNodes) { |
| 193 | + if (($startNode = $relation->getStartNode()) === null) { |
| 194 | + throw new InvalidArgumentException('Start node can not be null'); |
| 195 | + } |
| 196 | + $parts[] = self::nodeToString($startNode, true); |
| 197 | + $parts[] = '-'; |
| 198 | + } |
| 199 | + |
| 200 | + $relationParts = []; |
| 201 | + if ($type = $relation->getType()) { |
| 202 | + $relationParts[] = sprintf(':%s', $type); |
| 203 | + } |
| 204 | + $properties = $relation->getProperties(); |
| 205 | + if ($identifying) { |
| 206 | + $properties = $relation->getIdentifiers(); |
| 207 | + } |
| 208 | + $propertyString = self::propertyArrayToString($properties); |
| 209 | + if (strlen($propertyString) > 0) { |
| 210 | + $relationParts[] = sprintf("{%s}", $propertyString); |
| 211 | + } |
| 212 | + $parts[] = sprintf("[%s]", implode(' ', $relationParts)); |
| 213 | + |
| 214 | + if ($withNodes) { |
| 215 | + if (($endNode = $relation->getEndNode()) === null) { |
| 216 | + throw new InvalidArgumentException('End node can not be null'); |
| 217 | + } |
| 218 | + $parts[] = '->'; |
| 219 | + $parts[] = self::nodeToString($endNode, true); |
| 220 | + } |
| 221 | + |
| 222 | + return implode('', $parts); |
| 223 | + } |
162 | 224 | }
|
0 commit comments