Skip to content

Commit c7b68d7

Browse files
Add Image class to represent image widgets with validation and creation logic
1 parent 0a308b2 commit c7b68d7

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

src/Widget/Image.php

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?php
2+
3+
namespace PhpGui\Widget;
4+
5+
/**
6+
* Class Image
7+
* Represents an image widget in the GUI.
8+
*
9+
* @package PhpGui\Widget
10+
*/
11+
class Image extends AbstractWidget
12+
{
13+
private $imagePath;
14+
private static $supportedFormats = ['png', 'jpg', 'jpeg', 'gif', 'bmp'];
15+
16+
public function __construct(string $parentId, array $options = [])
17+
{
18+
if (!isset($options['path'])) {
19+
throw new \InvalidArgumentException("Image path is required");
20+
}
21+
22+
$this->imagePath = str_replace('\\', '/', $options['path']);
23+
24+
// Validate file exists
25+
if (!file_exists($this->imagePath)) {
26+
throw new \RuntimeException("Image file not found: {$options['path']}");
27+
}
28+
29+
// Validate file extension
30+
$extension = strtolower(pathinfo($this->imagePath, PATHINFO_EXTENSION));
31+
if (!in_array($extension, self::$supportedFormats)) {
32+
throw new \RuntimeException("Unsupported image format: {$extension}. Supported formats: " . implode(', ', self::$supportedFormats));
33+
}
34+
35+
parent::__construct($parentId, $options);
36+
$this->create();
37+
}
38+
39+
protected function create(): void
40+
{
41+
// Create unique photo image name
42+
$photoName = "photo_" . $this->id;
43+
44+
// Create photo image and load file
45+
$this->tcl->evalTcl("image create photo $photoName -file {$this->imagePath}");
46+
47+
// Create label to display the image with options
48+
$extra = $this->getOptionString();
49+
$this->tcl->evalTcl("label .{$this->parentId}.{$this->id} -image $photoName {$extra}");
50+
}
51+
52+
protected function getOptionString(): string
53+
{
54+
$opts = "";
55+
foreach ($this->options as $key => $value) {
56+
if ($key === 'path') continue;
57+
$opts .= " -$key \"$value\"";
58+
}
59+
return $opts;
60+
}
61+
}

0 commit comments

Comments
 (0)