CacheControl.fromHeader constructor

CacheControl.fromHeader(
  1. List<String>? headerValues
)

Builds Cache Control from header values

Implementation

factory CacheControl.fromHeader(List<String>? headerValues) {
  // Parses single header value
  void parseHeaderValue(
    StringScanner scanner,
    Map<String, String> parameters,
    List<String> other,
  ) {
    scanner.scan(whitespace);
    scanner.expect(token);

    final attribute = scanner.lastMatch![0]!;

    if (_knownAttributes.hasMatch(attribute)) {
      if (scanner.scan('=')) {
        scanner.expect(token);
        parameters[attribute] = scanner.lastMatch![0]!;
      } else {
        parameters[attribute] = attribute;
      }
    } else {
      if (scanner.scan('=')) {
        scanner.expect(token);
        other.add('$attribute=${scanner.lastMatch![0]!}');
      } else {
        other.add(attribute);
      }
    }
  }

  headerValues ??= [];

  final parameters = <String, String>{};
  final other = <String>[];

  for (var value in headerValues) {
    if (value.isNotEmpty) {
      final scanner = StringScanner(value);
      parseHeaderValue(scanner, parameters, other);

      while (scanner.scan(',')) {
        parseHeaderValue(scanner, parameters, other);
      }
      scanner.expectDone();
    }
  }

  return CacheControl(
    maxAge: int.tryParse(parameters[_maxAgeHeader] ?? '') ?? -1,
    maxStale: int.tryParse(parameters[_maxStaleHeader] ?? '') ?? -1,
    minFresh: int.tryParse(parameters[_minFreshHeader] ?? '') ?? -1,
    mustRevalidate: parameters.containsKey(_mustRevalidateHeader),
    privacy: parameters[_publicHeader] ?? parameters[_privateHeader],
    noCache: parameters.containsKey(_noCacheHeader),
    noStore: parameters.containsKey(_noStoreHeader),
    other: other,
  );
}