Skip to content

Commit

Permalink
Adds a toggle to allow shape files with no dbf (#41)
Browse files Browse the repository at this point in the history
Adds a toggle to allow shape files with no dbf

Fixes #36
Closes #38
  • Loading branch information
JoolsMcFly authored Dec 8, 2024
1 parent 20cad01 commit a21b619
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 4 deletions.
Binary file modified data/no-dbf.shp
Binary file not shown.
Binary file modified data/no-dbf.shx
Binary file not shown.
26 changes: 22 additions & 4 deletions src/ShapeFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ class ShapeFile
/** @var array */
public $records = [];

/** @var bool */
private $allowNoDbf = false;

/**
* Checks whether dbase manipulations are supported.
*/
Expand Down Expand Up @@ -121,6 +124,11 @@ public function __construct(
$this->fileLength = 50;
}

public function setAllowNoDbf(bool $allowNoDbf): void
{
$this->allowNoDbf = $allowNoDbf;
}

/**
* Loads shapefile and dbase (if supported).
*
Expand Down Expand Up @@ -326,8 +334,16 @@ public function getIndexFromDBFData(string $field, $value): int
*/
private function loadDBFHeader(): array
{
$DBFFile = fopen($this->getFilename('.dbf'), 'r');
if (! self::supportsDbase()) {
return [];
}

$dbfName = $this->getFilename('.dbf');
if (! file_exists($dbfName)) {
return [];
}

$DBFFile = fopen($dbfName, 'r');
$result = [];
$i = 1;
$inHeader = true;
Expand Down Expand Up @@ -405,9 +421,7 @@ private function loadHeaders(): bool
$this->boundingBox['mmin'] = Util::loadData('d', $this->readSHP(8));
$this->boundingBox['mmax'] = Util::loadData('d', $this->readSHP(8));

if (self::supportsDbase()) {
$this->dbfHeader = $this->loadDBFHeader();
}
$this->dbfHeader = $this->loadDBFHeader();

return true;
}
Expand Down Expand Up @@ -620,6 +634,10 @@ private function openDBFFile(): bool

$dbfName = $this->getFilename('.dbf');
if (! is_readable($dbfName)) {
if ($this->allowNoDbf) {
return true;
}

$this->setError(sprintf('It wasn\'t possible to find the DBase file "%s"', $dbfName));

return false;
Expand Down
11 changes: 11 additions & 0 deletions tests/ShapeFileTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -548,4 +548,15 @@ public function testSearch(): void
$shp->getIndexFromDBFData('CNTRY_NAME', 'Czech Republic')
);
}

public function testAllowsNoDbf(): void
{
if (! ShapeFile::supportsDbase()) {
self::markTestSkipped();
}

$shp = new ShapeFile(0);
$shp->setAllowNoDbf(true);
self::assertTrue($shp->loadFromFile('data/no-dbf.*'));
}
}

0 comments on commit a21b619

Please sign in to comment.