Skip to content
Merged

Docs #122

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2020 WebFiori Framework
Copyright (c) 2020-present WebFiori Framework

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
4 changes: 2 additions & 2 deletions WebFiori/Database/Attributes/AttributeTableBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public static function build(string $entityClass, string $dbType = 'mysql'): Tab

$tableAttr = $reflection->getAttributes(Table::class)[0] ?? null;
if (!$tableAttr) {
throw new \RuntimeException("Class $entityClass must have #[Table] attribute");
throw new InvalidAttributeException("Class $entityClass must have #[Table] attribute");
}

$tableConfig = $tableAttr->newInstance();
Expand All @@ -25,7 +25,7 @@ public static function build(string $entityClass, string $dbType = 'mysql'): Tab
if (!empty($classColumnAttrs)) {
foreach ($classColumnAttrs as $columnAttr) {
$columnConfig = $columnAttr->newInstance();
$columnKey = $columnConfig->name ?? throw new \RuntimeException("Column name is required for class-level attributes");
$columnKey = $columnConfig->name ?? throw new InvalidAttributeException("Column name is required for class-level attributes");
$columns[$columnKey] = self::columnConfigToArray($columnConfig);
}

Expand Down
3 changes: 1 addition & 2 deletions WebFiori/Database/Attributes/ForeignKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
namespace WebFiori\Database\Attributes;

use Attribute;
use InvalidArgumentException;

#[Attribute(Attribute::TARGET_PROPERTY | Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
class ForeignKey {
Expand All @@ -15,7 +14,7 @@ public function __construct(
public string $onDelete = 'set null'
) {
if ($column !== null && !empty($columns)) {
throw new InvalidArgumentException(
throw new InvalidAttributeException(
"ForeignKey: Use either 'column' or 'columns', not both"
);
}
Expand Down
8 changes: 8 additions & 0 deletions WebFiori/Database/Attributes/InvalidAttributeException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php
namespace WebFiori\Database\Attributes;

/**
* Exception thrown when PHP 8 attributes are invalid or misconfigured.
*/
class InvalidAttributeException extends \Exception {
}
54 changes: 16 additions & 38 deletions WebFiori/Database/Entity/EntityGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,52 +143,30 @@ private function buildGetters(): string {
* @return string The default value as PHP code
*/
private function getDefault(Column $col): string {
if ($col->isAutoInc()) {
if ($col->isAutoInc() || $col->isNull()) {
return ' = null';
}

if ($col->isNull()) {
return ' = null';
}

$default = $col->getDefault();

if ($default !== null) {
$phpType = $col->getPHPType();

if ($phpType === 'string') {
return " = '".addslashes($default)."'";
}

if ($phpType === 'int' || $phpType === 'float') {
return " = {$default}";
}

if ($phpType === 'bool') {
return $default ? ' = true' : ' = false';
}
}

// Required field with no default
$phpType = $col->getPHPType();
$default = $col->getDefault();

if ($phpType === 'string') {
return " = ''";
}

if ($phpType === 'int') {
return ' = 0';
}

if ($phpType === 'float') {
return ' = 0.0';
}
$typeDefaults = [
'string' => " = ''",
'int' => ' = 0',
'float' => ' = 0.0',
'bool' => ' = false'
];

if ($phpType === 'bool') {
return ' = false';
if ($default !== null) {
return match ($phpType) {
'string' => " = '" . addslashes($default) . "'",
'int', 'float' => " = {$default}",
'bool' => $default ? ' = true' : ' = false',
default => ''
};
}

return '';
return $typeDefaults[$phpType] ?? '';
}

/**
Expand Down
7 changes: 2 additions & 5 deletions WebFiori/Database/Entity/RecordMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,8 @@ public function map(array $record) {
foreach ($this->getSettersMap() as $method => $colsNames) {
if (is_callable([$instance, $method])) {
foreach ($colsNames as $colName) {
try {
if (isset($record[$colName])) {
$instance->$method($record[$colName]);
}
} catch (\Throwable $ex) {
if (isset($record[$colName])) {
$instance->$method($record[$colName]);
}
}
}
Expand Down
15 changes: 7 additions & 8 deletions WebFiori/Database/Query/InsertBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,17 +206,16 @@ private function build() {
}
private function buildColsArr() {
$colsArr = [];
$colsStr = '';
$table = $this->getTable();
$tableObj = $this->getTable();

foreach ($this->cols as $colKey) {
$colObj = $table->getColByKey($colKey);
$colObj = $tableObj->getColByKey($colKey);

if ($colObj === null) {
$table->addColumns([
$tableObj->addColumns([
$colKey => []
]);
$colObj = $table->getColByKey($colKey);
$colObj = $tableObj->getColByKey($colKey);
}
$colObj->setWithTablePrefix(false);
$colsArr[] = $colObj->getName();
Expand Down Expand Up @@ -266,7 +265,7 @@ private function initValsArr() {
$colsAndVals = $this->data;

if (isset($colsAndVals['cols']) && isset($colsAndVals['values'])) {
$cols = $colsAndVals['cols'];
$colsArr = $colsAndVals['cols'];
$tempVals = $colsAndVals['values'];
$temp = [];
$topIndex = 0;
Expand All @@ -275,14 +274,14 @@ private function initValsArr() {
$index = 0;
$temp[] = [];

foreach ($cols as $colKey) {
foreach ($colsArr as $colKey) {
$temp[$topIndex][$colKey] = $valsArr[$index];
$index++;
}
$topIndex++;
}
$this->vals = $temp;
$this->cols = $cols;
$this->cols = $colsArr;
} else {
$this->cols = array_keys($colsAndVals);
$this->vals = [$colsAndVals];
Expand Down
6 changes: 3 additions & 3 deletions WebFiori/Database/Repository/AbstractRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public function deleteAll(): void {
public function deleteById(mixed $id = null): void {
$id = $id ?? $this->getEntityId();
if ($id === null) {
throw new \InvalidArgumentException('Cannot delete: no ID provided');
throw new RepositoryException('Cannot delete: no ID provided');
}
$this->db->table($this->getTableName())
->delete()
Expand Down Expand Up @@ -94,7 +94,7 @@ public function findAll(): array {
public function findById(mixed $id = null): ?object {
$id = $id ?? $this->getEntityId();
if ($id === null) {
throw new \InvalidArgumentException('Cannot find: no ID provided');
throw new RepositoryException('Cannot find: no ID provided');
}
$result = $this->db->table($this->getTableName())
->select()
Expand Down Expand Up @@ -225,7 +225,7 @@ public function paginateByCursor(
*/
public function save(?object $entity = null): void {
if ($entity === null && !property_exists($this, $this->getIdField())) {
throw new \InvalidArgumentException('Cannot save: no entity provided');
throw new RepositoryException('Cannot save: no entity provided');
}
$entity = $entity ?? $this;
$data = $this->toArray($entity);
Expand Down
8 changes: 8 additions & 0 deletions WebFiori/Database/Repository/RepositoryException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php
namespace WebFiori\Database\Repository;

/**
* Exception thrown for repository operation errors.
*/
class RepositoryException extends \Exception {
}
4 changes: 3 additions & 1 deletion WebFiori/Database/Schema/DatabaseChangeGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
*/
namespace WebFiori\Database\Schema;

use WebFiori\Database\DatabaseException;

/**
* Generator for creating migration and seeder class files.
*
Expand Down Expand Up @@ -235,7 +237,7 @@ private function formatStringArray(array $items): string {

private function writeFile(string $name, string $content): string {
if (empty($this->path)) {
throw new \RuntimeException('Path not set. Call setPath() first.');
throw new DatabaseException('Path not set. Call setPath() first.');
}

if (!is_dir($this->path)) {
Expand Down
8 changes: 8 additions & 0 deletions WebFiori/Database/Schema/SchemaException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php
namespace WebFiori\Database\Schema;

/**
* Exception thrown for schema-related errors (migrations, seeders, schema operations).
*/
class SchemaException extends \Exception {
}
4 changes: 2 additions & 2 deletions WebFiori/Database/Schema/SchemaRunner.php
Original file line number Diff line number Diff line change
Expand Up @@ -425,11 +425,11 @@ public function register(DatabaseChange|string $change): bool {

if (is_string($change)) {
if (!class_exists($change)) {
throw new Exception("Class does not exist: {$change}");
throw new SchemaException("Class does not exist: {$change}");
}

if (!is_subclass_of($change, DatabaseChange::class)) {
throw new Exception("Class is not a subclass of DatabaseChange: {$change}");
throw new SchemaException("Class is not a subclass of DatabaseChange: {$change}");
}

$change = new $change();
Expand Down
24 changes: 12 additions & 12 deletions sonar-project.properties
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
sonar.projectKey=WebFiori_database
sonar.organization=webfiori
sonar.projectName=database
sonar.projectVersion=1.0
sonar.exclusions=tests/**
sonar.coverage.exclusions=tests/**
sonar.php.coverage.reportPaths=clover.xml
# Encoding of the source code. Default is default system encoding
sonar.sourceEncoding=UTF-8
sonar.projectKey=WebFiori_database
sonar.organization=webfiori

sonar.projectName=database
sonar.projectVersion=1.0

sonar.exclusions=tests/**,examples/**
sonar.coverage.exclusions=tests/**,examples/**

sonar.php.coverage.reportPaths=clover.xml
# Encoding of the source code. Default is default system encoding
sonar.sourceEncoding=UTF-8
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

namespace WebFiori\Tests\Database\Attributes;

use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use WebFiori\Database\Attributes\AttributeTableBuilder;
use WebFiori\Database\Attributes\Column;
use WebFiori\Database\Attributes\ForeignKey;
use WebFiori\Database\Attributes\InvalidAttributeException;
use WebFiori\Database\Attributes\Table;
use WebFiori\Database\DataType;

Expand Down Expand Up @@ -63,7 +63,7 @@ public function testMultipleColumnsFK() {
}

public function testBothColumnAndColumnsThrowsException() {
$this->expectException(InvalidArgumentException::class);
$this->expectException(InvalidAttributeException::class);
$this->expectExceptionMessage("ForeignKey: Use either 'column' or 'columns', not both");

new ForeignKey(table: 'users', column: 'id', columns: ['local_id' => 'id']);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use WebFiori\Database\ColOption;
use WebFiori\Database\DataType;
use WebFiori\Database\Repository\AbstractRepository;
use WebFiori\Database\Repository\RepositoryException;

class TestEntity {
public ?int $id = null;
Expand Down Expand Up @@ -176,14 +177,14 @@ public function testSaveAllMixed() {
}

public function testFindByIdWithNullThrowsException() {
$this->expectException(\InvalidArgumentException::class);
$this->expectException(RepositoryException::class);
$this->expectExceptionMessage('Cannot find: no ID provided');

self::$repo->findById(null);
}

public function testDeleteByIdWithNullThrowsException() {
$this->expectException(\InvalidArgumentException::class);
$this->expectException(RepositoryException::class);
$this->expectExceptionMessage('Cannot delete: no ID provided');

self::$repo->deleteById(null);
Expand Down Expand Up @@ -211,7 +212,7 @@ public function testDeleteByIdWithValidId() {
}

public function testSaveWithNullOnPureRepoThrowsException() {
$this->expectException(\InvalidArgumentException::class);
$this->expectException(RepositoryException::class);
$this->expectExceptionMessage('Cannot save: no entity provided');

self::$repo->save();
Expand All @@ -234,7 +235,7 @@ public function testReloadWithEntity() {
}

public function testReloadWithNullOnPureRepoThrowsException() {
$this->expectException(\InvalidArgumentException::class);
$this->expectException(RepositoryException::class);
$this->expectExceptionMessage('Cannot find: no ID provided');

self::$repo->reload();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ public function testCreateWithoutNamespace() {
public function testCreateWithoutPathThrows() {
$generator = new DatabaseChangeGenerator();

$this->expectException(\RuntimeException::class);
$this->expectException(\WebFiori\Database\DatabaseException::class);
$this->expectExceptionMessage('Path not set');

$generator->createMigration('CreateUsersTable');
Expand Down