graphql-php/src/Utils/PairSet.php

88 lines
1.7 KiB
PHP
Raw Normal View History

2015-07-15 23:05:46 +06:00
<?php
namespace GraphQL\Utils;
/**
* Class PairSet
* @package GraphQL\Utils
*/
2015-07-15 23:05:46 +06:00
class PairSet
{
/**
* @var \SplObjectStorage<any, Set<any>>
*/
private $data;
2015-07-15 23:05:46 +06:00
/**
* @var array
*/
private $wrappers = [];
2015-07-15 23:05:46 +06:00
/**
* PairSet constructor.
*/
2015-07-15 23:05:46 +06:00
public function __construct()
{
$this->data = new \SplObjectStorage(); // SplObject hash instead?
2015-07-15 23:05:46 +06:00
}
/**
* @param $a
* @param $b
* @return null|object
*/
2015-07-15 23:05:46 +06:00
public function has($a, $b)
{
$a = $this->toObj($a);
$b = $this->toObj($b);
2015-07-15 23:05:46 +06:00
/** @var \SplObjectStorage $first */
$first = isset($this->data[$a]) ? $this->data[$a] : null;
2015-07-15 23:05:46 +06:00
return isset($first, $first[$b]) ? $first[$b] : null;
}
/**
* @param $a
* @param $b
*/
2015-07-15 23:05:46 +06:00
public function add($a, $b)
{
$this->pairSetAdd($a, $b);
$this->pairSetAdd($b, $a);
2015-07-15 23:05:46 +06:00
}
/**
* @param $var
* @return mixed
*/
private function toObj($var)
2015-07-15 23:05:46 +06:00
{
// SplObjectStorage expects objects, so wrapping non-objects to objects
if (is_object($var)) {
return $var;
}
if (!isset($this->wrappers[$var])) {
2015-07-15 23:05:46 +06:00
$tmp = new \stdClass();
$tmp->_internal = $var;
$this->wrappers[$var] = $tmp;
2015-07-15 23:05:46 +06:00
}
return $this->wrappers[$var];
2015-07-15 23:05:46 +06:00
}
/**
* @param $a
* @param $b
*/
private function pairSetAdd($a, $b)
2015-07-15 23:05:46 +06:00
{
$a = $this->toObj($a);
$b = $this->toObj($b);
$set = isset($this->data[$a]) ? $this->data[$a] : null;
2015-07-15 23:05:46 +06:00
if (!isset($set)) {
$set = new \SplObjectStorage();
$this->data[$a] = $set;
2015-07-15 23:05:46 +06:00
}
$set[$b] = true;
}
}