Skip to content

Commit 1a171a3

Browse files
added View Class and more Collection methods
1 parent 63f1233 commit 1a171a3

File tree

10 files changed

+964
-40
lines changed

10 files changed

+964
-40
lines changed

Collections/Collection.php

Lines changed: 461 additions & 31 deletions
Large diffs are not rendered by default.

Collections/CollectionTrait.php

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tamedevelopers\Support\Collections;
6+
7+
use Traversable;
8+
use JsonSerializable;
9+
use Tamedevelopers\Support\Str;
10+
use Tamedevelopers\Support\Server;
11+
use Tamedevelopers\Database\Collections\Collection as DBCollection;
12+
13+
14+
trait CollectionTrait{
15+
16+
/**
17+
* Convert data to array
18+
*
19+
* @return array
20+
*/
21+
public function toArray()
22+
{
23+
return Server::toArray($this->items);
24+
}
25+
26+
/**
27+
* Convert data to object
28+
*
29+
* @return object
30+
*/
31+
public function toObject()
32+
{
33+
return Server::toObject($this->items);
34+
}
35+
36+
/**
37+
* Convert data to json
38+
*
39+
* @return string
40+
*/
41+
public function toJson()
42+
{
43+
return Server::toJson($this->items);
44+
}
45+
46+
/**
47+
* Results array of items from Collection or Arrayable.
48+
*
49+
* @param mixed $items
50+
* @return array
51+
*/
52+
private function getArrayableItems($items)
53+
{
54+
if (is_array($items)) {
55+
return $items;
56+
}
57+
58+
return match (true) {
59+
$items instanceof Traversable => iterator_to_array($items),
60+
$items instanceof JsonSerializable => $items->jsonSerialize(),
61+
$items instanceof DBCollection => $items->toArray(),
62+
default => (array) $items,
63+
};
64+
}
65+
66+
}

Str.php

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ static public function wrap($value)
3131
*/
3232
static public function head($array = null)
3333
{
34-
return isset($array[0]) ? $array[0] : null;
34+
return reset($array);
3535
}
3636

3737
/**
@@ -253,14 +253,10 @@ static public function bindings(array $bindings)
253253
static public function flattenValue(array $array)
254254
{
255255
$result = [];
256-
257-
foreach ($array as $value) {
258-
if (is_array($value)) {
259-
$result = array_merge($result, self::flattenValue($value));
260-
} else {
261-
$result[] = $value;
262-
}
263-
}
256+
257+
array_walk_recursive($array, function ($item) use (&$result) {
258+
$result[] = $item;
259+
});
264260

265261
return $result;
266262
}

Tests/collection.php

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
<?php
2+
3+
use Tamedevelopers\Support\Collections\Collection;
4+
5+
require_once __DIR__ . '/../vendor/autoload.php';
6+
7+
8+
9+
$data = [
10+
['id' => 1, 'name' => 'John', 'age' => 28],
11+
['id' => 2, 'name' => 'Jane', 'age' => 22],
12+
['id' => 3, 'name' => 'Doe', 'age' => 31],
13+
['id' => 4, 'name' => 'Smith', 'age' => 29],
14+
['id' => 5, 'name' => 'Emily', 'age' => 25],
15+
];
16+
17+
18+
19+
// Create a new collection instance
20+
$collection = TameCollect($data);
21+
22+
// getIterator()
23+
$iterator = $collection->getIterator();
24+
foreach ($iterator as $item) {
25+
// Process each item
26+
}
27+
28+
29+
// has()
30+
$hasId2 = $collection->has(1); // true
31+
32+
// count()
33+
$count = $collection->count(); // 5
34+
35+
// all()
36+
$allItems = $collection->all(); // All items in the collection
37+
38+
// first()
39+
$firstItem = $collection->first(); // ['id' => 1, 'name' => 'John', 'age' => 28]
40+
41+
// last()
42+
$lastItem = $collection->last(); // ['id' => 5, 'name' => 'Emily', 'age' => 25]
43+
44+
// isNotEmpty()
45+
$isNotEmpty = $collection->isNotEmpty(); // true
46+
47+
// isEmpty()
48+
$isEmpty = $collection->isEmpty(); // false
49+
50+
// filter()
51+
$filtered = $collection->filter(fn($item) => $item['age'] > 25); // Filter items with age > 25
52+
53+
// map()
54+
$mapped = $collection->map(fn($item) => $item['name']); // ['John', 'Jane', 'Doe', 'Smith', 'Emily']
55+
56+
// reduce()
57+
$sumAge = $collection->reduce(fn($carry, $item) => $carry + $item['age'], 0); // Sum of ages
58+
59+
// reverse()
60+
$reversed = $collection->reverse(); // Reverse the collection
61+
62+
// pad()
63+
$padded = $collection->pad(7, ['id' => 0, 'name' => 'Unknown', 'age' => 0]); // Pad with default values
64+
65+
// combine()
66+
$keys = ['first', 'second', 'third', 'fourth', 'fifth'];
67+
$combined = $collection->combine($keys); // Combine with new keys
68+
69+
// collapse()
70+
$multiDimensional = new Collection([
71+
['a' => 1, 'b' => 2],
72+
['c' => 3, 'd' => 4],
73+
]);
74+
$collapsed = $multiDimensional->collapse(); // Flatten nested collections
75+
76+
// flatten()
77+
$nested = new Collection([
78+
[1, 2], [3, 4], [5, 6], ['Peterson', 39, ['name' => 'Fredrick']]
79+
]);
80+
dump(
81+
$nested->flatten(),
82+
// [1, 2, 3, 4, 5, 6, 'Peterson', 39, 'Fredrick']
83+
);
84+
85+
// zip()
86+
$additionalArray = [10, 20, 30, 40, 50];
87+
dump(
88+
$collection->zip($additionalArray)
89+
// Combine items with another array
90+
);
91+
92+
// merge()
93+
dump(
94+
$collection->merge([['id' => 6, 'name' => 'Sarah', 'age' => 30]])
95+
);
96+
97+
// chunk()
98+
$chunked = $collection->chunk(2); // Split into chunks of size 2
99+
100+
// keys()
101+
$keys = $collection->keys(); // ['id', 'name', 'age']
102+
103+
// values()
104+
$values = $collection->values(); // [1, 2, 3, 4, 5]
105+
106+
// contains()
107+
$containsAge28 = $collection->contains(['age' => 28]); // true
108+
109+
// doesntContain()
110+
$doesNotContain = $collection->doesntContain('name', 'John'); // false
111+
112+
// pluck()
113+
dump(
114+
$collection->pluck('name', 'age')
115+
// ['John', 'Jane', 'Doe', 'Smith', 'Emily']
116+
);
117+
118+
// select()
119+
dump(
120+
$collection->select(['name', 'age'])->pluck('age')
121+
);
122+
123+
// search()
124+
dump(
125+
$collection->search('Jane')
126+
// 1
127+
);
128+
129+
// sort()
130+
$sortedByName = $collection->sort(); // Sort by values (default sorting)
131+
132+
// sortBy()
133+
$sortedByAge = $collection->sortBy('age'); // Sort by age
134+
135+
// sortByMany()
136+
dump(
137+
$collection->sortByMany(['age' => SORT_DESC, 'name' => SORT_ASC])
138+
// Sort by age descending, then name ascending
139+
);
140+
141+
// unique()
142+
dump(
143+
$collection->unique()
144+
// Get unique items
145+
);

Tests/layout/home.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<title>@yield('title')</title>
5+
</head>
6+
<body>
7+
@include('partials.navbar')
8+
9+
<main>
10+
@yield('content')
11+
</main>
12+
13+
@include('partials.footer')
14+
</body>
15+
</html>

Tests/layout/if.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
2+
<!DOCTYPE html>
3+
<html lang="en">
4+
<head>
5+
<meta charset="UTF-8">
6+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7+
<title>Document</title>
8+
</head>
9+
<body>
10+
@if ($condition)
11+
Condition is {{ $condition }}
12+
@else
13+
Condition `Else` is {{ $condition }}
14+
@endif
15+
16+
<br>
17+
{{ $name }}
18+
</body>
19+
</html>
20+
21+
22+

Tests/view.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
4+
5+
require_once __DIR__ . '/../vendor/autoload.php';
6+
7+
8+
$data = tview('tests.layout.if', [
9+
'name' => 'Peterson',
10+
'condition' => true,
11+
]);
12+
13+
// echo $data;
14+
15+
16+
dd(
17+
$data->render()
18+
);

Traits/SharedDataTrait.php

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tamedevelopers\Support\Traits;
6+
7+
8+
trait SharedDataTrait
9+
{
10+
11+
/**
12+
* Global shared data for all views.
13+
*
14+
* @var array
15+
*/
16+
protected static $sharedData = [];
17+
18+
19+
/**
20+
* Share data globally across all views.
21+
*
22+
* @param string $key The key for the data.
23+
* @param mixed $value The value to be shared.
24+
* @return void
25+
*/
26+
public static function share($key, $value)
27+
{
28+
self::$sharedData[$key] = $value;
29+
}
30+
31+
/**
32+
* Get all shared data.
33+
*
34+
* @return array
35+
*/
36+
public static function getSharedData()
37+
{
38+
return self::$sharedData;
39+
}
40+
41+
/**
42+
* Parse Directives
43+
*
44+
* @param mixed $content
45+
* @return void
46+
*/
47+
protected function parseDirectives($content)
48+
{
49+
// Parse @if, @elseif, @else, @endif
50+
$content = preg_replace('/@if\s*\((.+?)\)/', '<?php if ($1): ?>', $content);
51+
$content = preg_replace('/@elseif\s*\((.+?)\)/', '<?php elseif ($1): ?>', $content);
52+
$content = str_replace('@else', '<?php else: ?>', $content);
53+
$content = str_replace('@endif', '<?php endif; ?>', $content);
54+
55+
// Parse @foreach, @endforeach
56+
$content = preg_replace('/@foreach\s*\((.+?)\)/', '<?php foreach ($1): ?>', $content);
57+
$content = str_replace('@endforeach', '<?php endforeach; ?>', $content);
58+
59+
// Parse @for, @endfor
60+
$content = preg_replace('/@for\s*\((.+?)\)/', '<?php for ($1): ?>', $content);
61+
$content = str_replace('@endfor', '<?php endfor; ?>', $content);
62+
63+
// Parse @while, @endwhile
64+
$content = preg_replace('/@while\s*\((.+?)\)/', '<?php while ($1): ?>', $content);
65+
$content = str_replace('@endwhile', '<?php endwhile; ?>', $content);
66+
67+
// Parse @include
68+
$content = preg_replace_callback('/@include\s*\((.+?)\)/', function ($matches) {
69+
$view = trim($matches[1], '\'"');
70+
return "<?php echo (new self('$view', get_defined_vars()))->render(); ?>";
71+
}, $content);
72+
73+
// Parse @yield
74+
$content = preg_replace('/@yield\s*\((.+?)\)/', '<?php echo $this->yieldSection($1); ?>', $content);
75+
76+
// Parse @section and @endsection
77+
$content = preg_replace('/@section\s*\((.+?)\)/', '<?php $this->startSection($1); ?>', $content);
78+
$content = str_replace('@endsection', '<?php $this->endSection(); ?>', $content);
79+
80+
// Parse raw PHP blocks: @php and @endphp
81+
$content = str_replace('@php', '<?php', $content);
82+
$content = str_replace('@endphp', '?>', $content);
83+
84+
// Parse escaped output: {{ $variable }}
85+
$content = preg_replace('/\{\{\s*(.+?)\s*\}\}/', '<?php echo htmlspecialchars($1, ENT_QUOTES, \'UTF-8\'); ?>', $content);
86+
87+
// Parse unescaped output: {!! $variable !!}
88+
$content = preg_replace('/\{!!\s*(.+?)\s*!!\}/', '<?php echo $1; ?>', $content);
89+
90+
return $content;
91+
}
92+
93+
}

0 commit comments

Comments
 (0)