1<?php
2
3/**
4 * Helper class for segmenting large cache values without relying on serializing classes
5 *
6 * @since 1.34
7 */
8class SerializedValueContainer {
9	private const SCHEMA = '__svc_schema__';
10	private const SCHEMA_UNIFIED = 'DAAIDgoKAQw'; // 64 bit UID
11	private const SCHEMA_SEGMENTED = 'CAYCDAgCDw4'; // 64 bit UID
12
13	public const UNIFIED_DATA = '__data__';
14	public const SEGMENTED_HASHES = '__hashes__';
15
16	/**
17	 * @param string $serialized
18	 * @return stdClass
19	 */
20	public static function newUnified( $serialized ) {
21		return (object)[
22			self::SCHEMA => self::SCHEMA_UNIFIED,
23			self::UNIFIED_DATA => $serialized
24		];
25	}
26
27	/**
28	 * @param string[] $segmentHashList Ordered list of hashes for each segment
29	 * @return stdClass
30	 */
31	public static function newSegmented( array $segmentHashList ) {
32		return (object)[
33			self::SCHEMA => self::SCHEMA_SEGMENTED,
34			self::SEGMENTED_HASHES => $segmentHashList
35		];
36	}
37
38	/**
39	 * @param mixed $value
40	 * @return bool
41	 */
42	public static function isUnified( $value ) {
43		return self::instanceOf( $value, self::SCHEMA_UNIFIED );
44	}
45
46	/**
47	 * @param mixed $value
48	 * @return bool
49	 */
50	public static function isSegmented( $value ) {
51		return self::instanceOf( $value, self::SCHEMA_SEGMENTED );
52	}
53
54	/**
55	 * @param mixed $value
56	 * @param string $schema SCHEMA_* class constant
57	 * @return bool
58	 */
59	private static function instanceOf( $value, $schema ) {
60		return (
61			$value instanceof stdClass &&
62			property_exists( $value, self::SCHEMA ) &&
63			$value->{self::SCHEMA} === $schema
64		);
65	}
66}
67