Completed
Push — master ( 850851...b56f02 )
by Siro Díaz
02:49
created

DisjointSet::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 1
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 1
rs 10
cc 1
eloc 1
nc 1
nop 0
1
<?php
2
3
namespace DataStructures\Sets;
4
5
class DisjointNode {
6
    public $parent;
7
    public $rank;
8
    public $data;
9
10
    public function __construct(DisjointNode $parent = null, $rank, $data) {
11
        $this->parent = $parent;
12
        $this->rank = $rank;
13
        $this->data = $data;
14
    }
15
}
16
17
class DisjointSet {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
18
    public function __construct() {}
19
20
    public function makeSet($data) {
21
        $newSet = new DisjointNode(null, 0, $data);
22
        $newSet->parent = &$newSet;
23
24
        return $newSet;
25
    }
26
27
    public function find(DisjointNode $node) {
28
        if($node->parent !== $node) {
29
            $node->parent = $this->find($node->parent);
0 ignored issues
show
Bug introduced by
It seems like $node->parent can be null; however, find() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
30
        }
31
32
        return $node->parent;
33
    }
34
35
    public function union($x, $y) {
0 ignored issues
show
Unused Code introduced by
The parameter $x is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $y is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
36
        
37
    }
38
}