repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Null/BaseClass.php | tests/Unit/DataModel/Null/BaseClass.php | <?php
namespace Tests\Unit\DataModel\Null;
use Zerotoprod\DataModel\DataModel;
class BaseClass
{
use DataModel;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Null/NullTest.php | tests/Unit/DataModel/Null/NullTest.php | <?php
namespace Tests\Unit\DataModel\Null;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class NullTest extends TestCase
{
#[Test] public function bool(): void
{
$BaseClass = BaseClass::from(null);
$this->assertInstanceOf(BaseClass::class, $BaseClass);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Enum/EnumTest.php | tests/Unit/DataModel/Enum/EnumTest.php | <?php
namespace Tests\Unit\DataModel\Enum;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class EnumTest extends TestCase
{
#[Test] public function string(): void
{
$BaseClass = BaseClass::from([
BaseClass::string => 1,
BaseClass::StringEnum => StringEnum::string,
BaseClass::enum_value => 'string',
BaseClass::IntEnum => 1,
]);
$this->assertEquals('string', $BaseClass->StringEnum->value);
$this->assertEquals('string', $BaseClass->enum_value->value);
$this->assertInstanceOf(StringEnum::class, $BaseClass->StringEnum);
$this->assertEquals(1, $BaseClass->IntEnum->value);
$this->assertInstanceOf(IntEnum::class, $BaseClass->IntEnum);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Enum/StringEnum.php | tests/Unit/DataModel/Enum/StringEnum.php | <?php
namespace Tests\Unit\DataModel\Enum;
enum StringEnum: string
{
case string = 'string';
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Enum/BaseClass.php | tests/Unit/DataModel/Enum/BaseClass.php | <?php
namespace Tests\Unit\DataModel\Enum;
use Zerotoprod\DataModel\DataModel;
class BaseClass
{
use DataModel;
public const string = 'string';
public const StringEnum = 'StringEnum';
public const enum_value = 'enum_value';
public const IntEnum = 'IntEnum';
public string $string;
public StringEnum $StringEnum;
public StringEnum $enum_value;
public IntEnum $IntEnum;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Enum/IntEnum.php | tests/Unit/DataModel/Enum/IntEnum.php | <?php
namespace Tests\Unit\DataModel\Enum;
use Zerotoprod\DataModel\DataModel;
enum IntEnum: int
{
use DataModel;
case id = 1;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Float/BaseClass.php | tests/Unit/DataModel/Float/BaseClass.php | <?php
namespace Tests\Unit\DataModel\Float;
use Zerotoprod\DataModel\DataModel;
class BaseClass
{
use DataModel;
public const float = 'float';
public const Child = 'Child';
public float $float;
public Child $Child;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Float/Child.php | tests/Unit/DataModel/Float/Child.php | <?php
namespace Tests\Unit\DataModel\Float;
use Zerotoprod\DataModel\DataModel;
class Child
{
use DataModel;
public const float = 'float';
public float $float;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Float/FloatTest.php | tests/Unit/DataModel/Float/FloatTest.php | <?php
namespace Tests\Unit\DataModel\Float;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class FloatTest extends TestCase
{
#[Test] public function float(): void
{
$BaseClass = BaseClass::from([
BaseClass::float => '1.1',
BaseClass::Child => [
Child::float => '2.2'
],
]);
$this->assertEquals(1.1, $BaseClass->float);
$this->assertEquals(2.2, $BaseClass->Child->float);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/FromClass/BaseClass.php | tests/Unit/DataModel/FromClass/BaseClass.php | <?php
namespace Tests\Unit\DataModel\FromClass;
use Zerotoprod\DataModel\DataModel;
class BaseClass
{
use DataModel;
public const Child = 'Child';
public const ChildWithoutFrom = 'ChildWithoutFrom';
public Child $Child;
public ChildWithoutFrom $ChildWithoutFrom;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/FromClass/Child.php | tests/Unit/DataModel/FromClass/Child.php | <?php
namespace Tests\Unit\DataModel\FromClass;
class Child
{
public const id = 'id';
public int $id;
public static function from(): self
{
$self = new self();
$self->id = 1;
return $self;
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/FromClass/FromClassTest.php | tests/Unit/DataModel/FromClass/FromClassTest.php | <?php
namespace Tests\Unit\DataModel\FromClass;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use TypeError;
class FromClassTest extends TestCase
{
#[Test] public function calls_from_method(): void
{
$BaseClass = BaseClass::from([
BaseClass::Child => 1,
]);
$this->assertEquals(1, $BaseClass->Child->id);
}
#[Test] public function does_not_assign_without_from_method(): void
{
$this->expectException(TypeError::class);
BaseClass::from([
BaseClass::ChildWithoutFrom => [
ChildWithoutFrom::id => 1
],
]);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/FromClass/ChildWithoutFrom.php | tests/Unit/DataModel/FromClass/ChildWithoutFrom.php | <?php
namespace Tests\Unit\DataModel\FromClass;
class ChildWithoutFrom
{
public const id = 'id';
public int $id;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/IgnoresUnions/BaseClass.php | tests/Unit/DataModel/IgnoresUnions/BaseClass.php | <?php
namespace Tests\Unit\DataModel\IgnoresUnions;
use Zerotoprod\DataModel\DataModel;
use Zerotoprod\DataModel\Describe;
class BaseClass
{
use DataModel;
public const id = 'id';
public const required = 'required';
public const no_type = 'no_type';
public int|string $id;
#[Describe(['required' => true])]
public int|string $required;
#[Describe(['required' => true])]
public $no_type;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/IgnoresUnions/IgnoresUnionsTest.php | tests/Unit/DataModel/IgnoresUnions/IgnoresUnionsTest.php | <?php
namespace Tests\Unit\DataModel\IgnoresUnions;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use Zerotoprod\DataModel\PropertyRequiredException;
class IgnoresUnionsTest extends TestCase
{
#[Test] public function ignores_unions(): void
{
$BaseClass = BaseClass::from([
BaseClass::id => 1,
BaseClass::required => '1',
BaseClass::no_type => '1',
]);
$this->assertEquals(1, $BaseClass->id);
$this->assertEquals('1', $BaseClass->required);
$BaseClass = BaseClass::from([
BaseClass::id => '1',
BaseClass::required => '1',
BaseClass::no_type => '1',
]);
$this->assertEquals('1', $BaseClass->id);
$this->assertEquals('1', $BaseClass->required);
$this->assertEquals('1', $BaseClass->no_type);
}
#[Test] public function requires_unions(): void
{
$this->expectException(PropertyRequiredException::class);
BaseClass::from([
BaseClass::id => '1',
BaseClass::no_type => '1',
]);
}
#[Test] public function requires_no_type(): void
{
$this->expectException(PropertyRequiredException::class);
BaseClass::from([
BaseClass::id => '1',
BaseClass::required => '1',
]);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/MissingProperty/MissingPropertyTest.php | tests/Unit/DataModel/MissingProperty/MissingPropertyTest.php | <?php
namespace Tests\Unit\DataModel\MissingProperty;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class MissingPropertyTest extends TestCase
{
#[Test] public function handles_missing_property(): void
{
$BaseClass = BaseClass::from([
BaseClass::id => 1,
'name' => 'name'
]);
$this->assertEquals(1, $BaseClass->id);
$this->assertFalse(isset($BaseClass->name));
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/MissingProperty/BaseClass.php | tests/Unit/DataModel/MissingProperty/BaseClass.php | <?php
namespace Tests\Unit\DataModel\MissingProperty;
use Zerotoprod\DataModel\DataModel;
/**
* @property $name
*/
class BaseClass
{
use DataModel;
public const id = 'id';
public int $id;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/DynamicSet/BaseClass.php | tests/Unit/DataModel/DynamicSet/BaseClass.php | <?php
namespace Tests\Unit\DataModel\DynamicSet;
use Zerotoprod\DataModel\DataModel;
use Zerotoprod\DataModel\Describe;
class BaseClass
{
use DataModel;
public const foo = 'foo';
public const bar = 'bar';
public string $foo;
public string $bar;
#[Describe(self::foo)]
private function foo($value, $context): string
{
return $value.$context[self::bar];
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/DynamicSet/ClassDynamicTest.php | tests/Unit/DataModel/DynamicSet/ClassDynamicTest.php | <?php
namespace Tests\Unit\DataModel\DynamicSet;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class ClassDynamicTest extends TestCase
{
#[Test] public function fromDynamic(): void
{
$BaseClass = BaseClass::from([
BaseClass::foo => 'foo',
BaseClass::bar => 'bar',
]);
$this->assertEquals('foobar', $BaseClass->foo);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Bool/BoolTest.php | tests/Unit/DataModel/Bool/BoolTest.php | <?php
namespace Tests\Unit\DataModel\Bool;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use Zerotoprod\DataModel\PropertyRequiredException;
class BoolTest extends TestCase
{
#[Test] public function bool(): void
{
$BaseClass = BaseClass::from([
BaseClass::bool => 0,
BaseClass::bool_describe => '1',
BaseClass::bool_required => true,
BaseClass::Child => [
Child::bool => 1
],
]);
$this->assertFalse($BaseClass->bool);
$this->assertTrue($BaseClass->bool_describe);
$this->assertTrue($BaseClass->Child->bool);
}
#[Test] public function bool_required(): void
{
$this->expectException(PropertyRequiredException::class);
BaseClass::from(['bogus' => 'bogus']);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Bool/BaseClass.php | tests/Unit/DataModel/Bool/BaseClass.php | <?php
namespace Tests\Unit\DataModel\Bool;
use Zerotoprod\DataModel\DataModel;
use Zerotoprod\DataModel\Describe;
class BaseClass
{
use DataModel;
public const bool = 'bool';
public const bool_describe = 'bool_describe';
public const bool_required = 'bool_required';
public const Child = 'Child';
public bool $bool;
#[Describe('bogus')]
public bool $bool_describe;
#[Describe(['required' => true])]
public bool $bool_required;
public Child $Child;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Bool/Child.php | tests/Unit/DataModel/Bool/Child.php | <?php
namespace Tests\Unit\DataModel\Bool;
use Zerotoprod\DataModel\DataModel;
class Child
{
use DataModel;
public const bool = 'bool';
public bool $bool;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Recursion/BaseClass.php | tests/Unit/DataModel/Recursion/BaseClass.php | <?php
namespace Tests\Unit\DataModel\Recursion;
use stdClass;
use Zerotoprod\DataModel\DataModel;
class BaseClass
{
use DataModel;
public const id = 'id';
public const name = 'name';
public const price = 'price';
public const is_free = 'is_free';
public const list = 'list';
public const object = 'object';
public const stdClass = 'stdClass';
public const mixed = 'mixed';
public const Child = 'Child';
public const ShortNamespaceChild = 'ShortNamespaceChild';
public const self = 'self';
public int $id;
public string $name;
public float $price;
public bool $is_free;
public array $list;
public object $object;
public stdClass $stdClass;
public mixed $mixed;
public \Tests\Unit\DataModel\Recursion\Child $Child;
public ShortNamespaceChild $ShortNamespaceChild;
public self $self;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Recursion/ShortNamespaceChild.php | tests/Unit/DataModel/Recursion/ShortNamespaceChild.php | <?php
namespace Tests\Unit\DataModel\Recursion;
use Zerotoprod\DataModel\DataModel;
class ShortNamespaceChild
{
use DataModel;
public const id = 'id';
public const name = 'name';
public int $id;
public string $name;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Recursion/InstanceRecursionTest.php | tests/Unit/DataModel/Recursion/InstanceRecursionTest.php | <?php
namespace Tests\Unit\DataModel\Recursion;
use PHPUnit\Framework\Attributes\Test;
use stdClass;
use Tests\TestCase;
class InstanceRecursionTest extends TestCase
{
#[Test] public function recursively_creates_instance_from_array(): void
{
$object = new stdClass;
$object->id = 1;
$BaseClass = BaseClass::from([
BaseClass::id => 1,
BaseClass::name => 'name',
BaseClass::price => 1.00,
BaseClass::is_free => true,
BaseClass::list => [1, 2],
BaseClass::object => $object,
BaseClass::stdClass => $object,
BaseClass::mixed => 'mixed',
BaseClass::Child => [
Child::id => 1,
Child::name => 'name',
],
BaseClass::ShortNamespaceChild => [
ShortNamespaceChild::id => 1,
ShortNamespaceChild::name => 'name',
],
BaseClass::self => [
BaseClass::id => 1
]
]);
$this->assertEquals(1, $BaseClass->id);
$this->assertEquals('name', $BaseClass->name);
$this->assertEquals(1.00, $BaseClass->price);
$this->assertTrue($BaseClass->is_free);
$this->assertEquals([1, 2], $BaseClass->list);
$this->assertEquals($object, $BaseClass->object);
$this->assertEquals($object, $BaseClass->stdClass);
$this->assertEquals('mixed', $BaseClass->mixed);
$this->assertEquals(1, $BaseClass->Child->id);
$this->assertEquals('name', $BaseClass->Child->name);
$this->assertEquals(1, $BaseClass->ShortNamespaceChild->id);
$this->assertEquals('name', $BaseClass->ShortNamespaceChild->name);
$this->assertEquals(1, $BaseClass->self->id);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Recursion/Child.php | tests/Unit/DataModel/Recursion/Child.php | <?php
namespace Tests\Unit\DataModel\Recursion;
use Zerotoprod\DataModel\DataModel;
class Child
{
use DataModel;
public const id = 'id';
public const name = 'name';
public int $id;
public string $name;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/FromStdClass/BaseClass.php | tests/Unit/DataModel/FromStdClass/BaseClass.php | <?php
namespace Tests\Unit\DataModel\FromStdClass;
use stdClass;
use Zerotoprod\DataModel\DataModel;
class BaseClass
{
use DataModel;
public const id = 'id';
public const Child = 'Child';
public const stdClass = 'stdClass';
public const stdClassWithoutBackslash = 'stdClassWithoutBackslash';
public int $id;
public Child $Child;
public stdClass $stdClass;
public stdClass $stdClassWithoutBackslash;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/FromStdClass/FromStdClassTest.php | tests/Unit/DataModel/FromStdClass/FromStdClassTest.php | <?php
namespace Tests\Unit\DataModel\FromStdClass;
use PHPUnit\Framework\Attributes\Test;
use stdClass;
use Tests\TestCase;
class FromStdClassTest extends TestCase
{
#[Test] public function passes_object(): void
{
$Base = new stdClass();
$Base->id = 1;
$BaseClass = BaseClass::from($Base);
$this->assertEquals(1, $BaseClass->id);
}
#[Test] public function passes_object_to_child(): void
{
$Child = new stdClass();
$Child->id = 1;
$BaseClass = BaseClass::from([
BaseClass::Child => $Child,
]);
$this->assertEquals(1, $BaseClass->Child->id);
}
#[Test] public function passes_stdClass(): void
{
$stdClass = new stdClass();
$stdClass->id = 1;
$BaseClass = BaseClass::from([
BaseClass::stdClass => $stdClass,
]);
$this->assertEquals(1, $BaseClass->stdClass->id);
}
#[Test] public function passes_stdClass_without_backslash(): void
{
$stdClass = new stdClass();
$stdClass->id = 1;
$BaseClass = BaseClass::from([
BaseClass::stdClassWithoutBackslash => $stdClass,
]);
$this->assertEquals(1, $BaseClass->stdClassWithoutBackslash->id);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/FromStdClass/Child.php | tests/Unit/DataModel/FromStdClass/Child.php | <?php
namespace Tests\Unit\DataModel\FromStdClass;
class Child
{
public const id = 'id';
public int $id;
public static function from(): self
{
$self = new self();
$self->id = 1;
return $self;
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/FromStdClass/ChildWithoutFrom.php | tests/Unit/DataModel/FromStdClass/ChildWithoutFrom.php | <?php
namespace Tests\Unit\DataModel\FromStdClass;
class ChildWithoutFrom
{
public const id = 'id';
public int $id;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Instance/BaseClass.php | tests/Unit/DataModel/Instance/BaseClass.php | <?php
namespace Tests\Unit\DataModel\Instance;
use Zerotoprod\DataModel\DataModel;
class BaseClass
{
use DataModel;
public const id = 'id';
public const name = 'name';
public int $id;
public string $name;
public function __construct(array $data = [])
{
self::from($data, $this);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Instance/InstanceTest.php | tests/Unit/DataModel/Instance/InstanceTest.php | <?php
namespace Tests\Unit\DataModel\Instance;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class InstanceTest extends TestCase
{
#[Test] public function creates_instance_from_array(): void
{
$BaseClass = BaseClass::from([
BaseClass::id => 1,
BaseClass::name => 'name'
]);
$this->assertEquals(1, $BaseClass->id);
$this->assertEquals('name', $BaseClass->name);
}
#[Test] public function creates_instance_from_constructor(): void
{
$BaseClass = new BaseClass([
BaseClass::id => 1,
BaseClass::name => 'name'
]);
$this->assertEquals(1, $BaseClass->id);
$this->assertEquals('name', $BaseClass->name);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/String/BaseClass.php | tests/Unit/DataModel/String/BaseClass.php | <?php
namespace Tests\Unit\DataModel\String;
use Zerotoprod\DataModel\DataModel;
class BaseClass
{
use DataModel;
public const string = 'string';
public const Child = 'Child';
public string $string;
public Child $Child;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/String/Child.php | tests/Unit/DataModel/String/Child.php | <?php
namespace Tests\Unit\DataModel\String;
use Zerotoprod\DataModel\DataModel;
class Child
{
use DataModel;
public const string = 'string';
public string $string;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/String/StringTest.php | tests/Unit/DataModel/String/StringTest.php | <?php
namespace Tests\Unit\DataModel\String;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class StringTest extends TestCase
{
#[Test] public function string(): void
{
$BaseClass = BaseClass::from([
BaseClass::string => 1,
BaseClass::Child => [
Child::string => 1.1
],
]);
$this->assertEquals('1', $BaseClass->string);
$this->assertEquals('1.1', $BaseClass->Child->string);
}
#[Test] public function passes_string(): void
{
$BaseClass = BaseClass::from('user');
$this->assertInstanceOf(BaseClass::class, $BaseClass);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/FromDataModel/FromDataModelTest.php | tests/Unit/DataModel/FromDataModel/FromDataModelTest.php | <?php
namespace Tests\Unit\DataModel\FromDataModel;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class FromDataModelTest extends TestCase
{
#[Test] public function from_data_model(): void
{
$BaseClass = BaseClass::from([
BaseClass::id => 1,
BaseClass::Child => Child::from([
Child::id => 1,
]),
]);
$BaseClass = BaseClass::from($BaseClass);
$this->assertEquals(1, $BaseClass->id);
$this->assertEquals(1, $BaseClass->Child->id);
}
#[Test] public function from_child_data_model(): void
{
$BaseClass = BaseClass::from([
BaseClass::id => 1,
BaseClass::Child => Child::from([
Child::id => 1,
]),
]);
$this->assertEquals(1, $BaseClass->id);
$this->assertEquals(1, $BaseClass->Child->id);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/FromDataModel/BaseClass.php | tests/Unit/DataModel/FromDataModel/BaseClass.php | <?php
namespace Tests\Unit\DataModel\FromDataModel;
use Zerotoprod\DataModel\DataModel;
class BaseClass
{
use DataModel;
public const id = 'id';
public const Child = 'Child';
public const NullChild = 'NullChild';
public int $id;
public Child $Child;
public Child $NullChild;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/FromDataModel/Child.php | tests/Unit/DataModel/FromDataModel/Child.php | <?php
namespace Tests\Unit\DataModel\FromDataModel;
use Zerotoprod\DataModel\DataModel;
class Child
{
use DataModel;
public const id = 'id';
public int $id;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Int/BaseClass.php | tests/Unit/DataModel/Int/BaseClass.php | <?php
namespace Tests\Unit\DataModel\Int;
use Zerotoprod\DataModel\DataModel;
class BaseClass
{
use DataModel;
public const int = 'int';
public const Child = 'Child';
public int $int;
public Child $Child;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Int/IntTest.php | tests/Unit/DataModel/Int/IntTest.php | <?php
namespace Tests\Unit\DataModel\Int;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class IntTest extends TestCase
{
#[Test] public function int(): void
{
$BaseClass = BaseClass::from([
BaseClass::int => '1',
BaseClass::Child => [
Child::int => '1'
],
]);
$this->assertEquals(1, $BaseClass->int);
$this->assertEquals(1, $BaseClass->Child->int);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/Int/Child.php | tests/Unit/DataModel/Int/Child.php | <?php
namespace Tests\Unit\DataModel\Int;
use Zerotoprod\DataModel\DataModel;
class Child
{
use DataModel;
public const int = 'int';
public int $int;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/FromArray/ArrayTest.php | tests/Unit/DataModel/FromArray/ArrayTest.php | <?php
namespace Tests\Unit\DataModel\FromArray;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class ArrayTest extends TestCase
{
#[Test] public function array(): void
{
$BaseClass = BaseClass::from([
BaseClass::array => [1],
BaseClass::Child => [
Child::array => ['2']
],
BaseClass::object => ['foo' => 'bar']
]);
$this->assertEquals([1], $BaseClass->array);
$this->assertEquals(['2'], $BaseClass->Child->array);
$this->assertEquals(['foo' => 'bar'], $BaseClass->object);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/FromArray/BaseClass.php | tests/Unit/DataModel/FromArray/BaseClass.php | <?php
namespace Tests\Unit\DataModel\FromArray;
use Zerotoprod\DataModel\DataModel;
class BaseClass
{
use DataModel;
public const array = 'array';
public const object = 'object';
public const Child = 'Child';
public array $array;
public Child $Child;
public array $object;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/DataModel/FromArray/Child.php | tests/Unit/DataModel/FromArray/Child.php | <?php
namespace Tests\Unit\DataModel\FromArray;
use Zerotoprod\DataModel\DataModel;
class Child
{
use DataModel;
public const array = 'array';
public array $array;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/Post/BaseClass.php | tests/Unit/Examples/Post/BaseClass.php | <?php
namespace Tests\Unit\Examples\Post;
use Zerotoprod\DataModel\Describe;
class BaseClass
{
use \Zerotoprod\DataModel\DataModel;
public const int = 'int';
#[Describe([
'post' => [self::class, 'post'],
'message' => 'Value too large.',
])]
public int $int;
public static function post($value, array $context, ?\ReflectionAttribute $Attribute, \ReflectionProperty $Property): void
{
if ($value > 10) {
throw new \RuntimeException($value.$Attribute->getArguments()[0]['message']);
}
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/Post/PostTest.php | tests/Unit/Examples/Post/PostTest.php | <?php
namespace Tests\Unit\Examples\Post;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class
PostTest extends TestCase
{
#[Test] public function from(): void
{
$this->expectExceptionMessage('Value too large.');
BaseClass::from([
BaseClass::int => 100,
]);
}
#[Test] public function does_not_throw_exception(): void
{
$BaseClass = BaseClass::from([
BaseClass::int => 1,
]);
self::assertEquals(1, $BaseClass->int);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/From/User.php | tests/Unit/Examples/From/User.php | <?php
namespace Tests\Unit\Examples\From;
use Zerotoprod\DataModel\Describe;
class User
{
use \Zerotoprod\DataModel\DataModel;
public const first_name = 'first_name';
#[Describe(['from' => 'firstName'])]
public string $first_name;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/From/ClassTest.php | tests/Unit/Examples/From/ClassTest.php | <?php
namespace Tests\Unit\Examples\From;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class ClassTest extends TestCase
{
#[Test] public function from(): void
{
$User = User::from([
'firstName' => '1',
]);
$this->assertEquals('1', $User->first_name);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/ExtendsTrait/BaseClass.php | tests/Unit/Examples/ExtendsTrait/BaseClass.php | <?php
namespace Tests\Unit\Examples\ExtendsTrait;
class BaseClass
{
use DataModel;
public const string = 'string';
public string $string;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/ExtendsTrait/ClassTest.php | tests/Unit/Examples/ExtendsTrait/ClassTest.php | <?php
namespace Tests\Unit\Examples\ExtendsTrait;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class ClassTest extends TestCase
{
#[Test] public function from(): void
{
$BaseClass = BaseClass::from([
BaseClass::string => 'foo',
]);
$this->assertEquals('foo', $BaseClass->string);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/ExtendsTrait/DataModel.php | tests/Unit/Examples/ExtendsTrait/DataModel.php | <?php
namespace Tests\Unit\Examples\ExtendsTrait;
trait DataModel
{
use \Zerotoprod\DataModel\DataModel;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/ClassLevelCast/User.php | tests/Unit/Examples/ClassLevelCast/User.php | <?php
namespace Tests\Unit\Examples\ClassLevelCast;
use DateTimeImmutable;
use Zerotoprod\DataModel\DataModel;
use Zerotoprod\DataModel\Describe;
#[Describe([
'cast' => [
'string' => 'uppercase',
DateTimeImmutable::class => [__CLASS__, 'toDateTimeImmutable'],
]
])]
class User
{
use DataModel;
public string $first_name;
public DateTimeImmutable $registered;
public static function toDateTimeImmutable(string $value, array $context): DateTimeImmutable
{
return new DateTimeImmutable($value);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/ClassLevelCast/UserTest.php | tests/Unit/Examples/ClassLevelCast/UserTest.php | <?php
namespace Tests\Unit\Examples\ClassLevelCast;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class UserTest extends TestCase
{
#[Test] public function from(): void
{
$user = User::from([
'first_name' => 'Jane',
'registered' => '2015-10-04 17:24:43.000000',
]);
$this->assertEquals('JANE', $user->first_name);
$this->assertEquals('Sunday', $user->registered->format('l'));
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/PropertyLevelCast/User.php | tests/Unit/Examples/PropertyLevelCast/User.php | <?php
namespace Tests\Unit\Examples\PropertyLevelCast;
use ReflectionAttribute;
use ReflectionProperty;
use Zerotoprod\DataModel\DataModel;
use Zerotoprod\DataModel\Describe;
class User
{
use DataModel;
#[Describe(['cast' => [__CLASS__, 'firstName'], 'function' => 'strtoupper'])]
public string $first_name;
#[Describe(['cast' => 'uppercase'])]
public string $last_name;
#[Describe(['cast' => [__CLASS__, 'fullName']])]
public string $full_name;
private static function firstName(
mixed $value,
array $context,
?ReflectionAttribute $ReflectionAttribute,
ReflectionProperty $ReflectionProperty
): string {
return $ReflectionAttribute->getArguments()[0]['function']($value);
}
public static function fullName($value, array $context): string
{
return "{$context['first_name']} {$context['last_name']}";
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/PropertyLevelCast/UserTest.php | tests/Unit/Examples/PropertyLevelCast/UserTest.php | <?php
namespace Tests\Unit\Examples\PropertyLevelCast;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class UserTest extends TestCase
{
#[Test] public function from(): void
{
$user = User::from([
'first_name' => 'Jane',
'last_name' => 'Doe',
]);
$this->assertEquals('JANE', $user->first_name);
$this->assertEquals('DOE', $user->last_name);
$this->assertEquals('Jane Doe', $user->full_name);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/Ignore/User.php | tests/Unit/Examples/Ignore/User.php | <?php
namespace Tests\Unit\Examples\Ignore;
use Tests\Unit\Examples\ExtendsTrait\DataModel;
use Zerotoprod\DataModel\Describe;
class User
{
use DataModel;
public string $name;
#[Describe(['ignore' => true])]
public int $age;
#[Describe(['ignore'])]
public int $height;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/Ignore/IgnoreTest.php | tests/Unit/Examples/Ignore/IgnoreTest.php | <?php
namespace Tests\Unit\Examples\Ignore;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class IgnoreTest extends TestCase
{
#[Test] public function from(): void
{
$user = User::from([
'name' => 'John Doe',
'age' => '30',
'height' => '30',
]);
$this->assertEquals('John Doe', $user->name);
$this->assertFalse(isset($user->age));
$this->assertFalse(isset($user->height));
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/Instance/User.php | tests/Unit/Examples/Instance/User.php | <?php
namespace Tests\Unit\Examples\Instance;
use Zerotoprod\DataModel\DataModel;
class User
{
use DataModel;
public string $name;
public function __construct(array $data = [])
{
self::from($data, $this);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/Instance/InstanceTest.php | tests/Unit/Examples/Instance/InstanceTest.php | <?php
namespace Tests\Unit\Examples\Instance;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class InstanceTest extends TestCase
{
#[Test] public function creates_instance_from_array(): void
{
$BaseClass = new User([
'name' => 'name'
]);
$this->assertEquals('name', $BaseClass->name);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/MissingAsNull/User.php | tests/Unit/Examples/MissingAsNull/User.php | <?php
namespace Tests\Unit\Examples\MissingAsNull;
use Zerotoprod\DataModel\Describe;
#[Describe(['nullable' => true])]
class User
{
use \Zerotoprod\DataModel\DataModel;
public string $name;
public ?int $age;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/MissingAsNull/MissingAsNullTest.php | tests/Unit/Examples/MissingAsNull/MissingAsNullTest.php | <?php
namespace Tests\Unit\Examples\MissingAsNull;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class MissingAsNullTest extends TestCase
{
#[Test] public function from(): void
{
$User = User::from([
'name' => 'John',
]);
$this->assertEquals('John', $User->name);
$this->assertNull($User->age);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/Usage/User.php | tests/Unit/Examples/Usage/User.php | <?php
namespace Tests\Unit\Examples\Usage;
use Tests\Unit\Examples\ExtendsTrait\DataModel;
class User
{
use DataModel;
public string $name;
public int $age;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/Usage/UserTest.php | tests/Unit/Examples/Usage/UserTest.php | <?php
namespace Tests\Unit\Examples\Usage;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class UserTest extends TestCase
{
#[Test] public function from(): void
{
$user = User::from([
'name' => 'John Doe',
'age' => '30',
]);
$this->assertEquals('John Doe', $user->name);
$this->assertEquals(30, $user->age);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/Default/DefaultTest.php | tests/Unit/Examples/Default/DefaultTest.php | <?php
namespace Tests\Unit\Examples\Default;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class DefaultTest extends TestCase
{
#[Test] public function from(): void
{
$user = User::from();
$this->assertEquals('James', $user->name);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/Default/User.php | tests/Unit/Examples/Default/User.php | <?php
namespace Tests\Unit\Examples\Default;
use Tests\Unit\Examples\ExtendsTrait\DataModel;
use Zerotoprod\DataModel\Describe;
class User
{
use DataModel;
#[Describe(['default' => 'James'])]
public string $name;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/Pre/BaseClass.php | tests/Unit/Examples/Pre/BaseClass.php | <?php
namespace Tests\Unit\Examples\Pre;
use Zerotoprod\DataModel\Describe;
class BaseClass
{
use \Zerotoprod\DataModel\DataModel;
public const int = 'int';
#[Describe(['pre' => [self::class, 'pre'], 'message' => 'Value too large.'])]
public int $int;
public static function pre($value, array $context, ?\ReflectionAttribute $Attribute, \ReflectionProperty $Property): void
{
if ($value > 10) {
throw new \RuntimeException($Attribute->getArguments()[0]['message']);
}
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/Pre/PreTest.php | tests/Unit/Examples/Pre/PreTest.php | <?php
namespace Tests\Unit\Examples\Pre;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class
PreTest extends TestCase
{
#[Test] public function from(): void
{
$this->expectExceptionMessage('Value too large.');
BaseClass::from([
BaseClass::int => 100,
]);
}
#[Test] public function fails_check(): void
{
$BaseClass = BaseClass::from([
BaseClass::int => 1,
]);
self::assertEquals(1, $BaseClass->int);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/AutomaticInstantiation/Address.php | tests/Unit/Examples/AutomaticInstantiation/Address.php | <?php
namespace Tests\Unit\Examples\AutomaticInstantiation;
use Tests\Unit\Examples\ExtendsTrait\DataModel;
class Address
{
use DataModel;
public string $street;
public string $city;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/AutomaticInstantiation/AutomaticInstantiationTest.php | tests/Unit/Examples/AutomaticInstantiation/AutomaticInstantiationTest.php | <?php
namespace Tests\Unit\Examples\AutomaticInstantiation;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class AutomaticInstantiationTest extends TestCase
{
#[Test] public function from(): void
{
$user = User::from([
'name' => 'John Doe',
'address' => [
'street' => '123 Main St',
'city' => 'Hometown',
],
]);
self::assertEquals('Hometown', $user->address->city);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/AutomaticInstantiation/User.php | tests/Unit/Examples/AutomaticInstantiation/User.php | <?php
namespace Tests\Unit\Examples\AutomaticInstantiation;
use Tests\Unit\Examples\ExtendsTrait\DataModel;
class User
{
use DataModel;
public string $name;
public Address $address;
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/MethodLevelCast/User.php | tests/Unit/Examples/MethodLevelCast/User.php | <?php
namespace Tests\Unit\Examples\MethodLevelCast;
use Zerotoprod\DataModel\DataModel;
use Zerotoprod\DataModel\Describe;
class User
{
use DataModel;
public string $first_name;
public string $last_name;
public string $fullName;
#[Describe('last_name')]
public function lastName(?string $value, array $context, ?\ReflectionAttribute $Attribute, \ReflectionProperty $Property): string
{
return strtoupper($value ?? '');
}
#[Describe('fullName')]
public function fullName($value, array $context, ?\ReflectionAttribute $Attribute, \ReflectionProperty $Property): string
{
$last_name = $context['last_name'] ?? null;
$first_name = $context['first_name'] ?? null;
return "$first_name $last_name";
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
zero-to-prod/data-model | https://github.com/zero-to-prod/data-model/blob/af1a3958fdf2d4cccbab4b787d2c510d04cdd384/tests/Unit/Examples/MethodLevelCast/UserTest.php | tests/Unit/Examples/MethodLevelCast/UserTest.php | <?php
namespace Tests\Unit\Examples\MethodLevelCast;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class UserTest extends TestCase
{
#[Test] public function from(): void
{
$user = User::from([
'first_name' => 'Jane',
'last_name' => 'Doe',
]);
$this->assertEquals('Jane', $user->first_name);
$this->assertEquals('DOE', $user->last_name);
$this->assertEquals('Jane Doe', $user->fullName);
}
#[Test] public function without_value(): void
{
$user = User::from([
'last_name' => 'Doe',
]);
$this->assertEquals('DOE', $user->last_name);
$this->assertEquals(' Doe', $user->fullName);
}
#[Test] public function without_matching_value(): void
{
$user = User::from([
'first_name' => 'Jane',
]);
$this->assertEquals('Jane', $user->first_name);
$this->assertEquals('Jane ', $user->fullName);
}
} | php | MIT | af1a3958fdf2d4cccbab4b787d2c510d04cdd384 | 2026-01-05T04:40:32.643481Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Directed.php | src/Directed.php | <?php
namespace Graphp\Algorithms;
use Graphp\Graph\EdgeDirected;
use Graphp\Graph\EdgeUndirected;
/**
* Basic algorithms for working with the undirected or directed Graphs (digraphs) / Walks.
*
* @link http://en.wikipedia.org/wiki/Glossary_of_graph_theory#Direction
* @link http://en.wikipedia.org/wiki/Digraph_%28mathematics%29
*/
class Directed extends BaseDual
{
/**
* checks whether the graph has any directed edges
*
* This method is intentionally not named "isDirected()" (aka digraph),
* because that might be misleading in regards to empty and/or mixed graphs.
*
* @return bool
*/
public function hasDirected()
{
foreach ($this->set->getEdges() as $edge) {
if ($edge instanceof EdgeDirected) {
return true;
}
}
return false;
}
/**
* checks whether the graph has any undirected edges
*
* This method is intentionally not named "isUndirected()",
* because that might be misleading in regards to empty and/or mixed graphs.
*
* @return bool
*/
public function hasUndirected()
{
foreach ($this->set->getEdges() as $edge) {
if ($edge instanceof EdgeUndirected) {
return true;
}
}
return false;
}
/**
* checks whether this is a mixed graph (contains both directed and undirected edges)
*
* @return bool
* @uses self::hasDirected()
* @uses self::hasUndirected()
*/
public function isMixed()
{
return ($this->hasDirected() && $this->hasUndirected());
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/DetectNegativeCycle.php | src/DetectNegativeCycle.php | <?php
namespace Graphp\Algorithms;
use Graphp\Algorithms\ShortestPath\MooreBellmanFord as SpMooreBellmanFord;
use Graphp\Graph\Exception\NegativeCycleException;
use Graphp\Graph\Exception\UnderflowException;
use Graphp\Graph\Graph;
use Graphp\Graph\Walk;
class DetectNegativeCycle extends BaseGraph
{
/**
* check if the input graph has any negative cycles
*
* @return bool
* @uses AlgorithmDetectNegativeCycle::getCycleNegative()
*/
public function hasCycleNegative()
{
try {
$this->getCycleNegative();
// cycle was found => okay
return true;
// no cycle found
} catch (UnderflowException $ignore) {}
return false;
}
/**
* Searches all vertices for the first negative cycle
*
* @return Walk
* @throws UnderflowException if there's no negative cycle
* @uses AlgorithmSpMooreBellmanFord::getVertices()
*/
public function getCycleNegative()
{
// remember vertices already visited, as they can not lead to a new cycle
$verticesVisited = array();
// check for all vertices
foreach ($this->graph->getVertices()->getMap() as $vid => $vertex) {
// skip vertices already visited
if (!isset($verticesVisited[$vid])) {
// start MBF algorithm on current vertex
$alg = new SpMooreBellmanFord($vertex);
try {
// try to get all connected vertices (or throw new cycle)
foreach ($alg->getVertices()->getIds() as $vid) {
// getting connected vertices succeeded, so skip over all of them
$verticesVisited[$vid] = true;
// no cycle found, check next vertex...
}
// yey, negative cycle encountered => return
} catch (NegativeCycleException $e) {
return $e->getCycle();
}
}
// no more vertices to check => abort
}
throw new UnderflowException('No negative cycle found');
}
/**
* create new graph clone with only vertices and edges in negative cycle
*
* @return Graph
* @throws UnderflowException if there's no negative cycle
* @uses AlgorithmDetectNegativeCycle::getCycleNegative()
* @uses Walk::createGraph()
*/
public function createGraph()
{
return $this->getCycleNegative()->createGraph();
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/ConnectedComponents.php | src/ConnectedComponents.php | <?php
namespace Graphp\Algorithms;
use Graphp\Algorithms\Search\BreadthFirst as SearchBreadthFirst;
use Graphp\Graph\Exception\InvalidArgumentException;
use Graphp\Graph\Exception\UnderflowException;
use Graphp\Graph\Graph;
use Graphp\Graph\Vertex;
/**
* Algorithm for working with connected components
*
* @link http://en.wikipedia.org/wiki/Connected_component_%28graph_theory%29
* @link http://mathworld.wolfram.com/ConnectedGraph.html
* @link http://math.stackexchange.com/questions/50551/is-the-empty-graph-connected
*/
class ConnectedComponents extends BaseGraph
{
/**
* create subgraph with all vertices connected to given vertex (i.e. the connected component of ths given vertex)
*
* @param Vertex $vertex
* @return Graph
* @throws InvalidArgumentException if given vertex is not from same graph
* @uses AlgorithmSearchBreadthFirst::getVertices()
* @uses Graph::createGraphCloneVertices()
*/
public function createGraphComponentVertex(Vertex $vertex)
{
if ($vertex->getGraph() !== $this->graph) {
throw new InvalidArgumentException('This graph does not contain the given vertex');
}
return $this->graph->createGraphCloneVertices($this->createSearch($vertex)->getVertices());
}
/**
*
* @param Vertex $vertex
* @return SearchBreadthFirst
*/
private function createSearch(Vertex $vertex)
{
$alg = new SearchBreadthFirst($vertex);
// follow into both directions (loosely connected)
return $alg->setDirection(SearchBreadthFirst::DIRECTION_BOTH);
}
/**
* check whether this graph consists of only a single component
*
* If a Graph consists of only a single component, it is said to be a
* connected Graph, otherwise it's called a disconnected Graph.
*
* This method returns exactly the same result as checking
* <pre>($this->getNumberOfComponents() === 1)</pre>. However, using this
* method is faster than calling getNumberOfComponents(), as it only has to
* count all vertices in one component to see if the graph consists of only
* a single component.
*
* As such, a null Graph (a Graph with no vertices) is not considered
* connected here.
*
* @return bool
* @see self::getNumberOfComponents()
*/
public function isSingle()
{
try {
$vertex = $this->graph->getVertices()->getVertexFirst();
} catch (UnderflowException $e) {
// no first vertex => empty graph => has zero components
return false;
}
$alg = $this->createSearch($vertex);
return (\count($this->graph->getVertices()) === \count($alg->getVertices()));
}
/**
* count number of connected components
*
* A null Graph (a Graph with no vertices) will return 0 components.
*
* @return int number of components
* @uses Graph::getVertices()
* @uses AlgorithmSearchBreadthFirst::getVertices()
*/
public function getNumberOfComponents()
{
$visitedVertices = array();
$components = 0;
// for each vertices
foreach ($this->graph->getVertices()->getMap() as $vid => $vertex) {
// did I visit this vertex before?
if (!isset($visitedVertices[$vid])) {
// get all vertices of this component
$newVertices = $this->createSearch($vertex)->getVertices()->getIds();
++$components;
// mark the vertices of this component as visited
foreach ($newVertices as $vid) {
$visitedVertices[$vid] = true;
}
}
}
// return number of components
return $components;
}
/**
* separate input graph into separate independant and unconnected graphs
*
* @return Graph[]
* @uses Graph::getVertices()
* @uses AlgorithmSearchBreadthFirst::getVertices()
*/
public function createGraphsComponents()
{
$visitedVertices = array();
$graphs = array();
// for each vertices
foreach ($this->graph->getVertices()->getMap() as $vid => $vertex) {
// did I visit this vertex before?
if (!isset($visitedVertices[$vid])) {
$alg = $this->createSearch($vertex);
// get all vertices of this component
$newVertices = $alg->getVertices();
// mark the vertices of this component as visited
foreach ($newVertices->getIds() as $vid) {
$visitedVertices[$vid] = true;
}
$graphs[] = $this->graph->createGraphCloneVertices($newVertices);
}
}
return $graphs;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/TransposeGraph.php | src/TransposeGraph.php | <?php
namespace Graphp\Algorithms;
use Graphp\Graph\EdgeDirected;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Graph;
class TransposeGraph extends BaseGraph
{
/**
* create transpose graph
*
* @throws UnexpectedValueException if input graph has undirected edges
* @return Graph
* @uses Graph::createGraphCloneEdgeless()
* @uses Graph::createEdgeClone()
* @uses Graph::createEdgeCloneInverted()
*/
public function createGraph()
{
$newgraph = $this->graph->createGraphCloneEdgeless();
foreach ($this->graph->getEdges() as $edge) {
if (!($edge instanceof EdgeDirected)) {
throw new UnexpectedValueException('Edge is undirected');
}
$newgraph->createEdgeCloneInverted($edge);
}
return $newgraph;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Base.php | src/Base.php | <?php
namespace Graphp\Algorithms;
/**
* @deprecated
*/
abstract class Base{ }
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Eulerian.php | src/Eulerian.php | <?php
namespace Graphp\Algorithms;
class Eulerian extends BaseGraph
{
/**
* check whether this graph has an eulerian cycle
*
* @return bool
* @uses ConnectedComponents::isSingle()
* @uses Degree::getDegreeVertex()
* @todo isolated vertices should be ignored
* @todo definition is only valid for undirected graphs
*/
public function hasCycle()
{
$components = new ConnectedComponents($this->graph);
if ($components->isSingle()) {
$alg = new Degree($this->graph);
foreach ($this->graph->getVertices() as $vertex) {
// uneven degree => fail
if ($alg->getDegreeVertex($vertex) & 1) {
return false;
}
}
return true;
}
return false;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Weight.php | src/Weight.php | <?php
namespace Graphp\Algorithms;
use Graphp\Graph\Graph;
/**
* Basic algorithms for working with the (total) weight of a Graph/Walk
*
* A weighted graph associates a label (weight) with every edge in the graph.
* Sometimes the word cost is used instead of weight. The term network is a
* synonym for a weighted graph.
*
* @link http://en.wikipedia.org/wiki/Glossary_of_graph_theory#Weighted_graphs_and_networks
*/
class Weight extends BaseDual
{
/**
* checks whether this graph has any weighted edges
*
* edges usually have no weight attached. a weight explicitly set to (int) 0
* will be considered as 'weighted'.
*
* @return bool
* @uses Edge::getWeight()
*/
public function isWeighted()
{
foreach ($this->set->getEdges() as $edge) {
if ($edge->getWeight() !== NULL) {
return true;
}
}
return false;
}
/**
* get total weight of graph (sum of weight of all edges)
*
* edges with no weight assigned will evaluate to weight (int) 0. thus an
* unweighted graph (see isWeighted()) will return total weight of (int) 0.
*
* returned weight can also be negative or (int) 0 if edges have been
* assigned a negative weight or a weight of (int) 0.
*
* @return float total weight
* @see self::isWeighted()
* @uses Edge::getWeight()
*/
public function getWeight()
{
$weight = 0;
foreach ($this->set->getEdges() as $edge) {
$w = $edge->getWeight();
if ($w !== NULL) {
$weight += $w;
}
}
return $weight;
}
/**
* get minimum weight assigned to all edges
*
* minimum weight is often needed because some algorithms do not support
* negative weights or edges with zero weight.
*
* edges with NO (null) weight will NOT be considered for the minimum weight.
*
* @return float|NULL minimum edge weight or NULL if graph is not weighted or empty
* @uses Edge::getWeight()
*/
public function getWeightMin()
{
$min = NULL;
foreach ($this->set->getEdges() as $edge) {
$weight = $edge->getWeight();
if ($weight !== null && ($min === NULL || $weight < $min)) {
$min = $weight;
}
}
return $min;
}
/**
* get total weight of current flow (sum of all edges flow(e) * weight(e))
*
* @return float
* @see Graph::getWeight() to just get the sum of all edges' weights
* @uses Edge::getFlow()
* @uses Edge::getWeight()
*/
public function getWeightFlow()
{
$sum = 0;
foreach ($this->set->getEdges() as $edge) {
$sum += $edge->getFlow() * $edge->getWeight();
}
return $sum;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/BaseDual.php | src/BaseDual.php | <?php
namespace Graphp\Algorithms;
use Graphp\Graph\Graph;
use Graphp\Graph\Set\DualAggregate;
use Graphp\Graph\Walk;
/**
* Abstract base class for algorithms that operate on a given Set instance
*
* @see Set
* @deprecated
*/
abstract class BaseDual extends Base
{
/**
* Set to operate on
*
* @var DualAggregate
*/
protected $set;
/**
* instantiate new algorithm
*
* @param Graph|Walk|DualAggregate $graphOrWalk either the Graph or Walk to operate on (or the common base class Set)
*/
public function __construct(DualAggregate $graphOrWalk)
{
$this->set = $graphOrWalk;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/ResidualGraph.php | src/ResidualGraph.php | <?php
namespace Graphp\Algorithms;
use Graphp\Graph\Edge;
use Graphp\Graph\EdgeDirected;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Graph;
class ResidualGraph extends BaseGraph
{
private $keepNullCapacity = false;
private $mergeParallelEdges = false;
public function setKeepNullCapacity($toggle)
{
$this->keepNullCapacity = !!$toggle;
return $this;
}
public function setMergeParallelEdges($toggle)
{
$this->mergeParallelEdges = !!$toggle;
return $this;
}
/**
* create residual graph
*
* @throws UnexpectedValueException if input graph has undirected edges or flow/capacity is not set
* @return Graph
* @uses Graph::createGraphCloneEdgeless()
* @uses Graph::createEdgeClone()
* @uses Graph::createEdgeCloneInverted()
*/
public function createGraph()
{
$newgraph = $this->graph->createGraphCloneEdgeless();
foreach ($this->graph->getEdges() as $edge) {
if (!($edge instanceof EdgeDirected)) {
throw new UnexpectedValueException('Edge is undirected');
}
$flow = $edge->getFlow();
if ($flow === NULL) {
throw new UnexpectedValueException('Flow not set');
}
$capacity = $edge->getCapacity();
if ($capacity === NULL) {
throw new UnexpectedValueException('Capacity not set');
}
// capacity is still available, clone remaining capacity into new edge
if ($this->keepNullCapacity || $flow < $capacity) {
$newEdge = $newgraph->createEdgeClone($edge)->setFlow(0)->setCapacity($capacity - $flow);
if ($this->mergeParallelEdges) {
$this->mergeParallelEdges($newEdge);
}
}
// flow is set, clone current flow as capacity for back-flow into new inverted edge (opposite direction)
if ($this->keepNullCapacity || $flow > 0) {
$newEdge = $newgraph->createEdgeCloneInverted($edge)->setFlow(0)->setCapacity($flow);
// if weight is set, use negative weight for back-edges
if ($newEdge->getWeight() !== NULL) {
$newEdge->setWeight(-$newEdge->getWeight());
}
if ($this->mergeParallelEdges) {
$this->mergeParallelEdges($newEdge);
}
}
}
return $newgraph;
}
/**
* Will merge all edges that are parallel to to given edge
*
* @param Edge $newEdge
*/
private function mergeParallelEdges(Edge $newEdge)
{
$alg = new Parallel($this->graph);
$parallelEdges = $alg->getEdgesParallelEdge($newEdge)->getVector();
if (!$parallelEdges) {
return;
}
$mergedCapacity = 0;
foreach ($parallelEdges as $parallelEdge) {
$mergedCapacity += $parallelEdge->getCapacity();
}
$newEdge->setCapacity($newEdge->getCapacity() + $mergedCapacity);
foreach ($parallelEdges as $parallelEdge) {
$parallelEdge->destroy();
}
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Symmetric.php | src/Symmetric.php | <?php
namespace Graphp\Algorithms;
use Graphp\Graph\EdgeDirected;
/**
* Basic algorithms for working with symmetric digraphs
*
* A directed graph is called symmetric if, for every arc that belongs to it,
* the corresponding reversed arc (antiparallel directed edge) also belongs to it.
*
* @link http://en.wikipedia.org/wiki/Directed_graph#Classes_of_digraphs
*/
class Symmetric extends BaseGraph
{
/**
* checks whether this graph is symmetric (for every edge a->b there's also an edge b->a)
*
* @return bool
* @uses Graph::getEdges()
* @uses EdgeDirected::getVertexStart()
* @uses EdgeDirected::getVertedEnd()
* @uses Vertex::hasEdgeTo()
*/
public function isSymmetric()
{
// check all edges
foreach ($this->graph->getEdges() as $edge) {
// only check directed edges (undirected ones are symmetric by definition)
if ($edge instanceof EdgeDirected) {
// check if end also has an edge to start
if (!$edge->getVertexEnd()->hasEdgeTo($edge->getVertexStart())) {
return false;
}
}
}
return true;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Bipartit.php | src/Bipartit.php | <?php
namespace Graphp\Algorithms;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Graph;
class Bipartit extends BaseGraph
{
/**
* check whether this graph is bipartit
*
* @return bool
* @uses AlgorithmBipartit::getColors()
*/
public function isBipartit()
{
try {
$this->getColors();
return true;
} catch (UnexpectedValueException $ignore) { }
return false;
}
/**
* checks whether the input graph's vertex groups are a valid bipartition
*
* @return bool
* @uses AlgorithmGroups::isBipartit()
*/
public function isBipartitGroups()
{
$alg = new Groups($this->graph);
return $alg->isBipartit();
}
/**
* get map of vertex ID to vertex color
*
* @return int[]
* @throws UnexpectedValueException if graph is not bipartit
* @uses AlgorithmBipartit::checkVertex() for every vertex not already colored
*/
public function getColors()
{
$colors = array();
// get color for each vertex
foreach ($this->graph->getVertices()->getMap() as $vid => $startVertex) {
if (!isset($colors[$vid])) {
$queue = array($startVertex);
// initialize each components color
$colors[$vid] = 0;
// breadth search all vertices in same component
do {
// next vertex in color
$vertex = \array_shift($queue);
$color = $colors[$vertex->getId()];
$nextColor = 1-$color;
// scan all vertices connected to this vertex
foreach ($vertex->getVerticesEdge()->getMap() as $vid => $nextVertex) {
// color unknown, so expect next color for this vertex
if (!isset($colors[$vid])) {
$colors[$vid] = $nextColor;
$queue[] = $nextVertex;
// color is known but differs => can not be bipartit
} elseif ($colors[$vid] !== $nextColor) {
throw new UnexpectedValueException('Graph is not bipartit');
}
}
} while ($queue);
}
}
return $colors;
}
/**
* get groups of vertices per color
*
* @return array[] array of arrays of vertices
*/
public function getColorVertices()
{
$colors = $this->getColors();
$ret = array(0 => array(), 1 => array());
foreach ($this->graph->getVertices()->getMap() as $vid => $vertex) {
$ret[$colors[$vid]][$vid] = $vertex;
}
return $ret;
}
/**
* create new graph with valid groups set according to bipartition colors
*
* @return Graph
* @throws UnexpectedValueException if graph is not bipartit
* @uses AlgorithmBipartit::getColors()
* @uses Graph::createGraphClone()
* @uses Vertex::setGroup()
*/
public function createGraphGroups()
{
$colors = $this->getColors();
$graph = $this->graph->createGraphClone();
foreach ($graph->getVertices()->getMap() as $vid => $vertex) {
$vertex->setGroup($colors[$vid]);
}
return $graph;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Loop.php | src/Loop.php | <?php
namespace Graphp\Algorithms;
use Graphp\Graph\Vertex;
/**
* Basic algorithms for working with loop edges
*
* A loop (also called a self-loop or a "buckle") is an edge that connects a
* Vertex to itself. A simple graph contains no loops.
*
* @link http://en.wikipedia.org/wiki/Loop_%28graph_theory%29
*/
class Loop extends BaseDual
{
/**
* checks whether this graph has any loops (edges from vertex to itself)
*
* @return bool
* @uses Edge::isLoop()
*/
public function hasLoop()
{
foreach ($this->set->getEdges() as $edge) {
if ($edge->isLoop()) {
return true;
}
}
return false;
}
/**
* checks whether this vertex has a loop (edge to itself)
*
* @return bool
* @uses Edge::isLoop()
*/
public function hasLoopVertex(Vertex $vertex)
{
foreach ($vertex->getEdges() as $edge) {
if ($edge->isLoop()) {
return true;
}
}
return false;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Flow.php | src/Flow.php | <?php
namespace Graphp\Algorithms;
use Graphp\Graph\EdgeDirected;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Vertex;
/**
* Basic algorithms for working with flow graphs
*
* A flow network (also known as a transportation network) is a directed graph
* where each edge has a capacity and each edge receives a flow.
*
* @link http://en.wikipedia.org/wiki/Flow_network
* @see Algorithm\Balance
*/
class Flow extends BaseDual
{
/**
* check if this graph has any flow set (any edge has a non-NULL flow)
*
* @return bool
* @uses Edge::getFlow()
*/
public function hasFlow()
{
foreach ($this->set->getEdges() as $edge) {
if ($edge->getFlow() !== NULL) {
return true;
}
}
return false;
}
/**
* Calculates the flow for this Vertex: sum(outflow) - sum(inflow)
*
* Usually, vertices should have a resulting flow of 0: The sum of flows
* entering a vertex must equal the sum of flows leaving a vertex. If the
* resulting flow is < 0, this vertex is considered a sink (i.e. there's
* more flow into this vertex). If the resulting flow is > 0, this vertex
* is considered a "source" (i.e. there's more flow leaving this vertex).
*
* @param Vertex $vertex
* @return float
* @throws UnexpectedValueException if they are undirected edges
* @see Vertex::getBalance()
* @uses Vertex::getEdges()
* @uses Edge::getFlow()
*/
public function getFlowVertex(Vertex $vertex)
{
$sumOfFlow = 0;
foreach ($vertex->getEdges() as $edge) {
if (!($edge instanceof EdgeDirected)) {
throw new UnexpectedValueException("TODO: undirected edges not suported yet");
}
// edge is an outgoing edge of this vertex
if ($edge->hasVertexStart($vertex)) {
// flowing out (flow is "pointing away")
$sumOfFlow += $edge->getFlow();
// this is an ingoing edge
} else {
// flowing in
$sumOfFlow -= $edge->getFlow();
}
}
return $sumOfFlow;
}
public function getBalance()
{
$balance = 0;
// Sum for all vertices of value
foreach ($this->set->getVertices() as $vertex) {
$balance += $vertex->getBalance();
}
return $balance;
}
/**
* check if the current flow is balanced (aka "balanced flow" or "b-flow")
*
* a flow is considered balanced if each edge's current flow does not exceed its
* maximum capacity (which is always guaranteed due to the implementation
* of Edge::setFlow()) and each vertices' flow (i.e. outflow-inflow) equals
* its balance.
*
* checking whether the FLOW is balanced is not to be confused with checking
* whether the GRAPH is balanced (see Graph::isBalanced() instead)
*
* @return bool
* @see Degree::isBalanced() if you merely want to check indegree=outdegree
* @uses self::getFlowVertex()
* @uses Vertex::getBalance()
*/
public function isBalancedFlow()
{
// no need to check for each edge: flow <= capacity (setters already check that)
// check for each vertex: outflow-inflow = balance
foreach ($this->set->getVertices() as $vertex) {
if ($this->getFlowVertex($vertex) !== $vertex->getBalance()) {
return false;
}
}
return true;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/TopologicalSort.php | src/TopologicalSort.php | <?php
namespace Graphp\Algorithms;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Set\Vertices;
use Graphp\Graph\Vertex;
/**
* topological sorting / order, also known as toposort / topsort, commonly used in resolving dependencies
*
* @author clue
* @link http://en.wikipedia.org/wiki/Topological_sorting
*/
class TopologicalSort extends BaseGraph
{
/**
* run algorithm and return an ordered/sorted set of Vertices
*
* the topological sorting may be non-unique depending on your edges
*
* @return Vertices
*/
public function getVertices()
{
$stack = array(); // visited nodes with unvisited children
$visited = array();
$output = array();
// TODO: avoid having to reverse all vertices multiple times
// pick a node to examine next - assume there are isolated nodes
foreach (\array_reverse($this->graph->getVertices()->getVector()) as $top) {
assert($top instanceof Vertex);
$tid = $top->getId();
if (!isset($visited[$tid])) { // don't examine if already found
\array_push($stack, $top);
}
while ($stack) {
$node = \end($stack);
assert($node instanceof Vertex);
$nid = $node->getId();
$visited[$nid] = false; // temporary mark
$found = false; // new children found during visit to this node
// find the next node to visit
foreach (\array_reverse($node->getVerticesEdgeTo()->getVector()) as $child) {
assert($child instanceof Vertex);
$cid = $child->getId();
if (!isset($visited[$cid])) {
// found a new node - push it onto the stack
\array_push($stack, $child);
$found = true; // move onto the new node
break;
} else if ($visited[$cid] === false) {
// temporary mark => not a DAG
throw new UnexpectedValueException('Not a DAG');
}
}
if (!$found) {
\array_pop($stack); // no new children found - we're done with this node
$visited[$nid] = true; // mark as visited
\array_push($output, $node); // add to results
}
}
}
return new Vertices(\array_reverse($output, true));
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Parallel.php | src/Parallel.php | <?php
namespace Graphp\Algorithms;
use Graphp\Graph\Edge;
use Graphp\Graph\EdgeDirected as EdgeDirected;
use Graphp\Graph\Set\Edges;
/**
* Basic algorithms for working with parallel edges
*
* Parallel edges (also called multiple edges or a multi-edge), are two or more
* edges that are incident to the same two vertices. A simple graph has no
* multiple edges.
*
* @link http://en.wikipedia.org/wiki/Multiple_edges
*/
class Parallel extends BaseGraph
{
/**
* checks whether this graph has any parallel edges (aka multigraph)
*
* @return bool
* @uses Edge::hasEdgeParallel() for every edge
*/
public function hasEdgeParallel()
{
foreach ($this->graph->getEdges() as $edge) {
if ($this->hasEdgeParallelEdge($edge)) {
return true;
}
}
return false;
}
/**
* checks whether this edge has any parallel edges
*
* @return bool
* @uses Edge::getEdgesParallel()
*/
public function hasEdgeParallelEdge(Edge $edge)
{
return !$this->getEdgesParallelEdge($edge)->isEmpty();
}
/**
* get set of all Edges parallel to this edge (excluding self)
*
* @param Edge $edge
* @return Edges
*/
public function getEdgesParallelEdge(Edge $edge)
{
if ($edge instanceof EdgeDirected) {
// get all edges between this edge's endpoints
$edges = $edge->getVertexStart()->getEdgesTo($edge->getVertexEnd())->getVector();
} else {
// edge points into both directions (undirected/bidirectional edge)
// also get all edges in other direction
$ends = $edge->getVertices();
$edges = $ends->getVertexFirst()->getEdges()->getEdgesIntersection($ends->getVertexLast()->getEdges())->getVector();
}
$pos = \array_search($edge, $edges, true);
assert($pos !== false);
// exclude current edge from parallel edges
unset($edges[$pos]);
return new Edges(\array_values($edges));
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Groups.php | src/Groups.php | <?php
namespace Graphp\Algorithms;
use Graphp\Graph\Set\Vertices;
use Graphp\Graph\Vertex;
class Groups extends BaseGraph
{
/**
* count total number of different groups assigned to vertices
*
* @return int
* @uses AlgorithmGroups::getGroups()
*/
public function getNumberOfGroups()
{
return \count($this->getGroups());
}
/**
* checks whether the input graph's vertex groups are a valid bipartition
*
* @return bool
* @see AlgorithmBipartit() if you do NOT want to take vertex groups into consideration
* @uses AlgorithmGroups::getNumberOfGroups()
* @uses Vertex::getGroup()
*/
public function isBipartit()
{
// graph has to contain exactly 2 groups
if ($this->getNumberOfGroups() !== 2) {
return false;
}
// for each vertex
foreach ($this->graph->getVertices() as $vertex) {
// get current group
$group = $vertex->getGroup();
// for every neighbor vertex
foreach ($vertex->getVerticesEdge() as $vertexNeighbor) {
// vertex group must be other group
if ($vertexNeighbor->getGroup() === $group) {
return false;
}
}
}
return true;
}
/**
* get vector of all group numbers
*
* @return int[]
* @uses Vertex::getGroup()
*/
public function getGroups()
{
$groups = array();
foreach ($this->graph->getVertices() as $vertex) {
assert($vertex instanceof Vertex);
$groups[$vertex->getGroup()] = true;
}
return \array_keys($groups);
}
/**
* get set of all Vertices in the given group
*
* @param int $group
* @return Vertices
* @uses Vertex::getGroup()
*/
public function getVerticesGroup($group)
{
$vertices = array();
foreach ($this->graph->getVertices()->getMap() as $vid => $vertex) {
if ($vertex->getGroup() === $group) {
$vertices[$vid] = $vertex;
}
}
return new Vertices($vertices);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Complete.php | src/Complete.php | <?php
namespace Graphp\Algorithms;
/**
* Basic algorithms for working with complete graphs
*
* A complete graph is a graph in which every pair of vertices is connected
* by an edge.
*
* @link http://en.wikipedia.org/wiki/Complete_graph
* @link http://mathworld.wolfram.com/CompleteGraph.html
*/
class Complete extends BaseGraph
{
/**
* checks whether this graph is complete (every vertex has an edge to any other vertex)
*
* @return bool
* @uses Graph::getVertices()
* @uses Vertex::hasEdgeTo()
*/
public function isComplete()
{
// copy of array (separate iterator but same vertices)
$c = $vertices = $this->graph->getVertices()->getVector();
// from each vertex
foreach ($vertices as $vertex) {
// to each vertex
foreach ($c as $other) {
// missing edge => fail
if ($other !== $vertex && !$vertex->hasEdgeTo($other)) {
return false;
}
}
}
return true;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Degree.php | src/Degree.php | <?php
namespace Graphp\Algorithms;
use Graphp\Graph\Exception\UnderflowException;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Vertex;
/**
* Basic algorithms for working with the degrees of Graphs.
*
* The degree (or valency) of a Vertex of a Graph is the number of Edges
* incident to the Vertex, with Loops counted twice.
*
* @link http://en.wikipedia.org/wiki/Degree_%28graph_theory%29
* @link http://en.wikipedia.org/wiki/Regular_graph
*/
class Degree extends BaseGraph
{
/**
* get degree for k-regular-graph (only if each vertex has the same degree)
*
* @return int
* @throws UnderflowException if graph is empty
* @throws UnexpectedValueException if graph is not regular (i.e. vertex degrees are not equal)
* @uses self::getDegreeVertex()
* @see self::isRegular()
*/
public function getDegree()
{
// get initial degree of any start vertex to compare others to
$degree = $this->getDegreeVertex($this->graph->getVertices()->getVertexFirst());
foreach ($this->graph->getVertices() as $vertex) {
assert($vertex instanceof Vertex);
$i = $this->getDegreeVertex($vertex);
if ($i !== $degree) {
throw new UnexpectedValueException('Graph is not k-regular (vertex degrees differ)');
}
}
return $degree;
}
/**
* get minimum degree of vertices
*
* @return int
* @throws UnderflowException if graph is empty
* @uses Vertices::getVertexOrder()
* @uses self::getDegreeVertex()
*/
public function getDegreeMin()
{
return $this->getDegreeVertex($this->graph->getVertices()->getVertexOrder(array($this, 'getDegreeVertex')));
}
/**
* get maximum degree of vertices
*
* @return int
* @throws UnderflowException if graph is empty
* @uses Vertices::getVertexOrder()
* @uses self::getDegreeVertex()
*/
public function getDegreeMax()
{
return $this->getDegreeVertex($this->graph->getVertices()->getVertexOrder(array($this, 'getDegreeVertex'), true));
}
/**
* checks whether this graph is regular, i.e. each vertex has the same indegree/outdegree
*
* @return bool
* @uses self::getDegree()
*/
public function isRegular()
{
// an empty graph is considered regular
if ($this->graph->getVertices()->isEmpty()) {
return true;
}
try {
$this->getDegree();
return true;
} catch (UnexpectedValueException $ignore) { }
return false;
}
/**
* checks whether the indegree of every vertex equals its outdegree
*
* @return bool
* @uses self::getDegreeInVertex()
* @uses self::getDegreeOutVertex()
*/
public function isBalanced()
{
foreach ($this->graph->getVertices() as $vertex) {
if ($this->getDegreeInVertex($vertex) !== $this->getDegreeOutVertex($vertex)) {
return false;
}
}
return true;
}
/**
* checks whether this vertex is a source, i.e. its indegree is zero
*
* @param Vertex $vertex
* @return bool
* @uses Edge::hasVertexTarget()
* @see self::getDegreeInVertex()
*/
public function isVertexSource(Vertex $vertex)
{
foreach ($vertex->getEdges() as $edge) {
if ($edge->hasVertexTarget($vertex)) {
return false;
}
}
// reach this point: no edge to this vertex
return true;
}
/**
* checks whether this vertex is a sink, i.e. its outdegree is zero
*
* @param Vertex $vertex
* @return bool
* @uses Edge::hasVertexStart()
* @see self::getDegreeOutVertex()
*/
public function isVertexSink(Vertex $vertex)
{
foreach ($vertex->getEdges() as $edge) {
if ($edge->hasVertexStart($vertex)) {
return false;
}
}
// reach this point: no edge away from this vertex
return true;
}
/**
* get degree of this vertex (total number of edges)
*
* vertex degree counts the total number of edges attached to this vertex
* regardless of whether they're directed or not. loop edges are counted
* twice as both start and end form a 'line' to the same vertex.
*
* @param Vertex $vertex
* @return int
* @see self::getDegreeInVertex()
* @see self::getDegreeOutVertex()
*/
public function getDegreeVertex(Vertex $vertex)
{
return \count($vertex->getEdges());
}
/**
* check whether this vertex is isolated (i.e. has no edges attached)
*
* @param Vertex $vertex
* @return bool
*/
public function isVertexIsolated(Vertex $vertex)
{
return $vertex->getEdges()->isEmpty();
}
/**
* get indegree of this vertex (number of edges TO this vertex)
*
* @param Vertex $vertex
* @return int
* @uses Edge::hasVertexTarget()
* @see self::getDegreeVertex()
*/
public function getDegreeInVertex($vertex)
{
$n = 0;
foreach ($vertex->getEdges() as $edge) {
if ($edge->hasVertexTarget($vertex)) {
++$n;
}
}
return $n;
}
/**
* get outdegree of this vertex (number of edges FROM this vertex TO other vertices)
*
* @param Vertex $vertex
* @return int
* @uses Edge::hasVertexStart()
* @see self::getDegreeVertex()
*/
public function getDegreeOutVertex(Vertex $vertex)
{
$n = 0;
foreach ($vertex->getEdges() as $edge) {
if ($edge->hasVertexStart($vertex)) {
++$n;
}
}
return $n;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/BaseVertex.php | src/BaseVertex.php | <?php
namespace Graphp\Algorithms;
use Graphp\Graph\Vertex;
/**
* Abstract base class for algorithms that operate on a given Vertex instance
*
* @deprecated
*/
abstract class BaseVertex extends Base
{
/**
* Vertex to operate on
*
* @var Vertex
*/
protected $vertex;
/**
* instantiate new algorithm
*
* @param Vertex $vertex Vertex to operate on
*/
public function __construct(Vertex $vertex)
{
$this->vertex = $vertex;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/BaseGraph.php | src/BaseGraph.php | <?php
namespace Graphp\Algorithms;
use Graphp\Graph\Graph;
/**
* Abstract base class for algorithms that operate on a given Graph instance
*
* @deprecated
*/
abstract class BaseGraph extends Base
{
/**
* Graph to operate on
*
* @var Graph
*/
protected $graph;
/**
* instantiate new algorithm
*
* @param Graph $graph Graph to operate on
*/
public function __construct(Graph $graph)
{
$this->graph = $graph;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/ShortestPath/BreadthFirst.php | src/ShortestPath/BreadthFirst.php | <?php
namespace Graphp\Algorithms\ShortestPath;
use Graphp\Graph\Vertex;
use Graphp\Graph\Exception\OutOfBoundsException;
use Graphp\Graph\Set\Edges;
use Graphp\Graph\Set\Vertices;
/**
* Simple breadth-first shortest path algorithm
*
* This algorithm ignores edge weights and operates as a level-order algorithm
* on the number of hops. As such, it considers the path with the least number
* of hops to be shortest.
*
* This is particularly useful your Graph doesn't have Edge weights assigned to
* begin with or if you're merely interested in knowing which Vertices can be
* reached at all (path finding). This avoids running expensive operations to
* determine the actual weight (distance) of a path.
*/
class BreadthFirst extends Base
{
/**
* get distance between start vertex and given end vertex
*
* @param Vertex $endVertex
* @throws OutOfBoundsException if there's no path to given end vertex
* @return float
* @uses self::getEdgesTo()
*/
public function getDistance(Vertex $endVertex)
{
return (float)\count($this->getEdgesTo($endVertex));
}
/**
* get array of edges on the walk for each vertex (vertex ID => array of walk edges)
*
* @return array[]
*/
public function getEdgesMap()
{
$vertexQueue = array();
$edges = array();
// $edges[$this->vertex->getId()] = array();
$vertexCurrent = $this->vertex;
$edgesCurrent = array();
do {
foreach ($vertexCurrent->getEdgesOut() as $edge) {
$vertexTarget = $edge->getVertexToFrom($vertexCurrent);
$vid = $vertexTarget->getId();
if (!isset($edges[$vid])) {
$vertexQueue[] = $vertexTarget;
$edges[$vid] = \array_merge($edgesCurrent, array($edge));
}
}
// get next from queue
$vertexCurrent = \array_shift($vertexQueue);
if ($vertexCurrent) {
$edgesCurrent = $edges[$vertexCurrent->getId()];
}
// untill queue is empty
} while ($vertexCurrent);
return $edges;
}
public function getEdgesTo(Vertex $endVertex)
{
if ($endVertex->getGraph() === $this->vertex->getGraph()) {
$map = $this->getEdgesMap();
if (isset($map[$endVertex->getId()])) {
return new Edges($map[$endVertex->getId()]);
}
}
throw new OutOfBoundsException('Given target vertex can not be reached from start vertex');
}
/**
* get map of vertex IDs to distance
*
* @return float[]
* @uses Vertex::hasLoop()
*/
public function getDistanceMap()
{
$ret = array();
foreach ($this->getEdgesMap() as $vid => $edges) {
$ret[$vid] = (float)\count($edges);
}
return $ret;
}
/**
* get array of all target vertices this vertex has a path to
*
* @return Vertices
* @uses self::getEdgesMap()
*/
public function getVertices()
{
$ret = array();
$graph = $this->vertex->getGraph();
foreach (\array_keys($this->getEdgesMap()) as $vid) {
$ret[$vid] = $graph->getVertex($vid);
}
return new Vertices($ret);
}
public function getEdges()
{
$ret = array();
foreach ($this->getEdgesMap() as $edges) {
foreach ($edges as $edge) {
if (!\in_array($edge, $ret, true)) {
$ret[] = $edge;
}
}
}
return new Edges($ret);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/ShortestPath/Base.php | src/ShortestPath/Base.php | <?php
namespace Graphp\Algorithms\ShortestPath;
use Graphp\Algorithms\BaseVertex;
use Graphp\Graph\Edge;
use Graphp\Graph\Exception\InvalidArgumentException;
use Graphp\Graph\Exception\OutOfBoundsException;
use Graphp\Graph\Graph;
use Graphp\Graph\Set\Edges;
use Graphp\Graph\Set\Vertices;
use Graphp\Graph\Vertex;
use Graphp\Graph\Walk;
/**
* Abstract base class for shortest path algorithms
*
* This abstract base class provides the base interface for working with
* single-source shortest paths (SSSP).
*
* The shortest path problem is the problem of finding a path between two
* vertices such that the sum of the weights of its constituent edges is
* minimized. The weight of the shortest path is referred to as distance.
*
* A--[10]-------------B---E<--F
* \ /
* \--[4]--C--[2]--D
*
* In the above pictured graph, the distance (weight of the shortest path)
* between A and C is 4, and the shortest path between A and B is "A->C->D->B"
* with a distance (total weight) of 6.
*
* In graph theory, it is usually assumed that a path to an unreachable vertex
* has infinite distance. In the above pictured graph, there's no way path
* from A to F, i.e. vertex F is unreachable from vertex A because of the
* directed edge "E <- F" pointing in the opposite direction. This library
* considers this an Exception instead. So if you're asking for the distance
* between A and F, you'll receive an OutOfBoundsException instead.
*
* In graph theory, it is usually assumed that each vertex has a (pseudo-)path
* to itself with a distance of 0. In order to produce reliable, consistent
* results, this library considers this (pseudo-)path to be non-existant, i.e.
* there's NO "magic" path between A and A. So if you're asking for the distance
* between A and A, you'll receive an OutOfBoundsException instead. This allows
* us to check hether there's a real path between A and A (cycle via other
* vertices) as well as working with loop edges.
*
* @link http://en.wikipedia.org/wiki/Shortest_path_problem
* @link http://en.wikipedia.org/wiki/Tree_%28data_structure%29
* @see ShortestPath\Dijkstra
* @see ShortestPath\MooreBellmanFord which also supports negative Edge weights
* @see ShortestPath\BreadthFirst with does not consider Edge weights, but only the number of hops
*/
abstract class Base extends BaseVertex
{
/**
* get walk (path) from start vertex to given end vertex
*
* @param Vertex $endVertex
* @return Walk
* @throws OutOfBoundsException if there's no path to the given end vertex
* @uses self::getEdgesTo()
* @uses Walk::factoryFromEdges()
*/
public function getWalkTo(Vertex $endVertex)
{
return Walk::factoryFromEdges($this->getEdgesTo($endVertex), $this->vertex);
}
/**
* get array of edges (path) from start vertex to given end vertex
*
* @param Vertex $endVertex
* @throws OutOfBoundsException if there's no path to the given end vertex
* @return Edges
* @uses self::getEdges()
* @uses self::getEdgesToInternal()
*/
public function getEdgesTo(Vertex $endVertex)
{
return $this->getEdgesToInternal($endVertex, $this->getEdges());
}
/**
* get array of edges (path) from start vertex to given end vertex
*
* @param Vertex $endVertex
* @param Edges|Edge[] $edges set or array of all input edges to operate on
* @throws OutOfBoundsException if there's no path to the given vertex
* @return Edges
* @uses self::getEdges() if no edges were given
*/
protected function getEdgesToInternal(Vertex $endVertex, $edges)
{
$currentVertex = $endVertex;
$path = array();
do {
$pre = NULL;
// check all edges to search for edge that points TO current vertex
foreach ($edges as $edge) {
try {
// get start point of this edge (fails if current vertex is not its end point)
$pre = $edge->getVertexFromTo($currentVertex);
$path[] = $edge;
$currentVertex = $pre;
break;
} catch (InvalidArgumentException $ignore) {
} // ignore: this edge does not point TO current vertex
}
if ($pre === NULL) {
throw new OutOfBoundsException('No edge leading to vertex');
}
} while ($currentVertex !== $this->vertex);
return new Edges(\array_reverse($path));
}
/**
* get sum of weight of given edges
*
* @param Edges $edges
* @return float
* @uses Edge::getWeight()
*/
private function sumEdges(Edges $edges)
{
$sum = 0;
foreach ($edges as $edge) {
$sum += $edge->getWeight();
}
return $sum;
}
/**
* get set of all Vertices the given start vertex has a path to
*
* @return Vertices
* @uses self::getDistanceMap()
*/
public function getVertices()
{
$vertices = array();
$map = $this->getDistanceMap();
foreach ($this->vertex->getGraph()->getVertices()->getMap() as $vid => $vertex) {
if (isset($map[$vid])) {
$vertices[$vid] = $vertex;
}
}
return new Vertices($vertices);
}
/**
* checks whether there's a path from this start vertex to given end vertex
*
* @param Vertex $vertex
* @return bool
* @uses self::getEdgesTo()
*/
public function hasVertex(Vertex $vertex)
{
try {
$this->getEdgesTo($vertex);
} catch (OutOfBoundsException $e) {
return false;
}
return true;
}
/**
* get map of vertex IDs to distance
*
* @return float[]
* @uses self::getEdges()
* @uses self::getEdgesToInternal()
* @uses self::sumEdges()
*/
public function getDistanceMap()
{
$edges = $this->getEdges();
$ret = array();
foreach ($this->vertex->getGraph()->getVertices()->getMap() as $vid => $vertex) {
try {
$ret[$vid] = $this->sumEdges($this->getEdgesToInternal($vertex, $edges));
} catch (OutOfBoundsException $ignore) {
} // ignore vertices that can not be reached
}
return $ret;
}
/**
* get distance (sum of weights) between start vertex and given end vertex
*
* @param Vertex $endVertex
* @return float
* @throws OutOfBoundsException if there's no path to the given end vertex
* @uses self::getEdgesTo()
* @uses self::sumEdges()
*/
public function getDistance(Vertex $endVertex)
{
return $this->sumEdges($this->getEdgesTo($endVertex));
}
/**
* create new resulting graph with only edges on shortest path
*
* The resulting Graph will always represent a tree with the start vertex
* being the root vertex.
*
* For example considering the following input Graph with equal weights on
* each edge:
*
* A----->F
* / \ ^
* / \ /
* / \ /
* | E
* | \
* | \
* B--->C<---D
*
* The resulting shortest path tree Graph will look like this:
*
* A----->F
* / \
* / \
* / \
* | E
* | \
* | \
* B--->C D
*
* Or by just arranging the Vertices slightly different:
*
* A
* /|\
* / | \
* B E \->F
* / |
* C<-/ D
*
* @return Graph
* @uses self::getEdges()
* @uses Graph::createGraphCloneEdges()
*/
public function createGraph()
{
return $this->vertex->getGraph()->createGraphCloneEdges($this->getEdges());
}
/**
* get cheapest edges (lowest weight) for given map of vertex predecessors
*
* @param Vertex[] $predecessor
* @return Edges
* @uses Graph::getVertices()
* @uses Vertex::getEdgesTo()
* @uses Edges::getEdgeOrder()
*/
protected function getEdgesCheapestPredecesor(array $predecessor)
{
$vertices = $this->vertex->getGraph()->getVertices()->getMap();
$edges = array();
foreach ($vertices as $vid => $vertex) {
if (isset($predecessor[$vid])) {
// get predecor
$predecesVertex = $predecessor[$vid];
// get cheapest edge
$edges[] = $predecesVertex->getEdgesTo($vertex)->getEdgeOrder(Edges::ORDER_WEIGHT);
}
}
return new Edges($edges);
}
/**
* get all edges on shortest path for this vertex
*
* @return Edges
*/
abstract public function getEdges();
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/ShortestPath/Dijkstra.php | src/ShortestPath/Dijkstra.php | <?php
namespace Graphp\Algorithms\ShortestPath;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Set\Edges;
use SplPriorityQueue;
/**
* Commonly used Dijkstra's shortest path algorithm
*
* This is asymptotically the fastest known single-source shortest-path
* algorithm for arbitrary graphs with non-negative weights. If your Graph
* contains an Edge with negative weight, if will throw an
* UnexpectedValueException. Consider using (the slower) MooreBellmanFord
* algorithm instead.
*
* @link http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
* @see MooreBellmanFord
*/
class Dijkstra extends Base
{
/**
* get all edges on shortest path for this vertex
*
* @return Edges
* @throws UnexpectedValueException when encountering an Edge with negative weight
*/
public function getEdges()
{
$totalCostOfCheapestPathTo = Array();
// start node distance
$totalCostOfCheapestPathTo[$this->vertex->getId()] = INF;
// just to get the cheapest vertex in the correct order
$cheapestVertex = new SplPriorityQueue();
$cheapestVertex->insert($this->vertex, 0);
// predecessor
$predecesVertexOfCheapestPathTo = Array();
$predecesVertexOfCheapestPathTo[$this->vertex->getId()] = $this->vertex;
// mark vertices when their cheapest path has been found
$usedVertices = Array();
$isFirst = true;
// Repeat until all vertices have been marked
$totalCountOfVertices = \count($this->vertex->getGraph()->getVertices());
for ($i = 0; $i < $totalCountOfVertices; ++$i) {
$currentVertex = NULL;
$currentVertexId = NULL;
$isEmpty = false;
do {
// if the priority queue is empty there are isolated vertices, but the algorithm visited all other vertices
if ($cheapestVertex->isEmpty()) {
$isEmpty = true;
break;
}
// Get cheapest unmarked vertex
$currentVertex = $cheapestVertex->extract();
$currentVertexId = $currentVertex->getId();
// Vertices can be in the priority queue multiple times, with different path costs (if vertex is already marked, this is an old unvalid entry)
} while (isset($usedVertices[$currentVertexId]));
// catch "algorithm ends" condition
if ($isEmpty) {
break;
}
if ($isFirst) {
$isFirst = false;
} else {
// mark this vertex
$usedVertices[$currentVertexId] = true;
}
// check for all edges of current vertex if there is a cheaper path (or IN OTHER WORDS: Add reachable nodes from currently added node and refresh the current possible distances)
foreach ($currentVertex->getEdgesOut() as $edge) {
$weight = $edge->getWeight();
if ($weight < 0) {
throw new UnexpectedValueException('Djkstra not supported for negative weights - Consider using MooreBellmanFord');
}
$targetVertex = $edge->getVertexToFrom($currentVertex);
$targetVertexId = $targetVertex->getId();
// if the targetVertex is marked, the cheapest path for this vertex has already been found (no negative edges) {
if (!isset($usedVertices[$targetVertexId])) {
// calculate new cost to vertex
$newCostsToTargetVertex = $totalCostOfCheapestPathTo[$currentVertexId] + $weight;
if (\is_infinite($newCostsToTargetVertex)) {
$newCostsToTargetVertex = $weight;
}
if ((!isset($predecesVertexOfCheapestPathTo[$targetVertexId]))
// is the new path cheaper?
|| $totalCostOfCheapestPathTo[$targetVertexId] > $newCostsToTargetVertex){
// Not an update, just an new insert with lower cost
$cheapestVertex->insert($targetVertex, - $newCostsToTargetVertex);
// so the lowest cost will be extraced first
// and higher cost will be skipped during extraction
// update/set costs found with the new connection
$totalCostOfCheapestPathTo[$targetVertexId] = $newCostsToTargetVertex;
// update/set predecessor vertex from the new connection
$predecesVertexOfCheapestPathTo[$targetVertexId] = $currentVertex;
}
}
}
}
if ($totalCostOfCheapestPathTo[$this->vertex->getId()] === INF) {
unset($predecesVertexOfCheapestPathTo[$this->vertex->getId()]);
}
// algorithm is done, return resulting edges
return $this->getEdgesCheapestPredecesor($predecesVertexOfCheapestPathTo);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/ShortestPath/MooreBellmanFord.php | src/ShortestPath/MooreBellmanFord.php | <?php
namespace Graphp\Algorithms\ShortestPath;
use Graphp\Graph\Exception\NegativeCycleException;
use Graphp\Graph\Exception\UnderflowException;
use Graphp\Graph\Set\Edges;
use Graphp\Graph\Vertex;
use Graphp\Graph\Walk;
/**
* Moore-Bellman-Ford's shortest path algorithm
*
* It is slower than Dijkstra's algorithm for the same problem, but more
* versatile, as it is capable of handling Graphs with negative Edge weights.
*
* Also known as just "Bellman–Ford algorithm".
*
* @link http://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm
*/
class MooreBellmanFord extends Base
{
/**
* @param Edges $edges
* @param int[] $totalCostOfCheapestPathTo
* @param Vertex[] $predecessorVertexOfCheapestPathTo
* @return Vertex|NULL
*/
private function bigStep(Edges $edges, array &$totalCostOfCheapestPathTo, array &$predecessorVertexOfCheapestPathTo)
{
$changed = NULL;
// check for all edges
foreach ($edges as $edge) {
// check for all "ends" of this edge (or for all targetes)
foreach ($edge->getVerticesTarget() as $toVertex) {
$fromVertex = $edge->getVertexFromTo($toVertex);
// If the fromVertex already has a path
if (isset($totalCostOfCheapestPathTo[$fromVertex->getId()])) {
// New possible costs of this path
$newCost = $totalCostOfCheapestPathTo[$fromVertex->getId()] + $edge->getWeight();
if (\is_infinite($newCost)) {
$newCost = $edge->getWeight() + 0;
}
// No path has been found yet
if (!isset($totalCostOfCheapestPathTo[$toVertex->getId()])
// OR this path is cheaper than the old path
|| $totalCostOfCheapestPathTo[$toVertex->getId()] > $newCost){
$changed = $toVertex;
$totalCostOfCheapestPathTo[$toVertex->getId()] = $newCost;
$predecessorVertexOfCheapestPathTo[$toVertex->getId()] = $fromVertex;
}
}
}
}
return $changed;
}
/**
* Calculate the Moore-Bellman-Ford-Algorithm and get all edges on shortest path for this vertex
*
* @return Edges
* @throws NegativeCycleException if there is a negative cycle
*/
public function getEdges()
{
// start node distance, add placeholder weight
$totalCostOfCheapestPathTo = array($this->vertex->getId() => INF);
// predecessor
$predecessorVertexOfCheapestPathTo = array($this->vertex->getId() => $this->vertex);
// the usal algorithm says we repeat (n-1) times.
// but because we also want to check for loop edges on the start vertex,
// we have to add an additional step:
$numSteps = \count($this->vertex->getGraph()->getVertices());
$edges = $this->vertex->getGraph()->getEdges();
$changed = true;
for ($i = 0; $i < $numSteps && $changed; ++$i) {
$changed = $this->bigStep($edges, $totalCostOfCheapestPathTo, $predecessorVertexOfCheapestPathTo);
}
// no cheaper edge to start vertex found => remove placeholder weight
if ($totalCostOfCheapestPathTo[$this->vertex->getId()] === INF) {
unset($predecessorVertexOfCheapestPathTo[$this->vertex->getId()]);
}
// algorithm is done, build graph
$returnEdges = $this->getEdgesCheapestPredecesor($predecessorVertexOfCheapestPathTo);
// Check for negative cycles (only if last step didn't already finish anyway)
// something is still changing...
if ($changed && $changed = $this->bigStep($edges, $totalCostOfCheapestPathTo, $predecessorVertexOfCheapestPathTo)) {
$cycle = Walk::factoryCycleFromPredecessorMap($predecessorVertexOfCheapestPathTo, $changed, Edges::ORDER_WEIGHT);
throw new NegativeCycleException('Negative cycle found', 0, NULL, $cycle);
}
return $returnEdges;
}
/**
* get negative cycle
*
* @return Walk
* @throws UnderflowException if there's no negative cycle
*/
public function getCycleNegative()
{
try {
$this->getEdges();
} catch (NegativeCycleException $e) {
return $e->getCycle();
}
throw new UnderflowException('No cycle found');
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/MinimumCostFlow/Base.php | src/MinimumCostFlow/Base.php | <?php
namespace Graphp\Algorithms\MinimumCostFlow;
use Graphp\Algorithms\BaseGraph;
use Graphp\Algorithms\Weight as AlgorithmWeight;
use Graphp\Algorithms\Flow as AlgorithmFlow;
use Graphp\Graph\Exception\UnderflowException;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Graph;
use Graphp\Graph\Set\Edges;
abstract class Base extends BaseGraph
{
/**
* check if balance is okay and throw exception otherwise
*
* @return $this (chainable)
* @throws UnexpectedValueException
*/
protected function checkBalance()
{
$alg = new AlgorithmFlow($this->graph);
$balance = $alg->getBalance();
$tolerance = 0.000001;
if ($balance >= $tolerance || $balance <= -$tolerance) {
throw new UnexpectedValueException('The given graph is not balanced value is: ' . $balance);
}
return $this;
}
/**
* helper used to add $newFlow to original edges of $clonedEdges in graph $resultGraph
*
* @param Graph $resultGraph graph to look for original edges
* @param Edges $clonedEdges set of cloned edges to be modified
* @param number $newFlow flow to add
* @uses Graph::getEdgeClone()
* @uses Graph::getEdgeCloneInverted()
* @uses Edge::getFlow()
* @uses Edge::setFlow()
*/
protected function addFlow(Graph $resultGraph, Edges $clonedEdges, $newFlow)
{
foreach ($clonedEdges as $clonedEdge) {
try {
// get edge from clone
$edge = $resultGraph->getEdgeClone($clonedEdge);
// add flow
$edge->setFlow($edge->getFlow() + $newFlow);
} catch (UnderflowException $ignore) {
// if the edge doesn't exist => use the residual edge
$edge = $resultGraph->getEdgeCloneInverted($clonedEdge);
// remove flow
$edge->setFlow($edge->getFlow() - $newFlow);
}
}
}
/**
* calculate total weight along minimum-cost flow
*
* @return float
* @uses self::createGraph()
* @uses AlgorithmWeight::getWeightFlow()
*/
public function getWeightFlow()
{
$alg = new AlgorithmWeight($this->createGraph());
return $alg->getWeightFlow();
}
/**
* create new resulting graph with minimum-cost flow on edges
*
* @return Graph
* @throws UnexpectedValueException for undirected edges
* @throws UnexpectedValueException if the graph has not enough capacity for the minimum-cost flow
*/
abstract public function createGraph();
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/MinimumCostFlow/CycleCanceling.php | src/MinimumCostFlow/CycleCanceling.php | <?php
namespace Graphp\Algorithms\MinimumCostFlow;
use Graphp\Algorithms\DetectNegativeCycle;
use Graphp\Algorithms\MaxFlow\EdmondsKarp as MaxFlowEdmondsKarp;
use Graphp\Algorithms\ResidualGraph;
use Graphp\Graph\Exception\UnderflowException;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Set\Edges;
class CycleCanceling extends Base
{
public function createGraph()
{
$this->checkBalance();
// create resulting graph with supersource and supersink
$resultGraph = $this->graph->createGraphClone();
$superSource = $resultGraph->createVertex();
$superSink = $resultGraph->createVertex();
$sumBalance = 0;
// connect supersource s* and supersink t* with all "normal" sources and sinks
foreach ($resultGraph->getVertices() as $vertex) {
$balance = $vertex->getBalance();
if ($balance > 0) {
// positive balance => source capacity
$resultGraph->createEdgeDirected($superSource, $vertex)->setCapacity($balance);
$sumBalance += $balance;
} elseif ($balance < 0) {
// negative balance => sink capacity (positive)
$resultGraph->createEdgeDirected($vertex, $superSink)->setCapacity(-$balance);
}
}
// calculate (s*, t*)-flow
$algMaxFlow = new MaxFlowEdmondsKarp($superSource, $superSink);
$flowMax = $algMaxFlow->getFlowMax();
if ($flowMax !== $sumBalance) {
throw new UnexpectedValueException('Network does not support required flow of ' . $sumBalance . ' (maximum possible flow limited to ' . $flowMax . ')');
}
$resultGraph = $algMaxFlow->createGraph();
while (true) {
// create residual graph
$algRG = new ResidualGraph($resultGraph);
$residualGraph = $algRG->createGraph();
// get negative cycle
$alg = new DetectNegativeCycle($residualGraph);
try {
$clonedEdges = $alg->getCycleNegative()->getEdges();
} catch (UnderflowException $ignore) {
// no negative cycle found => end algorithm
break;
}
// calculate maximal possible flow = minimum capacity remaining for all edges
$newFlow = $clonedEdges->getEdgeOrder(Edges::ORDER_CAPACITY_REMAINING)->getCapacityRemaining();
// set flow on original graph
assert($newFlow !== null);
$this->addFlow($resultGraph, $clonedEdges, $newFlow);
}
// destroy temporary supersource and supersink again
$resultGraph->getVertex($superSink->getId())->destroy();
$resultGraph->getVertex($superSource->getId())->destroy();
return $resultGraph;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/MinimumCostFlow/SuccessiveShortestPath.php | src/MinimumCostFlow/SuccessiveShortestPath.php | <?php
namespace Graphp\Algorithms\MinimumCostFlow;
use Graphp\Algorithms\ResidualGraph;
use Graphp\Algorithms\ShortestPath\MooreBellmanFord as SpMooreBellmanFord;
use Graphp\Algorithms\Search\BreadthFirst as SearchBreadthFirst;
use Graphp\Graph\EdgeDirected;
use Graphp\Graph\Exception\UnderflowException;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Graph;
use Graphp\Graph\Set\Edges;
use Graphp\Graph\Vertex;
class SuccessiveShortestPath extends Base
{
/**
* @uses Graph::createGraphClone()
* @uses ResidualGraph::createGraph()
* @uses SpMooreBellmanFord::getEdgesTo(Vertex $targetVertex)
* @see Base::createGraph()
*/
public function createGraph()
{
$this->checkBalance();
$resultGraph = $this->graph->createGraphClone();
// initial balance to 0
$vertices = $resultGraph->getVertices();
foreach ($vertices as $vertex) {
$vertex->setBalance(0);
}
// initial flow of edges
$edges = $resultGraph->getEdges();
foreach ($edges as $edge) {
if (!($edge instanceof EdgeDirected)) {
throw new UnexpectedValueException('Undirected edges are not supported for SuccessiveShortestPath');
}
// 0 if weight of edge is positive
$flow = 0;
// maximal flow if weight of edge is negative
if ($edge->getWeight() < 0) {
$flow = $edge->getCapacity();
$startVertex = $edge->getVertexStart();
$endVertex = $edge->getVertexEnd();
// add balance to start- and end-vertex
$this->addBalance($startVertex, $flow);
$this->addBalance($endVertex, - $flow);
}
$edge->setFlow($flow);
}
// return or Exception inside this while
while (true) {
// create residual graph
$algRG = new ResidualGraph($resultGraph);
$residualGraph = $algRG->createGraph();
// search for a source
try {
$sourceVertex = $this->getVertexSource($residualGraph);
} catch (UnderflowException $ignore) {
// no source is found => minimum-cost flow is found
break;
}
// search for reachable target sink from this source
try {
$targetVertex = $this->getVertexSink($sourceVertex);
} catch (UnderflowException $e) {
// no target found => network does not have enough capacity
throw new UnexpectedValueException('The graph has not enough capacity for the minimum-cost flow', 0, $e);
}
// calculate shortest path between source- and target-vertex
$algSP = new SpMooreBellmanFord($sourceVertex);
$edgesOnFlow = $algSP->getEdgesTo($targetVertex);
// calculate the maximal possible flow
// new flow is the maximal possible flow for this path
$newflow = $this->graph->getVertex($sourceVertex->getId())->getBalance() - $sourceVertex->getBalance();
$targetFlow = - ($this->graph->getVertex($targetVertex->getId())->getBalance() - $targetVertex->getBalance());
// get minimum of source and target
if ($targetFlow < $newflow) {
$newflow = $targetFlow;
}
// get minimum of capacity remaining on path
$minCapacity = $edgesOnFlow->getEdgeOrder(Edges::ORDER_CAPACITY_REMAINING)->getCapacityRemaining();
if ($minCapacity < $newflow) {
$newflow = $minCapacity;
}
// add the new flow to the path
assert($newflow !== null);
$this->addFlow($resultGraph, $edgesOnFlow, $newflow);
// add balance to source and remove for the target sink
$oriSourceVertex = $resultGraph->getVertex($sourceVertex->getId());
$oriTargetVertex = $resultGraph->getVertex($targetVertex->getId());
$this->addBalance($oriSourceVertex, $newflow);
$this->addBalance($oriTargetVertex, - $newflow);
}
return $resultGraph;
}
/**
* @param Graph $graph
* @return Vertex a source vertex in the given graph
* @throws UnderflowException if there is no left source vertex
*/
private function getVertexSource(Graph $graph)
{
foreach ($graph->getVertices()->getMap() as $vid => $vertex) {
if ($this->graph->getVertex($vid)->getBalance() - $vertex->getBalance() > 0) {
return $vertex;
}
}
throw new UnderflowException('No source vertex found in graph');
}
/**
* @param Vertex $source
* @return Vertex a sink-vertex that is reachable from the source
* @throws UnderflowException if there is no reachable sink vertex
* @uses BreadthFirst::getVertices()
*/
private function getVertexSink(Vertex $source)
{
// search for reachable Vertices
$algBFS = new SearchBreadthFirst($source);
foreach ($algBFS->getVertices()->getMap() as $vid => $vertex) {
if ($this->graph->getVertex($vid)->getBalance() - $vertex->getBalance() < 0) {
return $vertex;
}
}
throw new UnderflowException('No sink vertex connected to given source vertex found');
}
private function addBalance(Vertex $vertex, $balance)
{
$vertex->setBalance($vertex->getBalance() + $balance);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/TravelingSalesmanProblem/Base.php | src/TravelingSalesmanProblem/Base.php | <?php
namespace Graphp\Algorithms\TravelingSalesmanProblem;
use Graphp\Algorithms\Base as AlgorithmBase;
use Graphp\Graph\Graph;
use Graphp\Graph\Set\Edges;
use Graphp\Graph\Vertex;
use Graphp\Graph\Walk;
abstract class Base extends AlgorithmBase
{
/**
* get resulting graph with the (first) best circle of edges connecting all vertices
*
* @throws \Exception on error
* @return Graph
* @uses self::getGraph()
* @uses self::getEdges()
* @uses Graph::createGraphCloneEdges()
*/
public function createGraph()
{
return $this->getGraph()->createGraphCloneEdges($this->getEdges());
}
/**
* get graph this algorithm operates on
*
* @return Graph
*/
abstract protected function getGraph();
/**
* get start vertex this algorithm starts on
*
* @return Vertex
*/
abstract protected function getVertexStart();
/**
* get (first) best circle connecting all vertices
*
* @return Walk
* @uses self::getEdges()
* @uses self::getVertexStart()
* @uses Walk::factoryCycleFromEdges()
*/
public function getCycle()
{
return Walk::factoryCycleFromEdges($this->getEdges(), $this->getVertexStart());
}
public function getWeight()
{
$weight = 0;
foreach ($this->getEdges() as $edge) {
$weight += $edge->getWeight();
}
return $weight;
}
/**
* get array of edges connecting all vertices in a circle
*
* @return Edges
*/
abstract public function getEdges();
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.