Skip to content

Contributing

Rumen Damyanov edited this page Jul 31, 2025 · 1 revision

Contributing

How to contribute to the php-chatbot project.

Table of Contents

Getting Started

We welcome contributions to php-chatbot! Whether you're fixing bugs, adding features, improving documentation, or suggesting enhancements, your help is appreciated.

Ways to Contribute

  • 🐛 Bug Reports - Report issues you've found
  • Feature Requests - Suggest new functionality
  • 🔧 Code Contributions - Submit bug fixes or new features
  • 📚 Documentation - Improve guides, examples, or API docs
  • 🧪 Testing - Add test cases or improve test coverage
  • 🌍 Translations - Help translate the project
  • 📝 Examples - Create real-world usage examples

Before You Start

  1. Check existing issues - Someone might already be working on it
  2. Read the documentation - Understand the project structure
  3. Join discussions - Ask questions in issues or discussions
  4. Start small - Begin with simple bug fixes or documentation improvements

Quick Links

Development Setup

Prerequisites

Make sure you have the following installed:

  • PHP 8.3+ with extensions: curl, json, mbstring
  • Composer 2.0+ for dependency management
  • Git for version control
  • Node.js 18+ (for frontend development)

Local Development

  1. Fork and Clone

    # Fork the repository on GitHub, then clone your fork
    git clone https://github.com/YOUR_USERNAME/php-chatbot.git
    cd php-chatbot
    
    # Add upstream remote
    git remote add upstream https://github.com/RumenDamyanov/php-chatbot.git
  2. Install Dependencies

    # Install PHP dependencies
    composer install
    
    # Install dev dependencies for testing
    composer install --dev
    
    # Install frontend dependencies (if working on UI)
    npm install
  3. Environment Setup

    # Copy environment file
    cp .env.example .env
    
    # Edit .env with your API keys for testing
    nano .env
  4. Run Tests

    # Run the test suite
    composer test
    
    # Run with coverage
    composer test:coverage
    
    # Run specific test file
    ./vendor/bin/pest tests/PhpChatbotTest.php
  5. Code Quality

    # Run static analysis
    composer analyse
    
    # Fix code style
    composer cs-fix
    
    # Check code style
    composer cs-check

Development Workflow

  1. Create a branch for your feature/fix:

    git checkout -b feature/your-feature-name
    # or
    git checkout -b fix/issue-number
  2. Make changes following our coding standards

  3. Test your changes:

    composer test
    composer analyse
  4. Commit your changes:

    git add .
    git commit -m "feat: add new AI model support"
  5. Push and create PR:

    git push origin feature/your-feature-name

Available Commands

# Testing
composer test                 # Run test suite
composer test:unit           # Unit tests only
composer test:integration    # Integration tests only
composer test:coverage       # Generate coverage report

# Code Quality
composer analyse             # PHPStan static analysis
composer cs-fix             # Fix code style with PHP CS Fixer
composer cs-check           # Check code style
composer rector             # Run Rector for code improvements

# Documentation
composer docs:generate      # Generate API documentation
composer docs:serve        # Serve docs locally

# CI/CD
composer ci                 # Run full CI pipeline locally
composer security          # Check for security vulnerabilities

Contribution Guidelines

Types of Contributions

🐛 Bug Fixes

  • Always include tests that reproduce the bug
  • Keep changes minimal and focused on the specific issue
  • Update documentation if behavior changes
  • Reference the issue number in your commit message

✨ New Features

  • Discuss first in an issue or discussion
  • Follow existing patterns and conventions
  • Include comprehensive tests for new functionality
  • Update documentation and examples
  • Consider backward compatibility

📚 Documentation

  • Fix typos and improve clarity
  • Add missing examples or use cases
  • Update outdated information
  • Improve code comments and PHPDoc blocks

🧪 Tests

  • Increase test coverage for existing code
  • Add edge case tests that aren't covered
  • Improve test readability and organization
  • Add integration tests for real-world scenarios

Issue Guidelines

Reporting Bugs

Use the Bug Report template and include:

**Bug Description**
A clear description of the bug.

**Steps to Reproduce**
1. Configure chatbot with...
2. Send message...
3. Observe error...

**Expected Behavior**
What should happen.

**Actual Behavior**
What actually happens.

**Environment**
- PHP version: 8.2
- Package version: 1.0.0
- Framework: Laravel 10.x
- AI Provider: OpenAI

**Additional Context**
Error logs, screenshots, etc.

Feature Requests

Use the Feature Request template:

**Feature Description**
Clear description of the proposed feature.

**Use Case**
Why is this feature needed? What problem does it solve?

**Proposed Implementation**
How should this work?

**Alternatives Considered**
Other approaches you've considered.

**Additional Context**
Examples, mockups, related issues.

Communication Guidelines

  • Be respectful and professional
  • Stay on topic in issues and discussions
  • Use clear, descriptive titles for issues and PRs
  • Provide context and examples when asking questions
  • Search existing issues before creating new ones

Code Standards

PHP Standards

We follow PSR-12 coding standards with additional project-specific rules.

Code Style

<?php

declare(strict_types=1);

namespace RumenX\PhpChatbot\Models;

use RumenX\PhpChatbot\Contracts\AiModelInterface;

/**
 * Example AI model implementation.
 */
final class ExampleModel implements AiModelInterface
{
    private const DEFAULT_TEMPERATURE = 0.7;
    
    public function __construct(
        private readonly string $apiKey,
        private readonly float $temperature = self::DEFAULT_TEMPERATURE,
    ) {
    }
    
    public function sendMessage(string $message, array $options = []): string
    {
        // Method implementation
        return $this->processMessage($message);
    }
    
    private function processMessage(string $message): string
    {
        // Private method implementation
    }
}

Naming Conventions

  • Classes: PascalCase (e.g., ChatbotService, OpenAiModel)
  • Methods: camelCase (e.g., sendMessage, getApiKey)
  • Variables: camelCase (e.g., $apiResponse, $messageText)
  • Constants: SCREAMING_SNAKE_CASE (e.g., DEFAULT_TIMEOUT)
  • Files: PascalCase.php (e.g., OpenAiModel.php)

Documentation Standards

/**
 * Send a message to the AI model and return the response.
 *
 * @param string $message The user message to process
 * @param array<string, mixed> $options Additional options for the request
 * @return string The AI model's response
 * 
 * @throws \InvalidArgumentException If message is empty
 * @throws \RuntimeException If API request fails
 */
public function sendMessage(string $message, array $options = []): string
{
    // Implementation
}

Error Handling

// Use specific exception types
throw new \InvalidArgumentException('Message cannot be empty');

// Provide helpful error messages
throw new \RuntimeException(
    sprintf('Failed to connect to %s API: %s', $this->provider, $error)
);

// Chain exceptions for context
try {
    $response = $this->makeApiCall($data);
} catch (\Exception $e) {
    throw new \RuntimeException('API call failed', 0, $e);
}

Frontend Standards

JavaScript/TypeScript

// Use modern ES6+ features
const sendMessage = async (message) => {
  try {
    const response = await fetch('/api/chatbot', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message })
    });
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('Failed to send message:', error);
    throw error;
  }
};

// TypeScript interfaces
interface ChatbotConfig {
  apiUrl: string;
  title: string;
  theme: 'light' | 'dark';
}

CSS/SCSS

// Use CSS custom properties for theming
.chatbot-container {
  --primary-color: #4f46e5;
  --background-color: #ffffff;
  
  background: var(--background-color);
  border: 1px solid var(--primary-color);
}

// Follow BEM methodology
.chatbot {
  &__header {
    padding: 1rem;
    
    &--dark {
      background: #1f2937;
    }
  }
  
  &__message {
    margin-bottom: 0.5rem;
    
    &--user {
      text-align: right;
    }
  }
}

Version Control

Commit Message Format

Use Conventional Commits format:

<type>[optional scope]: <description>

[optional body]

[optional footer(s)]

Types:

  • feat: New feature
  • fix: Bug fix
  • docs: Documentation changes
  • style: Code style changes (formatting, etc.)
  • refactor: Code refactoring
  • test: Adding or updating tests
  • chore: Maintenance tasks

Examples:

feat(models): add support for Claude-3 model
fix(security): validate input length before processing
docs(readme): update installation instructions
test(integration): add OpenAI API error handling tests

Branch Naming

  • Features: feature/feature-name or feat/short-description
  • Bug fixes: fix/issue-number or fix/short-description
  • Documentation: docs/section-name
  • Chores: chore/task-description

Testing Requirements

Test Coverage

We maintain 90%+ test coverage. All new code must include tests.

Unit Tests

<?php

use RumenX\PhpChatbot\Models\OpenAiModel;

it('sends message to OpenAI API', function () {
    $model = new OpenAiModel('test-api-key');
    
    // Mock HTTP client
    Http::fake([
        'api.openai.com/*' => Http::response([
            'choices' => [
                ['message' => ['content' => 'Test response']]
            ]
        ])
    ]);
    
    $response = $model->sendMessage('Hello');
    
    expect($response)->toBe('Test response');
});

it('throws exception for empty message', function () {
    $model = new OpenAiModel('test-api-key');
    
    expect(fn() => $model->sendMessage(''))
        ->toThrow(\InvalidArgumentException::class);
});

Integration Tests

it('handles full chatbot conversation flow', function () {
    $chatbot = new PhpChatbot([
        'model' => 'openai',
        'api_key' => 'test-key',
    ]);
    
    Http::fake([
        'api.openai.com/*' => Http::response([
            'choices' => [
                ['message' => ['content' => 'Hello! How can I help?']]
            ]
        ])
    ]);
    
    $response = $chatbot->sendMessage('Hi there');
    
    expect($response)
        ->toBeArray()
        ->toHaveKey('reply', 'Hello! How can I help?')
        ->toHaveKey('conversation_id');
});

Frontend Tests

// Jest/Vitest tests
describe('Chatbot Component', () => {
  it('sends message when button clicked', async () => {
    const mockSend = jest.fn().mockResolvedValue({
      reply: 'Test response'
    });
    
    render(<Chatbot onSendMessage={mockSend} />);
    
    await user.type(screen.getByRole('textbox'), 'Hello');
    await user.click(screen.getByRole('button', { name: /send/i }));
    
    expect(mockSend).toHaveBeenCalledWith('Hello');
  });
});

Running Tests

# Run all tests
composer test

# Run specific test types
composer test:unit
composer test:integration
composer test:feature

# Run with coverage
composer test:coverage

# Watch mode (if available)
composer test:watch

# Parallel execution
composer test:parallel

Test Guidelines

  • Test behavior, not implementation
  • Use descriptive test names that explain what's being tested
  • Follow AAA pattern: Arrange, Act, Assert
  • Mock external dependencies (APIs, databases)
  • Test edge cases and error conditions
  • Keep tests simple and focused on one thing

Documentation

Types of Documentation

API Documentation

  • PHPDoc blocks for all public methods
  • Type hints for parameters and return values
  • Usage examples in docblocks
  • Exception documentation for error cases

User Documentation

  • Installation guides for different environments
  • Configuration examples with explanations
  • Common use cases and recipes
  • Troubleshooting guides for known issues

Developer Documentation

  • Architecture decisions and rationale
  • Extension points and customization
  • Contributing guidelines (this document)
  • Release notes and changelog

Documentation Standards

Writing Style

  • Clear and concise language
  • Active voice when possible
  • Consistent terminology throughout
  • Practical examples over theoretical explanations

Code Examples

// ✅ Good: Complete, runnable example
$chatbot = new PhpChatbot([
    'model' => 'openai',
    'api_key' => env('OPENAI_API_KEY'),
    'temperature' => 0.7,
]);

$response = $chatbot->sendMessage('Hello!');
echo $response['reply']; // "Hello! How can I help you?"

// ❌ Bad: Incomplete or unclear
$chatbot = new PhpChatbot($config);
$response = $chatbot->sendMessage($message);

Update Requirements

  • Update docs when adding new features
  • Fix outdated examples when changing APIs
  • Add migration guides for breaking changes
  • Include version compatibility information

Pull Request Process

Before Submitting

  1. Ensure tests pass: composer test
  2. Check code quality: composer analyse
  3. Fix code style: composer cs-fix
  4. Update documentation if needed
  5. Rebase on latest main: git rebase upstream/main

PR Template

## Description
Brief description of the changes.

## Type of Change
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] Documentation update

## Testing
- [ ] Tests pass locally
- [ ] New tests added for new functionality
- [ ] Manual testing completed

## Checklist
- [ ] Code follows project style guidelines
- [ ] Self-review completed
- [ ] Documentation updated
- [ ] No new warnings or errors introduced

## Related Issues
Fixes #123
Related to #456

Review Process

  1. Automated checks must pass (CI/CD)
  2. Code review by maintainers
  3. Testing in staging environment
  4. Approval by project maintainer
  5. Merge when all requirements met

Review Criteria

Code Quality

  • Follows coding standards and best practices
  • Includes appropriate tests with good coverage
  • Has clear, descriptive commit messages
  • Doesn't introduce security vulnerabilities

Functionality

  • Solves the intended problem effectively
  • Doesn't break existing functionality
  • Handles edge cases appropriately
  • Includes proper error handling

Documentation

  • Updates relevant documentation
  • Includes clear code comments
  • Provides usage examples when appropriate

Community Guidelines

Code of Conduct

We are committed to providing a welcoming and inclusive environment for all contributors.

Our Standards

Examples of behavior that contributes to a positive environment:

  • Using welcoming and inclusive language
  • Being respectful of differing viewpoints and experiences
  • Gracefully accepting constructive criticism
  • Focusing on what is best for the community
  • Showing empathy towards other community members

Examples of unacceptable behavior:

  • Use of sexualized language or imagery and unwelcome sexual attention
  • Trolling, insulting/derogatory comments, and personal or political attacks
  • Public or private harassment
  • Publishing others' private information without explicit permission
  • Other conduct which could reasonably be considered inappropriate

Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances.

Communication Channels

  • GitHub Issues - Bug reports and feature requests
  • GitHub Discussions - Questions, ideas, and general discussion
  • GitHub Projects - Development planning and roadmap
  • Email - Private communication with maintainers

Recognition

We appreciate all contributions and recognize contributors in:

  • README.md contributors section
  • Release notes for significant contributions
  • GitHub contributors graph
  • Special mentions in project updates

Getting Help

  • Check the documentation first
  • Search existing issues and discussions
  • Ask questions in GitHub Discussions
  • Join community discussions and help others
  • Contact maintainers for private matters

Thank you for contributing to php-chatbot! Your efforts help make this project better for everyone. 🚀


Next: FAQ

Clone this wiki locally