### Install phpstan/phpdoc-parser
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/phpstan/phpdoc-parser/README.md
Install the library using Composer.
```bash
composer require phpstan/phpdoc-parser
```
--------------------------------
### Install CodeMirror 5 via npm
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/App/assets/vendor/codemirror/README.md
Use this command to install CodeMirror 5 if you have Node.js installed. This is the recommended way to get the library.
```bash
npm install codemirror@5
```
--------------------------------
### Install Library with Composer
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/jumbojett/openid-connect-php/README.md
Use Composer to install the library. Ensure you include the autoloader in your project.
```bash
composer require jumbojett/openid-connect-php
```
```php
require __DIR__ . '/vendor/autoload.php';
```
--------------------------------
### Install getallheaders for PHP >= 5.6
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/ralouphie/getallheaders/README.md
Use this command to install the library for PHP versions 5.6 and newer.
```bash
composer require ralouphie/getallheaders
```
--------------------------------
### Options Array Examples
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/claviska/simpleimage/README.md
Examples of using the options array for various mime types.
```APIDOC
```php
$image->toFile($file, 'image/avif', [
// JPG, WEBP, AVIF (default 100)
'quality' => 100,
// AVIF (default -1 which is 6)
// range of slow and small file 0 to 10 fast but big file
'speed' => -1,
]);
```
```
```APIDOC
```php
$image->toFile($file, 'image/bmp', [
// BMP: boolean (default true)
'compression' => true,
// BMP, JPG (default null, keep the same)
'interlace' => null,
]);
```
```
```APIDOC
```php
$image->toFile($file, 'image/gif', [
// GIF, PNG (default true)
'alpha' => true,
]);
```
```
```APIDOC
```php
$image->toFile($file, 'image/jpeg', [
// BMP, JPG (default null, keep the same)
'interlace' => null,
// JPG, WEBP, AVIF (default 100)
'quality' => 100,
]);
```
```
```APIDOC
```php
$image->toFile($file, 'image/png', [
// GIF, PNG (default true)
'alpha' => true,
// PNG: 0-10, defaults to zlib (default 6)
'compression' => -1,
// PNG (default -1)
'filters' => -1,
// has no effect on PNG images, since the format is lossless
// 'quality' => 100,
]);
```
```
```APIDOC
```php
$image->toFile($file, 'image/webp', [
// JPG, WEBP, AVIF (default 100)
'quality' => 100,
]);
```
```
--------------------------------
### Install JSON5 for PHP via Composer
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/colinodell/json5/README.md
Use Composer to install the colinodell/json5 package.
```bash
$ composer require colinodell/json5
```
--------------------------------
### Install sodium_compat with Composer (Optional)
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/firebase/php-jwt/README.md
If your PHP environment lacks libsodium, install the `paragonie/sodium_compat` package.
```bash
composer require paragonie/sodium_compat
```
--------------------------------
### Build and Run CodeMirror 5 Project
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/App/assets/vendor/codemirror/README.md
After installing Node.js, run 'npm install' to set up the project. Open 'index.html' in your browser to view the editor. Run tests with 'npm test'.
```bash
npm install
```
```bash
npm test
```
--------------------------------
### Basic ZipStream PHP Usage Example
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/maennchen/zipstream-php/guides/index.rst
A simple example demonstrating how to create a zip stream, add files from string, path, and stream resources, and finish the stream.
```php
// Autoload the dependencies
require 'vendor/autoload.php';
// create a new zipstream object
$zip = new ZipStream\ZipStream(
outputName: 'example.zip',
// enable output of HTTP headers
sendHttpHeaders: true,
);
// create a file named 'hello.txt'
$zip->addFile(
fileName: 'hello.txt',
data: 'This is the contents of hello.txt',
);
// add a file named 'some_image.jpg' from a local file 'path/to/image.jpg'
$zip->addFileFromPath(
fileName: 'some_image.jpg',
path: 'path/to/image.jpg',
);
// add a file named 'goodbye.txt' from an open stream resource
$filePointer = tmpfile();
fwrite($filePointer, 'The quick brown fox jumped over the lazy dog.');
rewind($filePointer);
$zip->addFileFromStream(
fileName: 'goodbye.txt',
stream: $filePointer,
);
fclose($filePointer);
// add a file named 'streamfile.txt' from the body of a `guzzle` response
// Setup with `psr/http-message` & `guzzlehttp/psr7` dependencies required.
$zip->addFileFromPsr7Stream(
fileName: 'streamfile.txt',
stream: $response->getBody(),
);
// finish the zip stream
$zip->finish();
```
--------------------------------
### Install with Composer
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/paragonie/constant_time_encoding/README.md
Use Composer to add the library as a project dependency.
```sh
composer require paragonie/constant_time_encoding
```
--------------------------------
### Install getallheaders for PHP < 5.6
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/ralouphie/getallheaders/README.md
Use this command to install version 2 of the library for PHP versions older than 5.6.
```bash
composer require ralouphie/getallheaders "^2"
```
--------------------------------
### Install PSR7 and GuzzleHTTP Dependencies
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/maennchen/zipstream-php/guides/index.rst
Install these dependencies if you plan to use `addFileFromPsr7Stream` or stream output.
```sh
composer require psr/http-message guzzlehttp/psr7
```
--------------------------------
### Run Dev Server for Local Documentation Development
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/zircote/swagger-php/CONTRIBUTING.md
Start a local development server to preview the documentation website.
```shell
composer docs:dev
```
--------------------------------
### Install doctrine/annotations (Optional)
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/zircote/swagger-php/README.md
If your project uses Doctrine annotations, install the library manually as it is no longer a default dependency.
```shell
composer require doctrine/annotations
```
--------------------------------
### Install SimpleImage using Composer
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/claviska/simpleimage/README.md
Installs the SimpleImage library using Composer, the standard dependency manager for PHP.
```bash
composer require claviska/simpleimage
```
--------------------------------
### Install swagger-php Globally
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/zircote/swagger-php/README.md
Install swagger-php globally for CLI usage and ensure the vendor bin directory is in your PATH.
```shell
composer global require zircote/swagger-php
```
--------------------------------
### Install Guzzle Promises
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/guzzlehttp/promises/README.md
Use Composer to install the Guzzle Promises library.
```shell
composer require guzzlehttp/promises
```
--------------------------------
### Install type-info-extras for PHP 8.2+
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/zircote/swagger-php/README.md
Install the optional radebatz/type-info-extras package for improved type resolution on PHP 8.2 and higher.
```shell
composer require radebatz/type-info-extras
```
--------------------------------
### Install Development Dependencies
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/phpseclib/phpseclib/README.md
Install the necessary development dependencies using Composer, which is required for contributing to the phpseclib project.
```sh
composer install
```
--------------------------------
### REST API File-based Routing Example
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/App/README.md
Example of a dynamic REST API route file for fetching a user by ID. Accesses parameters via $API_ARGS and uses the app instance context.
```php
// config/api/users/[id].php
$this->dataStorage->findOne('users', ['_id' => $userId])
];
```
--------------------------------
### Install ColorExtractor via Composer
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/league/color-extractor/README.md
Use Composer to install the ColorExtractor library, specifying version 0.4.*.
```bash
$ composer require league/color-extractor:0.4.*
```
--------------------------------
### Session Configuration Example
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/App/README.md
Configures session name and lifetime in minutes. The session lifetime is set in seconds.
```php
// config/config.php
return [
'session.name' => 'cockpit-session',
'session.lifetime' => 5400, // 90 minutes
];
```
--------------------------------
### SCSS Example
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/App/assets/vendor/codemirror/mode/css/scss.html
This snippet demonstrates various SCSS features like variables, nesting, mixins, and extends.
```scss
/* Some example SCSS */ @import "compass/css3"; $variable: #333; $blue: #3bbfce; $margin: 16px; .content-navigation { #nested { background-color: black; } border-color: $blue; color: darken($blue, 9%); } .border { padding: $margin / 2; margin: $margin / 2; border-color: $blue; } @mixin table-base { th { text-align: center; font-weight: bold; } td, th {padding: 2px} } table.hl { margin: 2em 0; td.ln { text-align: right; } } li { font: { family: serif; weight: bold; size: 1.2em; } } @mixin left($dist) { float: left; margin-left: $dist; } #data { @include left(10px); @include table-base; } .source { @include flow-into(target); border: 10px solid green; margin: 20px; width: 200px; } .new-container { @include flow-from(target); border: 10px solid red; margin: 20px; width: 200px; } body { margin: 0; padding: 3em 6em; font-family: tahoma, arial, sans-serif; color: #000; } @mixin yellow() { background: yellow; } .big { font-size: 14px; } .nested { @include border-radius(3px); @extend .big; p { background: whitesmoke; a { color: red; } } } #navigation a { font-weight: bold; text-decoration: none !important; } h1 { font-size: 2.5em; } h2 { font-size: 1.7em; } h1:before, h2:before { content: "::"; }
```
--------------------------------
### PHP Development Server Command
Source: https://github.com/cockpit-hq/cockpit/blob/develop/AGENTS.md
Starts the PHP development server. Access the application at localhost:8080.
```bash
composer serve # Start dev server at localhost:8080
```
--------------------------------
### Install graphql-php via Composer
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/webonyx/graphql-php/README.md
Use this command to add the graphql-php package to your project using Composer.
```sh
composer require webonyx/graphql-php
```
--------------------------------
### JavaScript/Frontend Usage
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/Content/README.md
Examples of how to interact with the Content module's API from frontend JavaScript.
```APIDOC
## Frontend JavaScript Examples
### Fetching Multiple Items
```javascript
// Fetch published blog posts
const posts = await fetch('/api/content/items/blog?filter={"published":true}')
.then(res => res.json());
```
### Creating a New Item
```javascript
const newPost = await fetch('/api/content/item/blog', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Cockpit-Token': 'your-api-token' // Replace with your token
},
body: JSON.stringify({
title: 'New Post',
content: '
Content here
',
published: true
})
}).then(res => res.json());
```
### GraphQL Query
```javascript
const query = `
query {
contentItems(model: "blog", filter: {published: true}) {
_id
title
content
_created
}
}
`;
const data = await fetch('/api/gql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query })
}).then(res => res.json());
```
```
--------------------------------
### JavaScript/Frontend Usage - Upload Assets
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/Assets/README.md
Example of how to upload assets using the Fetch API in JavaScript.
```APIDOC
## Upload assets via fetch API
### Description
Demonstrates uploading an asset using the `fetch` API, including setting headers and appending form data.
### Code Example
```javascript
const formData = new FormData();
formData.append('files', fileInput.files[0]);
formData.append('meta[title]', 'Uploaded Image');
const result = await fetch('/api/assets/upload', {
method: 'POST',
headers: {
'Cockpit-Token': 'your-api-token'
},
body: formData
}).then(res => res.json());
console.log('Uploaded asset:', result.assets[0]);
```
```
--------------------------------
### Unit Test Setup and Operations
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/MongoLite/README.md
Demonstrates setting up an in-memory database, inserting documents, performing find and aggregate operations, and asserting results for unit testing.
```php
selectCollection('test');
// Test insert
$doc = ['name' => 'Test', 'value' => 123];
$collection->insert($doc);
// Test query
$result = $collection->findOne(['name' => 'Test']);
assert($result['value'] === 123);
// Test aggregation
$stats = $collection->aggregate([
['$group' => [
'_id' => null,
'total' => ['$sum' => '$value']
]]
])->toArray();
assert($stats[0]['total'] === 123);
```
--------------------------------
### Get File Listing via API
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/Finder/README.md
Perform file operations by sending POST requests to the Finder API. This example shows how to list directory contents.
```javascript
fetch('/finder/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': COCKPIT_CSRF_TOKEN
},
body: JSON.stringify({
cmd: 'ls',
path: 'config',
root: '#root:'
})
});
```
--------------------------------
### Creating Test Data Example
Source: https://github.com/cockpit-hq/cockpit/blob/develop/AGENTS.md
Demonstrates how to create test data using the data storage abstraction, callable via CLI or module bootstrap files.
```php
// Via CLI or bootstrap
$app = Cockpit::instance();
$app->dataStorage->save('collection_name', [
'field' => 'value'
]);
```
--------------------------------
### Get QR Code Binary Data for Two-Factor Authentication
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/App/README.md
Retrieves the QR code image data as binary for two-factor authentication setup. The default size is 150 pixels.
```php
$qrCodeBinary = $app->helper('twfa')->getQRCodeImage($secret, $size = 150);
```
--------------------------------
### Build PHP with Debug Symbols using PHPBrew
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/aws/aws-crt-php/README.md
Install PHP with debug symbols enabled using PHPBrew, which is necessary for debugging native extensions. This example shows PHP 8 and PHP 5.5.
```shell
# PHP 8 example
$ phpbrew install --stdout -j 8 8.0 +default -- CFLAGS=-Wno-error --disable-cgi --enable-debug
# PHP 5.5 example
$ phpbrew install --stdout -j 8 5.5 +default -openssl -mbstring -- CFLAGS="-w -Wno-error" --enable-debug --with-zlib=/usr/local/opt/zlib
```
--------------------------------
### Install ZipStream-PHP using Composer
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/maennchen/zipstream-php/README.md
Use Composer to add the ZipStream-PHP package to your project's dependencies.
```bash
composer require maennchen/zipstream-php
```
--------------------------------
### Download and Install Cockpit (Traditional)
Source: https://github.com/cockpit-hq/cockpit/blob/develop/README.md
Use these bash commands to download, extract, and set up Cockpit manually. Ensure storage is writable.
```bash
# Download and extract
wget https://github.com/cockpit-hq/cockpit/releases/latest/download/cockpit.zip
unzip cockpit.zip && cd cockpit
# Make storage writable
chmod -R 755 storage/
# Open in browser and complete setup
open http://localhost/cockpit/install
```
--------------------------------
### Install Symfony Polyfill for Mbstring
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/maennchen/zipstream-php/guides/index.rst
Install this package if your installation is missing the mbstring extension and you encounter a composer error.
```sh
composer require symfony/polyfill-mbstring
```
--------------------------------
### Install Guzzle PSR-7
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/guzzlehttp/psr7/README.md
Use Composer to install the Guzzle PSR-7 package.
```shell
composer require guzzlehttp/psr7
```
--------------------------------
### Create and Open an Index with IndexLite
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/IndexLite/README.md
Demonstrates how to create a new search index with specified fields or open an existing one.
```php
use IndexLite\Index;
// Create a new index
Index::create('search.db', ['title', 'content', 'tags', 'category']);
// Open existing index
$index = new Index('search.db');
```
--------------------------------
### Create Performance Indexes (CLI)
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/Content/README.md
Examples of creating indexes optimized for performance, including sorting by date and filtering by category. Index definitions are provided as JSON strings.
```bash
./tower content:index:create blog '{"published": 1, "_created": -1}' # Published posts by date
```
```bash
./tower content:index:create products '{"category": 1, "featured": -1, "price": 1}' # Category browsing
```
--------------------------------
### XML Service Description Example
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/guzzlehttp/guzzle/UPGRADING.md
An example of an XML service description used before conversion.
```xml
Get a list of groups
Uses a search query to get a list of groups
Create a group
Delete a group by ID
Update a group
```
--------------------------------
### Run Full Build
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/phpstan/phpdoc-parser/README.md
Execute the complete build process, which includes linting and coding standards checks.
```bash
make
```
--------------------------------
### Backup Database and Files
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/Updater/README.md
Before updating, it is crucial to back up your database and application files. These bash commands demonstrate how to create a database backup and a compressed archive of your files.
```bash
# Backup database
./tower app:backup
# Backup files
tar -czf cockpit-backup.tar.gz /path/to/cockpit
```
--------------------------------
### Create Search Indexes (CLI)
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/Content/README.md
Examples of creating text indexes for effective search functionality across multiple fields. The '$**' syntax allows for full-text search on all fields.
```bash
./tower content:index:create blog '{"$": "text"}' # Full-text search on all fields
```
```bash
./tower content:index:create products '{"name": "text", "description": "text"}' # Product search
```
--------------------------------
### JSON-LD Example Data
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/App/assets/vendor/codemirror/mode/javascript/json-ld.html
Example of JSON-LD data structure used for representing Linked Data.
```json
{
"@context": {
"name": "http://schema.org/name",
"description": "http://schema.org/description",
"image": {
"@id": "http://schema.org/image",
"@type": "@id"
},
"geo": "http://schema.org/geo",
"latitude": {
"@id": "http://schema.org/latitude",
"@type": "xsd:float"
},
"longitude": {
"@id": "http://schema.org/longitude",
"@type": "xsd:float"
},
"xsd": "http://www.w3.org/2001/XMLSchema#"
},
"name": "The Empire State Building",
"description": "The Empire State Building is a 102-story landmark in New York City.",
"image": "http://www.civil.usherbrooke.ca/cours/gci215a/empire-state-building.jpg",
"geo": {
"latitude": "40.75",
"longitude": "73.98"
}
}
```
--------------------------------
### Install PHPMailer via Composer CLI
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/phpmailer/phpmailer/README.md
Execute this command in your terminal to install PHPMailer using Composer.
```sh
composer require phpmailer/phpmailer
```
--------------------------------
### Creating a Custom Docker Image with Configuration
Source: https://github.com/cockpit-hq/cockpit/blob/develop/README.md
Demonstrates how to create a custom Docker image for Cockpit by copying a local configuration file into the image.
```dockerfile
FROM cockpithq/cockpit:core-latest
COPY ./config/config.php /var/www/html/config/config.php
```
--------------------------------
### Run Cockpit with Docker (Recommended)
Source: https://github.com/cockpit-hq/cockpit/blob/develop/README.md
This Docker command sets up Cockpit with persistent storage using a named volume. Access the installation via http://localhost:8080/install.
```bash
# Run Cockpit with persistent storage
docker run -d \
--name cockpit \
-p 8080:80 \
-v cockpit_storage:/var/www/html/storage \
cockpithq/cockpit:core-latest
# Access at http://localhost:8080/install
```
--------------------------------
### Create New Post (REST API)
Source: https://github.com/cockpit-hq/cockpit/blob/develop/README.md
Example of creating a new blog post using a POST request with JSON data and an API token.
```bash
# Create new post
curl -X POST "https://yoursite.com/api/content/item/blog" \
-H "Cockpit-Token: your-token" \
-H "Content-Type: application/json" \
-d '{"title":"New Post","content":"Content here","tags":["cms"]}'
```
--------------------------------
### PHP Example Class Structure
Source: https://github.com/cockpit-hq/cockpit/blob/develop/AGENTS.md
Illustrates a typical class structure within the App\Helper namespace, extending a Lime framework base class and using typed properties and return types.
```php
namespace App\Helper;
class ExampleHelper extends \Lime\Helper {
public string $property = 'value';
public function methodName(array $data): mixed {
// Implementation
}
}
```
--------------------------------
### Instantiate ScriptLite Engine
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/ScriptLite/README.md
Demonstrates how to instantiate the Engine class. When the ScriptLite C extension is loaded, the default Engine instantiation transparently delegates to `ScriptLiteExt\Engine`. You can force the use of the PHP VM by passing `false`.
```php
$engine = new Engine(); // uses ScriptLiteExt\Engine when available
$engine = new Engine(true); // same as default
$engine = new Engine(false); // force PHP VM/transpiler, ignore extension
```
--------------------------------
### Install Guzzle with Composer
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/guzzlehttp/guzzle/README.md
The recommended method for installing Guzzle is via Composer. This command adds Guzzle to your project's dependencies.
```bash
composer require guzzlehttp/guzzle
```
--------------------------------
### Pagination - Get Total Count
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/Content/README.md
Get the total count of items matching a filter to calculate the total number of pages for pagination.
```php
// Get total count for pagination
$total = $app->module('content')->count('blog', ['published' => true]);
$totalPages = ceil($total / $limit);
```
--------------------------------
### Get String Representation of an HTTP Message
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/guzzlehttp/psr7/README.md
Use Message::toString to get the string representation of an HTTP message. This is useful for debugging or logging.
```php
$request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com');
echo GuzzleHttp\Psr7\Message::toString($request);
```
--------------------------------
### Create and Use an Index
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/IndexHybrid/README.md
Define an index with specified fields, add documents to it, and then perform searches using a unified interface. This demonstrates the basic workflow for managing and querying data.
```php
// Create an index
$manager->createIndex('products', ['title', 'description', 'category', 'price']);
// Get index instance
$index = $manager->index('products');
// Add documents
$index->addDocument('prod1', [
'title' => 'iPhone 15 Pro',
'description' => 'Latest Apple smartphone with advanced features',
'category' => 'Electronics',
'price' => 999
]);
// Search with unified interface
$results = $index->search('phone', [
'fuzzy' => true,
'limit' => 20,
'boosts' => ['title' => 2.0],
'filter' => 'category = "Electronics"'
]);
```
--------------------------------
### Install AWS CRT PHP with Composer (Windows)
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/aws/aws-crt-php/README.md
After building the native extension on Windows, install the AWS CRT PHP package using Composer.
```bash
composer require aws/aws-crt-php
```
--------------------------------
### Create Index with Options (CLI)
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/Content/README.md
Create an index with specific options, such as enforcing unique values. The index definition and options are provided as JSON strings.
```bash
./tower content:index:create blog '{"slug": 1}' '{"unique": true}'
```
--------------------------------
### Install phpseclib for PS256 Support (Bash)
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/firebase/php-jwt/README.md
Installs the phpseclib library, which is a soft dependency required for using the PS256 (RSASSA-PSS) signature algorithm with the JWT library.
```bash
composer install phpseclib/phpseclib:^3.0
```
--------------------------------
### Install phpseclib 1.0 via Composer
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/phpseclib/phpseclib/README.md
Install the phpseclib 1.0 release, a long-term support version that is PHP4 compatible and Composer compatible (PSR-0 autoloading).
```sh
composer require phpseclib/phpseclib:~1.0
```
--------------------------------
### After: Using \Guzzle\Common\Collection::fromConfig
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/guzzlehttp/guzzle/UPGRADING.md
Demonstrates the updated method using \Guzzle\Common\Collection::fromConfig, reflecting the change in Guzzle's API for configuration handling in client factories.
```php
use Guzzle\Common\Collection;
class YourClient extends \Guzzle\Service\Client
{
public static function factory($config = array())
{
$default = array();
$required = array('base_url', 'username', 'api_key');
$config = Collection::fromConfig($config, $default, $required);
$client = new self(
$config->get('base_url'),
$config->get('username'),
$config->get('api_key')
);
$client->setConfig($config);
$client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json'));
return $client;
}
}
```
--------------------------------
### GSS Example Code
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/App/assets/vendor/codemirror/mode/css/gss.html
An example of Closure Stylesheets (GSS) syntax, including directives like @provide, @require, and @component, along with mixins and nested rules.
```css
/* Some example Closure Stylesheets */ @provide 'some.styles'; @require 'other.styles'; @component { @def FONT_FAMILY "Times New Roman", Georgia, Serif; @def FONT_SIZE_NORMAL 15px; @def FONT_NORMAL normal FONT_SIZE_NORMAL FONT_FAMILY; @def BG_COLOR rgb(235, 239, 249); @def DIALOG_BORDER_COLOR rgb(107, 144, 218); @def DIALOG_BG_COLOR BG_COLOR; @def LEFT_HAND_NAV_WIDTH 180px; @def LEFT_HAND_NAV_PADDING 3px; @mixin size(WIDTH, HEIGHT) { width: WIDTH; height: HEIGHT; } body { background-color: BG_COLOR; margin: 0; padding: 3em 6em; font: FONT_NORMAL; color: #000; } #navigation a { font-weight: bold; text-decoration: none !important; } .dialog { background-color: DIALOG_BG_COLOR; border: 1px solid DIALOG_BORDER_COLOR; } .content { position: absolute; margin-left: add(LEFT_HAND_NAV_PADDING, /* padding left */ LEFT_HAND_NAV_WIDTH, LEFT_HAND_NAV_PADDING); /* padding right */ } .logo { @mixin size(150px, 55px); background-image: url('http://www.google.com/images/logo_sm.gif'); }
```
--------------------------------
### Database Class API Reference
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/MongoLite/README.md
Shows how to instantiate the Database class and manage collections. Includes methods for selecting, creating, dropping, and listing collections, as well as sanitizing names and performing database maintenance.
```php
$db = new Database($path, $options = []);
// Collection management
$collection = $db->selectCollection($name);
$db->createCollection($name);
$db->dropCollection($name);
$names = $db->getCollectionNames();
// Security
$safeName = $db->sanitizeCollectionName($name);
// Utility
$db->vacuum(); // Optimize database
$db->drop(); // Delete database
```
--------------------------------
### Install phpseclib 2.0 via Composer
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/phpseclib/phpseclib/README.md
Install the phpseclib 2.0 release, a long-term support version with a minimum PHP version of 5.3.3 and PSR-4 autoloading under the \\phpseclib namespace.
```sh
composer require phpseclib/phpseclib:~2.0
```
--------------------------------
### Install phpseclib 3.0 via Composer
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/phpseclib/phpseclib/README.md
Install the phpseclib 3.0 release, a long-term support version with a minimum PHP version of 5.6.1 and PSR-4 autoloading under the \\phpseclib3 namespace.
```sh
composer require phpseclib/phpseclib:~3.0
```
--------------------------------
### Install AWS CRT PHP with Composer/PECL (UNIX)
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/aws/aws-crt-php/README.md
Install the AWS CRT PHP extension using PECL for the native extension and Composer for the PHP package on UNIX systems.
```bash
pecl install awscrt
composer require aws/aws-crt-php
```
--------------------------------
### Before: Using \Guzzle\Service\Inspector::fromConfig
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/guzzlehttp/guzzle/UPGRADING.md
Illustrates the older method of using \Guzzle\Service\Inspector::fromConfig for configuration management within a Guzzle client factory.
```php
use Guzzle\Service\Inspector;
class YourClient extends \Guzzle\Service\Client
{
public static function factory($config = array())
{
$default = array();
$required = array('base_url', 'username', 'api_key');
$config = Inspector::fromConfig($config, $default, $required);
$client = new self(
$config->get('base_url'),
$config->get('username'),
$config->get('api_key')
);
$client->setConfig($config);
$client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json'));
return $client;
}
}
```
--------------------------------
### System Helper Usage
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/System/README.md
Retrieve system information, server load, disk usage, and execute shell commands.
```php
// Get system information
$info = $app->helper('system')->getInfo();
// Get server load
$load = $app->helper('system')->getServerLoad();
// Get disk usage
$disk = $app->helper('system')->getDiskUsage();
// Execute command
$output = $app->helper('system')->exec('ls -la');
```
--------------------------------
### Install phpseclib 4.0.x-dev via Composer
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/phpseclib/phpseclib/README.md
Install the development version of phpseclib 4.0.x, which is a long-term support release with a minimum PHP version of 8.1.0 and PSR-4 autoloading under the \\phpseclib4 namespace.
```sh
composer require phpseclib/phpseclib:4.0.x-dev
```
--------------------------------
### Generate QR Code with GDLib Renderer
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/bacon/bacon-qr-code/README.md
This example demonstrates generating a QR code using the GDLib renderer. This is an alternative to Imagick, suitable when GD library is available and Imagick is not preferred. Note that GDLibRenderer has limitations such as no gradient support and squared modules.
```php
use BaconQrCode\Renderer\GDLibRenderer;
use BaconQrCode\Writer;
$renderer = new GDLibRenderer(400);
$writer = new Writer($renderer);
$writer->writeFile('Hello World!', 'qrcode.png');
```
--------------------------------
### RFC 2047 Header Encoding Example
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/phpmailer/phpmailer/SMTPUTF8.md
Demonstrates how UTF-8 characters in email headers were encoded using RFC 2047 and quoted-printable to survive 7-bit channels. The example shows a subject line with an accented character.
```text
Subject: =?utf-8?Q?Schr=C3=B6dinger=92s_Cat?=
```
--------------------------------
### Initialize Manager for IndexLite or Meilisearch
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/IndexHybrid/README.md
Instantiate the Manager class with the appropriate backend URL. For Meilisearch, provide an API key in the options array. This sets up the connection to your chosen search engine.
```php
use IndexHybrid\Manager;
// IndexLite backend
$manager = new Manager('indexlite://storage/search.db');
// Meilisearch backend
$manager = new Manager('meilisearch://localhost:7700', [
'api_key' => 'your_master_key'
]);
// Check what the backend supports
$capabilities = $manager->getCapabilities();
```
--------------------------------
### Constructor
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/ESQL/README.md
Initializes a new ESQL client instance. Supports various connection options and automatic JSON handling.
```APIDOC
## Constructor
```php
public function __construct(string $dsn, array $options = [])
```
### Description
Initializes a new ESQL client instance.
### Parameters
- **$dsn** (string): Data Source Name (e.g., `mysql:host=localhost;dbname=mydb`)
- **$options** (array): Array of configuration options
### Available Options
- `username`: Database username
- `password`: Database password
- `encodeJson`: Auto-encode arrays/objects to JSON (default: `true`)
- `decodeJson`: Auto-decode JSON strings back to arrays/objects (default: `true`)
- `pdo`: Array of PDO connection options
### Examples
```php
// Basic connection
$db = new Client('mysql:host=localhost;dbname=myapp', [
'username' => 'user',
'password' => 'pass'
]);
// PostgreSQL with custom options
$db = new Client('pgsql:host=localhost;dbname=myapp', [
'username' => 'user',
'password' => 'pass',
'encodeJson' => true, // Enable auto JSON encoding (default)
'decodeJson' => true, // Enable auto JSON decoding (default)
'pdo' => [
PDO::ATTR_TIMEOUT => 30
]
]);
// SQLite with JSON disabled
$db = new Client('sqlite:/path/to/database.db', [
'encodeJson' => false,
'decodeJson' => false
]);
```
```
--------------------------------
### grapheme_strlen
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/symfony/polyfill-intl-grapheme/README.md
Gets the string length in grapheme units.
```APIDOC
## grapheme_strlen
### Description
Get string length in grapheme units.
### Method
`grapheme_strlen`
### Parameters
(No specific parameters documented in the source)
### Request Example
(No request example provided in the source)
### Response
(No specific response details provided in the source)
```
--------------------------------
### LESS Syntax Examples
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/App/assets/vendor/codemirror/mode/css/less.html
Illustrates various LESS syntax features including media queries, pseudo-classes, attribute selectors, and vendor prefixes.
```css
@media screen and (device-aspect-ratio: 16/9) { … }
```
```css
@media screen and (device-aspect-ratio: 1280/720) { … }
```
```css
@media screen and (device-aspect-ratio: 2560/1440) { … }
```
```css
html:lang(fr-be) tr:nth-child(2n+1) /* represents every odd row of an HTML table */ img:nth-of-type(2n+1) { float: right; }
```
```css
img:nth-of-type(2n) { float: left; }
```
```css
body > h2:not(:first-of-type):not(:last-of-type)
```
```css
html|*:not(:link):not(:visited) *|*:not(:hover) p::first-line { text-transform: uppercase }
```
```css
@namespace foo url(http://www.example.com);
```
```css
foo|h1 { color: blue } /* first rule */
```
```css
span[hello="Ocean"][goodbye="Land"] E[foo] { padding:65px; }
```
```css
input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-cancel-button { -webkit-appearance: none; // Inner-padding issues in Chrome OSX, Safari 5 }
```
```css
button::-moz-focus-inner, input::-moz-focus-inner { // Inner padding and border oddities in FF3/4 padding: 0; border: 0; }
```
```css
.btn { // reset here as of 2.0.3 due to Recess property order border-color: #ccc; border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25); }
```
```css
fieldset span button, fieldset span input[type="file"] { font-size:12px; font-family:Arial, Helvetica, sans-serif; }
```
```css
.rounded-corners (@radius: 5px) { border-radius: @radius; -webkit-border-radius: @radius; -moz-border-radius: @radius; }
```
```css
@import url("something.css");
```
```css
@light-blue: hsl(190, 50%, 65%);
```
```css
#menu { position: absolute; width: 100%; z-index: 3; clear: both; display: block; background-color: @blue; height: 42px; border-top: 2px solid lighten(@alpha-blue, 20%); border-bottom: 2px solid darken(@alpha-blue, 25%); .box-shadow(0, 1px, 8px, 0.6); -moz-box-shadow: 0 0 0 #000; // Because firefox sucks. &.docked { background-color: hsla(210, 60%, 40%, 0.4); } &:hover { background-color: @blue; } #dropdown { margin: 0 0 0 117px; padding: 0; padding-top: 5px; display: none; width: 190px; border-top: 2px solid @medium; color: @highlight; border: 2px solid darken(@medium, 25%); border-left-color: darken(@medium, 15%); border-right-color: darken(@medium, 15%); border-top-width: 0; background-color: darken(@medium, 10%); ul { padding: 0px; } li { font-size: 14px; display: block; text-align: left; padding: 0; border: 0; a { display: block; padding: 0px 15px; text-decoration: none; color: white; &:hover { background-color: darken(@medium, 15%); text-decoration: none; } } } .border-radius(5px, bottom); .box-shadow(0, 6px, 8px, 0.5); } }
```
--------------------------------
### Get Image Width
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/claviska/simpleimage/README.md
Retrieve the current width of the image in pixels.
```php
$image->getWidth();
```
--------------------------------
### Custom Release Server Structure
Source: https://github.com/cockpit-hq/cockpit/blob/develop/modules/Updater/README.md
This illustrates the expected directory structure for a custom release server. It should include a `latest.json` file for version information and zip archives for different versions and targets (core/pro).
```text
/releases/
├── latest.json # Latest version info
├── master/
│ ├── cockpit-core.zip
│ └── cockpit-pro.zip
├── 2.8.0/
│ ├── cockpit-core.zip
│ └── cockpit-pro.zip
└── 2.7.0/
├── cockpit-core.zip
└── cockpit-pro.zip
```
--------------------------------
### Get Image Resolution
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/claviska/simpleimage/README.md
Retrieve the current resolution of the image in DPI.
```php
$image->getResolution();
```
--------------------------------
### Get Image Height
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/claviska/simpleimage/README.md
Retrieve the current height of the image in pixels.
```php
$image->getHeight();
```
--------------------------------
### Setting Instance Flags via Constructor
Source: https://github.com/cockpit-hq/cockpit/blob/develop/lib/vendor/claviska/simpleimage/README.md
Demonstrates setting instance flags directly when creating a SimpleImage object using an associative array. This can be done with or without an image file.
```php
$image = new \claviska\SimpleImage('image.jpeg', ['foo' => 'bar']);
```
```php
$image = new \claviska\SimpleImage(flags: ['foo' => 'bar']);
```