Skip to content
This repository was archived by the owner on Feb 6, 2023. It is now read-only.

Commit 9eaf631

Browse files
Add class info helper
1 parent b885d09 commit 9eaf631

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

src/Classes/ProvidesClassInfo.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
namespace SebastiaanLuca\PhpHelpers\Classes;
4+
5+
use ReflectionClass;
6+
7+
Trait ProvidesClassInfo
8+
{
9+
protected $classDirectory;
10+
11+
/**
12+
* Get the directory of the current class.
13+
*
14+
* Uses reflection to get the directory of the child class instead of the parent if applicable.
15+
*
16+
* @return string
17+
*/
18+
protected function getClassDirectory() : string
19+
{
20+
// Some primitive caching
21+
if ($this->classDirectory) {
22+
return $this->classDirectory;
23+
}
24+
25+
$reflection = new ReflectionClass(get_class($this));
26+
27+
$this->classDirectory = dirname($reflection->getFileName());
28+
29+
return $this->classDirectory;
30+
}
31+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
namespace SebastiaanLuca\Helpers\Tests\Unit\Classes;
4+
5+
use ReflectionClass;
6+
use SebastiaanLuca\PhpHelpers\Classes\ProvidesClassInfo;
7+
use SebastiaanLuca\PhpHelpers\Tests\TestCase;
8+
9+
class ProvidesClassInfoTest extends TestCase
10+
{
11+
/**
12+
* @test
13+
*/
14+
public function it returns the class directory() : void
15+
{
16+
$class = new class
17+
{
18+
use ProvidesClassInfo;
19+
20+
public function getDirectory()
21+
{
22+
return $this->getClassDirectory();
23+
}
24+
};
25+
26+
$this->assertSame(
27+
dirname((new ReflectionClass($this))->getFileName()),
28+
$class->getDirectory()
29+
);
30+
}
31+
}

0 commit comments

Comments
 (0)