Skip to content

Commit 0a308b2

Browse files
Refactor Checkbutton class to improve variable management and callback registration
1 parent c7d6c56 commit 0a308b2

File tree

1 file changed

+52
-10
lines changed

1 file changed

+52
-10
lines changed

src/Widget/Checkbutton.php

Lines changed: 52 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,61 @@
11
<?php
2+
23
namespace PhpGui\Widget;
34

4-
class Checkbutton extends AbstractWidget {
5-
protected function create(): void {
5+
use PhpGui\ProcessTCL;
6+
7+
class Checkbutton extends AbstractWidget
8+
{
9+
private $callback;
10+
private $variable;
11+
12+
public function __construct(string $parentId, array $options = [])
13+
{
14+
parent::__construct($parentId, $options);
15+
$this->callback = $options['command'] ?? null;
16+
$this->variable = "cb_var_" . $this->id;
17+
$this->create();
18+
}
19+
20+
protected function create(): void
21+
{
622
$text = $this->options['text'] ?? 'Checkbutton';
7-
$this->tcl->evalTcl("checkbutton .{$this->parentId}.{$this->id} -text \"{$text}\"");
23+
$extra = $this->getOptionString();
24+
25+
// Initialize variable and register callback if provided
26+
$this->tcl->evalTcl("set {$this->variable} 0");
27+
28+
if ($this->callback) {
29+
ProcessTCL::getInstance()->registerCallback($this->id, $this->callback);
30+
$this->tcl->evalTcl("checkbutton .{$this->parentId}.{$this->id} -text \"{$text}\" -variable {$this->variable} -command {php::executeCallback {$this->id}} {$extra}");
31+
} else {
32+
$this->tcl->evalTcl("checkbutton .{$this->parentId}.{$this->id} -text \"{$text}\" -variable {$this->variable} {$extra}");
33+
}
834
}
9-
10-
public function setChecked(bool $state): void {
35+
36+
public function setChecked(bool $state): void
37+
{
1138
$value = $state ? 1 : 0;
12-
$this->tcl->evalTcl("set {$this->id} $value");
39+
$this->tcl->evalTcl("set {$this->variable} $value");
40+
}
41+
42+
public function isChecked(): bool
43+
{
44+
return (bool)$this->tcl->evalTcl("set {$this->variable}");
1345
}
14-
15-
public function isChecked(): bool {
16-
$this->tcl->evalTcl("set _val [set {$this->id}]");
17-
return (bool)$this->tcl->getResult();
46+
47+
public function toggle(): void
48+
{
49+
$this->setChecked(!$this->isChecked());
50+
}
51+
52+
protected function getOptionString(): string
53+
{
54+
$opts = "";
55+
foreach ($this->options as $key => $value) {
56+
if (in_array($key, ['text', 'command'])) continue;
57+
$opts .= " -$key \"$value\"";
58+
}
59+
return $opts;
1860
}
1961
}

0 commit comments

Comments
 (0)