Skip to content

Commit bbf80fc

Browse files
committed
docs: Updated Example 09
1 parent 80adba0 commit bbf80fc

3 files changed

Lines changed: 352 additions & 0 deletions

File tree

Lines changed: 276 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,276 @@
1+
# File Processing Example
2+
3+
This example demonstrates file processing capabilities in WebFiori CLI, showcasing text file operations, statistics calculation, and content manipulation.
4+
5+
## 🎯 What You'll Learn
6+
7+
- Reading and processing text files
8+
- File content analysis and statistics
9+
- Text transformation operations
10+
- Error handling for file operations
11+
- Command argument validation
12+
- File existence and accessibility checks
13+
14+
## 📁 Files
15+
16+
- `app.php` - Main file processing command implementation
17+
- `sample.txt` - Sample text file for testing
18+
- `README.md` - This documentation
19+
20+
## 🚀 Running the Example
21+
22+
### Basic Usage
23+
```bash
24+
# Process sample file with default action (count)
25+
php app.php process-file --file=sample.txt
26+
27+
# Show help
28+
php app.php help --command=process-file
29+
```
30+
31+
### File Statistics (Count Action)
32+
```bash
33+
# Count lines, words, and characters
34+
php app.php process-file --file=sample.txt --action=count
35+
36+
# Default action is count (can be omitted)
37+
php app.php process-file --file=sample.txt
38+
```
39+
40+
### Text Transformation
41+
```bash
42+
# Convert to uppercase
43+
php app.php process-file --file=sample.txt --action=uppercase
44+
45+
# Reverse line order
46+
php app.php process-file --file=sample.txt --action=reverse
47+
```
48+
49+
## 📋 Available Options
50+
51+
### Actions (`--action`)
52+
- `count` - Display file statistics (lines, words, characters) - **Default**
53+
- `uppercase` - Convert all text to uppercase
54+
- `reverse` - Reverse the order of lines in the file
55+
56+
### Parameters
57+
- `--file` - Path to the file to process (**Required**)
58+
- `--action` - Action to perform (optional, defaults to `count`)
59+
60+
### Validation Rules
61+
- File path is required
62+
- File must exist and be readable
63+
- Action must be one of: count, uppercase, reverse
64+
- Invalid actions show available options
65+
66+
## 🎨 Example Output
67+
68+
### File Statistics (Count Action)
69+
```bash
70+
php app.php process-file --file=sample.txt --action=count
71+
```
72+
```
73+
File Statistics for: sample.txt
74+
Lines: 5
75+
Words: 14
76+
Characters: 82
77+
```
78+
79+
### Uppercase Transformation
80+
```bash
81+
php app.php process-file --file=sample.txt --action=uppercase
82+
```
83+
```
84+
Uppercase content:
85+
HELLO WORLD
86+
THIS IS A SAMPLE FILE
87+
FOR TESTING FILE PROCESSING
88+
WITH MULTIPLE LINES
89+
```
90+
91+
### Line Reversal
92+
```bash
93+
php app.php process-file --file=sample.txt --action=reverse
94+
```
95+
```
96+
Reversed content:
97+
98+
With multiple lines
99+
For testing file processing
100+
This is a sample file
101+
Hello World
102+
```
103+
104+
### Error Handling Examples
105+
106+
#### File Not Found
107+
```bash
108+
php app.php process-file --file=nonexistent.txt --action=count
109+
```
110+
```
111+
Error: File not found: nonexistent.txt
112+
```
113+
114+
#### Missing Required Argument
115+
```bash
116+
php app.php process-file --action=count
117+
```
118+
```
119+
Error: The following required argument(s) are missing: '--file'
120+
```
121+
122+
#### Invalid Action
123+
```bash
124+
php app.php process-file --file=sample.txt --action=invalid
125+
```
126+
```
127+
Error: The following argument(s) have invalid values: '--action'
128+
Info: Allowed values for the argument '--action':
129+
count
130+
uppercase
131+
reverse
132+
```
133+
134+
## 🧪 Test Scenarios
135+
136+
### 1. Basic File Operations
137+
```bash
138+
# Test all actions on sample file
139+
php app.php process-file --file=sample.txt --action=count
140+
php app.php process-file --file=sample.txt --action=uppercase
141+
php app.php process-file --file=sample.txt --action=reverse
142+
```
143+
144+
### 2. Different File Types
145+
```bash
146+
# Create test files
147+
echo -e "Line 1\nLine 2\nLine 3" > test1.txt
148+
echo "Single line file" > test2.txt
149+
touch empty.txt
150+
151+
# Test with different content
152+
php app.php process-file --file=test1.txt --action=count
153+
php app.php process-file --file=test2.txt --action=count
154+
php app.php process-file --file=empty.txt --action=count
155+
```
156+
157+
### 3. Large File Processing
158+
```bash
159+
# Create large file
160+
for i in {1..100}; do echo "Line $i with some content"; done > large.txt
161+
162+
# Process large file
163+
php app.php process-file --file=large.txt --action=count
164+
```
165+
166+
### 4. Error Cases
167+
```bash
168+
# Test error handling
169+
php app.php process-file --file=nonexistent.txt --action=count
170+
php app.php process-file --action=count
171+
php app.php process-file --file=sample.txt --action=invalid
172+
```
173+
174+
### 5. Edge Cases
175+
```bash
176+
# Test with special files
177+
echo " " > spaces.txt # Only spaces
178+
echo -e "\x00\x01\x02" > binary.txt # Binary content
179+
mkdir testdir # Directory instead of file
180+
181+
php app.php process-file --file=spaces.txt --action=count
182+
php app.php process-file --file=binary.txt --action=count
183+
php app.php process-file --file=testdir --action=count # Shows warning
184+
```
185+
186+
## 💡 Key Features Demonstrated
187+
188+
### 1. File Operations
189+
- **File Reading**: Safe file content reading with error handling
190+
- **File Validation**: Check file existence and accessibility
191+
- **Content Processing**: Line-by-line and full content processing
192+
- **Statistics Calculation**: Lines, words, and character counting
193+
194+
### 2. Text Processing
195+
- **Case Conversion**: Transform text to uppercase
196+
- **Line Manipulation**: Reverse line order in files
197+
- **Content Analysis**: Word and character counting
198+
- **Encoding Handling**: Process various text encodings
199+
200+
### 3. Error Handling
201+
- **File Not Found**: Clear error messages for missing files
202+
- **Invalid Arguments**: Validation with helpful suggestions
203+
- **Required Parameters**: Check for mandatory arguments
204+
- **File Access Issues**: Handle permission and directory errors
205+
206+
### 4. User Experience
207+
- **Clear Output**: Well-formatted results with labels
208+
- **Help Integration**: Built-in help command support
209+
- **Validation Messages**: Helpful error messages with suggestions
210+
- **Default Values**: Sensible defaults for optional parameters
211+
212+
## 🔧 Technical Implementation
213+
214+
### Core Functionality
215+
```php
216+
class FileProcessCommand extends Command {
217+
public function __construct() {
218+
parent::__construct('process-file', [
219+
'--file' => [
220+
ArgumentOption::OPTIONAL => false,
221+
ArgumentOption::DESCRIPTION => 'Path to the file to process'
222+
],
223+
'--action' => [
224+
ArgumentOption::OPTIONAL => true,
225+
ArgumentOption::DEFAULT => 'count',
226+
ArgumentOption::VALUES => ['count', 'uppercase', 'reverse'],
227+
ArgumentOption::DESCRIPTION => 'Action to perform'
228+
]
229+
], 'Process text files in various ways');
230+
}
231+
}
232+
```
233+
234+
### File Processing Methods
235+
- `validateFile()`: Check file existence and readability
236+
- `countStatistics()`: Calculate lines, words, characters
237+
- `transformContent()`: Apply text transformations
238+
- `handleErrors()`: Provide meaningful error messages
239+
240+
### Statistics Calculation
241+
- **Lines**: Count newline characters + 1
242+
- **Words**: Split by whitespace and count non-empty elements
243+
- **Characters**: Total byte count including whitespace and newlines
244+
245+
## 🎯 Best Practices Demonstrated
246+
247+
### 1. Input Validation
248+
- Required parameter checking
249+
- File existence validation
250+
- Action value validation with allowed options
251+
- Clear error messages for invalid input
252+
253+
### 2. File Handling
254+
- Safe file reading with error checking
255+
- Proper handling of empty files
256+
- Binary file detection and handling
257+
- Directory vs file differentiation
258+
259+
### 3. User Experience
260+
- Consistent output formatting
261+
- Helpful error messages
262+
- Default parameter values
263+
- Comprehensive help documentation
264+
265+
### 4. Error Recovery
266+
- Graceful handling of missing files
267+
- Clear validation error messages
268+
- Suggestions for valid parameter values
269+
- Non-zero exit codes for errors
270+
271+
## 🔗 Related Examples
272+
273+
- **[03-user-input](../03-user-input/)** - Input validation and handling
274+
- **[04-output-formatting](../04-output-formatting/)** - Text formatting and colors
275+
- **[07-progress-bars](../07-progress-bars/)** - Progress tracking for file operations
276+
- **[10-multi-command-app](../10-multi-command-app/)** - Complete CLI applications
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
<?php
2+
require_once '../../vendor/autoload.php';
3+
4+
use WebFiori\Cli\ArgumentOption;
5+
use WebFiori\Cli\Command;
6+
use WebFiori\Cli\Runner;
7+
8+
class FileProcessCommand extends Command {
9+
public function __construct() {
10+
parent::__construct('process-file', [
11+
'--file' => [
12+
ArgumentOption::OPTIONAL => false,
13+
ArgumentOption::DESCRIPTION => 'Path to the file to process'
14+
],
15+
'--action' => [
16+
ArgumentOption::OPTIONAL => true,
17+
ArgumentOption::DEFAULT => 'count',
18+
ArgumentOption::VALUES => ['count', 'uppercase', 'reverse'],
19+
ArgumentOption::DESCRIPTION => 'Action to perform (count, uppercase, reverse)'
20+
]
21+
], 'Process text files in various ways');
22+
}
23+
24+
public function exec(): int {
25+
$filePath = $this->getArgValue('--file');
26+
$action = $this->getArgValue('--action');
27+
28+
if (!file_exists($filePath)) {
29+
$this->error("File not found: $filePath");
30+
return 1;
31+
}
32+
33+
if (!is_readable($filePath)) {
34+
$this->error("File is not readable: $filePath");
35+
return 1;
36+
}
37+
38+
$content = file_get_contents($filePath);
39+
40+
switch ($action) {
41+
case 'count':
42+
$lines = substr_count($content, "\n") + 1;
43+
$words = str_word_count($content);
44+
$chars = strlen($content);
45+
46+
$this->println("File Statistics for: %s", $filePath);
47+
$this->println("Lines: %d", $lines);
48+
$this->println("Words: %d", $words);
49+
$this->println("Characters: %d", $chars);
50+
break;
51+
52+
case 'uppercase':
53+
$result = strtoupper($content);
54+
$this->println("Uppercase content:");
55+
$this->println($result);
56+
break;
57+
58+
case 'reverse':
59+
$lines = explode("\n", $content);
60+
$reversed = array_reverse($lines);
61+
$this->println("Reversed content:");
62+
$this->println(implode("\n", $reversed));
63+
break;
64+
}
65+
66+
return 0;
67+
}
68+
}
69+
70+
$runner = new Runner();
71+
$runner->register(new FileProcessCommand());
72+
exit($runner->start());
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Hello World
2+
This is a sample file
3+
For testing file processing
4+
With multiple lines

0 commit comments

Comments
 (0)