Completed
Pull Request — 8.x-2.x (#27)
by Frédéric G.
07:11
created

MongoDb::libraryVersion()   B

Complexity

Conditions 8
Paths 13

Size

Total Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
nc 13
nop 0
dl 0
loc 38
rs 8.0675
c 0
b 0
f 0
1
<?php
2
3
namespace Drupal\mongodb;
4
5
use MongoDB\Collection;
6
7
/**
8
 * Class MongoDb contains constants usable by all modules using the driver.
9
 */
10
class MongoDb {
11
  const CLIENT_DEFAULT = 'default';
12
  const DB_DEFAULT = 'default';
13
14
  const MODULE = 'mongodb';
15
16
  const SERVICE_DB_FACTORY = 'mongodb.database_factory';
17
18
  protected static $libraryVersion;
19
20
  /**
21
   * Guess an approximation of the library version, to handle API changes.
22
   *
23
   * - 1.2.0 is the minimum version requires from our composer.json.
0 ignored issues
show
introduced by
Doc comment long description must start with a capital letter
Loading history...
24
   * - 1.3.0 adds Collection::watch().
25
   * - 1.4.0 deprecates Collection::count().
26
   *
27
   * @return string
28
   *   A semantic versioning version string.
29
   *
30
   * @internal
31
   *
32
   * @see https://github.com/mongodb/mongo-php-library/issues/558
33
   */
34
  public static function libraryVersion(): string {
0 ignored issues
show
introduced by
Expected 1 space after closing parenthesis; found 0
Loading history...
35
    $guess = '1.2.0';
36
37
    if (empty(static::$libraryVersion)) {
38
      try {
39
        $rcl = new \ReflectionClass(Collection::class);
40
        if ($rcl->hasMethod('watch')) {
41
          $guess = '1.3.0';
42
        }
43
44
        $rm = $rcl->getMethod('count');
45
        $rdoc = explode(PHP_EOL, $rm->getDocComment());
46
        $pattern = '/^[\s]+\*[\s]+@deprecated[\s]+(.*)[\s]*$/';
47
        $deprecations = array_reduce($rdoc, function ($carry, $item) use ($pattern) {
48
          if (strpos($item, '@deprecated') === FALSE) {
49
            return $carry;
50
          }
51
          $sts = preg_match($pattern, $item, $matches);
52
          if (!$sts || count($matches) !== 2) {
53
            return $carry;
54
          }
55
56
          $carry[$matches[1]] = $matches[1];
57
          return $carry;
58
        });
59
        if (isset($deprecations['1.4'])) {
60
          $guess = '1.4.0';
61
        }
62
      }
63
      catch (\ReflectionException $e) {
64
        // Nothing to do: remain with previous guess.
65
      }
66
67
      static::$libraryVersion = $guess;
68
    }
69
70
    return static::$libraryVersion;
71
  }
72
73
}
74