-
-
Notifications
You must be signed in to change notification settings - Fork 1
Contributing
How to contribute to the php-chatbot project.
- Getting Started
- Development Setup
- Contribution Guidelines
- Code Standards
- Testing Requirements
- Documentation
- Pull Request Process
- Community Guidelines
We welcome contributions to php-chatbot! Whether you're fixing bugs, adding features, improving documentation, or suggesting enhancements, your help is appreciated.
- 🐛 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
- Check existing issues - Someone might already be working on it
- Read the documentation - Understand the project structure
- Join discussions - Ask questions in issues or discussions
- Start small - Begin with simple bug fixes or documentation improvements
- Issues - Bug reports and feature requests
- Discussions - Questions and ideas
- Projects - Development roadmap
- Wiki - Comprehensive documentation
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)
-
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
-
Install Dependencies
# Install PHP dependencies composer install # Install dev dependencies for testing composer install --dev # Install frontend dependencies (if working on UI) npm install
-
Environment Setup
# Copy environment file cp .env.example .env # Edit .env with your API keys for testing nano .env
-
Run Tests
# Run the test suite composer test # Run with coverage composer test:coverage # Run specific test file ./vendor/bin/pest tests/PhpChatbotTest.php
-
Code Quality
# Run static analysis composer analyse # Fix code style composer cs-fix # Check code style composer cs-check
-
Create a branch for your feature/fix:
git checkout -b feature/your-feature-name # or git checkout -b fix/issue-number -
Make changes following our coding standards
-
Test your changes:
composer test composer analyse -
Commit your changes:
git add . git commit -m "feat: add new AI model support"
-
Push and create PR:
git push origin feature/your-feature-name
# 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- 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
- 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
- Fix typos and improve clarity
- Add missing examples or use cases
- Update outdated information
- Improve code comments and PHPDoc blocks
- 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
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.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.- 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
We follow PSR-12 coding standards with additional project-specific rules.
<?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
}
}-
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)
/**
* 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
}// 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);
}// 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';
}// 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;
}
}
}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-
Features:
feature/feature-nameorfeat/short-description -
Bug fixes:
fix/issue-numberorfix/short-description -
Documentation:
docs/section-name -
Chores:
chore/task-description
We maintain 90%+ test coverage. All new code must include 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);
});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');
});// 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');
});
});# 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 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
- PHPDoc blocks for all public methods
- Type hints for parameters and return values
- Usage examples in docblocks
- Exception documentation for error cases
- Installation guides for different environments
- Configuration examples with explanations
- Common use cases and recipes
- Troubleshooting guides for known issues
- Architecture decisions and rationale
- Extension points and customization
- Contributing guidelines (this document)
- Release notes and changelog
- Clear and concise language
- Active voice when possible
- Consistent terminology throughout
- Practical examples over theoretical explanations
// ✅ 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 docs when adding new features
- Fix outdated examples when changing APIs
- Add migration guides for breaking changes
- Include version compatibility information
-
Ensure tests pass:
composer test -
Check code quality:
composer analyse -
Fix code style:
composer cs-fix - Update documentation if needed
-
Rebase on latest main:
git rebase upstream/main
## 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- Automated checks must pass (CI/CD)
- Code review by maintainers
- Testing in staging environment
- Approval by project maintainer
- Merge when all requirements met
- Follows coding standards and best practices
- Includes appropriate tests with good coverage
- Has clear, descriptive commit messages
- Doesn't introduce security vulnerabilities
- Solves the intended problem effectively
- Doesn't break existing functionality
- Handles edge cases appropriately
- Includes proper error handling
- Updates relevant documentation
- Includes clear code comments
- Provides usage examples when appropriate
We are committed to providing a welcoming and inclusive environment for all contributors.
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
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.
- 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
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
- 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